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,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/EndIfKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class EndIfKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public EndIfKeywordRecommender() : base(SyntaxKind.EndIfKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.IsPreProcessorKeywordContext; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class EndIfKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public EndIfKeywordRecommender() : base(SyntaxKind.EndIfKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.IsPreProcessorKeywordContext; } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/VisualStudio/Core/Test.Next/Remote/RemoteHostClientServiceFactoryTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.Remote.UnitTests { [UseExportProvider] [Trait(Traits.Feature, Traits.Features.RemoteHost)] public class RemoteHostClientServiceFactoryTests { private static readonly TestComposition s_composition = FeaturesTestCompositions.Features.WithTestHostParts(TestHost.OutOfProcess); private static AdhocWorkspace CreateWorkspace() => new(s_composition.GetHostServices()); [Fact] public async Task UpdaterService() { using var workspace = CreateWorkspace(); var exportProvider = (IMefHostExportProvider)workspace.Services.HostServices; var listenerProvider = exportProvider.GetExportedValue<AsynchronousOperationListenerProvider>(); var globalOptions = exportProvider.GetExportedValue<IGlobalOptionService>(); globalOptions.SetGlobalOption(RemoteHostOptions.SolutionChecksumMonitorBackOffTimeSpanInMS, 1); var checksumUpdater = new SolutionChecksumUpdater(workspace, globalOptions, listenerProvider, CancellationToken.None); var service = workspace.Services.GetRequiredService<IRemoteHostClientProvider>(); // make sure client is ready using var client = await service.TryGetRemoteHostClientAsync(CancellationToken.None); // add solution, change document workspace.AddSolution(SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default)); var project = workspace.AddProject("proj", LanguageNames.CSharp); var document = workspace.AddDocument(project.Id, "doc.cs", SourceText.From("code")); workspace.ApplyTextChanges(document.Id, new[] { new TextChange(new TextSpan(0, 1), "abc") }, CancellationToken.None); // wait for listener var workspaceListener = listenerProvider.GetWaiter(FeatureAttribute.Workspace); await workspaceListener.ExpeditedWaitAsync(); var listener = listenerProvider.GetWaiter(FeatureAttribute.SolutionChecksumUpdater); await listener.ExpeditedWaitAsync(); // checksum should already exist Assert.True(workspace.CurrentSolution.State.TryGetStateChecksums(out _)); checksumUpdater.Shutdown(); } [Fact] public async Task TestSessionWithNoSolution() { using var workspace = CreateWorkspace(); var service = workspace.Services.GetRequiredService<IRemoteHostClientProvider>(); var mock = new MockLogService(); var client = await service.TryGetRemoteHostClientAsync(CancellationToken.None); using var connection = client.CreateConnection<IRemoteSymbolSearchUpdateService>(callbackTarget: mock); Assert.True(await connection.TryInvokeAsync( (service, callbackId, cancellationToken) => service.UpdateContinuouslyAsync(callbackId, "emptySource", Path.GetTempPath(), cancellationToken), CancellationToken.None)); } [Fact] public async Task TestSessionClosed() { using var workspace = CreateWorkspace(); using var client = await InProcRemoteHostClient.GetTestClientAsync(workspace).ConfigureAwait(false); var serviceName = new RemoteServiceName("Test"); // register local service TestService testService = null; client.RegisterService(serviceName, (s, p, o) => { testService = new TestService(s, p); return testService; }); // create session that stay alive until client alive (ex, SymbolSearchUpdateEngine) using var connection = await client.CreateConnectionAsync(serviceName, callbackTarget: null, CancellationToken.None); // mimic unfortunate call that happens to be in the middle of communication. var task = connection.RunRemoteAsync("TestMethodAsync", solution: null, arguments: null, CancellationToken.None); // make client to go away client.Dispose(); // let the service to return testService.Event.Set(); // make sure task finished gracefully await task; } private class TestService : ServiceBase { public TestService(Stream stream, IServiceProvider serviceProvider) : base(serviceProvider, stream) { Event = new ManualResetEvent(false); StartService(); } public readonly ManualResetEvent Event; public Task TestMethodAsync() { Event.WaitOne(); return Task.CompletedTask; } } private class NullAssemblyAnalyzerLoader : IAnalyzerAssemblyLoader { public void AddDependencyLocation(string fullPath) { } public Assembly LoadFromPath(string fullPath) { // doesn't matter what it returns return typeof(object).Assembly; } } private class MockLogService : ISymbolSearchLogService { public ValueTask LogExceptionAsync(string exception, string text, CancellationToken cancellationToken) => default; public ValueTask LogInfoAsync(string text, CancellationToken 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; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.Remote.UnitTests { [UseExportProvider] [Trait(Traits.Feature, Traits.Features.RemoteHost)] public class RemoteHostClientServiceFactoryTests { private static readonly TestComposition s_composition = FeaturesTestCompositions.Features.WithTestHostParts(TestHost.OutOfProcess); private static AdhocWorkspace CreateWorkspace() => new(s_composition.GetHostServices()); [Fact] public async Task UpdaterService() { using var workspace = CreateWorkspace(); var exportProvider = (IMefHostExportProvider)workspace.Services.HostServices; var listenerProvider = exportProvider.GetExportedValue<AsynchronousOperationListenerProvider>(); var globalOptions = exportProvider.GetExportedValue<IGlobalOptionService>(); globalOptions.SetGlobalOption(RemoteHostOptions.SolutionChecksumMonitorBackOffTimeSpanInMS, 1); var checksumUpdater = new SolutionChecksumUpdater(workspace, globalOptions, listenerProvider, CancellationToken.None); var service = workspace.Services.GetRequiredService<IRemoteHostClientProvider>(); // make sure client is ready using var client = await service.TryGetRemoteHostClientAsync(CancellationToken.None); // add solution, change document workspace.AddSolution(SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default)); var project = workspace.AddProject("proj", LanguageNames.CSharp); var document = workspace.AddDocument(project.Id, "doc.cs", SourceText.From("code")); workspace.ApplyTextChanges(document.Id, new[] { new TextChange(new TextSpan(0, 1), "abc") }, CancellationToken.None); // wait for listener var workspaceListener = listenerProvider.GetWaiter(FeatureAttribute.Workspace); await workspaceListener.ExpeditedWaitAsync(); var listener = listenerProvider.GetWaiter(FeatureAttribute.SolutionChecksumUpdater); await listener.ExpeditedWaitAsync(); // checksum should already exist Assert.True(workspace.CurrentSolution.State.TryGetStateChecksums(out _)); checksumUpdater.Shutdown(); } [Fact] public async Task TestSessionWithNoSolution() { using var workspace = CreateWorkspace(); var service = workspace.Services.GetRequiredService<IRemoteHostClientProvider>(); var mock = new MockLogService(); var client = await service.TryGetRemoteHostClientAsync(CancellationToken.None); using var connection = client.CreateConnection<IRemoteSymbolSearchUpdateService>(callbackTarget: mock); Assert.True(await connection.TryInvokeAsync( (service, callbackId, cancellationToken) => service.UpdateContinuouslyAsync(callbackId, "emptySource", Path.GetTempPath(), cancellationToken), CancellationToken.None)); } [Fact] public async Task TestSessionClosed() { using var workspace = CreateWorkspace(); using var client = await InProcRemoteHostClient.GetTestClientAsync(workspace).ConfigureAwait(false); var serviceName = new RemoteServiceName("Test"); // register local service TestService testService = null; client.RegisterService(serviceName, (s, p, o) => { testService = new TestService(s, p); return testService; }); // create session that stay alive until client alive (ex, SymbolSearchUpdateEngine) using var connection = await client.CreateConnectionAsync(serviceName, callbackTarget: null, CancellationToken.None); // mimic unfortunate call that happens to be in the middle of communication. var task = connection.RunRemoteAsync("TestMethodAsync", solution: null, arguments: null, CancellationToken.None); // make client to go away client.Dispose(); // let the service to return testService.Event.Set(); // make sure task finished gracefully await task; } private class TestService : ServiceBase { public TestService(Stream stream, IServiceProvider serviceProvider) : base(serviceProvider, stream) { Event = new ManualResetEvent(false); StartService(); } public readonly ManualResetEvent Event; public Task TestMethodAsync() { Event.WaitOne(); return Task.CompletedTask; } } private class NullAssemblyAnalyzerLoader : IAnalyzerAssemblyLoader { public void AddDependencyLocation(string fullPath) { } public Assembly LoadFromPath(string fullPath) { // doesn't matter what it returns return typeof(object).Assembly; } } private class MockLogService : ISymbolSearchLogService { public ValueTask LogExceptionAsync(string exception, string text, CancellationToken cancellationToken) => default; public ValueTask LogInfoAsync(string text, CancellationToken cancellationToken) => default; } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Features/Core/Portable/RQName/Nodes/RQOutParameter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Features.RQName.SimpleTree; namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal class RQOutParameter : RQParameter { public RQOutParameter(RQType type) : base(type) { } public override SimpleTreeNode CreateSimpleTreeForType() => new SimpleGroupNode(RQNameStrings.ParamMod, new SimpleLeafNode(RQNameStrings.Out), Type.ToSimpleTree()); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Features.RQName.SimpleTree; namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal class RQOutParameter : RQParameter { public RQOutParameter(RQType type) : base(type) { } public override SimpleTreeNode CreateSimpleTreeForType() => new SimpleGroupNode(RQNameStrings.ParamMod, new SimpleLeafNode(RQNameStrings.Out), Type.ToSimpleTree()); } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/Core/Portable/Syntax/SeparatedSyntaxListBuilder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace Microsoft.CodeAnalysis.Syntax { internal struct SeparatedSyntaxListBuilder<TNode> where TNode : SyntaxNode { private readonly SyntaxListBuilder _builder; private bool _expectedSeparator; public SeparatedSyntaxListBuilder(int size) : this(new SyntaxListBuilder(size)) { } public static SeparatedSyntaxListBuilder<TNode> Create() { return new SeparatedSyntaxListBuilder<TNode>(8); } internal SeparatedSyntaxListBuilder(SyntaxListBuilder builder) { _builder = builder; _expectedSeparator = false; } public bool IsNull { get { return _builder == null; } } public int Count { get { return _builder.Count; } } public void Clear() { _builder.Clear(); } private void CheckExpectedElement() { if (_expectedSeparator) { throw new InvalidOperationException(CodeAnalysisResources.SeparatorIsExpected); } } private void CheckExpectedSeparator() { if (!_expectedSeparator) { throw new InvalidOperationException(CodeAnalysisResources.ElementIsExpected); } } public SeparatedSyntaxListBuilder<TNode> Add(TNode node) { CheckExpectedElement(); _expectedSeparator = true; _builder.Add(node); return this; } public SeparatedSyntaxListBuilder<TNode> AddSeparator(in SyntaxToken separatorToken) { Debug.Assert(separatorToken.Node is object); CheckExpectedSeparator(); _expectedSeparator = false; _builder.AddInternal(separatorToken.Node); return this; } public SeparatedSyntaxListBuilder<TNode> AddRange(in SeparatedSyntaxList<TNode> nodes) { CheckExpectedElement(); SyntaxNodeOrTokenList list = nodes.GetWithSeparators(); _builder.AddRange(list); _expectedSeparator = ((_builder.Count & 1) != 0); return this; } public SeparatedSyntaxListBuilder<TNode> AddRange(in SeparatedSyntaxList<TNode> nodes, int count) { CheckExpectedElement(); SyntaxNodeOrTokenList list = nodes.GetWithSeparators(); _builder.AddRange(list, this.Count, Math.Min(count << 1, list.Count)); _expectedSeparator = ((_builder.Count & 1) != 0); return this; } public SeparatedSyntaxList<TNode> ToList() { if (_builder == null) { return new SeparatedSyntaxList<TNode>(); } return _builder.ToSeparatedList<TNode>(); } public SeparatedSyntaxList<TDerived> ToList<TDerived>() where TDerived : TNode { if (_builder == null) { return new SeparatedSyntaxList<TDerived>(); } return _builder.ToSeparatedList<TDerived>(); } public static implicit operator SyntaxListBuilder(in SeparatedSyntaxListBuilder<TNode> builder) { return builder._builder; } public static implicit operator SeparatedSyntaxList<TNode>(in SeparatedSyntaxListBuilder<TNode> builder) { if (builder._builder != null) { return builder.ToList(); } return default(SeparatedSyntaxList<TNode>); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace Microsoft.CodeAnalysis.Syntax { internal struct SeparatedSyntaxListBuilder<TNode> where TNode : SyntaxNode { private readonly SyntaxListBuilder _builder; private bool _expectedSeparator; public SeparatedSyntaxListBuilder(int size) : this(new SyntaxListBuilder(size)) { } public static SeparatedSyntaxListBuilder<TNode> Create() { return new SeparatedSyntaxListBuilder<TNode>(8); } internal SeparatedSyntaxListBuilder(SyntaxListBuilder builder) { _builder = builder; _expectedSeparator = false; } public bool IsNull { get { return _builder == null; } } public int Count { get { return _builder.Count; } } public void Clear() { _builder.Clear(); } private void CheckExpectedElement() { if (_expectedSeparator) { throw new InvalidOperationException(CodeAnalysisResources.SeparatorIsExpected); } } private void CheckExpectedSeparator() { if (!_expectedSeparator) { throw new InvalidOperationException(CodeAnalysisResources.ElementIsExpected); } } public SeparatedSyntaxListBuilder<TNode> Add(TNode node) { CheckExpectedElement(); _expectedSeparator = true; _builder.Add(node); return this; } public SeparatedSyntaxListBuilder<TNode> AddSeparator(in SyntaxToken separatorToken) { Debug.Assert(separatorToken.Node is object); CheckExpectedSeparator(); _expectedSeparator = false; _builder.AddInternal(separatorToken.Node); return this; } public SeparatedSyntaxListBuilder<TNode> AddRange(in SeparatedSyntaxList<TNode> nodes) { CheckExpectedElement(); SyntaxNodeOrTokenList list = nodes.GetWithSeparators(); _builder.AddRange(list); _expectedSeparator = ((_builder.Count & 1) != 0); return this; } public SeparatedSyntaxListBuilder<TNode> AddRange(in SeparatedSyntaxList<TNode> nodes, int count) { CheckExpectedElement(); SyntaxNodeOrTokenList list = nodes.GetWithSeparators(); _builder.AddRange(list, this.Count, Math.Min(count << 1, list.Count)); _expectedSeparator = ((_builder.Count & 1) != 0); return this; } public SeparatedSyntaxList<TNode> ToList() { if (_builder == null) { return new SeparatedSyntaxList<TNode>(); } return _builder.ToSeparatedList<TNode>(); } public SeparatedSyntaxList<TDerived> ToList<TDerived>() where TDerived : TNode { if (_builder == null) { return new SeparatedSyntaxList<TDerived>(); } return _builder.ToSeparatedList<TDerived>(); } public static implicit operator SyntaxListBuilder(in SeparatedSyntaxListBuilder<TNode> builder) { return builder._builder; } public static implicit operator SeparatedSyntaxList<TNode>(in SeparatedSyntaxListBuilder<TNode> builder) { if (builder._builder != null) { return builder.ToList(); } return default(SeparatedSyntaxList<TNode>); } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Features/Core/Portable/PullMemberUp/Dialog/IPullMemberUpOptionsService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Host; using Microsoft.CodeAnalysis.PullMemberUp; namespace Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp.Dialog { internal interface IPullMemberUpOptionsService : IWorkspaceService { PullMembersUpOptions GetPullMemberUpOptions(Document document, ISymbol selectedNodeSymbol); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Host; using Microsoft.CodeAnalysis.PullMemberUp; namespace Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp.Dialog { internal interface IPullMemberUpOptionsService : IWorkspaceService { PullMembersUpOptions GetPullMemberUpOptions(Document document, ISymbol selectedNodeSymbol); } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/VisualBasic/Portable/Symbols/WellKnownMembers.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.PooledObjects Imports Microsoft.CodeAnalysis.RuntimeMembers Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic Partial Public Class VisualBasicCompilation Private ReadOnly _wellKnownMemberSignatureComparer As New WellKnownMembersSignatureComparer(Me) ''' <summary> ''' An array of cached well known types available for use in this Compilation. ''' Lazily filled by GetWellKnownType method. ''' </summary> ''' <remarks></remarks> Private _lazyWellKnownTypes() As NamedTypeSymbol ''' <summary> ''' Lazy cache of well known members. ''' Not yet known value is represented by ErrorTypeSymbol.UnknownResultType ''' </summary> Private _lazyWellKnownTypeMembers() As Symbol Private _lazyExtensionAttributeConstructor As Symbol = ErrorTypeSymbol.UnknownResultType ' Not yet known. Private _lazyExtensionAttributeConstructorErrorInfo As Object 'Actually, DiagnosticInfo #Region "Synthesized Attributes" Friend Function GetExtensionAttributeConstructor(<Out> ByRef useSiteInfo As UseSiteInfo(Of AssemblySymbol)) As MethodSymbol Dim attributeCtor As MethodSymbol = Nothing Dim ctorError As DiagnosticInfo = Nothing If _lazyExtensionAttributeConstructor Is ErrorTypeSymbol.UnknownResultType Then Dim system_Runtime_CompilerServices = Me.GlobalNamespace.LookupNestedNamespace(ImmutableArray.Create(MetadataHelpers.SystemString, "Runtime", "CompilerServices")) Dim attributeType As NamedTypeSymbol = Nothing Dim sourceModuleSymbol = DirectCast(Me.SourceModule, SourceModuleSymbol) Dim sourceModuleBinder As Binder = BinderBuilder.CreateSourceModuleBinder(sourceModuleSymbol) If system_Runtime_CompilerServices IsNot Nothing Then Dim candidates = system_Runtime_CompilerServices.GetTypeMembers(AttributeDescription.CaseInsensitiveExtensionAttribute.Name, 0) Dim ambiguity As Boolean = False For Each candidate As NamedTypeSymbol In candidates If Not sourceModuleBinder.IsAccessible(candidate, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then Continue For End If If candidate.ContainingModule Is sourceModuleSymbol Then ' Type from this module always better. attributeType = candidate ambiguity = False Exit For End If If attributeType Is Nothing Then Debug.Assert(Not ambiguity) attributeType = candidate ElseIf candidate.ContainingAssembly Is Me.Assembly Then If attributeType.ContainingAssembly Is Me.Assembly Then ambiguity = True Else attributeType = candidate ambiguity = False End If ElseIf attributeType.ContainingAssembly IsNot Me.Assembly Then Debug.Assert(candidate.ContainingAssembly IsNot Me.Assembly) ambiguity = True End If Next If ambiguity Then Debug.Assert(attributeType IsNot Nothing) attributeType = Nothing End If End If If attributeType IsNot Nothing AndAlso Not attributeType.IsStructureType AndAlso Not attributeType.IsMustInherit AndAlso GetWellKnownType(WellKnownType.System_Attribute).IsBaseTypeOf(attributeType, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) AndAlso sourceModuleBinder.IsAccessible(attributeType, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then For Each ctor In attributeType.InstanceConstructors If ctor.ParameterCount = 0 Then If sourceModuleBinder.IsAccessible(ctor, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then attributeCtor = ctor End If Exit For End If Next End If If attributeCtor Is Nothing Then ' TODO (tomat): It is not clear under what circumstances is this error reported since the binder already reports errors when the conditions above are not satisfied. ctorError = ErrorFactory.ErrorInfo(ERRID.ERR_MissingRuntimeHelper, AttributeDescription.CaseInsensitiveExtensionAttribute.FullName & "." & WellKnownMemberNames.InstanceConstructorName) Else Dim attributeUsage As AttributeUsageInfo = attributeCtor.ContainingType.GetAttributeUsageInfo() Debug.Assert(Not attributeUsage.IsNull) Const requiredTargets As AttributeTargets = AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method If (attributeUsage.ValidTargets And requiredTargets) <> requiredTargets Then ctorError = ErrorFactory.ErrorInfo(ERRID.ERR_ExtensionAttributeInvalid) End If End If ' Storing m_LazyExtensionAttributeConstructorErrorInfo first. _lazyExtensionAttributeConstructorErrorInfo = ctorError Interlocked.CompareExchange(_lazyExtensionAttributeConstructor, DirectCast(attributeCtor, Symbol), DirectCast(ErrorTypeSymbol.UnknownResultType, Symbol)) End If attributeCtor = DirectCast(_lazyExtensionAttributeConstructor, MethodSymbol) ctorError = DirectCast(Volatile.Read(_lazyExtensionAttributeConstructorErrorInfo), DiagnosticInfo) If ctorError IsNot Nothing Then useSiteInfo = New UseSiteInfo(Of AssemblySymbol)(ctorError) Else useSiteInfo = Binder.GetUseSiteInfoForMemberAndContainingType(attributeCtor) End If Return attributeCtor End Function ''' <summary> ''' Synthesizes a custom attribute. ''' Returns Nothing if the <paramref name="constructor"/> symbol is missing, ''' or any of the members in <paramref name="namedArguments" /> are missing. ''' The attribute is synthesized only if present. ''' </summary> ''' <param name="namedArguments"> ''' Takes a list of pairs of well-known members and constants. The constants ''' will be passed to the field/property referenced by the well-known member. ''' If the well-known member does Not exist in the compilation then no attribute ''' will be synthesized. ''' </param> ''' <param name="isOptionalUse"> ''' Indicates if this particular attribute application should be considered optional. ''' </param> Friend Function TrySynthesizeAttribute( constructor As WellKnownMember, Optional arguments As ImmutableArray(Of TypedConstant) = Nothing, Optional namedArguments As ImmutableArray(Of KeyValuePair(Of WellKnownMember, TypedConstant)) = Nothing, Optional isOptionalUse As Boolean = False ) As SynthesizedAttributeData Dim constructorSymbol = TryCast(GetWellKnownTypeMember(constructor), MethodSymbol) If constructorSymbol Is Nothing OrElse Binder.GetUseSiteInfoForWellKnownTypeMember(constructorSymbol, constructor, False).DiagnosticInfo IsNot Nothing Then Return ReturnNothingOrThrowIfAttributeNonOptional(constructor, isOptionalUse) End If If arguments.IsDefault Then arguments = ImmutableArray(Of TypedConstant).Empty End If Dim namedStringArguments As ImmutableArray(Of KeyValuePair(Of String, TypedConstant)) If namedArguments.IsDefault Then namedStringArguments = ImmutableArray(Of KeyValuePair(Of String, TypedConstant)).Empty Else Dim builder = New ArrayBuilder(Of KeyValuePair(Of String, TypedConstant))(namedArguments.Length) For Each arg In namedArguments Dim wellKnownMember = GetWellKnownTypeMember(arg.Key) If wellKnownMember Is Nothing OrElse TypeOf wellKnownMember Is ErrorTypeSymbol OrElse Binder.GetUseSiteInfoForWellKnownTypeMember(wellKnownMember, arg.Key, False).DiagnosticInfo IsNot Nothing Then Return ReturnNothingOrThrowIfAttributeNonOptional(constructor) Else builder.Add(New KeyValuePair(Of String, TypedConstant)(wellKnownMember.Name, arg.Value)) End If Next namedStringArguments = builder.ToImmutableAndFree() End If Return New SynthesizedAttributeData(constructorSymbol, arguments, namedStringArguments) End Function Private Shared Function ReturnNothingOrThrowIfAttributeNonOptional(constructor As WellKnownMember, Optional isOptionalUse As Boolean = False) As SynthesizedAttributeData If isOptionalUse OrElse WellKnownMembers.IsSynthesizedAttributeOptional(constructor) Then Return Nothing Else Throw ExceptionUtilities.Unreachable End If End Function Friend Function SynthesizeExtensionAttribute() As SynthesizedAttributeData Dim constructor As MethodSymbol = GetExtensionAttributeConstructor(useSiteInfo:=Nothing) Debug.Assert(constructor IsNot Nothing AndAlso constructor.GetUseSiteInfo().DiagnosticInfo Is Nothing AndAlso constructor.ContainingType.GetUseSiteInfo().DiagnosticInfo Is Nothing) Return SynthesizedAttributeData.Create(constructor, WellKnownMember.System_Runtime_CompilerServices_ExtensionAttribute__ctor) End Function Friend Function SynthesizeStateMachineAttribute(method As MethodSymbol, compilationState As ModuleCompilationState) As SynthesizedAttributeData Debug.Assert(method.IsAsync OrElse method.IsIterator) ' The async state machine type is not synthesized until the async method body is rewritten. If we are ' only emitting metadata the method body will not have been rewritten, and the async state machine ' type will not have been created. In this case, omit the attribute. Dim stateMachineType As NamedTypeSymbol = Nothing If compilationState.TryGetStateMachineType(method, stateMachineType) Then Dim ctor = If(method.IsAsync, WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor, WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor) Dim arg = New TypedConstant(GetWellKnownType(WellKnownType.System_Type), TypedConstantKind.Type, If(stateMachineType.IsGenericType, stateMachineType.ConstructUnboundGenericType(), stateMachineType)) Return TrySynthesizeAttribute(ctor, ImmutableArray.Create(arg)) End If Return Nothing End Function Friend Function SynthesizeDecimalConstantAttribute(value As Decimal) As SynthesizedAttributeData Dim isNegative As Boolean Dim scale As Byte Dim low, mid, high As UInteger value.GetBits(isNegative, scale, low, mid, high) Dim specialTypeByte = GetSpecialType(SpecialType.System_Byte) Debug.Assert(specialTypeByte.GetUseSiteInfo().DiagnosticInfo Is Nothing) Dim specialTypeUInt32 = GetSpecialType(SpecialType.System_UInt32) Debug.Assert(specialTypeUInt32.GetUseSiteInfo().DiagnosticInfo Is Nothing) Return TrySynthesizeAttribute( WellKnownMember.System_Runtime_CompilerServices_DecimalConstantAttribute__ctor, ImmutableArray.Create( New TypedConstant(specialTypeByte, TypedConstantKind.Primitive, scale), New TypedConstant(specialTypeByte, TypedConstantKind.Primitive, CByte(If(isNegative, 128, 0))), New TypedConstant(specialTypeUInt32, TypedConstantKind.Primitive, high), New TypedConstant(specialTypeUInt32, TypedConstantKind.Primitive, mid), New TypedConstant(specialTypeUInt32, TypedConstantKind.Primitive, low) )) End Function Friend Function SynthesizeDebuggerBrowsableNeverAttribute() As SynthesizedAttributeData If Options.OptimizationLevel <> OptimizationLevel.Debug Then Return Nothing End If Return TrySynthesizeAttribute( WellKnownMember.System_Diagnostics_DebuggerBrowsableAttribute__ctor, ImmutableArray.Create(New TypedConstant(GetWellKnownType(WellKnownType.System_Diagnostics_DebuggerBrowsableState), TypedConstantKind.Enum, DebuggerBrowsableState.Never))) End Function Friend Function SynthesizeDebuggerHiddenAttribute() As SynthesizedAttributeData If Options.OptimizationLevel <> OptimizationLevel.Debug Then Return Nothing End If Return TrySynthesizeAttribute(WellKnownMember.System_Diagnostics_DebuggerHiddenAttribute__ctor) End Function Friend Function SynthesizeEditorBrowsableNeverAttribute() As SynthesizedAttributeData Return TrySynthesizeAttribute( WellKnownMember.System_ComponentModel_EditorBrowsableAttribute__ctor, ImmutableArray.Create(New TypedConstant(GetWellKnownType(WellKnownType.System_ComponentModel_EditorBrowsableState), TypedConstantKind.Enum, System.ComponentModel.EditorBrowsableState.Never))) End Function Friend Function SynthesizeDebuggerNonUserCodeAttribute() As SynthesizedAttributeData If Options.OptimizationLevel <> OptimizationLevel.Debug Then Return Nothing End If Return TrySynthesizeAttribute(WellKnownMember.System_Diagnostics_DebuggerNonUserCodeAttribute__ctor) End Function Friend Function SynthesizeOptionalDebuggerStepThroughAttribute() As SynthesizedAttributeData If Options.OptimizationLevel <> OptimizationLevel.Debug Then Return Nothing End If Debug.Assert( WellKnownMembers.IsSynthesizedAttributeOptional( WellKnownMember.System_Diagnostics_DebuggerStepThroughAttribute__ctor)) Return TrySynthesizeAttribute(WellKnownMember.System_Diagnostics_DebuggerStepThroughAttribute__ctor) End Function #End Region ''' <summary> ''' Lookup member declaration in well known type used by this Compilation. ''' </summary> Friend Function GetWellKnownTypeMember(member As WellKnownMember) As Symbol Debug.Assert(member >= 0 AndAlso member < WellKnownMember.Count) ' Test hook If a member Is marked missing, Then Return null. If IsMemberMissing(member) Then Return Nothing End If If _lazyWellKnownTypeMembers Is Nothing OrElse _lazyWellKnownTypeMembers(member) Is ErrorTypeSymbol.UnknownResultType Then If (_lazyWellKnownTypeMembers Is Nothing) Then Dim wellKnownTypeMembers = New Symbol(WellKnownMember.Count - 1) {} For i As Integer = 0 To wellKnownTypeMembers.Length - 1 wellKnownTypeMembers(i) = ErrorTypeSymbol.UnknownResultType Next Interlocked.CompareExchange(_lazyWellKnownTypeMembers, wellKnownTypeMembers, Nothing) End If Dim descriptor = WellKnownMembers.GetDescriptor(member) Dim type = If(descriptor.DeclaringTypeId <= SpecialType.Count, GetSpecialType(CType(descriptor.DeclaringTypeId, SpecialType)), GetWellKnownType(CType(descriptor.DeclaringTypeId, WellKnownType))) Dim result As Symbol = Nothing If Not type.IsErrorType() Then result = VisualBasicCompilation.GetRuntimeMember(type, descriptor, _wellKnownMemberSignatureComparer, accessWithinOpt:=Me.Assembly) End If Interlocked.CompareExchange(_lazyWellKnownTypeMembers(member), result, DirectCast(ErrorTypeSymbol.UnknownResultType, Symbol)) End If Return _lazyWellKnownTypeMembers(member) End Function Friend Overrides Function IsSystemTypeReference(type As ITypeSymbolInternal) As Boolean Return TypeSymbol.Equals(DirectCast(type, TypeSymbol), GetWellKnownType(WellKnownType.System_Type), TypeCompareKind.ConsiderEverything) End Function Friend Overrides Function CommonGetWellKnownTypeMember(member As WellKnownMember) As ISymbolInternal Return GetWellKnownTypeMember(member) End Function Friend Overrides Function CommonGetWellKnownType(wellknownType As WellKnownType) As ITypeSymbolInternal Return GetWellKnownType(wellknownType) End Function Friend Overrides Function IsAttributeType(type As ITypeSymbol) As Boolean If type.Kind <> SymbolKind.NamedType Then Return False End If Return DirectCast(type, NamedTypeSymbol).IsOrDerivedFromWellKnownClass(WellKnownType.System_Attribute, Me, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) End Function ''' <summary> ''' In case duplicate types are encountered, returns an error type. ''' But if the IgnoreCorLibraryDuplicatedTypes compilation option is set, any duplicate type found in corlib is ignored and doesn't count as a duplicate. ''' </summary> Friend Function GetWellKnownType(type As WellKnownType) As NamedTypeSymbol Debug.Assert(type.IsWellKnownType()) Dim index As Integer = type - WellKnownType.First If _lazyWellKnownTypes Is Nothing OrElse _lazyWellKnownTypes(index) Is Nothing Then If (_lazyWellKnownTypes Is Nothing) Then Interlocked.CompareExchange(_lazyWellKnownTypes, New NamedTypeSymbol(WellKnownTypes.Count - 1) {}, Nothing) End If Dim mdName As String = WellKnownTypes.GetMetadataName(type) Dim result As NamedTypeSymbol Dim conflicts As (AssemblySymbol, AssemblySymbol) = Nothing If IsTypeMissing(type) Then result = Nothing Else result = Me.Assembly.GetTypeByMetadataName(mdName, includeReferences:=True, isWellKnownType:=True, useCLSCompliantNameArityEncoding:=True, conflicts:=conflicts, ignoreCorLibraryDuplicatedTypes:=Me.Options.IgnoreCorLibraryDuplicatedTypes) End If If result Is Nothing Then Dim emittedName As MetadataTypeName = MetadataTypeName.FromFullName(mdName, useCLSCompliantNameArityEncoding:=True) If type.IsValueTupleType() Then Dim delayedErrorInfo As Func(Of MissingMetadataTypeSymbol.TopLevelWithCustomErrorInfo, DiagnosticInfo) If conflicts.Item1 Is Nothing Then Debug.Assert(conflicts.Item2 Is Nothing) delayedErrorInfo = Function(t) ErrorFactory.ErrorInfo(ERRID.ERR_ValueTupleTypeRefResolutionError1, t) Else Dim capturedConflicts = conflicts delayedErrorInfo = Function(t) ErrorFactory.ErrorInfo(ERRID.ERR_ValueTupleResolutionAmbiguous3, t, capturedConflicts.Item1, capturedConflicts.Item2) End If result = New MissingMetadataTypeSymbol.TopLevelWithCustomErrorInfo(Assembly.Modules(0), emittedName, delayedErrorInfo) Else result = New MissingMetadataTypeSymbol.TopLevel(Assembly.Modules(0), emittedName) End If End If If (Interlocked.CompareExchange(_lazyWellKnownTypes(index), result, Nothing) IsNot Nothing) Then Debug.Assert(result Is _lazyWellKnownTypes(index) OrElse (_lazyWellKnownTypes(index).IsErrorType() AndAlso result.IsErrorType())) End If End If Return _lazyWellKnownTypes(index) End Function Friend Shared Function GetRuntimeMember( ByVal declaringType As NamedTypeSymbol, ByRef descriptor As MemberDescriptor, ByVal comparer As SignatureComparer(Of MethodSymbol, FieldSymbol, PropertySymbol, TypeSymbol, ParameterSymbol), ByVal accessWithinOpt As AssemblySymbol ) As Symbol Dim result As Symbol = Nothing Dim targetSymbolKind As SymbolKind Dim targetMethodKind As MethodKind = MethodKind.Ordinary Dim isShared As Boolean = (descriptor.Flags And MemberFlags.Static) <> 0 Select Case descriptor.Flags And MemberFlags.KindMask Case MemberFlags.Constructor targetSymbolKind = SymbolKind.Method targetMethodKind = MethodKind.Constructor Debug.Assert(Not isShared) 'static constructors are never called explicitly Case MemberFlags.Method targetSymbolKind = SymbolKind.Method Case MemberFlags.PropertyGet targetSymbolKind = SymbolKind.Method targetMethodKind = MethodKind.PropertyGet Case MemberFlags.Field targetSymbolKind = SymbolKind.Field Case MemberFlags.Property targetSymbolKind = SymbolKind.Property Case Else Throw ExceptionUtilities.UnexpectedValue(descriptor.Flags) End Select For Each m In declaringType.GetMembers(descriptor.Name) If m.Kind <> targetSymbolKind OrElse m.IsShared <> isShared OrElse Not (m.DeclaredAccessibility = Accessibility.Public OrElse (accessWithinOpt IsNot Nothing AndAlso Symbol.IsSymbolAccessible(m, accessWithinOpt))) Then Continue For End If If Not String.Equals(m.Name, descriptor.Name, StringComparison.Ordinal) Then Continue For End If Select Case targetSymbolKind Case SymbolKind.Method Dim method = DirectCast(m, MethodSymbol) Dim methodKind = method.MethodKind ' Treat user-defined conversions and operators as ordinary methods for the purpose ' of matching them here. If methodKind = MethodKind.Conversion OrElse methodKind = MethodKind.UserDefinedOperator Then methodKind = MethodKind.Ordinary End If If method.Arity <> descriptor.Arity OrElse methodKind <> targetMethodKind OrElse ((descriptor.Flags And MemberFlags.Virtual) <> 0) <> (method.IsOverridable OrElse method.IsOverrides OrElse method.IsMustOverride) Then Continue For End If If Not comparer.MatchMethodSignature(method, descriptor.Signature) Then Continue For End If Case SymbolKind.Property Dim [property] = DirectCast(m, PropertySymbol) If ((descriptor.Flags And MemberFlags.Virtual) <> 0) <> ([property].IsOverridable OrElse [property].IsOverrides OrElse [property].IsMustOverride) Then Continue For End If If Not comparer.MatchPropertySignature([property], descriptor.Signature) Then Continue For End If Case SymbolKind.Field If Not comparer.MatchFieldSignature(DirectCast(m, FieldSymbol), descriptor.Signature) Then Continue For End If Case Else Throw ExceptionUtilities.UnexpectedValue(targetSymbolKind) End Select If result IsNot Nothing Then ' ambiguity result = Nothing Exit For Else result = m End If Next Return result End Function Friend Class SpecialMembersSignatureComparer Inherits SignatureComparer(Of MethodSymbol, FieldSymbol, PropertySymbol, TypeSymbol, ParameterSymbol) Public Shared ReadOnly Instance As New SpecialMembersSignatureComparer() Protected Sub New() End Sub Protected Overrides Function GetMDArrayElementType(type As TypeSymbol) As TypeSymbol If type.Kind <> SymbolKind.ArrayType Then Return Nothing End If Dim array = DirectCast(type, ArrayTypeSymbol) If array.IsSZArray Then Return Nothing ' This is not a multidimensional array End If Return array.ElementType End Function Protected Overrides Function MatchArrayRank(type As TypeSymbol, countOfDimensions As Integer) As Boolean If countOfDimensions = 1 Then Return Nothing ' This must be a multidimensional array End If If type.Kind <> SymbolKind.ArrayType Then Return Nothing End If Dim array = DirectCast(type, ArrayTypeSymbol) Return array.Rank = countOfDimensions End Function Protected Overrides Function GetSZArrayElementType(type As TypeSymbol) As TypeSymbol If type.Kind <> SymbolKind.ArrayType Then Return Nothing End If Dim array = DirectCast(type, ArrayTypeSymbol) If Not array.IsSZArray Then Return Nothing ' This is a multidimensional array End If Return array.ElementType End Function Protected Overrides Function GetFieldType(field As FieldSymbol) As TypeSymbol Return field.Type End Function Protected Overrides Function GetPropertyType(prop As PropertySymbol) As TypeSymbol Return prop.Type End Function Protected Overrides Function GetGenericTypeArgument(ByVal type As TypeSymbol, ByVal argumentIndex As Integer) As TypeSymbol If type.Kind <> SymbolKind.NamedType Then Return Nothing End If Dim named = DirectCast(type, NamedTypeSymbol) If named.Arity <= argumentIndex Then Return Nothing End If 'We don't support nested types at the moment If named.ContainingType IsNot Nothing Then Return Nothing End If Return named.TypeArgumentsNoUseSiteDiagnostics(argumentIndex) End Function Protected Overrides Function GetGenericTypeDefinition(type As TypeSymbol) As TypeSymbol If type.Kind <> SymbolKind.NamedType Then Return Nothing End If Dim named = DirectCast(type, NamedTypeSymbol) 'We don't support nested types at the moment If named.ContainingType IsNot Nothing Then Return Nothing End If If named.Arity = 0 Then Return Nothing ' Not generic End If Return named.OriginalDefinition End Function Protected Overrides Function GetParameters(ByVal method As MethodSymbol) As ImmutableArray(Of ParameterSymbol) Return method.Parameters End Function Protected Overrides Function GetParameters(ByVal [property] As PropertySymbol) As ImmutableArray(Of ParameterSymbol) Return [property].Parameters End Function Protected Overrides Function GetParamType(ByVal parameter As ParameterSymbol) As TypeSymbol Return parameter.Type End Function Protected Overrides Function GetPointedToType(type As TypeSymbol) As TypeSymbol Return Nothing ' Do not support pointers End Function Protected Overrides Function GetReturnType(method As MethodSymbol) As TypeSymbol Return method.ReturnType End Function Protected Overrides Function IsByRefParam(ByVal parameter As ParameterSymbol) As Boolean Return parameter.IsByRef End Function Protected Overrides Function IsByRefMethod(ByVal method As MethodSymbol) As Boolean Return method.ReturnsByRef End Function Protected Overrides Function IsByRefProperty(ByVal [property] As PropertySymbol) As Boolean Return [property].ReturnsByRef End Function Protected Overrides Function IsGenericMethodTypeParam(type As TypeSymbol, paramPosition As Integer) As Boolean If type.Kind <> SymbolKind.TypeParameter Then Return False End If Dim typeParam = DirectCast(type, TypeParameterSymbol) If typeParam.ContainingSymbol.Kind <> SymbolKind.Method Then Return False End If Return typeParam.Ordinal = paramPosition End Function Protected Overrides Function IsGenericTypeParam(type As TypeSymbol, paramPosition As Integer) As Boolean If type.Kind <> SymbolKind.TypeParameter Then Return False End If Dim typeParam = DirectCast(type, TypeParameterSymbol) If typeParam.ContainingSymbol.Kind <> SymbolKind.NamedType Then Return False End If Return typeParam.Ordinal = paramPosition End Function Protected Overrides Function MatchTypeToTypeId(type As TypeSymbol, typeId As Integer) As Boolean Return type.SpecialType = typeId End Function End Class Private Class WellKnownMembersSignatureComparer Inherits SpecialMembersSignatureComparer Private ReadOnly _compilation As VisualBasicCompilation Public Sub New(compilation As VisualBasicCompilation) _compilation = compilation End Sub Protected Overrides Function MatchTypeToTypeId(type As TypeSymbol, typeId As Integer) As Boolean Dim wellKnownId = CType(typeId, WellKnownType) If wellKnownId.IsWellKnownType() Then Return type Is _compilation.GetWellKnownType(wellKnownId) End If Return MyBase.MatchTypeToTypeId(type, typeId) End Function End Class Friend Function SynthesizeTupleNamesAttribute(type As TypeSymbol) As SynthesizedAttributeData Debug.Assert(type IsNot Nothing) Debug.Assert(type.ContainsTuple()) Dim stringType = GetSpecialType(SpecialType.System_String) Debug.Assert(stringType IsNot Nothing) Dim names As ImmutableArray(Of TypedConstant) = TupleNamesEncoder.Encode(type, stringType) Debug.Assert(Not names.IsDefault, "should not need the attribute when no tuple names") Dim stringArray = ArrayTypeSymbol.CreateSZArray(stringType, ImmutableArray(Of CustomModifier).Empty, stringType.ContainingAssembly) Dim args = ImmutableArray.Create(New TypedConstant(stringArray, names)) Return TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_TupleElementNamesAttribute__ctorTransformNames, args) End Function Friend Class TupleNamesEncoder Public Shared Function Encode(type As TypeSymbol) As ImmutableArray(Of String) Dim namesBuilder = ArrayBuilder(Of String).GetInstance() If Not TryGetNames(type, namesBuilder) Then namesBuilder.Free() Return Nothing End If Return namesBuilder.ToImmutableAndFree() End Function Public Shared Function Encode(type As TypeSymbol, stringType As TypeSymbol) As ImmutableArray(Of TypedConstant) Dim namesBuilder = ArrayBuilder(Of String).GetInstance() If Not TryGetNames(type, namesBuilder) Then namesBuilder.Free() Return Nothing End If Dim names = namesBuilder.SelectAsArray(Function(name, constantType) Return New TypedConstant(constantType, TypedConstantKind.Primitive, name) End Function, stringType) namesBuilder.Free() Return names End Function Friend Shared Function TryGetNames(type As TypeSymbol, namesBuilder As ArrayBuilder(Of String)) As Boolean type.VisitType(Function(t As TypeSymbol, builder As ArrayBuilder(Of String)) AddNames(t, builder), namesBuilder) Return namesBuilder.Any(Function(name) name IsNot Nothing) End Function Private Shared Function AddNames(type As TypeSymbol, namesBuilder As ArrayBuilder(Of String)) As Boolean If type.IsTupleType Then If type.TupleElementNames.IsDefaultOrEmpty Then ' If none of the tuple elements have names, put ' null placeholders in. namesBuilder.AddMany(Nothing, type.TupleElementTypes.Length) Else namesBuilder.AddRange(type.TupleElementNames) End If End If ' Always recur into nested types Return False End Function End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.RuntimeMembers Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic Partial Public Class VisualBasicCompilation Private ReadOnly _wellKnownMemberSignatureComparer As New WellKnownMembersSignatureComparer(Me) ''' <summary> ''' An array of cached well known types available for use in this Compilation. ''' Lazily filled by GetWellKnownType method. ''' </summary> ''' <remarks></remarks> Private _lazyWellKnownTypes() As NamedTypeSymbol ''' <summary> ''' Lazy cache of well known members. ''' Not yet known value is represented by ErrorTypeSymbol.UnknownResultType ''' </summary> Private _lazyWellKnownTypeMembers() As Symbol Private _lazyExtensionAttributeConstructor As Symbol = ErrorTypeSymbol.UnknownResultType ' Not yet known. Private _lazyExtensionAttributeConstructorErrorInfo As Object 'Actually, DiagnosticInfo #Region "Synthesized Attributes" Friend Function GetExtensionAttributeConstructor(<Out> ByRef useSiteInfo As UseSiteInfo(Of AssemblySymbol)) As MethodSymbol Dim attributeCtor As MethodSymbol = Nothing Dim ctorError As DiagnosticInfo = Nothing If _lazyExtensionAttributeConstructor Is ErrorTypeSymbol.UnknownResultType Then Dim system_Runtime_CompilerServices = Me.GlobalNamespace.LookupNestedNamespace(ImmutableArray.Create(MetadataHelpers.SystemString, "Runtime", "CompilerServices")) Dim attributeType As NamedTypeSymbol = Nothing Dim sourceModuleSymbol = DirectCast(Me.SourceModule, SourceModuleSymbol) Dim sourceModuleBinder As Binder = BinderBuilder.CreateSourceModuleBinder(sourceModuleSymbol) If system_Runtime_CompilerServices IsNot Nothing Then Dim candidates = system_Runtime_CompilerServices.GetTypeMembers(AttributeDescription.CaseInsensitiveExtensionAttribute.Name, 0) Dim ambiguity As Boolean = False For Each candidate As NamedTypeSymbol In candidates If Not sourceModuleBinder.IsAccessible(candidate, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then Continue For End If If candidate.ContainingModule Is sourceModuleSymbol Then ' Type from this module always better. attributeType = candidate ambiguity = False Exit For End If If attributeType Is Nothing Then Debug.Assert(Not ambiguity) attributeType = candidate ElseIf candidate.ContainingAssembly Is Me.Assembly Then If attributeType.ContainingAssembly Is Me.Assembly Then ambiguity = True Else attributeType = candidate ambiguity = False End If ElseIf attributeType.ContainingAssembly IsNot Me.Assembly Then Debug.Assert(candidate.ContainingAssembly IsNot Me.Assembly) ambiguity = True End If Next If ambiguity Then Debug.Assert(attributeType IsNot Nothing) attributeType = Nothing End If End If If attributeType IsNot Nothing AndAlso Not attributeType.IsStructureType AndAlso Not attributeType.IsMustInherit AndAlso GetWellKnownType(WellKnownType.System_Attribute).IsBaseTypeOf(attributeType, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) AndAlso sourceModuleBinder.IsAccessible(attributeType, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then For Each ctor In attributeType.InstanceConstructors If ctor.ParameterCount = 0 Then If sourceModuleBinder.IsAccessible(ctor, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then attributeCtor = ctor End If Exit For End If Next End If If attributeCtor Is Nothing Then ' TODO (tomat): It is not clear under what circumstances is this error reported since the binder already reports errors when the conditions above are not satisfied. ctorError = ErrorFactory.ErrorInfo(ERRID.ERR_MissingRuntimeHelper, AttributeDescription.CaseInsensitiveExtensionAttribute.FullName & "." & WellKnownMemberNames.InstanceConstructorName) Else Dim attributeUsage As AttributeUsageInfo = attributeCtor.ContainingType.GetAttributeUsageInfo() Debug.Assert(Not attributeUsage.IsNull) Const requiredTargets As AttributeTargets = AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method If (attributeUsage.ValidTargets And requiredTargets) <> requiredTargets Then ctorError = ErrorFactory.ErrorInfo(ERRID.ERR_ExtensionAttributeInvalid) End If End If ' Storing m_LazyExtensionAttributeConstructorErrorInfo first. _lazyExtensionAttributeConstructorErrorInfo = ctorError Interlocked.CompareExchange(_lazyExtensionAttributeConstructor, DirectCast(attributeCtor, Symbol), DirectCast(ErrorTypeSymbol.UnknownResultType, Symbol)) End If attributeCtor = DirectCast(_lazyExtensionAttributeConstructor, MethodSymbol) ctorError = DirectCast(Volatile.Read(_lazyExtensionAttributeConstructorErrorInfo), DiagnosticInfo) If ctorError IsNot Nothing Then useSiteInfo = New UseSiteInfo(Of AssemblySymbol)(ctorError) Else useSiteInfo = Binder.GetUseSiteInfoForMemberAndContainingType(attributeCtor) End If Return attributeCtor End Function ''' <summary> ''' Synthesizes a custom attribute. ''' Returns Nothing if the <paramref name="constructor"/> symbol is missing, ''' or any of the members in <paramref name="namedArguments" /> are missing. ''' The attribute is synthesized only if present. ''' </summary> ''' <param name="namedArguments"> ''' Takes a list of pairs of well-known members and constants. The constants ''' will be passed to the field/property referenced by the well-known member. ''' If the well-known member does Not exist in the compilation then no attribute ''' will be synthesized. ''' </param> ''' <param name="isOptionalUse"> ''' Indicates if this particular attribute application should be considered optional. ''' </param> Friend Function TrySynthesizeAttribute( constructor As WellKnownMember, Optional arguments As ImmutableArray(Of TypedConstant) = Nothing, Optional namedArguments As ImmutableArray(Of KeyValuePair(Of WellKnownMember, TypedConstant)) = Nothing, Optional isOptionalUse As Boolean = False ) As SynthesizedAttributeData Dim constructorSymbol = TryCast(GetWellKnownTypeMember(constructor), MethodSymbol) If constructorSymbol Is Nothing OrElse Binder.GetUseSiteInfoForWellKnownTypeMember(constructorSymbol, constructor, False).DiagnosticInfo IsNot Nothing Then Return ReturnNothingOrThrowIfAttributeNonOptional(constructor, isOptionalUse) End If If arguments.IsDefault Then arguments = ImmutableArray(Of TypedConstant).Empty End If Dim namedStringArguments As ImmutableArray(Of KeyValuePair(Of String, TypedConstant)) If namedArguments.IsDefault Then namedStringArguments = ImmutableArray(Of KeyValuePair(Of String, TypedConstant)).Empty Else Dim builder = New ArrayBuilder(Of KeyValuePair(Of String, TypedConstant))(namedArguments.Length) For Each arg In namedArguments Dim wellKnownMember = GetWellKnownTypeMember(arg.Key) If wellKnownMember Is Nothing OrElse TypeOf wellKnownMember Is ErrorTypeSymbol OrElse Binder.GetUseSiteInfoForWellKnownTypeMember(wellKnownMember, arg.Key, False).DiagnosticInfo IsNot Nothing Then Return ReturnNothingOrThrowIfAttributeNonOptional(constructor) Else builder.Add(New KeyValuePair(Of String, TypedConstant)(wellKnownMember.Name, arg.Value)) End If Next namedStringArguments = builder.ToImmutableAndFree() End If Return New SynthesizedAttributeData(constructorSymbol, arguments, namedStringArguments) End Function Private Shared Function ReturnNothingOrThrowIfAttributeNonOptional(constructor As WellKnownMember, Optional isOptionalUse As Boolean = False) As SynthesizedAttributeData If isOptionalUse OrElse WellKnownMembers.IsSynthesizedAttributeOptional(constructor) Then Return Nothing Else Throw ExceptionUtilities.Unreachable End If End Function Friend Function SynthesizeExtensionAttribute() As SynthesizedAttributeData Dim constructor As MethodSymbol = GetExtensionAttributeConstructor(useSiteInfo:=Nothing) Debug.Assert(constructor IsNot Nothing AndAlso constructor.GetUseSiteInfo().DiagnosticInfo Is Nothing AndAlso constructor.ContainingType.GetUseSiteInfo().DiagnosticInfo Is Nothing) Return SynthesizedAttributeData.Create(constructor, WellKnownMember.System_Runtime_CompilerServices_ExtensionAttribute__ctor) End Function Friend Function SynthesizeStateMachineAttribute(method As MethodSymbol, compilationState As ModuleCompilationState) As SynthesizedAttributeData Debug.Assert(method.IsAsync OrElse method.IsIterator) ' The async state machine type is not synthesized until the async method body is rewritten. If we are ' only emitting metadata the method body will not have been rewritten, and the async state machine ' type will not have been created. In this case, omit the attribute. Dim stateMachineType As NamedTypeSymbol = Nothing If compilationState.TryGetStateMachineType(method, stateMachineType) Then Dim ctor = If(method.IsAsync, WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor, WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor) Dim arg = New TypedConstant(GetWellKnownType(WellKnownType.System_Type), TypedConstantKind.Type, If(stateMachineType.IsGenericType, stateMachineType.ConstructUnboundGenericType(), stateMachineType)) Return TrySynthesizeAttribute(ctor, ImmutableArray.Create(arg)) End If Return Nothing End Function Friend Function SynthesizeDecimalConstantAttribute(value As Decimal) As SynthesizedAttributeData Dim isNegative As Boolean Dim scale As Byte Dim low, mid, high As UInteger value.GetBits(isNegative, scale, low, mid, high) Dim specialTypeByte = GetSpecialType(SpecialType.System_Byte) Debug.Assert(specialTypeByte.GetUseSiteInfo().DiagnosticInfo Is Nothing) Dim specialTypeUInt32 = GetSpecialType(SpecialType.System_UInt32) Debug.Assert(specialTypeUInt32.GetUseSiteInfo().DiagnosticInfo Is Nothing) Return TrySynthesizeAttribute( WellKnownMember.System_Runtime_CompilerServices_DecimalConstantAttribute__ctor, ImmutableArray.Create( New TypedConstant(specialTypeByte, TypedConstantKind.Primitive, scale), New TypedConstant(specialTypeByte, TypedConstantKind.Primitive, CByte(If(isNegative, 128, 0))), New TypedConstant(specialTypeUInt32, TypedConstantKind.Primitive, high), New TypedConstant(specialTypeUInt32, TypedConstantKind.Primitive, mid), New TypedConstant(specialTypeUInt32, TypedConstantKind.Primitive, low) )) End Function Friend Function SynthesizeDebuggerBrowsableNeverAttribute() As SynthesizedAttributeData If Options.OptimizationLevel <> OptimizationLevel.Debug Then Return Nothing End If Return TrySynthesizeAttribute( WellKnownMember.System_Diagnostics_DebuggerBrowsableAttribute__ctor, ImmutableArray.Create(New TypedConstant(GetWellKnownType(WellKnownType.System_Diagnostics_DebuggerBrowsableState), TypedConstantKind.Enum, DebuggerBrowsableState.Never))) End Function Friend Function SynthesizeDebuggerHiddenAttribute() As SynthesizedAttributeData If Options.OptimizationLevel <> OptimizationLevel.Debug Then Return Nothing End If Return TrySynthesizeAttribute(WellKnownMember.System_Diagnostics_DebuggerHiddenAttribute__ctor) End Function Friend Function SynthesizeEditorBrowsableNeverAttribute() As SynthesizedAttributeData Return TrySynthesizeAttribute( WellKnownMember.System_ComponentModel_EditorBrowsableAttribute__ctor, ImmutableArray.Create(New TypedConstant(GetWellKnownType(WellKnownType.System_ComponentModel_EditorBrowsableState), TypedConstantKind.Enum, System.ComponentModel.EditorBrowsableState.Never))) End Function Friend Function SynthesizeDebuggerNonUserCodeAttribute() As SynthesizedAttributeData If Options.OptimizationLevel <> OptimizationLevel.Debug Then Return Nothing End If Return TrySynthesizeAttribute(WellKnownMember.System_Diagnostics_DebuggerNonUserCodeAttribute__ctor) End Function Friend Function SynthesizeOptionalDebuggerStepThroughAttribute() As SynthesizedAttributeData If Options.OptimizationLevel <> OptimizationLevel.Debug Then Return Nothing End If Debug.Assert( WellKnownMembers.IsSynthesizedAttributeOptional( WellKnownMember.System_Diagnostics_DebuggerStepThroughAttribute__ctor)) Return TrySynthesizeAttribute(WellKnownMember.System_Diagnostics_DebuggerStepThroughAttribute__ctor) End Function #End Region ''' <summary> ''' Lookup member declaration in well known type used by this Compilation. ''' </summary> Friend Function GetWellKnownTypeMember(member As WellKnownMember) As Symbol Debug.Assert(member >= 0 AndAlso member < WellKnownMember.Count) ' Test hook If a member Is marked missing, Then Return null. If IsMemberMissing(member) Then Return Nothing End If If _lazyWellKnownTypeMembers Is Nothing OrElse _lazyWellKnownTypeMembers(member) Is ErrorTypeSymbol.UnknownResultType Then If (_lazyWellKnownTypeMembers Is Nothing) Then Dim wellKnownTypeMembers = New Symbol(WellKnownMember.Count - 1) {} For i As Integer = 0 To wellKnownTypeMembers.Length - 1 wellKnownTypeMembers(i) = ErrorTypeSymbol.UnknownResultType Next Interlocked.CompareExchange(_lazyWellKnownTypeMembers, wellKnownTypeMembers, Nothing) End If Dim descriptor = WellKnownMembers.GetDescriptor(member) Dim type = If(descriptor.DeclaringTypeId <= SpecialType.Count, GetSpecialType(CType(descriptor.DeclaringTypeId, SpecialType)), GetWellKnownType(CType(descriptor.DeclaringTypeId, WellKnownType))) Dim result As Symbol = Nothing If Not type.IsErrorType() Then result = VisualBasicCompilation.GetRuntimeMember(type, descriptor, _wellKnownMemberSignatureComparer, accessWithinOpt:=Me.Assembly) End If Interlocked.CompareExchange(_lazyWellKnownTypeMembers(member), result, DirectCast(ErrorTypeSymbol.UnknownResultType, Symbol)) End If Return _lazyWellKnownTypeMembers(member) End Function Friend Overrides Function IsSystemTypeReference(type As ITypeSymbolInternal) As Boolean Return TypeSymbol.Equals(DirectCast(type, TypeSymbol), GetWellKnownType(WellKnownType.System_Type), TypeCompareKind.ConsiderEverything) End Function Friend Overrides Function CommonGetWellKnownTypeMember(member As WellKnownMember) As ISymbolInternal Return GetWellKnownTypeMember(member) End Function Friend Overrides Function CommonGetWellKnownType(wellknownType As WellKnownType) As ITypeSymbolInternal Return GetWellKnownType(wellknownType) End Function Friend Overrides Function IsAttributeType(type As ITypeSymbol) As Boolean If type.Kind <> SymbolKind.NamedType Then Return False End If Return DirectCast(type, NamedTypeSymbol).IsOrDerivedFromWellKnownClass(WellKnownType.System_Attribute, Me, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) End Function ''' <summary> ''' In case duplicate types are encountered, returns an error type. ''' But if the IgnoreCorLibraryDuplicatedTypes compilation option is set, any duplicate type found in corlib is ignored and doesn't count as a duplicate. ''' </summary> Friend Function GetWellKnownType(type As WellKnownType) As NamedTypeSymbol Debug.Assert(type.IsWellKnownType()) Dim index As Integer = type - WellKnownType.First If _lazyWellKnownTypes Is Nothing OrElse _lazyWellKnownTypes(index) Is Nothing Then If (_lazyWellKnownTypes Is Nothing) Then Interlocked.CompareExchange(_lazyWellKnownTypes, New NamedTypeSymbol(WellKnownTypes.Count - 1) {}, Nothing) End If Dim mdName As String = WellKnownTypes.GetMetadataName(type) Dim result As NamedTypeSymbol Dim conflicts As (AssemblySymbol, AssemblySymbol) = Nothing If IsTypeMissing(type) Then result = Nothing Else result = Me.Assembly.GetTypeByMetadataName(mdName, includeReferences:=True, isWellKnownType:=True, useCLSCompliantNameArityEncoding:=True, conflicts:=conflicts, ignoreCorLibraryDuplicatedTypes:=Me.Options.IgnoreCorLibraryDuplicatedTypes) End If If result Is Nothing Then Dim emittedName As MetadataTypeName = MetadataTypeName.FromFullName(mdName, useCLSCompliantNameArityEncoding:=True) If type.IsValueTupleType() Then Dim delayedErrorInfo As Func(Of MissingMetadataTypeSymbol.TopLevelWithCustomErrorInfo, DiagnosticInfo) If conflicts.Item1 Is Nothing Then Debug.Assert(conflicts.Item2 Is Nothing) delayedErrorInfo = Function(t) ErrorFactory.ErrorInfo(ERRID.ERR_ValueTupleTypeRefResolutionError1, t) Else Dim capturedConflicts = conflicts delayedErrorInfo = Function(t) ErrorFactory.ErrorInfo(ERRID.ERR_ValueTupleResolutionAmbiguous3, t, capturedConflicts.Item1, capturedConflicts.Item2) End If result = New MissingMetadataTypeSymbol.TopLevelWithCustomErrorInfo(Assembly.Modules(0), emittedName, delayedErrorInfo) Else result = New MissingMetadataTypeSymbol.TopLevel(Assembly.Modules(0), emittedName) End If End If If (Interlocked.CompareExchange(_lazyWellKnownTypes(index), result, Nothing) IsNot Nothing) Then Debug.Assert(result Is _lazyWellKnownTypes(index) OrElse (_lazyWellKnownTypes(index).IsErrorType() AndAlso result.IsErrorType())) End If End If Return _lazyWellKnownTypes(index) End Function Friend Shared Function GetRuntimeMember( ByVal declaringType As NamedTypeSymbol, ByRef descriptor As MemberDescriptor, ByVal comparer As SignatureComparer(Of MethodSymbol, FieldSymbol, PropertySymbol, TypeSymbol, ParameterSymbol), ByVal accessWithinOpt As AssemblySymbol ) As Symbol Dim result As Symbol = Nothing Dim targetSymbolKind As SymbolKind Dim targetMethodKind As MethodKind = MethodKind.Ordinary Dim isShared As Boolean = (descriptor.Flags And MemberFlags.Static) <> 0 Select Case descriptor.Flags And MemberFlags.KindMask Case MemberFlags.Constructor targetSymbolKind = SymbolKind.Method targetMethodKind = MethodKind.Constructor Debug.Assert(Not isShared) 'static constructors are never called explicitly Case MemberFlags.Method targetSymbolKind = SymbolKind.Method Case MemberFlags.PropertyGet targetSymbolKind = SymbolKind.Method targetMethodKind = MethodKind.PropertyGet Case MemberFlags.Field targetSymbolKind = SymbolKind.Field Case MemberFlags.Property targetSymbolKind = SymbolKind.Property Case Else Throw ExceptionUtilities.UnexpectedValue(descriptor.Flags) End Select For Each m In declaringType.GetMembers(descriptor.Name) If m.Kind <> targetSymbolKind OrElse m.IsShared <> isShared OrElse Not (m.DeclaredAccessibility = Accessibility.Public OrElse (accessWithinOpt IsNot Nothing AndAlso Symbol.IsSymbolAccessible(m, accessWithinOpt))) Then Continue For End If If Not String.Equals(m.Name, descriptor.Name, StringComparison.Ordinal) Then Continue For End If Select Case targetSymbolKind Case SymbolKind.Method Dim method = DirectCast(m, MethodSymbol) Dim methodKind = method.MethodKind ' Treat user-defined conversions and operators as ordinary methods for the purpose ' of matching them here. If methodKind = MethodKind.Conversion OrElse methodKind = MethodKind.UserDefinedOperator Then methodKind = MethodKind.Ordinary End If If method.Arity <> descriptor.Arity OrElse methodKind <> targetMethodKind OrElse ((descriptor.Flags And MemberFlags.Virtual) <> 0) <> (method.IsOverridable OrElse method.IsOverrides OrElse method.IsMustOverride) Then Continue For End If If Not comparer.MatchMethodSignature(method, descriptor.Signature) Then Continue For End If Case SymbolKind.Property Dim [property] = DirectCast(m, PropertySymbol) If ((descriptor.Flags And MemberFlags.Virtual) <> 0) <> ([property].IsOverridable OrElse [property].IsOverrides OrElse [property].IsMustOverride) Then Continue For End If If Not comparer.MatchPropertySignature([property], descriptor.Signature) Then Continue For End If Case SymbolKind.Field If Not comparer.MatchFieldSignature(DirectCast(m, FieldSymbol), descriptor.Signature) Then Continue For End If Case Else Throw ExceptionUtilities.UnexpectedValue(targetSymbolKind) End Select If result IsNot Nothing Then ' ambiguity result = Nothing Exit For Else result = m End If Next Return result End Function Friend Class SpecialMembersSignatureComparer Inherits SignatureComparer(Of MethodSymbol, FieldSymbol, PropertySymbol, TypeSymbol, ParameterSymbol) Public Shared ReadOnly Instance As New SpecialMembersSignatureComparer() Protected Sub New() End Sub Protected Overrides Function GetMDArrayElementType(type As TypeSymbol) As TypeSymbol If type.Kind <> SymbolKind.ArrayType Then Return Nothing End If Dim array = DirectCast(type, ArrayTypeSymbol) If array.IsSZArray Then Return Nothing ' This is not a multidimensional array End If Return array.ElementType End Function Protected Overrides Function MatchArrayRank(type As TypeSymbol, countOfDimensions As Integer) As Boolean If countOfDimensions = 1 Then Return Nothing ' This must be a multidimensional array End If If type.Kind <> SymbolKind.ArrayType Then Return Nothing End If Dim array = DirectCast(type, ArrayTypeSymbol) Return array.Rank = countOfDimensions End Function Protected Overrides Function GetSZArrayElementType(type As TypeSymbol) As TypeSymbol If type.Kind <> SymbolKind.ArrayType Then Return Nothing End If Dim array = DirectCast(type, ArrayTypeSymbol) If Not array.IsSZArray Then Return Nothing ' This is a multidimensional array End If Return array.ElementType End Function Protected Overrides Function GetFieldType(field As FieldSymbol) As TypeSymbol Return field.Type End Function Protected Overrides Function GetPropertyType(prop As PropertySymbol) As TypeSymbol Return prop.Type End Function Protected Overrides Function GetGenericTypeArgument(ByVal type As TypeSymbol, ByVal argumentIndex As Integer) As TypeSymbol If type.Kind <> SymbolKind.NamedType Then Return Nothing End If Dim named = DirectCast(type, NamedTypeSymbol) If named.Arity <= argumentIndex Then Return Nothing End If 'We don't support nested types at the moment If named.ContainingType IsNot Nothing Then Return Nothing End If Return named.TypeArgumentsNoUseSiteDiagnostics(argumentIndex) End Function Protected Overrides Function GetGenericTypeDefinition(type As TypeSymbol) As TypeSymbol If type.Kind <> SymbolKind.NamedType Then Return Nothing End If Dim named = DirectCast(type, NamedTypeSymbol) 'We don't support nested types at the moment If named.ContainingType IsNot Nothing Then Return Nothing End If If named.Arity = 0 Then Return Nothing ' Not generic End If Return named.OriginalDefinition End Function Protected Overrides Function GetParameters(ByVal method As MethodSymbol) As ImmutableArray(Of ParameterSymbol) Return method.Parameters End Function Protected Overrides Function GetParameters(ByVal [property] As PropertySymbol) As ImmutableArray(Of ParameterSymbol) Return [property].Parameters End Function Protected Overrides Function GetParamType(ByVal parameter As ParameterSymbol) As TypeSymbol Return parameter.Type End Function Protected Overrides Function GetPointedToType(type As TypeSymbol) As TypeSymbol Return Nothing ' Do not support pointers End Function Protected Overrides Function GetReturnType(method As MethodSymbol) As TypeSymbol Return method.ReturnType End Function Protected Overrides Function IsByRefParam(ByVal parameter As ParameterSymbol) As Boolean Return parameter.IsByRef End Function Protected Overrides Function IsByRefMethod(ByVal method As MethodSymbol) As Boolean Return method.ReturnsByRef End Function Protected Overrides Function IsByRefProperty(ByVal [property] As PropertySymbol) As Boolean Return [property].ReturnsByRef End Function Protected Overrides Function IsGenericMethodTypeParam(type As TypeSymbol, paramPosition As Integer) As Boolean If type.Kind <> SymbolKind.TypeParameter Then Return False End If Dim typeParam = DirectCast(type, TypeParameterSymbol) If typeParam.ContainingSymbol.Kind <> SymbolKind.Method Then Return False End If Return typeParam.Ordinal = paramPosition End Function Protected Overrides Function IsGenericTypeParam(type As TypeSymbol, paramPosition As Integer) As Boolean If type.Kind <> SymbolKind.TypeParameter Then Return False End If Dim typeParam = DirectCast(type, TypeParameterSymbol) If typeParam.ContainingSymbol.Kind <> SymbolKind.NamedType Then Return False End If Return typeParam.Ordinal = paramPosition End Function Protected Overrides Function MatchTypeToTypeId(type As TypeSymbol, typeId As Integer) As Boolean Return type.SpecialType = typeId End Function End Class Private Class WellKnownMembersSignatureComparer Inherits SpecialMembersSignatureComparer Private ReadOnly _compilation As VisualBasicCompilation Public Sub New(compilation As VisualBasicCompilation) _compilation = compilation End Sub Protected Overrides Function MatchTypeToTypeId(type As TypeSymbol, typeId As Integer) As Boolean Dim wellKnownId = CType(typeId, WellKnownType) If wellKnownId.IsWellKnownType() Then Return type Is _compilation.GetWellKnownType(wellKnownId) End If Return MyBase.MatchTypeToTypeId(type, typeId) End Function End Class Friend Function SynthesizeTupleNamesAttribute(type As TypeSymbol) As SynthesizedAttributeData Debug.Assert(type IsNot Nothing) Debug.Assert(type.ContainsTuple()) Dim stringType = GetSpecialType(SpecialType.System_String) Debug.Assert(stringType IsNot Nothing) Dim names As ImmutableArray(Of TypedConstant) = TupleNamesEncoder.Encode(type, stringType) Debug.Assert(Not names.IsDefault, "should not need the attribute when no tuple names") Dim stringArray = ArrayTypeSymbol.CreateSZArray(stringType, ImmutableArray(Of CustomModifier).Empty, stringType.ContainingAssembly) Dim args = ImmutableArray.Create(New TypedConstant(stringArray, names)) Return TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_TupleElementNamesAttribute__ctorTransformNames, args) End Function Friend Class TupleNamesEncoder Public Shared Function Encode(type As TypeSymbol) As ImmutableArray(Of String) Dim namesBuilder = ArrayBuilder(Of String).GetInstance() If Not TryGetNames(type, namesBuilder) Then namesBuilder.Free() Return Nothing End If Return namesBuilder.ToImmutableAndFree() End Function Public Shared Function Encode(type As TypeSymbol, stringType As TypeSymbol) As ImmutableArray(Of TypedConstant) Dim namesBuilder = ArrayBuilder(Of String).GetInstance() If Not TryGetNames(type, namesBuilder) Then namesBuilder.Free() Return Nothing End If Dim names = namesBuilder.SelectAsArray(Function(name, constantType) Return New TypedConstant(constantType, TypedConstantKind.Primitive, name) End Function, stringType) namesBuilder.Free() Return names End Function Friend Shared Function TryGetNames(type As TypeSymbol, namesBuilder As ArrayBuilder(Of String)) As Boolean type.VisitType(Function(t As TypeSymbol, builder As ArrayBuilder(Of String)) AddNames(t, builder), namesBuilder) Return namesBuilder.Any(Function(name) name IsNot Nothing) End Function Private Shared Function AddNames(type As TypeSymbol, namesBuilder As ArrayBuilder(Of String)) As Boolean If type.IsTupleType Then If type.TupleElementNames.IsDefaultOrEmpty Then ' If none of the tuple elements have names, put ' null placeholders in. namesBuilder.AddMany(Nothing, type.TupleElementTypes.Length) Else namesBuilder.AddRange(type.TupleElementNames) End If End If ' Always recur into nested types Return False End Function End Class End Class End Namespace
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./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,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/EditorFeatures/Core/Shared/Options/PerformanceFunctionIdOptionsProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Editor.Shared.Options { [ExportOptionProvider, Shared] internal class PerformanceFunctionIdOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PerformanceFunctionIdOptionsProvider() { } public ImmutableArray<IOption> Options { get { using var resultDisposer = ArrayBuilder<IOption>.GetInstance(out var result); foreach (var id in (FunctionId[])Enum.GetValues(typeof(FunctionId))) { result.Add(FunctionIdOptions.GetOption(id)); } return result.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.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Editor.Shared.Options { [ExportOptionProvider, Shared] internal class PerformanceFunctionIdOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PerformanceFunctionIdOptionsProvider() { } public ImmutableArray<IOption> Options { get { using var resultDisposer = ArrayBuilder<IOption>.GetInstance(out var result); foreach (var id in (FunctionId[])Enum.GetValues(typeof(FunctionId))) { result.Add(FunctionIdOptions.GetOption(id)); } return result.ToImmutable(); } } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioIHostWorkspaceProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.VisualStudio.LanguageServices.Implementation { [Shared] [Export(typeof(IHostWorkspaceProvider))] internal sealed class VisualStudioIHostWorkspaceProvider : IHostWorkspaceProvider { public Workspace Workspace { get; } [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioIHostWorkspaceProvider(VisualStudioWorkspace workspace) { Workspace = workspace; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.VisualStudio.LanguageServices.Implementation { [Shared] [Export(typeof(IHostWorkspaceProvider))] internal sealed class VisualStudioIHostWorkspaceProvider : IHostWorkspaceProvider { public Workspace Workspace { get; } [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioIHostWorkspaceProvider(VisualStudioWorkspace workspace) { Workspace = workspace; } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Features/CSharp/Portable/ReplaceMethodWithProperty/CSharpReplaceMethodWithPropertyService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.ReplaceMethodWithProperty; namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.ReplaceMethodWithProperty { [ExportLanguageService(typeof(IReplaceMethodWithPropertyService), LanguageNames.CSharp), Shared] internal class CSharpReplaceMethodWithPropertyService : AbstractReplaceMethodWithPropertyService<MethodDeclarationSyntax>, IReplaceMethodWithPropertyService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpReplaceMethodWithPropertyService() { } public void RemoveSetMethod(SyntaxEditor editor, SyntaxNode setMethodDeclaration) => editor.RemoveNode(setMethodDeclaration); public void ReplaceGetMethodWithProperty( DocumentOptionSet documentOptions, ParseOptions parseOptions, SyntaxEditor editor, SemanticModel semanticModel, GetAndSetMethods getAndSetMethods, string propertyName, bool nameChanged) { if (!(getAndSetMethods.GetMethodDeclaration is MethodDeclarationSyntax getMethodDeclaration)) { return; } var newProperty = ConvertMethodsToProperty( documentOptions, parseOptions, semanticModel, editor.Generator, getAndSetMethods, propertyName, nameChanged); editor.ReplaceNode(getMethodDeclaration, newProperty); } public static SyntaxNode ConvertMethodsToProperty( DocumentOptionSet documentOptions, ParseOptions parseOptions, SemanticModel semanticModel, SyntaxGenerator generator, GetAndSetMethods getAndSetMethods, string propertyName, bool nameChanged) { var propertyDeclaration = ConvertMethodsToPropertyWorker( documentOptions, parseOptions, semanticModel, generator, getAndSetMethods, propertyName, nameChanged); var expressionBodyPreference = documentOptions.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties).Value; if (expressionBodyPreference != ExpressionBodyPreference.Never) { if (propertyDeclaration.AccessorList?.Accessors.Count == 1 && propertyDeclaration.AccessorList?.Accessors[0].Kind() == SyntaxKind.GetAccessorDeclaration) { var getAccessor = propertyDeclaration.AccessorList.Accessors[0]; if (getAccessor.ExpressionBody != null) { return propertyDeclaration.WithExpressionBody(getAccessor.ExpressionBody) .WithSemicolonToken(getAccessor.SemicolonToken) .WithAccessorList(null); } else if (getAccessor.Body != null && getAccessor.Body.TryConvertToArrowExpressionBody( propertyDeclaration.Kind(), parseOptions, expressionBodyPreference, out var arrowExpression, out var semicolonToken)) { return propertyDeclaration.WithExpressionBody(arrowExpression) .WithSemicolonToken(semicolonToken) .WithAccessorList(null); } } } else { if (propertyDeclaration.ExpressionBody != null && propertyDeclaration.ExpressionBody.TryConvertToBlock( propertyDeclaration.SemicolonToken, createReturnStatementForExpression: true, block: out var block)) { var accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .WithBody(block); var accessorList = SyntaxFactory.AccessorList(SyntaxFactory.SingletonList(accessor)); return propertyDeclaration.WithAccessorList(accessorList) .WithExpressionBody(null) .WithSemicolonToken(default); } } return propertyDeclaration; } public static PropertyDeclarationSyntax ConvertMethodsToPropertyWorker( DocumentOptionSet documentOptions, ParseOptions parseOptions, SemanticModel semanticModel, SyntaxGenerator generator, GetAndSetMethods getAndSetMethods, string propertyName, bool nameChanged) { var getMethodDeclaration = (MethodDeclarationSyntax)getAndSetMethods.GetMethodDeclaration; var setMethodDeclaration = getAndSetMethods.SetMethodDeclaration as MethodDeclarationSyntax; var getAccessor = CreateGetAccessor(getAndSetMethods, documentOptions, parseOptions); var setAccessor = CreateSetAccessor(semanticModel, generator, getAndSetMethods, documentOptions, parseOptions); var nameToken = GetPropertyName(getMethodDeclaration.Identifier, propertyName, nameChanged); var warning = GetWarning(getAndSetMethods); if (warning != null) { nameToken = nameToken.WithAdditionalAnnotations(WarningAnnotation.Create(warning)); } var property = SyntaxFactory.PropertyDeclaration( getMethodDeclaration.AttributeLists, getMethodDeclaration.Modifiers, getMethodDeclaration.ReturnType, getMethodDeclaration.ExplicitInterfaceSpecifier, nameToken, accessorList: null); // copy 'unsafe' from the set method, if it hasn't been already copied from the get method if (setMethodDeclaration?.Modifiers.Any(SyntaxKind.UnsafeKeyword) == true && !property.Modifiers.Any(SyntaxKind.UnsafeKeyword)) { property = property.AddModifiers(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); } property = SetLeadingTrivia( CSharpSyntaxFacts.Instance, getAndSetMethods, property); var accessorList = SyntaxFactory.AccessorList(SyntaxFactory.SingletonList(getAccessor)); if (setAccessor != null) { accessorList = accessorList.AddAccessors(setAccessor); } property = property.WithAccessorList(accessorList); return property.WithAdditionalAnnotations(Formatter.Annotation); } private static SyntaxToken GetPropertyName(SyntaxToken identifier, string propertyName, bool nameChanged) { return nameChanged ? SyntaxFactory.Identifier(propertyName) : identifier; } private static AccessorDeclarationSyntax CreateGetAccessor( GetAndSetMethods getAndSetMethods, DocumentOptionSet documentOptions, ParseOptions parseOptions) { var accessorDeclaration = CreateGetAccessorWorker(getAndSetMethods); return UseExpressionOrBlockBodyIfDesired( documentOptions, parseOptions, accessorDeclaration); } private static AccessorDeclarationSyntax UseExpressionOrBlockBodyIfDesired( DocumentOptionSet documentOptions, ParseOptions parseOptions, AccessorDeclarationSyntax accessorDeclaration) { var expressionBodyPreference = documentOptions.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors).Value; if (accessorDeclaration?.Body != null && expressionBodyPreference != ExpressionBodyPreference.Never) { if (accessorDeclaration.Body.TryConvertToArrowExpressionBody( accessorDeclaration.Kind(), parseOptions, expressionBodyPreference, out var arrowExpression, out var semicolonToken)) { return accessorDeclaration.WithBody(null) .WithExpressionBody(arrowExpression) .WithSemicolonToken(semicolonToken) .WithAdditionalAnnotations(Formatter.Annotation); } } else if (accessorDeclaration?.ExpressionBody != null && expressionBodyPreference == ExpressionBodyPreference.Never) { if (accessorDeclaration.ExpressionBody.TryConvertToBlock( accessorDeclaration.SemicolonToken, createReturnStatementForExpression: accessorDeclaration.Kind() == SyntaxKind.GetAccessorDeclaration, block: out var block)) { return accessorDeclaration.WithExpressionBody(null) .WithSemicolonToken(default) .WithBody(block) .WithAdditionalAnnotations(Formatter.Annotation); } } return accessorDeclaration; } private static AccessorDeclarationSyntax CreateGetAccessorWorker(GetAndSetMethods getAndSetMethods) { var getMethodDeclaration = getAndSetMethods.GetMethodDeclaration as MethodDeclarationSyntax; var accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration); if (getMethodDeclaration.ExpressionBody != null) { return accessor.WithExpressionBody(getMethodDeclaration.ExpressionBody) .WithSemicolonToken(getMethodDeclaration.SemicolonToken); } if (getMethodDeclaration.SemicolonToken.Kind() != SyntaxKind.None) { return accessor.WithSemicolonToken(getMethodDeclaration.SemicolonToken); } if (getMethodDeclaration.Body != null) { return accessor.WithBody(getMethodDeclaration.Body.WithAdditionalAnnotations(Formatter.Annotation)); } return accessor; } private static AccessorDeclarationSyntax CreateSetAccessor( SemanticModel semanticModel, SyntaxGenerator generator, GetAndSetMethods getAndSetMethods, DocumentOptionSet documentOptions, ParseOptions parseOptions) { var accessorDeclaration = CreateSetAccessorWorker(semanticModel, generator, getAndSetMethods); return UseExpressionOrBlockBodyIfDesired(documentOptions, parseOptions, accessorDeclaration); } private static AccessorDeclarationSyntax CreateSetAccessorWorker( SemanticModel semanticModel, SyntaxGenerator generator, GetAndSetMethods getAndSetMethods) { var setMethod = getAndSetMethods.SetMethod; if (!(getAndSetMethods.SetMethodDeclaration is MethodDeclarationSyntax setMethodDeclaration) || setMethod?.Parameters.Length != 1) { return null; } var getMethod = getAndSetMethods.GetMethod; var accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration); if (getMethod.DeclaredAccessibility != setMethod.DeclaredAccessibility) { accessor = (AccessorDeclarationSyntax)generator.WithAccessibility(accessor, setMethod.DeclaredAccessibility); } if (setMethodDeclaration.ExpressionBody != null) { var oldExpressionBody = setMethodDeclaration.ExpressionBody; var expression = ReplaceReferencesToParameterWithValue( semanticModel, setMethod.Parameters[0], oldExpressionBody.Expression); return accessor.WithExpressionBody(oldExpressionBody.WithExpression(expression)) .WithSemicolonToken(setMethodDeclaration.SemicolonToken); } if (setMethodDeclaration.SemicolonToken.Kind() != SyntaxKind.None) { return accessor.WithSemicolonToken(setMethodDeclaration.SemicolonToken); } if (setMethodDeclaration.Body != null) { var body = ReplaceReferencesToParameterWithValue(semanticModel, setMethod.Parameters[0], setMethodDeclaration.Body); return accessor.WithBody(body.WithAdditionalAnnotations(Formatter.Annotation)); } return accessor; } private static TNode ReplaceReferencesToParameterWithValue<TNode>(SemanticModel semanticModel, IParameterSymbol parameter, TNode node) where TNode : SyntaxNode { var rewriter = new Rewriter(semanticModel, parameter); return (TNode)rewriter.Visit(node); } private class Rewriter : CSharpSyntaxRewriter { private readonly SemanticModel _semanticModel; private readonly IParameterSymbol _parameter; public Rewriter(SemanticModel semanticModel, IParameterSymbol parameter) { _semanticModel = semanticModel; _parameter = parameter; } public override SyntaxNode VisitIdentifierName(IdentifierNameSyntax node) { if (_parameter.Equals(_semanticModel.GetSymbolInfo(node).Symbol)) { return SyntaxFactory.IdentifierName("value").WithTriviaFrom(node); } return node; } } // We use the callback form if "ReplaceNode" here because we want to see the // invocation expression after any rewrites we already did when rewriting previous // 'get' references. private static readonly Action<SyntaxEditor, InvocationExpressionSyntax, SimpleNameSyntax, SimpleNameSyntax> s_replaceGetReferenceInvocation = (editor, invocation, nameNode, newName) => editor.ReplaceNode(invocation, (i, g) => { var currentInvocation = (InvocationExpressionSyntax)i; var currentName = currentInvocation.Expression.GetRightmostName(); return currentInvocation.Expression.ReplaceNode(currentName, newName); }); private static readonly Action<SyntaxEditor, InvocationExpressionSyntax, SimpleNameSyntax, SimpleNameSyntax> s_replaceSetReferenceInvocation = (editor, invocation, nameNode, newName) => { if (invocation.ArgumentList?.Arguments.Count != 1 || invocation.ArgumentList.Arguments[0].Expression.Kind() == SyntaxKind.DeclarationExpression) { var annotation = ConflictAnnotation.Create(FeaturesResources.Only_methods_with_a_single_argument_which_is_not_an_out_variable_declaration_can_be_replaced_with_a_property); editor.ReplaceNode(nameNode, newName.WithIdentifier(newName.Identifier.WithAdditionalAnnotations(annotation))); return; } // We use the callback form if "ReplaceNode" here because we want to see the // invocation expression after any rewrites we already did when rewriting the // 'get' references. editor.ReplaceNode(invocation, (i, g) => { var currentInvocation = (InvocationExpressionSyntax)i; // looks like a.b.Goo(arg) => a.b.NewName = arg nameNode = currentInvocation.Expression.GetRightmostName(); currentInvocation = (InvocationExpressionSyntax)g.ReplaceNode(currentInvocation, nameNode, newName); // Wrap the argument in parentheses (in order to not introduce any precedence problems). // But also add a simplification annotation so we can remove the parens if possible. var argumentExpression = currentInvocation.ArgumentList.Arguments[0].Expression.Parenthesize(); var expression = SyntaxFactory.AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, currentInvocation.Expression, argumentExpression); return expression.Parenthesize(); }); }; public void ReplaceGetReference(SyntaxEditor editor, SyntaxToken nameToken, string propertyName, bool nameChanged) => ReplaceInvocation(editor, nameToken, propertyName, nameChanged, s_replaceGetReferenceInvocation); public void ReplaceSetReference(SyntaxEditor editor, SyntaxToken nameToken, string propertyName, bool nameChanged) => ReplaceInvocation(editor, nameToken, propertyName, nameChanged, s_replaceSetReferenceInvocation); public static void ReplaceInvocation(SyntaxEditor editor, SyntaxToken nameToken, string propertyName, bool nameChanged, Action<SyntaxEditor, InvocationExpressionSyntax, SimpleNameSyntax, SimpleNameSyntax> replace) { if (nameToken.Kind() != SyntaxKind.IdentifierToken) { return; } if (!(nameToken.Parent is IdentifierNameSyntax nameNode)) { return; } var invocation = nameNode?.FirstAncestorOrSelf<InvocationExpressionSyntax>(); var newName = nameNode; if (nameChanged) { if (invocation == null) { newName = SyntaxFactory.IdentifierName(SyntaxFactory.Identifier(propertyName) .WithTriviaFrom(nameToken)); } else { newName = SyntaxFactory.IdentifierName(SyntaxFactory.Identifier(propertyName) .WithLeadingTrivia(nameToken.LeadingTrivia) .WithTrailingTrivia(invocation.ArgumentList.CloseParenToken.TrailingTrivia)); } } var invocationExpression = invocation?.Expression; if (!IsInvocationName(nameNode, invocationExpression)) { // Wasn't invoked. Change the name, but report a conflict. var annotation = ConflictAnnotation.Create(FeaturesResources.Non_invoked_method_cannot_be_replaced_with_property); editor.ReplaceNode(nameNode, newName.WithIdentifier(newName.Identifier.WithAdditionalAnnotations(annotation))); return; } // It was invoked. Remove the invocation, and also change the name if necessary. replace(editor, invocation, nameNode, newName); } private static bool IsInvocationName(IdentifierNameSyntax nameNode, ExpressionSyntax invocationExpression) { if (invocationExpression == nameNode) { return true; } if (nameNode.IsAnyMemberAccessExpressionName() && nameNode.Parent == invocationExpression) { 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.Composition; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.ReplaceMethodWithProperty; namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.ReplaceMethodWithProperty { [ExportLanguageService(typeof(IReplaceMethodWithPropertyService), LanguageNames.CSharp), Shared] internal class CSharpReplaceMethodWithPropertyService : AbstractReplaceMethodWithPropertyService<MethodDeclarationSyntax>, IReplaceMethodWithPropertyService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpReplaceMethodWithPropertyService() { } public void RemoveSetMethod(SyntaxEditor editor, SyntaxNode setMethodDeclaration) => editor.RemoveNode(setMethodDeclaration); public void ReplaceGetMethodWithProperty( DocumentOptionSet documentOptions, ParseOptions parseOptions, SyntaxEditor editor, SemanticModel semanticModel, GetAndSetMethods getAndSetMethods, string propertyName, bool nameChanged) { if (!(getAndSetMethods.GetMethodDeclaration is MethodDeclarationSyntax getMethodDeclaration)) { return; } var newProperty = ConvertMethodsToProperty( documentOptions, parseOptions, semanticModel, editor.Generator, getAndSetMethods, propertyName, nameChanged); editor.ReplaceNode(getMethodDeclaration, newProperty); } public static SyntaxNode ConvertMethodsToProperty( DocumentOptionSet documentOptions, ParseOptions parseOptions, SemanticModel semanticModel, SyntaxGenerator generator, GetAndSetMethods getAndSetMethods, string propertyName, bool nameChanged) { var propertyDeclaration = ConvertMethodsToPropertyWorker( documentOptions, parseOptions, semanticModel, generator, getAndSetMethods, propertyName, nameChanged); var expressionBodyPreference = documentOptions.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties).Value; if (expressionBodyPreference != ExpressionBodyPreference.Never) { if (propertyDeclaration.AccessorList?.Accessors.Count == 1 && propertyDeclaration.AccessorList?.Accessors[0].Kind() == SyntaxKind.GetAccessorDeclaration) { var getAccessor = propertyDeclaration.AccessorList.Accessors[0]; if (getAccessor.ExpressionBody != null) { return propertyDeclaration.WithExpressionBody(getAccessor.ExpressionBody) .WithSemicolonToken(getAccessor.SemicolonToken) .WithAccessorList(null); } else if (getAccessor.Body != null && getAccessor.Body.TryConvertToArrowExpressionBody( propertyDeclaration.Kind(), parseOptions, expressionBodyPreference, out var arrowExpression, out var semicolonToken)) { return propertyDeclaration.WithExpressionBody(arrowExpression) .WithSemicolonToken(semicolonToken) .WithAccessorList(null); } } } else { if (propertyDeclaration.ExpressionBody != null && propertyDeclaration.ExpressionBody.TryConvertToBlock( propertyDeclaration.SemicolonToken, createReturnStatementForExpression: true, block: out var block)) { var accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .WithBody(block); var accessorList = SyntaxFactory.AccessorList(SyntaxFactory.SingletonList(accessor)); return propertyDeclaration.WithAccessorList(accessorList) .WithExpressionBody(null) .WithSemicolonToken(default); } } return propertyDeclaration; } public static PropertyDeclarationSyntax ConvertMethodsToPropertyWorker( DocumentOptionSet documentOptions, ParseOptions parseOptions, SemanticModel semanticModel, SyntaxGenerator generator, GetAndSetMethods getAndSetMethods, string propertyName, bool nameChanged) { var getMethodDeclaration = (MethodDeclarationSyntax)getAndSetMethods.GetMethodDeclaration; var setMethodDeclaration = getAndSetMethods.SetMethodDeclaration as MethodDeclarationSyntax; var getAccessor = CreateGetAccessor(getAndSetMethods, documentOptions, parseOptions); var setAccessor = CreateSetAccessor(semanticModel, generator, getAndSetMethods, documentOptions, parseOptions); var nameToken = GetPropertyName(getMethodDeclaration.Identifier, propertyName, nameChanged); var warning = GetWarning(getAndSetMethods); if (warning != null) { nameToken = nameToken.WithAdditionalAnnotations(WarningAnnotation.Create(warning)); } var property = SyntaxFactory.PropertyDeclaration( getMethodDeclaration.AttributeLists, getMethodDeclaration.Modifiers, getMethodDeclaration.ReturnType, getMethodDeclaration.ExplicitInterfaceSpecifier, nameToken, accessorList: null); // copy 'unsafe' from the set method, if it hasn't been already copied from the get method if (setMethodDeclaration?.Modifiers.Any(SyntaxKind.UnsafeKeyword) == true && !property.Modifiers.Any(SyntaxKind.UnsafeKeyword)) { property = property.AddModifiers(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); } property = SetLeadingTrivia( CSharpSyntaxFacts.Instance, getAndSetMethods, property); var accessorList = SyntaxFactory.AccessorList(SyntaxFactory.SingletonList(getAccessor)); if (setAccessor != null) { accessorList = accessorList.AddAccessors(setAccessor); } property = property.WithAccessorList(accessorList); return property.WithAdditionalAnnotations(Formatter.Annotation); } private static SyntaxToken GetPropertyName(SyntaxToken identifier, string propertyName, bool nameChanged) { return nameChanged ? SyntaxFactory.Identifier(propertyName) : identifier; } private static AccessorDeclarationSyntax CreateGetAccessor( GetAndSetMethods getAndSetMethods, DocumentOptionSet documentOptions, ParseOptions parseOptions) { var accessorDeclaration = CreateGetAccessorWorker(getAndSetMethods); return UseExpressionOrBlockBodyIfDesired( documentOptions, parseOptions, accessorDeclaration); } private static AccessorDeclarationSyntax UseExpressionOrBlockBodyIfDesired( DocumentOptionSet documentOptions, ParseOptions parseOptions, AccessorDeclarationSyntax accessorDeclaration) { var expressionBodyPreference = documentOptions.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors).Value; if (accessorDeclaration?.Body != null && expressionBodyPreference != ExpressionBodyPreference.Never) { if (accessorDeclaration.Body.TryConvertToArrowExpressionBody( accessorDeclaration.Kind(), parseOptions, expressionBodyPreference, out var arrowExpression, out var semicolonToken)) { return accessorDeclaration.WithBody(null) .WithExpressionBody(arrowExpression) .WithSemicolonToken(semicolonToken) .WithAdditionalAnnotations(Formatter.Annotation); } } else if (accessorDeclaration?.ExpressionBody != null && expressionBodyPreference == ExpressionBodyPreference.Never) { if (accessorDeclaration.ExpressionBody.TryConvertToBlock( accessorDeclaration.SemicolonToken, createReturnStatementForExpression: accessorDeclaration.Kind() == SyntaxKind.GetAccessorDeclaration, block: out var block)) { return accessorDeclaration.WithExpressionBody(null) .WithSemicolonToken(default) .WithBody(block) .WithAdditionalAnnotations(Formatter.Annotation); } } return accessorDeclaration; } private static AccessorDeclarationSyntax CreateGetAccessorWorker(GetAndSetMethods getAndSetMethods) { var getMethodDeclaration = getAndSetMethods.GetMethodDeclaration as MethodDeclarationSyntax; var accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration); if (getMethodDeclaration.ExpressionBody != null) { return accessor.WithExpressionBody(getMethodDeclaration.ExpressionBody) .WithSemicolonToken(getMethodDeclaration.SemicolonToken); } if (getMethodDeclaration.SemicolonToken.Kind() != SyntaxKind.None) { return accessor.WithSemicolonToken(getMethodDeclaration.SemicolonToken); } if (getMethodDeclaration.Body != null) { return accessor.WithBody(getMethodDeclaration.Body.WithAdditionalAnnotations(Formatter.Annotation)); } return accessor; } private static AccessorDeclarationSyntax CreateSetAccessor( SemanticModel semanticModel, SyntaxGenerator generator, GetAndSetMethods getAndSetMethods, DocumentOptionSet documentOptions, ParseOptions parseOptions) { var accessorDeclaration = CreateSetAccessorWorker(semanticModel, generator, getAndSetMethods); return UseExpressionOrBlockBodyIfDesired(documentOptions, parseOptions, accessorDeclaration); } private static AccessorDeclarationSyntax CreateSetAccessorWorker( SemanticModel semanticModel, SyntaxGenerator generator, GetAndSetMethods getAndSetMethods) { var setMethod = getAndSetMethods.SetMethod; if (!(getAndSetMethods.SetMethodDeclaration is MethodDeclarationSyntax setMethodDeclaration) || setMethod?.Parameters.Length != 1) { return null; } var getMethod = getAndSetMethods.GetMethod; var accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration); if (getMethod.DeclaredAccessibility != setMethod.DeclaredAccessibility) { accessor = (AccessorDeclarationSyntax)generator.WithAccessibility(accessor, setMethod.DeclaredAccessibility); } if (setMethodDeclaration.ExpressionBody != null) { var oldExpressionBody = setMethodDeclaration.ExpressionBody; var expression = ReplaceReferencesToParameterWithValue( semanticModel, setMethod.Parameters[0], oldExpressionBody.Expression); return accessor.WithExpressionBody(oldExpressionBody.WithExpression(expression)) .WithSemicolonToken(setMethodDeclaration.SemicolonToken); } if (setMethodDeclaration.SemicolonToken.Kind() != SyntaxKind.None) { return accessor.WithSemicolonToken(setMethodDeclaration.SemicolonToken); } if (setMethodDeclaration.Body != null) { var body = ReplaceReferencesToParameterWithValue(semanticModel, setMethod.Parameters[0], setMethodDeclaration.Body); return accessor.WithBody(body.WithAdditionalAnnotations(Formatter.Annotation)); } return accessor; } private static TNode ReplaceReferencesToParameterWithValue<TNode>(SemanticModel semanticModel, IParameterSymbol parameter, TNode node) where TNode : SyntaxNode { var rewriter = new Rewriter(semanticModel, parameter); return (TNode)rewriter.Visit(node); } private class Rewriter : CSharpSyntaxRewriter { private readonly SemanticModel _semanticModel; private readonly IParameterSymbol _parameter; public Rewriter(SemanticModel semanticModel, IParameterSymbol parameter) { _semanticModel = semanticModel; _parameter = parameter; } public override SyntaxNode VisitIdentifierName(IdentifierNameSyntax node) { if (_parameter.Equals(_semanticModel.GetSymbolInfo(node).Symbol)) { return SyntaxFactory.IdentifierName("value").WithTriviaFrom(node); } return node; } } // We use the callback form if "ReplaceNode" here because we want to see the // invocation expression after any rewrites we already did when rewriting previous // 'get' references. private static readonly Action<SyntaxEditor, InvocationExpressionSyntax, SimpleNameSyntax, SimpleNameSyntax> s_replaceGetReferenceInvocation = (editor, invocation, nameNode, newName) => editor.ReplaceNode(invocation, (i, g) => { var currentInvocation = (InvocationExpressionSyntax)i; var currentName = currentInvocation.Expression.GetRightmostName(); return currentInvocation.Expression.ReplaceNode(currentName, newName); }); private static readonly Action<SyntaxEditor, InvocationExpressionSyntax, SimpleNameSyntax, SimpleNameSyntax> s_replaceSetReferenceInvocation = (editor, invocation, nameNode, newName) => { if (invocation.ArgumentList?.Arguments.Count != 1 || invocation.ArgumentList.Arguments[0].Expression.Kind() == SyntaxKind.DeclarationExpression) { var annotation = ConflictAnnotation.Create(FeaturesResources.Only_methods_with_a_single_argument_which_is_not_an_out_variable_declaration_can_be_replaced_with_a_property); editor.ReplaceNode(nameNode, newName.WithIdentifier(newName.Identifier.WithAdditionalAnnotations(annotation))); return; } // We use the callback form if "ReplaceNode" here because we want to see the // invocation expression after any rewrites we already did when rewriting the // 'get' references. editor.ReplaceNode(invocation, (i, g) => { var currentInvocation = (InvocationExpressionSyntax)i; // looks like a.b.Goo(arg) => a.b.NewName = arg nameNode = currentInvocation.Expression.GetRightmostName(); currentInvocation = (InvocationExpressionSyntax)g.ReplaceNode(currentInvocation, nameNode, newName); // Wrap the argument in parentheses (in order to not introduce any precedence problems). // But also add a simplification annotation so we can remove the parens if possible. var argumentExpression = currentInvocation.ArgumentList.Arguments[0].Expression.Parenthesize(); var expression = SyntaxFactory.AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, currentInvocation.Expression, argumentExpression); return expression.Parenthesize(); }); }; public void ReplaceGetReference(SyntaxEditor editor, SyntaxToken nameToken, string propertyName, bool nameChanged) => ReplaceInvocation(editor, nameToken, propertyName, nameChanged, s_replaceGetReferenceInvocation); public void ReplaceSetReference(SyntaxEditor editor, SyntaxToken nameToken, string propertyName, bool nameChanged) => ReplaceInvocation(editor, nameToken, propertyName, nameChanged, s_replaceSetReferenceInvocation); public static void ReplaceInvocation(SyntaxEditor editor, SyntaxToken nameToken, string propertyName, bool nameChanged, Action<SyntaxEditor, InvocationExpressionSyntax, SimpleNameSyntax, SimpleNameSyntax> replace) { if (nameToken.Kind() != SyntaxKind.IdentifierToken) { return; } if (!(nameToken.Parent is IdentifierNameSyntax nameNode)) { return; } var invocation = nameNode?.FirstAncestorOrSelf<InvocationExpressionSyntax>(); var newName = nameNode; if (nameChanged) { if (invocation == null) { newName = SyntaxFactory.IdentifierName(SyntaxFactory.Identifier(propertyName) .WithTriviaFrom(nameToken)); } else { newName = SyntaxFactory.IdentifierName(SyntaxFactory.Identifier(propertyName) .WithLeadingTrivia(nameToken.LeadingTrivia) .WithTrailingTrivia(invocation.ArgumentList.CloseParenToken.TrailingTrivia)); } } var invocationExpression = invocation?.Expression; if (!IsInvocationName(nameNode, invocationExpression)) { // Wasn't invoked. Change the name, but report a conflict. var annotation = ConflictAnnotation.Create(FeaturesResources.Non_invoked_method_cannot_be_replaced_with_property); editor.ReplaceNode(nameNode, newName.WithIdentifier(newName.Identifier.WithAdditionalAnnotations(annotation))); return; } // It was invoked. Remove the invocation, and also change the name if necessary. replace(editor, invocation, nameNode, newName); } private static bool IsInvocationName(IdentifierNameSyntax nameNode, ExpressionSyntax invocationExpression) { if (invocationExpression == nameNode) { return true; } if (nameNode.IsAnyMemberAccessExpressionName() && nameNode.Parent == invocationExpression) { return true; } return false; } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/VisualStudio/Core/Impl/Options/AbstractAutomationObject.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Options; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { public abstract class AbstractAutomationObject { private readonly Workspace _workspace; private readonly string _languageName; protected AbstractAutomationObject(Workspace workspace, string languageName) => (_workspace, _languageName) = (workspace, languageName); private protected T GetOption<T>(PerLanguageOption2<T> key) => _workspace.Options.GetOption(key, _languageName); private protected void SetOption<T>(PerLanguageOption2<T> key, T value) => _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options .WithChangedOption(key, _languageName, value))); private protected T GetOption<T>(Option2<T> key) => _workspace.Options.GetOption(key); private protected void SetOption<T>(Option2<T> key, T value) => _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options .WithChangedOption(key, value))); private protected int GetBooleanOption(PerLanguageOption2<bool?> key) => NullableBooleanToInteger(GetOption(key)); private protected void SetBooleanOption(PerLanguageOption2<bool?> key, int value) => SetOption(key, IntegerToNullableBoolean(value)); private protected int GetBooleanOption(Option2<bool?> key) => NullableBooleanToInteger(GetOption(key)); private protected void SetBooleanOption(Option2<bool?> key, int value) => SetOption(key, IntegerToNullableBoolean(value)); private protected string GetXmlOption<T>(Option2<CodeStyleOption2<T>> option) => GetOption(option).ToXElement().ToString(); private protected string GetXmlOption<T>(PerLanguageOption2<CodeStyleOption2<T>> option) => GetOption(option).ToXElement().ToString(); private protected void SetXmlOption<T>(Option2<CodeStyleOption2<T>> option, string value) { var convertedValue = CodeStyleOption2<T>.FromXElement(XElement.Parse(value)); SetOption(option, convertedValue); } private protected void SetXmlOption<T>(PerLanguageOption2<CodeStyleOption2<T>> option, string value) { var convertedValue = CodeStyleOption2<T>.FromXElement(XElement.Parse(value)); SetOption(option, convertedValue); } private static int NullableBooleanToInteger(bool? value) { if (!value.HasValue) { return -1; } return value.Value ? 1 : 0; } private static bool? IntegerToNullableBoolean(int value) => (value < 0) ? null : (value > 0); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Options; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { public abstract class AbstractAutomationObject { private readonly Workspace _workspace; private readonly string _languageName; protected AbstractAutomationObject(Workspace workspace, string languageName) => (_workspace, _languageName) = (workspace, languageName); private protected T GetOption<T>(PerLanguageOption2<T> key) => _workspace.Options.GetOption(key, _languageName); private protected void SetOption<T>(PerLanguageOption2<T> key, T value) => _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options .WithChangedOption(key, _languageName, value))); private protected T GetOption<T>(Option2<T> key) => _workspace.Options.GetOption(key); private protected void SetOption<T>(Option2<T> key, T value) => _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options .WithChangedOption(key, value))); private protected int GetBooleanOption(PerLanguageOption2<bool?> key) => NullableBooleanToInteger(GetOption(key)); private protected void SetBooleanOption(PerLanguageOption2<bool?> key, int value) => SetOption(key, IntegerToNullableBoolean(value)); private protected int GetBooleanOption(Option2<bool?> key) => NullableBooleanToInteger(GetOption(key)); private protected void SetBooleanOption(Option2<bool?> key, int value) => SetOption(key, IntegerToNullableBoolean(value)); private protected string GetXmlOption<T>(Option2<CodeStyleOption2<T>> option) => GetOption(option).ToXElement().ToString(); private protected string GetXmlOption<T>(PerLanguageOption2<CodeStyleOption2<T>> option) => GetOption(option).ToXElement().ToString(); private protected void SetXmlOption<T>(Option2<CodeStyleOption2<T>> option, string value) { var convertedValue = CodeStyleOption2<T>.FromXElement(XElement.Parse(value)); SetOption(option, convertedValue); } private protected void SetXmlOption<T>(PerLanguageOption2<CodeStyleOption2<T>> option, string value) { var convertedValue = CodeStyleOption2<T>.FromXElement(XElement.Parse(value)); SetOption(option, convertedValue); } private static int NullableBooleanToInteger(bool? value) { if (!value.HasValue) { return -1; } return value.Value ? 1 : 0; } private static bool? IntegerToNullableBoolean(int value) => (value < 0) ? null : (value > 0); } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/EditorFeatures/Core.Wpf/Adornments/AbstractAdornmentManager.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Threading; using System.Windows.Threading; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Adornments { /// <summary> /// UI manager for graphic overlay tags. These tags will simply paint something related to the text. /// </summary> internal abstract class AbstractAdornmentManager<T> where T : GraphicsTag { private readonly object _invalidatedSpansLock = new(); private readonly IThreadingContext _threadingContext; /// <summary>Notification system about operations we do</summary> private readonly IAsynchronousOperationListener _asyncListener; /// <summary>Spans that are invalidated, and need to be removed from the layer..</summary> private List<IMappingSpan> _invalidatedSpans; /// <summary>View that created us.</summary> protected readonly IWpfTextView TextView; /// <summary>Layer where we draw adornments.</summary> protected readonly IAdornmentLayer AdornmentLayer; /// <summary>Aggregator that tells us where to draw.</summary> protected readonly ITagAggregator<T> TagAggregator; /// <summary> /// MUST BE CALLED ON UI THREAD!!!! This method touches WPF. /// /// This is where we apply visuals to the text. /// /// It happens when another region of the view becomes visible or there is a change in tags. /// For us the end result is the same - get tags from tagger and update visuals correspondingly. /// </summary> protected abstract void AddAdornmentsToAdornmentLayer_CallOnlyOnUIThread(NormalizedSnapshotSpanCollection changedSpanCollection); internal AbstractAdornmentManager( IThreadingContext threadingContext, IWpfTextView textView, IViewTagAggregatorFactoryService tagAggregatorFactoryService, IAsynchronousOperationListener asyncListener, string adornmentLayerName) { Contract.ThrowIfNull(threadingContext); Contract.ThrowIfNull(textView); Contract.ThrowIfNull(tagAggregatorFactoryService); Contract.ThrowIfNull(adornmentLayerName); Contract.ThrowIfNull(asyncListener); _threadingContext = threadingContext; TextView = textView; AdornmentLayer = textView.GetAdornmentLayer(adornmentLayerName); textView.LayoutChanged += OnLayoutChanged; _asyncListener = asyncListener; // If we are not on the UI thread, we are at race with Close, but we should be on UI thread Contract.ThrowIfFalse(textView.VisualElement.Dispatcher.CheckAccess()); textView.Closed += OnTextViewClosed; TagAggregator = tagAggregatorFactoryService.CreateTagAggregator<T>(textView); TagAggregator.TagsChanged += OnTagsChanged; } private void OnTextViewClosed(object sender, System.EventArgs e) { // release the aggregator TagAggregator.TagsChanged -= OnTagsChanged; TagAggregator.Dispose(); // unhook from view TextView.Closed -= OnTextViewClosed; TextView.LayoutChanged -= OnLayoutChanged; // At this point, this object should be available for garbage collection. } /// <summary> /// This handler gets called whenever there is a visual change in the view. /// Example: edit or a scroll. /// </summary> private void OnLayoutChanged(object sender, TextViewLayoutChangedEventArgs e) { using (Logger.LogBlock(FunctionId.Tagger_AdornmentManager_OnLayoutChanged, CancellationToken.None)) using (_asyncListener.BeginAsyncOperation(GetType() + ".OnLayoutChanged")) { // Make sure we're on the UI thread. Contract.ThrowIfFalse(TextView.VisualElement.Dispatcher.CheckAccess()); var reformattedSpans = e.NewOrReformattedSpans; var viewSnapshot = TextView.TextSnapshot; // No need to remove tags as these spans are reformatted anyways. UpdateSpans_CallOnlyOnUIThread(reformattedSpans, removeOldTags: false); // Compute any spans that had been invalidated but were not affected by layout. List<IMappingSpan> invalidated; lock (_invalidatedSpansLock) { invalidated = _invalidatedSpans; _invalidatedSpans = null; } if (invalidated != null) { var invalidatedAndNormalized = TranslateAndNormalize(invalidated, viewSnapshot); var invalidatedButNotReformatted = NormalizedSnapshotSpanCollection.Difference( invalidatedAndNormalized, e.NewOrReformattedSpans); UpdateSpans_CallOnlyOnUIThread(invalidatedButNotReformatted, removeOldTags: true); } } } private static NormalizedSnapshotSpanCollection TranslateAndNormalize( IEnumerable<IMappingSpan> spans, ITextSnapshot targetSnapshot) { Contract.ThrowIfNull(spans); var translated = spans.SelectMany(span => span.GetSpans(targetSnapshot)); return new NormalizedSnapshotSpanCollection(translated); } /// <summary> /// This handler is called when tag aggregator notifies us about tag changes. /// </summary> private void OnTagsChanged(object sender, TagsChangedEventArgs e) { using (_asyncListener.BeginAsyncOperation(GetType().Name + ".OnTagsChanged.1")) { var changedSpan = e.Span; if (changedSpan == null) { return; // nothing changed } var needToScheduleUpdate = false; lock (_invalidatedSpansLock) { if (_invalidatedSpans == null) { // set invalidated spans _invalidatedSpans = new List<IMappingSpan> { changedSpan }; needToScheduleUpdate = true; } else { // add to existing invalidated spans _invalidatedSpans.Add(changedSpan); } } if (needToScheduleUpdate) { // schedule an update _threadingContext.JoinableTaskFactory.WithPriority(TextView.VisualElement.Dispatcher, DispatcherPriority.Render).RunAsync(async () => { using (_asyncListener.BeginAsyncOperation(GetType() + ".OnTagsChanged.2")) { await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true); UpdateInvalidSpans(); } }); } } } /// <summary> /// MUST BE CALLED ON UI THREAD!!!! This method touches WPF. /// /// This function is used to update invalidates spans. /// </summary> protected void UpdateInvalidSpans() { using (_asyncListener.BeginAsyncOperation(GetType().Name + ".UpdateInvalidSpans.1")) using (Logger.LogBlock(FunctionId.Tagger_AdornmentManager_UpdateInvalidSpans, CancellationToken.None)) { // this method should only run on UI thread as we do WPF here. Contract.ThrowIfFalse(TextView.VisualElement.Dispatcher.CheckAccess()); List<IMappingSpan> invalidated; lock (_invalidatedSpansLock) { invalidated = _invalidatedSpans; _invalidatedSpans = null; } if (TextView.IsClosed) { return; // already closed } if (invalidated != null) { var viewSnapshot = TextView.TextSnapshot; var invalidatedNormalized = TranslateAndNormalize(invalidated, viewSnapshot); UpdateSpans_CallOnlyOnUIThread(invalidatedNormalized, removeOldTags: true); } } } protected void UpdateSpans_CallOnlyOnUIThread(NormalizedSnapshotSpanCollection changedSpanCollection, bool removeOldTags) { Contract.ThrowIfNull(changedSpanCollection); // this method should only run on UI thread as we do WPF here. Contract.ThrowIfFalse(TextView.VisualElement.Dispatcher.CheckAccess()); var viewLines = TextView.TextViewLines; if (viewLines == null || viewLines.Count == 0) { return; // nothing to draw on } // removing is a separate pass from adding so that new stuff is not removed. if (removeOldTags) { foreach (var changedSpan in changedSpanCollection) { // is there any effect on the view? if (viewLines.IntersectsBufferSpan(changedSpan)) { AdornmentLayer.RemoveAdornmentsByVisualSpan(changedSpan); } } } AddAdornmentsToAdornmentLayer_CallOnlyOnUIThread(changedSpanCollection); } protected bool ShouldDrawTag(SnapshotSpan snapshotSpan, IMappingTagSpan<GraphicsTag> mappingTagSpan) { var mappedPoint = GetMappedPoint(snapshotSpan, mappingTagSpan); if (mappedPoint is null) { return false; } if (!TryMapToSingleSnapshotSpan(mappingTagSpan.Span, TextView.TextSnapshot, out var span)) { return false; } if (!TextView.TextViewLines.IntersectsBufferSpan(span)) { return false; } return true; } protected SnapshotPoint? GetMappedPoint(SnapshotSpan snapshotSpan, IMappingTagSpan<GraphicsTag> mappingTagSpan) { var point = mappingTagSpan.Span.Start.GetPoint(snapshotSpan.Snapshot, PositionAffinity.Predecessor); if (point == null) { return null; } var mappedPoint = TextView.BufferGraph.MapUpToSnapshot( point.Value, PointTrackingMode.Negative, PositionAffinity.Predecessor, TextView.VisualSnapshot); if (mappedPoint == null) { return null; } return mappedPoint; } // Map the mapping span to the visual snapshot. note that as a result of projection // topology, originally single span may be mapped into several spans. Visual adornments do // not make much sense on disjoint spans. We will not decorate spans that could not make it // in one piece. protected static bool TryMapToSingleSnapshotSpan(IMappingSpan mappingSpan, ITextSnapshot viewSnapshot, out SnapshotSpan span) { // IMappingSpan.GetSpans is a surprisingly expensive function that allocates multiple // lists and collection if the view buffer is same as anchor we could just map the // anchor to the viewSnapshot however, since the _anchor is not available, we have to // map start and end TODO: verify that affinity is correct. If it does not matter we // should use the cheapest. if (viewSnapshot != null && mappingSpan.AnchorBuffer == viewSnapshot.TextBuffer) { var mappedStart = mappingSpan.Start.GetPoint(viewSnapshot, PositionAffinity.Predecessor).Value; var mappedEnd = mappingSpan.End.GetPoint(viewSnapshot, PositionAffinity.Successor).Value; span = new SnapshotSpan(mappedStart, mappedEnd); return true; } // TODO: actually adornments do not make much sense on "cropped" spans either - Consider line separator on "nd Su" // is it possible to cheaply detect cropping? var spans = mappingSpan.GetSpans(viewSnapshot); if (spans.Count != 1) { span = default; return false; // span is unmapped or disjoint. } span = spans[0]; return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Threading; using System.Windows.Threading; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Adornments { /// <summary> /// UI manager for graphic overlay tags. These tags will simply paint something related to the text. /// </summary> internal abstract class AbstractAdornmentManager<T> where T : GraphicsTag { private readonly object _invalidatedSpansLock = new(); private readonly IThreadingContext _threadingContext; /// <summary>Notification system about operations we do</summary> private readonly IAsynchronousOperationListener _asyncListener; /// <summary>Spans that are invalidated, and need to be removed from the layer..</summary> private List<IMappingSpan> _invalidatedSpans; /// <summary>View that created us.</summary> protected readonly IWpfTextView TextView; /// <summary>Layer where we draw adornments.</summary> protected readonly IAdornmentLayer AdornmentLayer; /// <summary>Aggregator that tells us where to draw.</summary> protected readonly ITagAggregator<T> TagAggregator; /// <summary> /// MUST BE CALLED ON UI THREAD!!!! This method touches WPF. /// /// This is where we apply visuals to the text. /// /// It happens when another region of the view becomes visible or there is a change in tags. /// For us the end result is the same - get tags from tagger and update visuals correspondingly. /// </summary> protected abstract void AddAdornmentsToAdornmentLayer_CallOnlyOnUIThread(NormalizedSnapshotSpanCollection changedSpanCollection); internal AbstractAdornmentManager( IThreadingContext threadingContext, IWpfTextView textView, IViewTagAggregatorFactoryService tagAggregatorFactoryService, IAsynchronousOperationListener asyncListener, string adornmentLayerName) { Contract.ThrowIfNull(threadingContext); Contract.ThrowIfNull(textView); Contract.ThrowIfNull(tagAggregatorFactoryService); Contract.ThrowIfNull(adornmentLayerName); Contract.ThrowIfNull(asyncListener); _threadingContext = threadingContext; TextView = textView; AdornmentLayer = textView.GetAdornmentLayer(adornmentLayerName); textView.LayoutChanged += OnLayoutChanged; _asyncListener = asyncListener; // If we are not on the UI thread, we are at race with Close, but we should be on UI thread Contract.ThrowIfFalse(textView.VisualElement.Dispatcher.CheckAccess()); textView.Closed += OnTextViewClosed; TagAggregator = tagAggregatorFactoryService.CreateTagAggregator<T>(textView); TagAggregator.TagsChanged += OnTagsChanged; } private void OnTextViewClosed(object sender, System.EventArgs e) { // release the aggregator TagAggregator.TagsChanged -= OnTagsChanged; TagAggregator.Dispose(); // unhook from view TextView.Closed -= OnTextViewClosed; TextView.LayoutChanged -= OnLayoutChanged; // At this point, this object should be available for garbage collection. } /// <summary> /// This handler gets called whenever there is a visual change in the view. /// Example: edit or a scroll. /// </summary> private void OnLayoutChanged(object sender, TextViewLayoutChangedEventArgs e) { using (Logger.LogBlock(FunctionId.Tagger_AdornmentManager_OnLayoutChanged, CancellationToken.None)) using (_asyncListener.BeginAsyncOperation(GetType() + ".OnLayoutChanged")) { // Make sure we're on the UI thread. Contract.ThrowIfFalse(TextView.VisualElement.Dispatcher.CheckAccess()); var reformattedSpans = e.NewOrReformattedSpans; var viewSnapshot = TextView.TextSnapshot; // No need to remove tags as these spans are reformatted anyways. UpdateSpans_CallOnlyOnUIThread(reformattedSpans, removeOldTags: false); // Compute any spans that had been invalidated but were not affected by layout. List<IMappingSpan> invalidated; lock (_invalidatedSpansLock) { invalidated = _invalidatedSpans; _invalidatedSpans = null; } if (invalidated != null) { var invalidatedAndNormalized = TranslateAndNormalize(invalidated, viewSnapshot); var invalidatedButNotReformatted = NormalizedSnapshotSpanCollection.Difference( invalidatedAndNormalized, e.NewOrReformattedSpans); UpdateSpans_CallOnlyOnUIThread(invalidatedButNotReformatted, removeOldTags: true); } } } private static NormalizedSnapshotSpanCollection TranslateAndNormalize( IEnumerable<IMappingSpan> spans, ITextSnapshot targetSnapshot) { Contract.ThrowIfNull(spans); var translated = spans.SelectMany(span => span.GetSpans(targetSnapshot)); return new NormalizedSnapshotSpanCollection(translated); } /// <summary> /// This handler is called when tag aggregator notifies us about tag changes. /// </summary> private void OnTagsChanged(object sender, TagsChangedEventArgs e) { using (_asyncListener.BeginAsyncOperation(GetType().Name + ".OnTagsChanged.1")) { var changedSpan = e.Span; if (changedSpan == null) { return; // nothing changed } var needToScheduleUpdate = false; lock (_invalidatedSpansLock) { if (_invalidatedSpans == null) { // set invalidated spans _invalidatedSpans = new List<IMappingSpan> { changedSpan }; needToScheduleUpdate = true; } else { // add to existing invalidated spans _invalidatedSpans.Add(changedSpan); } } if (needToScheduleUpdate) { // schedule an update _threadingContext.JoinableTaskFactory.WithPriority(TextView.VisualElement.Dispatcher, DispatcherPriority.Render).RunAsync(async () => { using (_asyncListener.BeginAsyncOperation(GetType() + ".OnTagsChanged.2")) { await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true); UpdateInvalidSpans(); } }); } } } /// <summary> /// MUST BE CALLED ON UI THREAD!!!! This method touches WPF. /// /// This function is used to update invalidates spans. /// </summary> protected void UpdateInvalidSpans() { using (_asyncListener.BeginAsyncOperation(GetType().Name + ".UpdateInvalidSpans.1")) using (Logger.LogBlock(FunctionId.Tagger_AdornmentManager_UpdateInvalidSpans, CancellationToken.None)) { // this method should only run on UI thread as we do WPF here. Contract.ThrowIfFalse(TextView.VisualElement.Dispatcher.CheckAccess()); List<IMappingSpan> invalidated; lock (_invalidatedSpansLock) { invalidated = _invalidatedSpans; _invalidatedSpans = null; } if (TextView.IsClosed) { return; // already closed } if (invalidated != null) { var viewSnapshot = TextView.TextSnapshot; var invalidatedNormalized = TranslateAndNormalize(invalidated, viewSnapshot); UpdateSpans_CallOnlyOnUIThread(invalidatedNormalized, removeOldTags: true); } } } protected void UpdateSpans_CallOnlyOnUIThread(NormalizedSnapshotSpanCollection changedSpanCollection, bool removeOldTags) { Contract.ThrowIfNull(changedSpanCollection); // this method should only run on UI thread as we do WPF here. Contract.ThrowIfFalse(TextView.VisualElement.Dispatcher.CheckAccess()); var viewLines = TextView.TextViewLines; if (viewLines == null || viewLines.Count == 0) { return; // nothing to draw on } // removing is a separate pass from adding so that new stuff is not removed. if (removeOldTags) { foreach (var changedSpan in changedSpanCollection) { // is there any effect on the view? if (viewLines.IntersectsBufferSpan(changedSpan)) { AdornmentLayer.RemoveAdornmentsByVisualSpan(changedSpan); } } } AddAdornmentsToAdornmentLayer_CallOnlyOnUIThread(changedSpanCollection); } protected bool ShouldDrawTag(SnapshotSpan snapshotSpan, IMappingTagSpan<GraphicsTag> mappingTagSpan) { var mappedPoint = GetMappedPoint(snapshotSpan, mappingTagSpan); if (mappedPoint is null) { return false; } if (!TryMapToSingleSnapshotSpan(mappingTagSpan.Span, TextView.TextSnapshot, out var span)) { return false; } if (!TextView.TextViewLines.IntersectsBufferSpan(span)) { return false; } return true; } protected SnapshotPoint? GetMappedPoint(SnapshotSpan snapshotSpan, IMappingTagSpan<GraphicsTag> mappingTagSpan) { var point = mappingTagSpan.Span.Start.GetPoint(snapshotSpan.Snapshot, PositionAffinity.Predecessor); if (point == null) { return null; } var mappedPoint = TextView.BufferGraph.MapUpToSnapshot( point.Value, PointTrackingMode.Negative, PositionAffinity.Predecessor, TextView.VisualSnapshot); if (mappedPoint == null) { return null; } return mappedPoint; } // Map the mapping span to the visual snapshot. note that as a result of projection // topology, originally single span may be mapped into several spans. Visual adornments do // not make much sense on disjoint spans. We will not decorate spans that could not make it // in one piece. protected static bool TryMapToSingleSnapshotSpan(IMappingSpan mappingSpan, ITextSnapshot viewSnapshot, out SnapshotSpan span) { // IMappingSpan.GetSpans is a surprisingly expensive function that allocates multiple // lists and collection if the view buffer is same as anchor we could just map the // anchor to the viewSnapshot however, since the _anchor is not available, we have to // map start and end TODO: verify that affinity is correct. If it does not matter we // should use the cheapest. if (viewSnapshot != null && mappingSpan.AnchorBuffer == viewSnapshot.TextBuffer) { var mappedStart = mappingSpan.Start.GetPoint(viewSnapshot, PositionAffinity.Predecessor).Value; var mappedEnd = mappingSpan.End.GetPoint(viewSnapshot, PositionAffinity.Successor).Value; span = new SnapshotSpan(mappedStart, mappedEnd); return true; } // TODO: actually adornments do not make much sense on "cropped" spans either - Consider line separator on "nd Su" // is it possible to cheaply detect cropping? var spans = mappingSpan.GetSpans(viewSnapshot); if (spans.Count != 1) { span = default; return false; // span is unmapped or disjoint. } span = spans[0]; return true; } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Features/LanguageServer/Protocol/ILspLogger.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.LanguageServer { internal interface ILspLogger { void TraceInformation(string message); void TraceWarning(string message); void TraceException(Exception exception); void TraceStart(string message); void TraceStop(string message); } internal class NoOpLspLogger : ILspLogger { public static readonly ILspLogger Instance = new NoOpLspLogger(); private NoOpLspLogger() { } public void TraceException(Exception exception) { } public void TraceInformation(string message) { } public void TraceWarning(string message) { } public void TraceStart(string message) { } public void TraceStop(string message) { } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.LanguageServer { internal interface ILspLogger { void TraceInformation(string message); void TraceWarning(string message); void TraceException(Exception exception); void TraceStart(string message); void TraceStop(string message); } internal class NoOpLspLogger : ILspLogger { public static readonly ILspLogger Instance = new NoOpLspLogger(); private NoOpLspLogger() { } public void TraceException(Exception exception) { } public void TraceInformation(string message) { } public void TraceWarning(string message) { } public void TraceStart(string message) { } public void TraceStop(string message) { } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.PragmaWarningBatchFixAllProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Concurrent; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes.Suppression { internal abstract partial class AbstractSuppressionCodeFixProvider : IConfigurationFixProvider { /// <summary> /// Batch fixer for pragma suppress code action. /// </summary> internal sealed class PragmaWarningBatchFixAllProvider : AbstractSuppressionBatchFixAllProvider { private readonly AbstractSuppressionCodeFixProvider _suppressionFixProvider; public PragmaWarningBatchFixAllProvider(AbstractSuppressionCodeFixProvider suppressionFixProvider) => _suppressionFixProvider = suppressionFixProvider; protected override async Task AddDocumentFixesAsync( Document document, ImmutableArray<Diagnostic> diagnostics, ConcurrentBag<(Diagnostic diagnostic, CodeAction action)> fixes, FixAllState fixAllState, CancellationToken cancellationToken) { var pragmaActionsBuilder = ArrayBuilder<IPragmaBasedCodeAction>.GetInstance(); var pragmaDiagnosticsBuilder = ArrayBuilder<Diagnostic>.GetInstance(); foreach (var diagnostic in diagnostics.Where(d => d.Location.IsInSource && !d.IsSuppressed)) { var span = diagnostic.Location.SourceSpan; var pragmaSuppressions = await _suppressionFixProvider.GetPragmaSuppressionsAsync( document, span, SpecializedCollections.SingletonEnumerable(diagnostic), cancellationToken).ConfigureAwait(false); var pragmaSuppression = pragmaSuppressions.SingleOrDefault(); if (pragmaSuppression != null) { if (fixAllState.IsFixMultiple) { pragmaSuppression = pragmaSuppression.CloneForFixMultipleContext(); } pragmaActionsBuilder.Add(pragmaSuppression); pragmaDiagnosticsBuilder.Add(diagnostic); } } // Get the pragma batch fix. if (pragmaActionsBuilder.Count > 0) { var pragmaBatchFix = PragmaBatchFixHelpers.CreateBatchPragmaFix( _suppressionFixProvider, document, pragmaActionsBuilder.ToImmutableAndFree(), pragmaDiagnosticsBuilder.ToImmutableAndFree(), fixAllState, cancellationToken); fixes.Add((diagnostic: null, pragmaBatchFix)); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Concurrent; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes.Suppression { internal abstract partial class AbstractSuppressionCodeFixProvider : IConfigurationFixProvider { /// <summary> /// Batch fixer for pragma suppress code action. /// </summary> internal sealed class PragmaWarningBatchFixAllProvider : AbstractSuppressionBatchFixAllProvider { private readonly AbstractSuppressionCodeFixProvider _suppressionFixProvider; public PragmaWarningBatchFixAllProvider(AbstractSuppressionCodeFixProvider suppressionFixProvider) => _suppressionFixProvider = suppressionFixProvider; protected override async Task AddDocumentFixesAsync( Document document, ImmutableArray<Diagnostic> diagnostics, ConcurrentBag<(Diagnostic diagnostic, CodeAction action)> fixes, FixAllState fixAllState, CancellationToken cancellationToken) { var pragmaActionsBuilder = ArrayBuilder<IPragmaBasedCodeAction>.GetInstance(); var pragmaDiagnosticsBuilder = ArrayBuilder<Diagnostic>.GetInstance(); foreach (var diagnostic in diagnostics.Where(d => d.Location.IsInSource && !d.IsSuppressed)) { var span = diagnostic.Location.SourceSpan; var pragmaSuppressions = await _suppressionFixProvider.GetPragmaSuppressionsAsync( document, span, SpecializedCollections.SingletonEnumerable(diagnostic), cancellationToken).ConfigureAwait(false); var pragmaSuppression = pragmaSuppressions.SingleOrDefault(); if (pragmaSuppression != null) { if (fixAllState.IsFixMultiple) { pragmaSuppression = pragmaSuppression.CloneForFixMultipleContext(); } pragmaActionsBuilder.Add(pragmaSuppression); pragmaDiagnosticsBuilder.Add(diagnostic); } } // Get the pragma batch fix. if (pragmaActionsBuilder.Count > 0) { var pragmaBatchFix = PragmaBatchFixHelpers.CreateBatchPragmaFix( _suppressionFixProvider, document, pragmaActionsBuilder.ToImmutableAndFree(), pragmaDiagnosticsBuilder.ToImmutableAndFree(), fixAllState, cancellationToken); fixes.Add((diagnostic: null, pragmaBatchFix)); } } } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/EditorFeatures/Core/ModernCommands/GoToImplementationCommandArgs.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding; namespace Microsoft.CodeAnalysis.Editor.Commanding.Commands { /// <summary> /// Arguments for Go To Implementation. /// </summary> [ExcludeFromCodeCoverage] internal sealed class GoToImplementationCommandArgs : EditorCommandArgs { public GoToImplementationCommandArgs(ITextView textView, ITextBuffer subjectBuffer) : base(textView, subjectBuffer) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding; namespace Microsoft.CodeAnalysis.Editor.Commanding.Commands { /// <summary> /// Arguments for Go To Implementation. /// </summary> [ExcludeFromCodeCoverage] internal sealed class GoToImplementationCommandArgs : EditorCommandArgs { public GoToImplementationCommandArgs(ITextView textView, ITextBuffer subjectBuffer) : base(textView, subjectBuffer) { } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Features/Core/Portable/SplitOrMergeIfStatements/IIfLikeStatementGenerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.SplitOrMergeIfStatements { /// <summary> /// When querying the syntax, C# else if chains are "flattened" and modeled to look like VB else-if clauses, /// so an "ifOrElseIf" can be followed a sequence of else-if clauses and an optional final else clause. /// These else-if clauses are treated as independent when removing or inserting. /// </summary> internal interface IIfLikeStatementGenerator : ILanguageService { bool IsIfOrElseIf(SyntaxNode node); bool IsCondition(SyntaxNode expression, out SyntaxNode ifOrElseIf); bool IsElseIfClause(SyntaxNode node, out SyntaxNode parentIfOrElseIf); bool HasElseIfClause(SyntaxNode ifOrElseIf, out SyntaxNode elseIfClause); SyntaxNode GetCondition(SyntaxNode ifOrElseIf); /// <summary> /// Returns the topmost if statement for an else-if clause. /// </summary> SyntaxNode GetRootIfStatement(SyntaxNode ifOrElseIf); /// <summary> /// Returns the list of subsequent else-if clauses and a final else clause (if present). /// </summary> ImmutableArray<SyntaxNode> GetElseIfAndElseClauses(SyntaxNode ifOrElseIf); SyntaxNode WithCondition(SyntaxNode ifOrElseIf, SyntaxNode condition); SyntaxNode WithStatementInBlock(SyntaxNode ifOrElseIf, SyntaxNode statement); SyntaxNode WithStatementsOf(SyntaxNode ifOrElseIf, SyntaxNode otherIfOrElseIf); SyntaxNode WithElseIfAndElseClausesOf(SyntaxNode ifStatement, SyntaxNode otherIfStatement); /// <summary> /// Converts an else-if clause to an if statement, preserving its subsequent else-if and else clauses. /// </summary> SyntaxNode ToIfStatement(SyntaxNode ifOrElseIf); /// <summary> /// Convert an if statement to an else-if clause, discarding any of its else-if and else clauses. /// </summary> SyntaxNode ToElseIfClause(SyntaxNode ifOrElseIf); /// <summary> /// Inserts <paramref name="elseIfClause"/> as a new else-if clause directly below /// <paramref name="afterIfOrElseIf"/>, between it and any of its existing else-if clauses. /// </summary> void InsertElseIfClause(SyntaxEditor editor, SyntaxNode afterIfOrElseIf, SyntaxNode elseIfClause); /// <summary> /// Removes <paramref name="elseIfClause"/> from a sequence of else-if clauses, preserving any subsequent clauses. /// </summary> void RemoveElseIfClause(SyntaxEditor editor, SyntaxNode elseIfClause); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.SplitOrMergeIfStatements { /// <summary> /// When querying the syntax, C# else if chains are "flattened" and modeled to look like VB else-if clauses, /// so an "ifOrElseIf" can be followed a sequence of else-if clauses and an optional final else clause. /// These else-if clauses are treated as independent when removing or inserting. /// </summary> internal interface IIfLikeStatementGenerator : ILanguageService { bool IsIfOrElseIf(SyntaxNode node); bool IsCondition(SyntaxNode expression, out SyntaxNode ifOrElseIf); bool IsElseIfClause(SyntaxNode node, out SyntaxNode parentIfOrElseIf); bool HasElseIfClause(SyntaxNode ifOrElseIf, out SyntaxNode elseIfClause); SyntaxNode GetCondition(SyntaxNode ifOrElseIf); /// <summary> /// Returns the topmost if statement for an else-if clause. /// </summary> SyntaxNode GetRootIfStatement(SyntaxNode ifOrElseIf); /// <summary> /// Returns the list of subsequent else-if clauses and a final else clause (if present). /// </summary> ImmutableArray<SyntaxNode> GetElseIfAndElseClauses(SyntaxNode ifOrElseIf); SyntaxNode WithCondition(SyntaxNode ifOrElseIf, SyntaxNode condition); SyntaxNode WithStatementInBlock(SyntaxNode ifOrElseIf, SyntaxNode statement); SyntaxNode WithStatementsOf(SyntaxNode ifOrElseIf, SyntaxNode otherIfOrElseIf); SyntaxNode WithElseIfAndElseClausesOf(SyntaxNode ifStatement, SyntaxNode otherIfStatement); /// <summary> /// Converts an else-if clause to an if statement, preserving its subsequent else-if and else clauses. /// </summary> SyntaxNode ToIfStatement(SyntaxNode ifOrElseIf); /// <summary> /// Convert an if statement to an else-if clause, discarding any of its else-if and else clauses. /// </summary> SyntaxNode ToElseIfClause(SyntaxNode ifOrElseIf); /// <summary> /// Inserts <paramref name="elseIfClause"/> as a new else-if clause directly below /// <paramref name="afterIfOrElseIf"/>, between it and any of its existing else-if clauses. /// </summary> void InsertElseIfClause(SyntaxEditor editor, SyntaxNode afterIfOrElseIf, SyntaxNode elseIfClause); /// <summary> /// Removes <paramref name="elseIfClause"/> from a sequence of else-if clauses, preserving any subsequent clauses. /// </summary> void RemoveElseIfClause(SyntaxEditor editor, SyntaxNode elseIfClause); } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Tools/AnalyzerRunner/Extensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Diagnostics.Telemetry; namespace AnalyzerRunner { internal static class Extensions { internal static void Add(this AnalyzerTelemetryInfo analyzerTelemetryInfo, AnalyzerTelemetryInfo addendum) { analyzerTelemetryInfo.CodeBlockActionsCount += addendum.CodeBlockActionsCount; analyzerTelemetryInfo.CodeBlockEndActionsCount += addendum.CodeBlockEndActionsCount; analyzerTelemetryInfo.CodeBlockStartActionsCount += addendum.CodeBlockStartActionsCount; analyzerTelemetryInfo.CompilationActionsCount += addendum.CompilationActionsCount; analyzerTelemetryInfo.CompilationEndActionsCount += addendum.CompilationEndActionsCount; analyzerTelemetryInfo.CompilationStartActionsCount += addendum.CompilationStartActionsCount; analyzerTelemetryInfo.ExecutionTime += addendum.ExecutionTime; analyzerTelemetryInfo.OperationActionsCount += addendum.OperationActionsCount; analyzerTelemetryInfo.OperationBlockActionsCount += addendum.OperationBlockActionsCount; analyzerTelemetryInfo.OperationBlockEndActionsCount += addendum.OperationBlockEndActionsCount; analyzerTelemetryInfo.OperationBlockStartActionsCount += addendum.OperationBlockStartActionsCount; analyzerTelemetryInfo.SemanticModelActionsCount += addendum.SemanticModelActionsCount; analyzerTelemetryInfo.SymbolActionsCount += addendum.SymbolActionsCount; analyzerTelemetryInfo.SymbolStartActionsCount += addendum.SymbolStartActionsCount; analyzerTelemetryInfo.SymbolEndActionsCount += addendum.SymbolEndActionsCount; analyzerTelemetryInfo.SyntaxNodeActionsCount += addendum.SyntaxNodeActionsCount; analyzerTelemetryInfo.SyntaxTreeActionsCount += addendum.SyntaxTreeActionsCount; analyzerTelemetryInfo.AdditionalFileActionsCount += addendum.AdditionalFileActionsCount; analyzerTelemetryInfo.SuppressionActionsCount += addendum.SuppressionActionsCount; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Diagnostics.Telemetry; namespace AnalyzerRunner { internal static class Extensions { internal static void Add(this AnalyzerTelemetryInfo analyzerTelemetryInfo, AnalyzerTelemetryInfo addendum) { analyzerTelemetryInfo.CodeBlockActionsCount += addendum.CodeBlockActionsCount; analyzerTelemetryInfo.CodeBlockEndActionsCount += addendum.CodeBlockEndActionsCount; analyzerTelemetryInfo.CodeBlockStartActionsCount += addendum.CodeBlockStartActionsCount; analyzerTelemetryInfo.CompilationActionsCount += addendum.CompilationActionsCount; analyzerTelemetryInfo.CompilationEndActionsCount += addendum.CompilationEndActionsCount; analyzerTelemetryInfo.CompilationStartActionsCount += addendum.CompilationStartActionsCount; analyzerTelemetryInfo.ExecutionTime += addendum.ExecutionTime; analyzerTelemetryInfo.OperationActionsCount += addendum.OperationActionsCount; analyzerTelemetryInfo.OperationBlockActionsCount += addendum.OperationBlockActionsCount; analyzerTelemetryInfo.OperationBlockEndActionsCount += addendum.OperationBlockEndActionsCount; analyzerTelemetryInfo.OperationBlockStartActionsCount += addendum.OperationBlockStartActionsCount; analyzerTelemetryInfo.SemanticModelActionsCount += addendum.SemanticModelActionsCount; analyzerTelemetryInfo.SymbolActionsCount += addendum.SymbolActionsCount; analyzerTelemetryInfo.SymbolStartActionsCount += addendum.SymbolStartActionsCount; analyzerTelemetryInfo.SymbolEndActionsCount += addendum.SymbolEndActionsCount; analyzerTelemetryInfo.SyntaxNodeActionsCount += addendum.SyntaxNodeActionsCount; analyzerTelemetryInfo.SyntaxTreeActionsCount += addendum.SyntaxTreeActionsCount; analyzerTelemetryInfo.AdditionalFileActionsCount += addendum.AdditionalFileActionsCount; analyzerTelemetryInfo.SuppressionActionsCount += addendum.SuppressionActionsCount; } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Analyzers/CSharp/Analyzers/AddRequiredParentheses/CSharpAddRequiredExpressionParenthesesDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.AddRequiredParentheses; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Precedence; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.AddRequiredParentheses { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpAddRequiredExpressionParenthesesDiagnosticAnalyzer : AbstractAddRequiredParenthesesDiagnosticAnalyzer< ExpressionSyntax, ExpressionSyntax, SyntaxKind> { public CSharpAddRequiredExpressionParenthesesDiagnosticAnalyzer() : base(CSharpExpressionPrecedenceService.Instance) { } private static readonly ImmutableArray<SyntaxKind> s_kinds = ImmutableArray.Create( SyntaxKind.AddExpression, SyntaxKind.SubtractExpression, SyntaxKind.MultiplyExpression, SyntaxKind.DivideExpression, SyntaxKind.ModuloExpression, SyntaxKind.LeftShiftExpression, SyntaxKind.RightShiftExpression, SyntaxKind.LogicalOrExpression, SyntaxKind.LogicalAndExpression, SyntaxKind.BitwiseOrExpression, SyntaxKind.BitwiseAndExpression, SyntaxKind.ExclusiveOrExpression, SyntaxKind.EqualsExpression, SyntaxKind.NotEqualsExpression, SyntaxKind.LessThanExpression, SyntaxKind.LessThanOrEqualExpression, SyntaxKind.GreaterThanExpression, SyntaxKind.GreaterThanOrEqualExpression, SyntaxKind.IsExpression, SyntaxKind.AsExpression, SyntaxKind.CoalesceExpression, SyntaxKind.IsPatternExpression); protected override ImmutableArray<SyntaxKind> GetSyntaxNodeKinds() => s_kinds; protected override int GetPrecedence(ExpressionSyntax binaryLike) => (int)binaryLike.GetOperatorPrecedence(); protected override bool IsBinaryLike(ExpressionSyntax node) => node is BinaryExpressionSyntax || node is IsPatternExpressionSyntax isPattern && isPattern.Pattern is ConstantPatternSyntax; protected override (ExpressionSyntax, SyntaxToken, ExpressionSyntax) GetPartsOfBinaryLike(ExpressionSyntax binaryLike) { Debug.Assert(IsBinaryLike(binaryLike)); switch (binaryLike) { case BinaryExpressionSyntax binaryExpression: return (binaryExpression.Left, binaryExpression.OperatorToken, binaryExpression.Right); case IsPatternExpressionSyntax isPatternExpression: return (isPatternExpression.Expression, isPatternExpression.IsKeyword, ((ConstantPatternSyntax)isPatternExpression.Pattern).Expression); default: throw ExceptionUtilities.UnexpectedValue(binaryLike); } } protected override ExpressionSyntax? TryGetAppropriateParent(ExpressionSyntax binaryLike) => binaryLike.Parent is ConstantPatternSyntax ? binaryLike.Parent.Parent as ExpressionSyntax : binaryLike.Parent as ExpressionSyntax; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.AddRequiredParentheses; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Precedence; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.AddRequiredParentheses { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpAddRequiredExpressionParenthesesDiagnosticAnalyzer : AbstractAddRequiredParenthesesDiagnosticAnalyzer< ExpressionSyntax, ExpressionSyntax, SyntaxKind> { public CSharpAddRequiredExpressionParenthesesDiagnosticAnalyzer() : base(CSharpExpressionPrecedenceService.Instance) { } private static readonly ImmutableArray<SyntaxKind> s_kinds = ImmutableArray.Create( SyntaxKind.AddExpression, SyntaxKind.SubtractExpression, SyntaxKind.MultiplyExpression, SyntaxKind.DivideExpression, SyntaxKind.ModuloExpression, SyntaxKind.LeftShiftExpression, SyntaxKind.RightShiftExpression, SyntaxKind.LogicalOrExpression, SyntaxKind.LogicalAndExpression, SyntaxKind.BitwiseOrExpression, SyntaxKind.BitwiseAndExpression, SyntaxKind.ExclusiveOrExpression, SyntaxKind.EqualsExpression, SyntaxKind.NotEqualsExpression, SyntaxKind.LessThanExpression, SyntaxKind.LessThanOrEqualExpression, SyntaxKind.GreaterThanExpression, SyntaxKind.GreaterThanOrEqualExpression, SyntaxKind.IsExpression, SyntaxKind.AsExpression, SyntaxKind.CoalesceExpression, SyntaxKind.IsPatternExpression); protected override ImmutableArray<SyntaxKind> GetSyntaxNodeKinds() => s_kinds; protected override int GetPrecedence(ExpressionSyntax binaryLike) => (int)binaryLike.GetOperatorPrecedence(); protected override bool IsBinaryLike(ExpressionSyntax node) => node is BinaryExpressionSyntax || node is IsPatternExpressionSyntax isPattern && isPattern.Pattern is ConstantPatternSyntax; protected override (ExpressionSyntax, SyntaxToken, ExpressionSyntax) GetPartsOfBinaryLike(ExpressionSyntax binaryLike) { Debug.Assert(IsBinaryLike(binaryLike)); switch (binaryLike) { case BinaryExpressionSyntax binaryExpression: return (binaryExpression.Left, binaryExpression.OperatorToken, binaryExpression.Right); case IsPatternExpressionSyntax isPatternExpression: return (isPatternExpression.Expression, isPatternExpression.IsKeyword, ((ConstantPatternSyntax)isPatternExpression.Pattern).Expression); default: throw ExceptionUtilities.UnexpectedValue(binaryLike); } } protected override ExpressionSyntax? TryGetAppropriateParent(ExpressionSyntax binaryLike) => binaryLike.Parent is ConstantPatternSyntax ? binaryLike.Parent.Parent as ExpressionSyntax : binaryLike.Parent as ExpressionSyntax; } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Features/Core/Portable/ExternalAccess/Razor/Api/IRazorDocumentOptionsService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.ExternalAccess.Razor.Api { internal interface IRazorDocumentOptionsService { Task<IRazorDocumentOptions> GetOptionsForDocumentAsync(Document document, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.ExternalAccess.Razor.Api { internal interface IRazorDocumentOptionsService { Task<IRazorDocumentOptions> GetOptionsForDocumentAsync(Document document, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/Core/Portable/MetadataReference/AssemblyIdentityMap.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Implements a map from an assembly identity to a value. The map allows to look up the value by an identity /// that either exactly matches the original identity key, or corresponds to a key with the lowest version among identities /// with higher version than the requested identity key. /// </summary> internal sealed class AssemblyIdentityMap<TValue> { private readonly Dictionary<string, OneOrMany<KeyValuePair<AssemblyIdentity, TValue>>> _map; public AssemblyIdentityMap() { _map = new Dictionary<string, OneOrMany<KeyValuePair<AssemblyIdentity, TValue>>>(AssemblyIdentityComparer.SimpleNameComparer); } public bool Contains(AssemblyIdentity identity, bool allowHigherVersion = true) { TValue value; return TryGetValue(identity, out value, allowHigherVersion); } public bool TryGetValue(AssemblyIdentity identity, out TValue value, bool allowHigherVersion = true) { OneOrMany<KeyValuePair<AssemblyIdentity, TValue>> sameName; if (_map.TryGetValue(identity.Name, out sameName)) { int minHigherVersionCandidate = -1; for (int i = 0; i < sameName.Count; i++) { AssemblyIdentity currentIdentity = sameName[i].Key; if (AssemblyIdentity.EqualIgnoringNameAndVersion(currentIdentity, identity)) { if (currentIdentity.Version == identity.Version) { value = sameName[i].Value; return true; } // only higher version candidates are considered for match: if (!allowHigherVersion || currentIdentity.Version < identity.Version) { continue; } if (minHigherVersionCandidate == -1 || currentIdentity.Version < sameName[minHigherVersionCandidate].Key.Version) { minHigherVersionCandidate = i; } } } if (minHigherVersionCandidate >= 0) { value = sameName[minHigherVersionCandidate].Value; return true; } } value = default(TValue); return false; } public bool TryGetValue(AssemblyIdentity identity, out TValue value, Func<Version, Version, TValue, bool> comparer) { OneOrMany<KeyValuePair<AssemblyIdentity, TValue>> sameName; if (_map.TryGetValue(identity.Name, out sameName)) { for (int i = 0; i < sameName.Count; i++) { AssemblyIdentity currentIdentity = sameName[i].Key; if (comparer(identity.Version, currentIdentity.Version, sameName[i].Value) && AssemblyIdentity.EqualIgnoringNameAndVersion(currentIdentity, identity)) { value = sameName[i].Value; return true; } } } value = default(TValue); return false; } public void Add(AssemblyIdentity identity, TValue value) { var pair = KeyValuePairUtil.Create(identity, value); OneOrMany<KeyValuePair<AssemblyIdentity, TValue>> sameName; _map[identity.Name] = _map.TryGetValue(identity.Name, out sameName) ? sameName.Add(pair) : OneOrMany.Create(pair); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Implements a map from an assembly identity to a value. The map allows to look up the value by an identity /// that either exactly matches the original identity key, or corresponds to a key with the lowest version among identities /// with higher version than the requested identity key. /// </summary> internal sealed class AssemblyIdentityMap<TValue> { private readonly Dictionary<string, OneOrMany<KeyValuePair<AssemblyIdentity, TValue>>> _map; public AssemblyIdentityMap() { _map = new Dictionary<string, OneOrMany<KeyValuePair<AssemblyIdentity, TValue>>>(AssemblyIdentityComparer.SimpleNameComparer); } public bool Contains(AssemblyIdentity identity, bool allowHigherVersion = true) { TValue value; return TryGetValue(identity, out value, allowHigherVersion); } public bool TryGetValue(AssemblyIdentity identity, out TValue value, bool allowHigherVersion = true) { OneOrMany<KeyValuePair<AssemblyIdentity, TValue>> sameName; if (_map.TryGetValue(identity.Name, out sameName)) { int minHigherVersionCandidate = -1; for (int i = 0; i < sameName.Count; i++) { AssemblyIdentity currentIdentity = sameName[i].Key; if (AssemblyIdentity.EqualIgnoringNameAndVersion(currentIdentity, identity)) { if (currentIdentity.Version == identity.Version) { value = sameName[i].Value; return true; } // only higher version candidates are considered for match: if (!allowHigherVersion || currentIdentity.Version < identity.Version) { continue; } if (minHigherVersionCandidate == -1 || currentIdentity.Version < sameName[minHigherVersionCandidate].Key.Version) { minHigherVersionCandidate = i; } } } if (minHigherVersionCandidate >= 0) { value = sameName[minHigherVersionCandidate].Value; return true; } } value = default(TValue); return false; } public bool TryGetValue(AssemblyIdentity identity, out TValue value, Func<Version, Version, TValue, bool> comparer) { OneOrMany<KeyValuePair<AssemblyIdentity, TValue>> sameName; if (_map.TryGetValue(identity.Name, out sameName)) { for (int i = 0; i < sameName.Count; i++) { AssemblyIdentity currentIdentity = sameName[i].Key; if (comparer(identity.Version, currentIdentity.Version, sameName[i].Value) && AssemblyIdentity.EqualIgnoringNameAndVersion(currentIdentity, identity)) { value = sameName[i].Value; return true; } } } value = default(TValue); return false; } public void Add(AssemblyIdentity identity, TValue value) { var pair = KeyValuePairUtil.Create(identity, value); OneOrMany<KeyValuePair<AssemblyIdentity, TValue>> sameName; _map[identity.Name] = _map.TryGetValue(identity.Name, out sameName) ? sameName.Add(pair) : OneOrMany.Create(pair); } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Tools/Source/CompilerGeneratorTools/Source/VisualBasicSyntaxGenerator/GreenNodes/GreenNodeWriter.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. '----------------------------------------------------------------------------------------------------------- ' This is the code that actually outputs the VB code that defines the tree. It is passed a read and validated ' ParseTree, and outputs the code to defined the node classes for that tree, and also additional data ' structures like the kinds, visitor, etc. '----------------------------------------------------------------------------------------------------------- Imports System.IO ' Class to write out the code for the code tree. Friend Class GreenNodeWriter Inherits WriteUtils Private _writer As TextWriter 'output is sent here. Private ReadOnly _nonterminalsWithOneChild As List(Of String) = New List(Of String) Private ReadOnly _nonterminalsWithTwoChildren As List(Of String) = New List(Of String) ' Initialize the class with the parse tree to write. Public Sub New(parseTree As ParseTree) MyBase.New(parseTree) End Sub ' Write out the code defining the tree to the give file. Public Sub WriteTreeAsCode(writer As TextWriter) _writer = writer GenerateFile() End Sub Private Sub GenerateFile() GenerateNamespace() End Sub Private Sub GenerateNamespace() _writer.WriteLine() If Not String.IsNullOrEmpty(_parseTree.NamespaceName) Then _writer.WriteLine("Namespace {0}", Ident(_parseTree.NamespaceName) + ".Syntax.InternalSyntax") _writer.WriteLine() End If GenerateNodeStructures() If Not String.IsNullOrEmpty(_parseTree.VisitorName) Then GenerateVisitorClass() End If If Not String.IsNullOrEmpty(_parseTree.RewriteVisitorName) Then GenerateRewriteVisitorClass() End If If Not String.IsNullOrEmpty(_parseTree.NamespaceName) Then _writer.WriteLine("End Namespace") End If 'DumpNames("Nodes with One Child", _nonterminalsWithOneChild) 'DumpNames("Nodes with Two Children", _nonterminalsWithTwoChildren) End Sub Private Sub DumpNames(title As String, names As List(Of String)) Console.WriteLine(title) Console.WriteLine("=======================================") Dim sortedNames = From n In names Order By n For Each name In sortedNames Console.WriteLine(name) Next Console.WriteLine() End Sub Private Sub GenerateNodeStructures() For Each nodeStructure In _parseTree.NodeStructures.Values If Not nodeStructure.NoFactory Then GenerateNodeStructureClass(nodeStructure) End If Next End Sub ' Generate a constant value Private Function GetConstantValue(val As Long) As String Return val.ToString() End Function ' Generate a class declaration for a node structure. Private Sub GenerateNodeStructureClass(nodeStructure As ParseNodeStructure) ' XML comment GenerateXmlComment(_writer, nodeStructure, 4, includeRemarks:=False) ' Class name _writer.Write(" ") If (nodeStructure.PartialClass) Then _writer.Write("Partial ") End If Dim visibility As String = "Friend" If _parseTree.IsAbstract(nodeStructure) Then _writer.WriteLine("{0} MustInherit Class {1}", visibility, StructureTypeName(nodeStructure)) ElseIf Not nodeStructure.HasDerivedStructure Then _writer.WriteLine("{0} NotInheritable Class {1}", visibility, StructureTypeName(nodeStructure)) Else _writer.WriteLine("{0} Class {1}", visibility, StructureTypeName(nodeStructure)) End If ' Base class If Not IsRoot(nodeStructure) Then _writer.WriteLine(" Inherits {0}", StructureTypeName(nodeStructure.ParentStructure)) End If _writer.WriteLine() 'Create members GenerateNodeStructureMembers(nodeStructure) ' Create the constructor. GenerateNodeStructureConstructor(nodeStructure, False, noExtra:=True) GenerateNodeStructureConstructor(nodeStructure, False, noExtra:=True, contextual:=True) GenerateNodeStructureConstructor(nodeStructure, False) ' Serialization GenerateNodeStructureSerialization(nodeStructure) GenerateCreateRed(nodeStructure) ' Create the property accessor for each of the fields Dim fields = nodeStructure.Fields For i = 0 To fields.Count - 1 GenerateNodeFieldProperty(fields(i), i, fields(i).ContainingStructure IsNot nodeStructure) Next ' Create the property accessor for each of the children Dim children = nodeStructure.Children For i = 0 To children.Count - 1 GenerateNodeChildProperty(nodeStructure, children(i), i) GenerateNodeWithChildProperty(children(i), i, nodeStructure) Next If Not (_parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken) Then If children.Count = 1 Then If Not children(0).IsList AndAlso Not KindTypeStructure(children(0).ChildKind).Name = "ExpressionSyntax" Then _nonterminalsWithOneChild.Add(nodeStructure.Name) End If ElseIf children.Count = 2 Then If Not children(0).IsList AndAlso Not KindTypeStructure(children(0).ChildKind).Name = "ExpressionSyntax" AndAlso Not children(1).IsList AndAlso Not KindTypeStructure(children(1).ChildKind).Name = "ExpressionSyntax" Then _nonterminalsWithTwoChildren.Add(nodeStructure.Name) End If End If End If 'Create GetChild GenerateGetChild(nodeStructure) GenerateWithTrivia(nodeStructure) GenerateSetDiagnostics(nodeStructure) GenerateSetAnnotations(nodeStructure) ' Visitor accept method If Not String.IsNullOrEmpty(_parseTree.VisitorName) Then GenerateAccept(nodeStructure) End If 'GenerateUpdate(nodeStructure) ' Special methods for the root node. If IsRoot(nodeStructure) Then GenerateRootNodeSpecialMethods(nodeStructure) End If ' End the class _writer.WriteLine(" End Class") _writer.WriteLine() End Sub ' Generate CreateRed method Private Sub GenerateCreateRed(nodeStructure As ParseNodeStructure) If _parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken OrElse nodeStructure.IsTrivia Then Return End If _writer.WriteLine(" Friend Overrides Function CreateRed(ByVal parent As SyntaxNode, ByVal startLocation As Integer) As SyntaxNode") _writer.WriteLine(" Return new {0}.Syntax.{1}(Me, parent, startLocation)", _parseTree.NamespaceName, StructureTypeName(nodeStructure)) _writer.WriteLine(" End Function") _writer.WriteLine() End Sub ' Generate SetDiagnostics method Private Sub GenerateSetDiagnostics(nodeStructure As ParseNodeStructure) If _parseTree.IsAbstract(nodeStructure) Then Return End If _writer.WriteLine(" Friend Overrides Function SetDiagnostics(ByVal newErrors As DiagnosticInfo()) As GreenNode") _writer.Write(" Return new {0}", StructureTypeName(nodeStructure)) GenerateNodeStructureConstructorParameters(nodeStructure, "newErrors", "GetAnnotations", "GetLeadingTrivia", "GetTrailingTrivia") _writer.WriteLine(" End Function") _writer.WriteLine() End Sub ' Generate SetAnnotations method Private Sub GenerateSetAnnotations(nodeStructure As ParseNodeStructure) If _parseTree.IsAbstract(nodeStructure) Then Return End If _writer.WriteLine(" Friend Overrides Function SetAnnotations(ByVal annotations As SyntaxAnnotation()) As GreenNode") _writer.Write(" Return new {0}", StructureTypeName(nodeStructure)) GenerateNodeStructureConstructorParameters(nodeStructure, "GetDiagnostics", "annotations", "GetLeadingTrivia", "GetTrailingTrivia") _writer.WriteLine(" End Function") _writer.WriteLine() End Sub ' Generate Update method . But only for non terminals Private Sub GenerateUpdate(nodeStructure As ParseNodeStructure) If _parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken OrElse nodeStructure.IsTrivia Then Return End If Dim structureName = StructureTypeName(nodeStructure) Dim factory = FactoryName(nodeStructure) Dim needComma = False _writer.Write(" Friend ") If nodeStructure.ParentStructure IsNot Nothing AndAlso Not nodeStructure.ParentStructure.Abstract Then _writer.Write("Shadows ") End If _writer.Write("Function Update(") For Each child In GetAllChildrenOfStructure(nodeStructure) If needComma Then _writer.Write(", ") End If GenerateFactoryChildParameter(nodeStructure, child, Nothing, False) needComma = True Next _writer.WriteLine(") As {0}", structureName) needComma = False _writer.Write(" If ") For Each child In GetAllChildrenOfStructure(nodeStructure) If needComma Then _writer.Write(" OrElse ") End If If child.IsList OrElse KindTypeStructure(child.ChildKind).IsToken Then _writer.Write("{0}.Node IsNot Me.{1}", ChildParamName(child), ChildVarName(child)) Else _writer.Write("{0} IsNot Me.{1}", ChildParamName(child), ChildVarName(child)) End If needComma = True Next _writer.WriteLine(" Then") needComma = False _writer.Write(" Return SyntaxFactory.{0}(", factory) If nodeStructure.NodeKinds.Count >= 2 And Not _parseTree.NodeKinds.ContainsKey(FactoryName(nodeStructure)) Then _writer.Write("Me.Kind, ") End If For Each child In GetAllChildrenOfStructure(nodeStructure) If needComma Then _writer.Write(", ") End If _writer.Write("{0}", ChildParamName(child)) needComma = True Next _writer.WriteLine(")") _writer.WriteLine(" End If") _writer.WriteLine(" Return Me") _writer.WriteLine(" End Function") _writer.WriteLine() End Sub ' Generate WithTrivia method s Private Sub GenerateWithTrivia(nodeStructure As ParseNodeStructure) If _parseTree.IsAbstract(nodeStructure) OrElse Not nodeStructure.IsToken Then Return End If _writer.WriteLine(" Public Overrides Function WithLeadingTrivia(ByVal trivia As GreenNode) As GreenNode") _writer.Write(" Return new {0}", StructureTypeName(nodeStructure)) GenerateNodeStructureConstructorParameters(nodeStructure, "GetDiagnostics", "GetAnnotations", "trivia", "GetTrailingTrivia") _writer.WriteLine(" End Function") _writer.WriteLine() _writer.WriteLine(" Public Overrides Function WithTrailingTrivia(ByVal trivia As GreenNode) As GreenNode") _writer.Write(" Return new {0}", StructureTypeName(nodeStructure)) GenerateNodeStructureConstructorParameters(nodeStructure, "GetDiagnostics", "GetAnnotations", "GetLeadingTrivia", "trivia") _writer.WriteLine(" End Function") _writer.WriteLine() End Sub ' Generate GetChild, GetChildrenCount so members can be accessed by index Private Sub GenerateGetChild(nodeStructure As ParseNodeStructure) If _parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken Then Return End If Dim allChildren = GetAllChildrenOfStructure(nodeStructure) Dim childrenCount = allChildren.Count If childrenCount = 0 Then Return End If _writer.WriteLine(" Friend Overrides Function GetSlot(i as Integer) as GreenNode") ' Create the property accessor for each of the children Dim children = allChildren If childrenCount <> 1 Then _writer.WriteLine(" Select case i") For i = 0 To childrenCount - 1 _writer.WriteLine(" Case {0}", i) _writer.WriteLine(" Return Me.{0}", ChildVarName(children(i))) Next _writer.WriteLine(" Case Else") _writer.WriteLine(" Debug.Assert(false, ""child index out of range"")") _writer.WriteLine(" Return Nothing") _writer.WriteLine(" End Select") Else _writer.WriteLine(" If i = 0 Then") _writer.WriteLine(" Return Me.{0}", ChildVarName(children(0))) _writer.WriteLine(" Else") _writer.WriteLine(" Debug.Assert(false, ""child index out of range"")") _writer.WriteLine(" Return Nothing") _writer.WriteLine(" End If") End If _writer.WriteLine(" End Function") _writer.WriteLine() '_writer.WriteLine(" Friend Overrides ReadOnly Property SlotCount() As Integer") '_writer.WriteLine(" Get") '_writer.WriteLine(" Return {0}", childrenCount) '_writer.WriteLine(" End Get") '_writer.WriteLine(" End Property") _writer.WriteLine() End Sub ' Generate IsTerminal property. Private Sub GenerateIsTerminal(nodeStructure As ParseNodeStructure) _writer.WriteLine(" Friend Overrides ReadOnly Property IsTerminal As Boolean") _writer.WriteLine(" Get") _writer.WriteLine(" Return {0}", If(nodeStructure.IsTerminal, "True", "False")) _writer.WriteLine(" End Get") _writer.WriteLine(" End Property") _writer.WriteLine() End Sub Private Sub GenerateNodeStructureMembers(nodeStructure As ParseNodeStructure) Dim fields = nodeStructure.Fields For Each field In fields _writer.WriteLine(" Friend ReadOnly {0} as {1}", FieldVarName(field), FieldTypeRef(field)) Next Dim children = nodeStructure.Children For Each child In children _writer.WriteLine(" Friend ReadOnly {0} as {1}", ChildVarName(child), ChildFieldTypeRef(child, True)) Next _writer.WriteLine() End Sub Private Sub GenerateNodeStructureSerialization(nodeStructure As ParseNodeStructure) If nodeStructure.IsTokenRoot OrElse nodeStructure.IsTriviaRoot OrElse nodeStructure.IsPredefined OrElse nodeStructure.Name = "StructuredTriviaSyntax" Then Return End If _writer.WriteLine(" Friend Sub New(reader as ObjectReader)") _writer.WriteLine(" MyBase.New(reader)") If Not nodeStructure.Abstract Then Dim allChildren = GetAllChildrenOfStructure(nodeStructure) Dim childrenCount = allChildren.Count If childrenCount <> 0 Then _writer.WriteLine(" MyBase._slotCount = {0}", childrenCount) End If End If For Each child In nodeStructure.Children _writer.WriteLine(" Dim {0} = DirectCast(reader.ReadValue(), {1})", ChildVarName(child), ChildFieldTypeRef(child, isGreen:=True)) _writer.WriteLine(" If {0} isnot Nothing", ChildVarName(child)) _writer.WriteLine(" AdjustFlagsAndWidth({0})", ChildVarName(child)) _writer.WriteLine(" Me.{0} = {0}", ChildVarName(child)) _writer.WriteLine(" End If") Next For Each field In nodeStructure.Fields _writer.WriteLine(" Me.{0} = CType(reader.{1}(), {2})", FieldVarName(field), ReaderMethod(FieldTypeRef(field)), FieldTypeRef(field)) Next 'TODO: BLUE If StructureTypeName(nodeStructure) = "DirectiveTriviaSyntax" Then _writer.WriteLine(" SetFlags(NodeFlags.ContainsDirectives)") End If _writer.WriteLine(" End Sub") If Not nodeStructure.Abstract Then ' Friend Shared CreateInstance As Func(Of ObjectReader, Object) = Function(o) New BinaryExpressionSyntax(o) _writer.WriteLine(" Friend Shared CreateInstance As Func(Of ObjectReader, Object) = Function(o) New {0}(o)", StructureTypeName(nodeStructure)) _writer.WriteLine() End If If nodeStructure.Children.Count > 0 OrElse nodeStructure.Fields.Count > 0 Then _writer.WriteLine() _writer.WriteLine(" Friend Overrides Sub WriteTo(writer as ObjectWriter)") _writer.WriteLine(" MyBase.WriteTo(writer)") For Each child In nodeStructure.Children _writer.WriteLine(" writer.WriteValue(Me.{0})", ChildVarName(child)) Next For Each field In nodeStructure.Fields _writer.WriteLine(" writer.{0}(Me.{1})", WriterMethod(FieldTypeRef(field)), FieldVarName(field)) Next _writer.WriteLine(" End Sub") End If If Not _parseTree.IsAbstract(nodeStructure) Then _writer.WriteLine() _writer.WriteLine(" Shared Sub New()") _writer.WriteLine(" ObjectBinder.RegisterTypeReader(GetType({0}), Function(r) New {0}(r))", StructureTypeName(nodeStructure)) _writer.WriteLine(" End Sub") End If _writer.WriteLine() End Sub Private Function ReaderMethod(type As String) As String Select Case type Case "Integer", "SyntaxKind", "TypeCharacter" Return "ReadInt32" Case "Boolean" Return "ReadBoolean" Case Else Return "ReadValue" End Select End Function Private Function WriterMethod(type As String) As String Select Case type Case "Integer", "SyntaxKind", "TypeCharacter" Return "WriteInt32" Case "Boolean" Return "WriteBoolean" Case Else Return "WriteValue" End Select End Function ' Generate constructor for a node structure Private Sub GenerateNodeStructureConstructor(nodeStructure As ParseNodeStructure, isRaw As Boolean, Optional noExtra As Boolean = False, Optional contextual As Boolean = False) ' these constructors are hardcoded If nodeStructure.IsTokenRoot OrElse nodeStructure.IsTriviaRoot OrElse nodeStructure.Name = "StructuredTriviaSyntax" Then Return End If If nodeStructure.ParentStructure Is Nothing Then Return End If Dim allFields = GetAllFieldsOfStructure(nodeStructure) _writer.Write(" Friend Sub New(") ' Generate each of the field parameters _writer.Write("ByVal kind As {0}", NodeKindType()) If Not noExtra Then _writer.Write(", ByVal errors as DiagnosticInfo(), ByVal annotations as SyntaxAnnotation()", NodeKindType()) End If If nodeStructure.IsTerminal Then ' terminals have a text _writer.Write(", text as String") End If If nodeStructure.IsToken Then ' tokens have trivia _writer.Write(", leadingTrivia As GreenNode, trailingTrivia As GreenNode", StructureTypeName(_parseTree.RootStructure)) End If For Each field In allFields _writer.Write(", ") GenerateNodeStructureFieldParameter(field) Next For Each child In GetAllChildrenOfStructure(nodeStructure) _writer.Write(", ") GenerateNodeStructureChildParameter(child, Nothing, True) Next If contextual Then _writer.Write(", context As ISyntaxFactoryContext") End If _writer.WriteLine(")") ' Generate each of the field parameters _writer.Write(" MyBase.New(kind", NodeKindType()) If Not noExtra Then _writer.Write(", errors, annotations") End If If nodeStructure.IsToken AndAlso Not nodeStructure.IsTokenRoot Then ' nonterminals have text. _writer.Write(", text") If Not nodeStructure.IsTrivia Then ' tokens have trivia, but only if they are not trivia. _writer.Write(", leadingTrivia, trailingTrivia") End If End If Dim baseClass = nodeStructure.ParentStructure If baseClass IsNot Nothing Then For Each child In GetAllChildrenOfStructure(baseClass) _writer.Write(", {0}", ChildParamName(child)) Next End If _writer.WriteLine(")") If Not nodeStructure.Abstract Then Dim allChildren = GetAllChildrenOfStructure(nodeStructure) Dim childrenCount = allChildren.Count If childrenCount <> 0 Then _writer.WriteLine(" MyBase._slotCount = {0}", childrenCount) End If End If ' Generate code to initialize this class If contextual Then _writer.WriteLine(" Me.SetFactoryContext(context)") End If If allFields.Count > 0 Then For i = 0 To allFields.Count - 1 _writer.WriteLine(" Me.{0} = {1}", FieldVarName(allFields(i)), FieldParamName(allFields(i))) Next End If If nodeStructure.Children.Count > 0 Then '_writer.WriteLine(" Dim fullWidth as integer") _writer.WriteLine() For Each child In nodeStructure.Children Dim indent = "" If child.IsOptional OrElse child.IsList Then 'If endKeyword IsNot Nothing Then _writer.WriteLine(" If {0} IsNot Nothing Then", ChildParamName(child)) indent = " " End If '_writer.WriteLine("{0} fullWidth += {1}.FullWidth", indent, ChildParamName(child)) _writer.WriteLine("{0} AdjustFlagsAndWidth({1})", indent, ChildParamName(child)) _writer.WriteLine("{0} Me.{1} = {2}", indent, ChildVarName(child), ChildParamName(child)) If child.IsOptional OrElse child.IsList Then 'If endKeyword IsNot Nothing Then _writer.WriteLine(" End If", ChildParamName(child)) End If Next '_writer.WriteLine(" Me._fullWidth += fullWidth") _writer.WriteLine() End If 'TODO: BLUE If StructureTypeName(nodeStructure) = "DirectiveTriviaSyntax" Then _writer.WriteLine(" SetFlags(NodeFlags.ContainsDirectives)") End If ' Generate End Sub _writer.WriteLine(" End Sub") _writer.WriteLine() End Sub Private Sub GenerateNodeStructureConstructorParameters(nodeStructure As ParseNodeStructure, errorParam As String, annotationParam As String, precedingTriviaParam As String, followingTriviaParam As String) ' Generate each of the field parameters _writer.Write("(Me.Kind") _writer.Write(", {0}", errorParam) _writer.Write(", {0}", annotationParam) If nodeStructure.IsToken Then ' nonterminals have text. _writer.Write(", text") If Not nodeStructure.IsTrivia Then ' tokens have trivia, but only if they are not trivia. _writer.Write(", {0}, {1}", precedingTriviaParam, followingTriviaParam) End If ElseIf nodeStructure.IsTrivia AndAlso nodeStructure.IsTriviaRoot Then _writer.Write(", Me.Text") End If For Each field In GetAllFieldsOfStructure(nodeStructure) _writer.Write(", {0}", FieldVarName(field)) Next For Each child In GetAllChildrenOfStructure(nodeStructure) _writer.Write(", {0}", ChildVarName(child)) Next _writer.WriteLine(")") End Sub ' Generate a parameter corresponding to a node structure field Private Sub GenerateNodeStructureFieldParameter(field As ParseNodeField, Optional conflictName As String = Nothing) _writer.Write("{0} As {1}", FieldParamName(field, conflictName), FieldTypeRef(field)) End Sub ' Generate a parameter corresponding to a node structure child Private Sub GenerateNodeStructureChildParameter(child As ParseNodeChild, Optional conflictName As String = Nothing, Optional isGreen As Boolean = False) _writer.Write("{0} As {1}", ChildParamName(child, conflictName), ChildConstructorTypeRef(child, isGreen)) End Sub ' Generate a parameter corresponding to a node structure child Private Sub GenerateFactoryChildParameter(node As ParseNodeStructure, child As ParseNodeChild, Optional conflictName As String = Nothing, Optional internalForm As Boolean = False) _writer.Write("{0} As {1}", ChildParamName(child, conflictName), ChildFactoryTypeRef(node, child, True, internalForm)) End Sub ' Get modifiers Private Function GetModifiers(containingStructure As ParseNodeStructure, isOverride As Boolean, name As String) As String ' Is this overridable or an override? Dim modifiers = "" 'If isOverride Then ' modifiers = "Overrides " 'ElseIf containingStructure.HasDerivedStructure Then ' modifiers = "Overridable " 'End If ' Put Shadows modifier on if useful. ' Object has Equals and GetType ' root name has members for every kind and structure (factory methods) If (name = "Equals" OrElse name = "GetType") Then 'OrElse _parseTree.NodeKinds.ContainsKey(name) OrElse _parseTree.NodeStructures.ContainsKey(name)) Then modifiers = "Shadows " + modifiers End If Return modifiers End Function ' Generate a public property for a node field Private Sub GenerateNodeFieldProperty(field As ParseNodeField, fieldIndex As Integer, isOverride As Boolean) ' XML comment GenerateXmlComment(_writer, field, 8) _writer.WriteLine(" Friend {2}ReadOnly Property {0} As {1}", FieldPropertyName(field), FieldTypeRef(field), GetModifiers(field.ContainingStructure, isOverride, field.Name)) _writer.WriteLine(" Get") _writer.WriteLine(" Return Me.{0}", FieldVarName(field)) _writer.WriteLine(" End Get") _writer.WriteLine(" End Property") _writer.WriteLine("") End Sub ' Generate a public property for a child Private Sub GenerateNodeChildProperty(node As ParseNodeStructure, child As ParseNodeChild, childIndex As Integer) ' XML comment GenerateXmlComment(_writer, child, 8) Dim isToken = KindTypeStructure(child.ChildKind).IsToken _writer.WriteLine(" Friend {2}ReadOnly Property {0} As {1}", ChildPropertyName(child), ChildPropertyTypeRef(node, child, True), GetModifiers(child.ContainingStructure, False, child.Name)) _writer.WriteLine(" Get") If Not child.IsList Then _writer.WriteLine(" Return Me.{0}", ChildVarName(child)) ElseIf child.IsSeparated Then _writer.WriteLine(" Return new {0}(New Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList(of {1})(Me.{2}))", ChildPropertyTypeRef(node, child, True), BaseTypeReference(child), ChildVarName(child)) ElseIf KindTypeStructure(child.ChildKind).IsToken Then _writer.WriteLine(" Return New Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList(of GreenNode)(Me.{1})", BaseTypeReference(child), ChildVarName(child)) Else _writer.WriteLine(" Return new {0}(Me.{1})", ChildPropertyTypeRef(node, child, True), ChildVarName(child)) End If _writer.WriteLine(" End Get") _writer.WriteLine(" End Property") _writer.WriteLine("") End Sub ' Generate a public property for a child Private Sub GenerateNodeWithChildProperty(withChild As ParseNodeChild, childIndex As Integer, nodeStructure As ParseNodeStructure) Dim isOverride As Boolean = withChild.ContainingStructure IsNot nodeStructure If withChild.GenerateWith Then Dim isAbstract As Boolean = _parseTree.IsAbstract(nodeStructure) If Not isAbstract Then ' XML comment GenerateWithXmlComment(_writer, withChild, 8) _writer.WriteLine(" Friend {2}Function {0}({3} as {4}) As {1}", ChildWithFunctionName(withChild), StructureTypeName(withChild.ContainingStructure), GetModifiers(withChild.ContainingStructure, isOverride, withChild.Name), Ident(UpperFirstCharacter(withChild.Name)), ChildConstructorTypeRef(withChild)) _writer.WriteLine(" Ensures(Result(Of {0}) IsNot Nothing)", StructureTypeName(withChild.ContainingStructure)) _writer.Write(" return New {0}(", StructureTypeName(nodeStructure)) _writer.Write("Kind, Green.Errors") Dim allFields = GetAllFieldsOfStructure(nodeStructure) If allFields.Count > 0 Then For i = 0 To allFields.Count - 1 _writer.Write(", {0}", FieldParamName(allFields(i))) Next End If For Each child In nodeStructure.Children If child IsNot withChild Then _writer.Write(", {0}", ChildParamName(child)) Else _writer.Write(", {0}", Ident(UpperFirstCharacter(child.Name))) End If Next _writer.WriteLine(")") _writer.WriteLine(" End Function") ElseIf nodeStructure.Children.Contains(withChild) Then ' XML comment GenerateWithXmlComment(_writer, withChild, 8) _writer.WriteLine(" Friend {2} Function {0}({3} as {4}) As {1}", ChildWithFunctionName(withChild), StructureTypeName(withChild.ContainingStructure), "MustOverride", Ident(UpperFirstCharacter(withChild.Name)), ChildConstructorTypeRef(withChild)) End If _writer.WriteLine("") End If End Sub ' Generate public properties for a child that is a separated list Private Sub GenerateAccept(nodeStructure As ParseNodeStructure) If nodeStructure.ParentStructure IsNot Nothing AndAlso (_parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken OrElse nodeStructure.IsTrivia) Then Return End If _writer.WriteLine(" Public {0} Function Accept(ByVal visitor As {1}) As VisualBasicSyntaxNode", If(IsRoot(nodeStructure), "Overridable", "Overrides"), _parseTree.VisitorName) _writer.WriteLine(" Return visitor.{0}(Me)", VisitorMethodName(nodeStructure)) _writer.WriteLine(" End Function") _writer.WriteLine() End Sub ' Generate special methods and properties for the root node. These only appear in the root node. Private Sub GenerateRootNodeSpecialMethods(nodeStructure As ParseNodeStructure) _writer.WriteLine() End Sub ' Generate the Visitor class definition Private Sub GenerateVisitorClass() _writer.WriteLine(" Friend MustInherit Class {0}", Ident(_parseTree.VisitorName)) ' Basic Visit method that dispatches. _writer.WriteLine(" Public Overridable Function Visit(ByVal node As {0}) As VisualBasicSyntaxNode", StructureTypeName(_parseTree.RootStructure)) _writer.WriteLine(" If node IsNot Nothing") _writer.WriteLine(" Return node.Accept(Me)") _writer.WriteLine(" Else") _writer.WriteLine(" Return Nothing") _writer.WriteLine(" End If") _writer.WriteLine(" End Function") For Each nodeStructure In _parseTree.NodeStructures.Values GenerateVisitorMethod(nodeStructure) Next _writer.WriteLine(" End Class") _writer.WriteLine() End Sub ' Generate a method in the Visitor class Private Sub GenerateVisitorMethod(nodeStructure As ParseNodeStructure) If nodeStructure.IsToken OrElse nodeStructure.IsTrivia Then Return End If Dim methodName = VisitorMethodName(nodeStructure) Dim structureName = StructureTypeName(nodeStructure) _writer.WriteLine(" Public Overridable Function {0}(ByVal node As {1}) As VisualBasicSyntaxNode", methodName, structureName) _writer.WriteLine(" Debug.Assert(node IsNot Nothing)") If Not IsRoot(nodeStructure) Then _writer.WriteLine(" Return {0}(node)", VisitorMethodName(nodeStructure.ParentStructure)) Else _writer.WriteLine(" Return node") End If _writer.WriteLine(" End Function") End Sub ' Generate the RewriteVisitor class definition Private Sub GenerateRewriteVisitorClass() _writer.WriteLine(" Friend MustInherit Class {0}", Ident(_parseTree.RewriteVisitorName)) _writer.WriteLine(" Inherits {0}", Ident(_parseTree.VisitorName), StructureTypeName(_parseTree.RootStructure)) _writer.WriteLine() For Each nodeStructure In _parseTree.NodeStructures.Values GenerateRewriteVisitorMethod(nodeStructure) Next _writer.WriteLine(" End Class") _writer.WriteLine() End Sub ' Generate a method in the RewriteVisitor class Private Sub GenerateRewriteVisitorMethod(nodeStructure As ParseNodeStructure) If nodeStructure.IsToken OrElse nodeStructure.IsTrivia Then Return End If If nodeStructure.Abstract Then ' do nothing for abstract nodes Return End If Dim methodName = VisitorMethodName(nodeStructure) Dim structureName = StructureTypeName(nodeStructure) _writer.WriteLine(" Public Overrides Function {0}(ByVal node As {1}) As {2}", methodName, structureName, StructureTypeName(_parseTree.RootStructure)) ' non-abstract non-terminals need to rewrite their children and recreate as needed. Dim allFields = GetAllFieldsOfStructure(nodeStructure) Dim allChildren = GetAllChildrenOfStructure(nodeStructure) ' create anyChanges variable _writer.WriteLine(" Dim anyChanges As Boolean = False") _writer.WriteLine() ' visit all children For i = 0 To allChildren.Count - 1 If allChildren(i).IsList Then _writer.WriteLine(" Dim {0} = VisitList(node.{1})" + Environment.NewLine + " If node.{2} IsNot {0}.Node Then anyChanges = True", ChildNewVarName(allChildren(i)), ChildPropertyName(allChildren(i)), ChildVarName(allChildren(i))) ElseIf KindTypeStructure(allChildren(i).ChildKind).IsToken Then _writer.WriteLine(" Dim {0} = DirectCast(Visit(node.{2}), {1})" + Environment.NewLine + " If node.{3} IsNot {0} Then anyChanges = True", ChildNewVarName(allChildren(i)), BaseTypeReference(allChildren(i)), ChildPropertyName(allChildren(i)), ChildVarName(allChildren(i))) Else _writer.WriteLine(" Dim {0} = DirectCast(Visit(node.{2}), {1})" + Environment.NewLine + " If node.{2} IsNot {0} Then anyChanges = True", ChildNewVarName(allChildren(i)), ChildPropertyTypeRef(nodeStructure, allChildren(i)), ChildVarName(allChildren(i))) End If Next _writer.WriteLine() ' check if any changes. _writer.WriteLine(" If anyChanges Then") _writer.Write(" Return New {0}(node.Kind", StructureTypeName(nodeStructure)) _writer.Write(", node.GetDiagnostics, node.GetAnnotations") For Each field In allFields _writer.Write(", node.{0}", FieldPropertyName(field)) Next For Each child In allChildren If child.IsList Then _writer.Write(", {0}.Node", ChildNewVarName(child)) ElseIf KindTypeStructure(child.ChildKind).IsToken Then _writer.Write(", {0}", ChildNewVarName(child)) Else _writer.Write(", {0}", ChildNewVarName(child)) End If Next _writer.WriteLine(")") _writer.WriteLine(" Else") _writer.WriteLine(" Return node") _writer.WriteLine(" End If") _writer.WriteLine(" End Function") _writer.WriteLine() End Sub End Class
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. '----------------------------------------------------------------------------------------------------------- ' This is the code that actually outputs the VB code that defines the tree. It is passed a read and validated ' ParseTree, and outputs the code to defined the node classes for that tree, and also additional data ' structures like the kinds, visitor, etc. '----------------------------------------------------------------------------------------------------------- Imports System.IO ' Class to write out the code for the code tree. Friend Class GreenNodeWriter Inherits WriteUtils Private _writer As TextWriter 'output is sent here. Private ReadOnly _nonterminalsWithOneChild As List(Of String) = New List(Of String) Private ReadOnly _nonterminalsWithTwoChildren As List(Of String) = New List(Of String) ' Initialize the class with the parse tree to write. Public Sub New(parseTree As ParseTree) MyBase.New(parseTree) End Sub ' Write out the code defining the tree to the give file. Public Sub WriteTreeAsCode(writer As TextWriter) _writer = writer GenerateFile() End Sub Private Sub GenerateFile() GenerateNamespace() End Sub Private Sub GenerateNamespace() _writer.WriteLine() If Not String.IsNullOrEmpty(_parseTree.NamespaceName) Then _writer.WriteLine("Namespace {0}", Ident(_parseTree.NamespaceName) + ".Syntax.InternalSyntax") _writer.WriteLine() End If GenerateNodeStructures() If Not String.IsNullOrEmpty(_parseTree.VisitorName) Then GenerateVisitorClass() End If If Not String.IsNullOrEmpty(_parseTree.RewriteVisitorName) Then GenerateRewriteVisitorClass() End If If Not String.IsNullOrEmpty(_parseTree.NamespaceName) Then _writer.WriteLine("End Namespace") End If 'DumpNames("Nodes with One Child", _nonterminalsWithOneChild) 'DumpNames("Nodes with Two Children", _nonterminalsWithTwoChildren) End Sub Private Sub DumpNames(title As String, names As List(Of String)) Console.WriteLine(title) Console.WriteLine("=======================================") Dim sortedNames = From n In names Order By n For Each name In sortedNames Console.WriteLine(name) Next Console.WriteLine() End Sub Private Sub GenerateNodeStructures() For Each nodeStructure In _parseTree.NodeStructures.Values If Not nodeStructure.NoFactory Then GenerateNodeStructureClass(nodeStructure) End If Next End Sub ' Generate a constant value Private Function GetConstantValue(val As Long) As String Return val.ToString() End Function ' Generate a class declaration for a node structure. Private Sub GenerateNodeStructureClass(nodeStructure As ParseNodeStructure) ' XML comment GenerateXmlComment(_writer, nodeStructure, 4, includeRemarks:=False) ' Class name _writer.Write(" ") If (nodeStructure.PartialClass) Then _writer.Write("Partial ") End If Dim visibility As String = "Friend" If _parseTree.IsAbstract(nodeStructure) Then _writer.WriteLine("{0} MustInherit Class {1}", visibility, StructureTypeName(nodeStructure)) ElseIf Not nodeStructure.HasDerivedStructure Then _writer.WriteLine("{0} NotInheritable Class {1}", visibility, StructureTypeName(nodeStructure)) Else _writer.WriteLine("{0} Class {1}", visibility, StructureTypeName(nodeStructure)) End If ' Base class If Not IsRoot(nodeStructure) Then _writer.WriteLine(" Inherits {0}", StructureTypeName(nodeStructure.ParentStructure)) End If _writer.WriteLine() 'Create members GenerateNodeStructureMembers(nodeStructure) ' Create the constructor. GenerateNodeStructureConstructor(nodeStructure, False, noExtra:=True) GenerateNodeStructureConstructor(nodeStructure, False, noExtra:=True, contextual:=True) GenerateNodeStructureConstructor(nodeStructure, False) ' Serialization GenerateNodeStructureSerialization(nodeStructure) GenerateCreateRed(nodeStructure) ' Create the property accessor for each of the fields Dim fields = nodeStructure.Fields For i = 0 To fields.Count - 1 GenerateNodeFieldProperty(fields(i), i, fields(i).ContainingStructure IsNot nodeStructure) Next ' Create the property accessor for each of the children Dim children = nodeStructure.Children For i = 0 To children.Count - 1 GenerateNodeChildProperty(nodeStructure, children(i), i) GenerateNodeWithChildProperty(children(i), i, nodeStructure) Next If Not (_parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken) Then If children.Count = 1 Then If Not children(0).IsList AndAlso Not KindTypeStructure(children(0).ChildKind).Name = "ExpressionSyntax" Then _nonterminalsWithOneChild.Add(nodeStructure.Name) End If ElseIf children.Count = 2 Then If Not children(0).IsList AndAlso Not KindTypeStructure(children(0).ChildKind).Name = "ExpressionSyntax" AndAlso Not children(1).IsList AndAlso Not KindTypeStructure(children(1).ChildKind).Name = "ExpressionSyntax" Then _nonterminalsWithTwoChildren.Add(nodeStructure.Name) End If End If End If 'Create GetChild GenerateGetChild(nodeStructure) GenerateWithTrivia(nodeStructure) GenerateSetDiagnostics(nodeStructure) GenerateSetAnnotations(nodeStructure) ' Visitor accept method If Not String.IsNullOrEmpty(_parseTree.VisitorName) Then GenerateAccept(nodeStructure) End If 'GenerateUpdate(nodeStructure) ' Special methods for the root node. If IsRoot(nodeStructure) Then GenerateRootNodeSpecialMethods(nodeStructure) End If ' End the class _writer.WriteLine(" End Class") _writer.WriteLine() End Sub ' Generate CreateRed method Private Sub GenerateCreateRed(nodeStructure As ParseNodeStructure) If _parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken OrElse nodeStructure.IsTrivia Then Return End If _writer.WriteLine(" Friend Overrides Function CreateRed(ByVal parent As SyntaxNode, ByVal startLocation As Integer) As SyntaxNode") _writer.WriteLine(" Return new {0}.Syntax.{1}(Me, parent, startLocation)", _parseTree.NamespaceName, StructureTypeName(nodeStructure)) _writer.WriteLine(" End Function") _writer.WriteLine() End Sub ' Generate SetDiagnostics method Private Sub GenerateSetDiagnostics(nodeStructure As ParseNodeStructure) If _parseTree.IsAbstract(nodeStructure) Then Return End If _writer.WriteLine(" Friend Overrides Function SetDiagnostics(ByVal newErrors As DiagnosticInfo()) As GreenNode") _writer.Write(" Return new {0}", StructureTypeName(nodeStructure)) GenerateNodeStructureConstructorParameters(nodeStructure, "newErrors", "GetAnnotations", "GetLeadingTrivia", "GetTrailingTrivia") _writer.WriteLine(" End Function") _writer.WriteLine() End Sub ' Generate SetAnnotations method Private Sub GenerateSetAnnotations(nodeStructure As ParseNodeStructure) If _parseTree.IsAbstract(nodeStructure) Then Return End If _writer.WriteLine(" Friend Overrides Function SetAnnotations(ByVal annotations As SyntaxAnnotation()) As GreenNode") _writer.Write(" Return new {0}", StructureTypeName(nodeStructure)) GenerateNodeStructureConstructorParameters(nodeStructure, "GetDiagnostics", "annotations", "GetLeadingTrivia", "GetTrailingTrivia") _writer.WriteLine(" End Function") _writer.WriteLine() End Sub ' Generate Update method . But only for non terminals Private Sub GenerateUpdate(nodeStructure As ParseNodeStructure) If _parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken OrElse nodeStructure.IsTrivia Then Return End If Dim structureName = StructureTypeName(nodeStructure) Dim factory = FactoryName(nodeStructure) Dim needComma = False _writer.Write(" Friend ") If nodeStructure.ParentStructure IsNot Nothing AndAlso Not nodeStructure.ParentStructure.Abstract Then _writer.Write("Shadows ") End If _writer.Write("Function Update(") For Each child In GetAllChildrenOfStructure(nodeStructure) If needComma Then _writer.Write(", ") End If GenerateFactoryChildParameter(nodeStructure, child, Nothing, False) needComma = True Next _writer.WriteLine(") As {0}", structureName) needComma = False _writer.Write(" If ") For Each child In GetAllChildrenOfStructure(nodeStructure) If needComma Then _writer.Write(" OrElse ") End If If child.IsList OrElse KindTypeStructure(child.ChildKind).IsToken Then _writer.Write("{0}.Node IsNot Me.{1}", ChildParamName(child), ChildVarName(child)) Else _writer.Write("{0} IsNot Me.{1}", ChildParamName(child), ChildVarName(child)) End If needComma = True Next _writer.WriteLine(" Then") needComma = False _writer.Write(" Return SyntaxFactory.{0}(", factory) If nodeStructure.NodeKinds.Count >= 2 And Not _parseTree.NodeKinds.ContainsKey(FactoryName(nodeStructure)) Then _writer.Write("Me.Kind, ") End If For Each child In GetAllChildrenOfStructure(nodeStructure) If needComma Then _writer.Write(", ") End If _writer.Write("{0}", ChildParamName(child)) needComma = True Next _writer.WriteLine(")") _writer.WriteLine(" End If") _writer.WriteLine(" Return Me") _writer.WriteLine(" End Function") _writer.WriteLine() End Sub ' Generate WithTrivia method s Private Sub GenerateWithTrivia(nodeStructure As ParseNodeStructure) If _parseTree.IsAbstract(nodeStructure) OrElse Not nodeStructure.IsToken Then Return End If _writer.WriteLine(" Public Overrides Function WithLeadingTrivia(ByVal trivia As GreenNode) As GreenNode") _writer.Write(" Return new {0}", StructureTypeName(nodeStructure)) GenerateNodeStructureConstructorParameters(nodeStructure, "GetDiagnostics", "GetAnnotations", "trivia", "GetTrailingTrivia") _writer.WriteLine(" End Function") _writer.WriteLine() _writer.WriteLine(" Public Overrides Function WithTrailingTrivia(ByVal trivia As GreenNode) As GreenNode") _writer.Write(" Return new {0}", StructureTypeName(nodeStructure)) GenerateNodeStructureConstructorParameters(nodeStructure, "GetDiagnostics", "GetAnnotations", "GetLeadingTrivia", "trivia") _writer.WriteLine(" End Function") _writer.WriteLine() End Sub ' Generate GetChild, GetChildrenCount so members can be accessed by index Private Sub GenerateGetChild(nodeStructure As ParseNodeStructure) If _parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken Then Return End If Dim allChildren = GetAllChildrenOfStructure(nodeStructure) Dim childrenCount = allChildren.Count If childrenCount = 0 Then Return End If _writer.WriteLine(" Friend Overrides Function GetSlot(i as Integer) as GreenNode") ' Create the property accessor for each of the children Dim children = allChildren If childrenCount <> 1 Then _writer.WriteLine(" Select case i") For i = 0 To childrenCount - 1 _writer.WriteLine(" Case {0}", i) _writer.WriteLine(" Return Me.{0}", ChildVarName(children(i))) Next _writer.WriteLine(" Case Else") _writer.WriteLine(" Debug.Assert(false, ""child index out of range"")") _writer.WriteLine(" Return Nothing") _writer.WriteLine(" End Select") Else _writer.WriteLine(" If i = 0 Then") _writer.WriteLine(" Return Me.{0}", ChildVarName(children(0))) _writer.WriteLine(" Else") _writer.WriteLine(" Debug.Assert(false, ""child index out of range"")") _writer.WriteLine(" Return Nothing") _writer.WriteLine(" End If") End If _writer.WriteLine(" End Function") _writer.WriteLine() '_writer.WriteLine(" Friend Overrides ReadOnly Property SlotCount() As Integer") '_writer.WriteLine(" Get") '_writer.WriteLine(" Return {0}", childrenCount) '_writer.WriteLine(" End Get") '_writer.WriteLine(" End Property") _writer.WriteLine() End Sub ' Generate IsTerminal property. Private Sub GenerateIsTerminal(nodeStructure As ParseNodeStructure) _writer.WriteLine(" Friend Overrides ReadOnly Property IsTerminal As Boolean") _writer.WriteLine(" Get") _writer.WriteLine(" Return {0}", If(nodeStructure.IsTerminal, "True", "False")) _writer.WriteLine(" End Get") _writer.WriteLine(" End Property") _writer.WriteLine() End Sub Private Sub GenerateNodeStructureMembers(nodeStructure As ParseNodeStructure) Dim fields = nodeStructure.Fields For Each field In fields _writer.WriteLine(" Friend ReadOnly {0} as {1}", FieldVarName(field), FieldTypeRef(field)) Next Dim children = nodeStructure.Children For Each child In children _writer.WriteLine(" Friend ReadOnly {0} as {1}", ChildVarName(child), ChildFieldTypeRef(child, True)) Next _writer.WriteLine() End Sub Private Sub GenerateNodeStructureSerialization(nodeStructure As ParseNodeStructure) If nodeStructure.IsTokenRoot OrElse nodeStructure.IsTriviaRoot OrElse nodeStructure.IsPredefined OrElse nodeStructure.Name = "StructuredTriviaSyntax" Then Return End If _writer.WriteLine(" Friend Sub New(reader as ObjectReader)") _writer.WriteLine(" MyBase.New(reader)") If Not nodeStructure.Abstract Then Dim allChildren = GetAllChildrenOfStructure(nodeStructure) Dim childrenCount = allChildren.Count If childrenCount <> 0 Then _writer.WriteLine(" MyBase._slotCount = {0}", childrenCount) End If End If For Each child In nodeStructure.Children _writer.WriteLine(" Dim {0} = DirectCast(reader.ReadValue(), {1})", ChildVarName(child), ChildFieldTypeRef(child, isGreen:=True)) _writer.WriteLine(" If {0} isnot Nothing", ChildVarName(child)) _writer.WriteLine(" AdjustFlagsAndWidth({0})", ChildVarName(child)) _writer.WriteLine(" Me.{0} = {0}", ChildVarName(child)) _writer.WriteLine(" End If") Next For Each field In nodeStructure.Fields _writer.WriteLine(" Me.{0} = CType(reader.{1}(), {2})", FieldVarName(field), ReaderMethod(FieldTypeRef(field)), FieldTypeRef(field)) Next 'TODO: BLUE If StructureTypeName(nodeStructure) = "DirectiveTriviaSyntax" Then _writer.WriteLine(" SetFlags(NodeFlags.ContainsDirectives)") End If _writer.WriteLine(" End Sub") If Not nodeStructure.Abstract Then ' Friend Shared CreateInstance As Func(Of ObjectReader, Object) = Function(o) New BinaryExpressionSyntax(o) _writer.WriteLine(" Friend Shared CreateInstance As Func(Of ObjectReader, Object) = Function(o) New {0}(o)", StructureTypeName(nodeStructure)) _writer.WriteLine() End If If nodeStructure.Children.Count > 0 OrElse nodeStructure.Fields.Count > 0 Then _writer.WriteLine() _writer.WriteLine(" Friend Overrides Sub WriteTo(writer as ObjectWriter)") _writer.WriteLine(" MyBase.WriteTo(writer)") For Each child In nodeStructure.Children _writer.WriteLine(" writer.WriteValue(Me.{0})", ChildVarName(child)) Next For Each field In nodeStructure.Fields _writer.WriteLine(" writer.{0}(Me.{1})", WriterMethod(FieldTypeRef(field)), FieldVarName(field)) Next _writer.WriteLine(" End Sub") End If If Not _parseTree.IsAbstract(nodeStructure) Then _writer.WriteLine() _writer.WriteLine(" Shared Sub New()") _writer.WriteLine(" ObjectBinder.RegisterTypeReader(GetType({0}), Function(r) New {0}(r))", StructureTypeName(nodeStructure)) _writer.WriteLine(" End Sub") End If _writer.WriteLine() End Sub Private Function ReaderMethod(type As String) As String Select Case type Case "Integer", "SyntaxKind", "TypeCharacter" Return "ReadInt32" Case "Boolean" Return "ReadBoolean" Case Else Return "ReadValue" End Select End Function Private Function WriterMethod(type As String) As String Select Case type Case "Integer", "SyntaxKind", "TypeCharacter" Return "WriteInt32" Case "Boolean" Return "WriteBoolean" Case Else Return "WriteValue" End Select End Function ' Generate constructor for a node structure Private Sub GenerateNodeStructureConstructor(nodeStructure As ParseNodeStructure, isRaw As Boolean, Optional noExtra As Boolean = False, Optional contextual As Boolean = False) ' these constructors are hardcoded If nodeStructure.IsTokenRoot OrElse nodeStructure.IsTriviaRoot OrElse nodeStructure.Name = "StructuredTriviaSyntax" Then Return End If If nodeStructure.ParentStructure Is Nothing Then Return End If Dim allFields = GetAllFieldsOfStructure(nodeStructure) _writer.Write(" Friend Sub New(") ' Generate each of the field parameters _writer.Write("ByVal kind As {0}", NodeKindType()) If Not noExtra Then _writer.Write(", ByVal errors as DiagnosticInfo(), ByVal annotations as SyntaxAnnotation()", NodeKindType()) End If If nodeStructure.IsTerminal Then ' terminals have a text _writer.Write(", text as String") End If If nodeStructure.IsToken Then ' tokens have trivia _writer.Write(", leadingTrivia As GreenNode, trailingTrivia As GreenNode", StructureTypeName(_parseTree.RootStructure)) End If For Each field In allFields _writer.Write(", ") GenerateNodeStructureFieldParameter(field) Next For Each child In GetAllChildrenOfStructure(nodeStructure) _writer.Write(", ") GenerateNodeStructureChildParameter(child, Nothing, True) Next If contextual Then _writer.Write(", context As ISyntaxFactoryContext") End If _writer.WriteLine(")") ' Generate each of the field parameters _writer.Write(" MyBase.New(kind", NodeKindType()) If Not noExtra Then _writer.Write(", errors, annotations") End If If nodeStructure.IsToken AndAlso Not nodeStructure.IsTokenRoot Then ' nonterminals have text. _writer.Write(", text") If Not nodeStructure.IsTrivia Then ' tokens have trivia, but only if they are not trivia. _writer.Write(", leadingTrivia, trailingTrivia") End If End If Dim baseClass = nodeStructure.ParentStructure If baseClass IsNot Nothing Then For Each child In GetAllChildrenOfStructure(baseClass) _writer.Write(", {0}", ChildParamName(child)) Next End If _writer.WriteLine(")") If Not nodeStructure.Abstract Then Dim allChildren = GetAllChildrenOfStructure(nodeStructure) Dim childrenCount = allChildren.Count If childrenCount <> 0 Then _writer.WriteLine(" MyBase._slotCount = {0}", childrenCount) End If End If ' Generate code to initialize this class If contextual Then _writer.WriteLine(" Me.SetFactoryContext(context)") End If If allFields.Count > 0 Then For i = 0 To allFields.Count - 1 _writer.WriteLine(" Me.{0} = {1}", FieldVarName(allFields(i)), FieldParamName(allFields(i))) Next End If If nodeStructure.Children.Count > 0 Then '_writer.WriteLine(" Dim fullWidth as integer") _writer.WriteLine() For Each child In nodeStructure.Children Dim indent = "" If child.IsOptional OrElse child.IsList Then 'If endKeyword IsNot Nothing Then _writer.WriteLine(" If {0} IsNot Nothing Then", ChildParamName(child)) indent = " " End If '_writer.WriteLine("{0} fullWidth += {1}.FullWidth", indent, ChildParamName(child)) _writer.WriteLine("{0} AdjustFlagsAndWidth({1})", indent, ChildParamName(child)) _writer.WriteLine("{0} Me.{1} = {2}", indent, ChildVarName(child), ChildParamName(child)) If child.IsOptional OrElse child.IsList Then 'If endKeyword IsNot Nothing Then _writer.WriteLine(" End If", ChildParamName(child)) End If Next '_writer.WriteLine(" Me._fullWidth += fullWidth") _writer.WriteLine() End If 'TODO: BLUE If StructureTypeName(nodeStructure) = "DirectiveTriviaSyntax" Then _writer.WriteLine(" SetFlags(NodeFlags.ContainsDirectives)") End If ' Generate End Sub _writer.WriteLine(" End Sub") _writer.WriteLine() End Sub Private Sub GenerateNodeStructureConstructorParameters(nodeStructure As ParseNodeStructure, errorParam As String, annotationParam As String, precedingTriviaParam As String, followingTriviaParam As String) ' Generate each of the field parameters _writer.Write("(Me.Kind") _writer.Write(", {0}", errorParam) _writer.Write(", {0}", annotationParam) If nodeStructure.IsToken Then ' nonterminals have text. _writer.Write(", text") If Not nodeStructure.IsTrivia Then ' tokens have trivia, but only if they are not trivia. _writer.Write(", {0}, {1}", precedingTriviaParam, followingTriviaParam) End If ElseIf nodeStructure.IsTrivia AndAlso nodeStructure.IsTriviaRoot Then _writer.Write(", Me.Text") End If For Each field In GetAllFieldsOfStructure(nodeStructure) _writer.Write(", {0}", FieldVarName(field)) Next For Each child In GetAllChildrenOfStructure(nodeStructure) _writer.Write(", {0}", ChildVarName(child)) Next _writer.WriteLine(")") End Sub ' Generate a parameter corresponding to a node structure field Private Sub GenerateNodeStructureFieldParameter(field As ParseNodeField, Optional conflictName As String = Nothing) _writer.Write("{0} As {1}", FieldParamName(field, conflictName), FieldTypeRef(field)) End Sub ' Generate a parameter corresponding to a node structure child Private Sub GenerateNodeStructureChildParameter(child As ParseNodeChild, Optional conflictName As String = Nothing, Optional isGreen As Boolean = False) _writer.Write("{0} As {1}", ChildParamName(child, conflictName), ChildConstructorTypeRef(child, isGreen)) End Sub ' Generate a parameter corresponding to a node structure child Private Sub GenerateFactoryChildParameter(node As ParseNodeStructure, child As ParseNodeChild, Optional conflictName As String = Nothing, Optional internalForm As Boolean = False) _writer.Write("{0} As {1}", ChildParamName(child, conflictName), ChildFactoryTypeRef(node, child, True, internalForm)) End Sub ' Get modifiers Private Function GetModifiers(containingStructure As ParseNodeStructure, isOverride As Boolean, name As String) As String ' Is this overridable or an override? Dim modifiers = "" 'If isOverride Then ' modifiers = "Overrides " 'ElseIf containingStructure.HasDerivedStructure Then ' modifiers = "Overridable " 'End If ' Put Shadows modifier on if useful. ' Object has Equals and GetType ' root name has members for every kind and structure (factory methods) If (name = "Equals" OrElse name = "GetType") Then 'OrElse _parseTree.NodeKinds.ContainsKey(name) OrElse _parseTree.NodeStructures.ContainsKey(name)) Then modifiers = "Shadows " + modifiers End If Return modifiers End Function ' Generate a public property for a node field Private Sub GenerateNodeFieldProperty(field As ParseNodeField, fieldIndex As Integer, isOverride As Boolean) ' XML comment GenerateXmlComment(_writer, field, 8) _writer.WriteLine(" Friend {2}ReadOnly Property {0} As {1}", FieldPropertyName(field), FieldTypeRef(field), GetModifiers(field.ContainingStructure, isOverride, field.Name)) _writer.WriteLine(" Get") _writer.WriteLine(" Return Me.{0}", FieldVarName(field)) _writer.WriteLine(" End Get") _writer.WriteLine(" End Property") _writer.WriteLine("") End Sub ' Generate a public property for a child Private Sub GenerateNodeChildProperty(node As ParseNodeStructure, child As ParseNodeChild, childIndex As Integer) ' XML comment GenerateXmlComment(_writer, child, 8) Dim isToken = KindTypeStructure(child.ChildKind).IsToken _writer.WriteLine(" Friend {2}ReadOnly Property {0} As {1}", ChildPropertyName(child), ChildPropertyTypeRef(node, child, True), GetModifiers(child.ContainingStructure, False, child.Name)) _writer.WriteLine(" Get") If Not child.IsList Then _writer.WriteLine(" Return Me.{0}", ChildVarName(child)) ElseIf child.IsSeparated Then _writer.WriteLine(" Return new {0}(New Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList(of {1})(Me.{2}))", ChildPropertyTypeRef(node, child, True), BaseTypeReference(child), ChildVarName(child)) ElseIf KindTypeStructure(child.ChildKind).IsToken Then _writer.WriteLine(" Return New Microsoft.CodeAnalysis.Syntax.InternalSyntax.SyntaxList(of GreenNode)(Me.{1})", BaseTypeReference(child), ChildVarName(child)) Else _writer.WriteLine(" Return new {0}(Me.{1})", ChildPropertyTypeRef(node, child, True), ChildVarName(child)) End If _writer.WriteLine(" End Get") _writer.WriteLine(" End Property") _writer.WriteLine("") End Sub ' Generate a public property for a child Private Sub GenerateNodeWithChildProperty(withChild As ParseNodeChild, childIndex As Integer, nodeStructure As ParseNodeStructure) Dim isOverride As Boolean = withChild.ContainingStructure IsNot nodeStructure If withChild.GenerateWith Then Dim isAbstract As Boolean = _parseTree.IsAbstract(nodeStructure) If Not isAbstract Then ' XML comment GenerateWithXmlComment(_writer, withChild, 8) _writer.WriteLine(" Friend {2}Function {0}({3} as {4}) As {1}", ChildWithFunctionName(withChild), StructureTypeName(withChild.ContainingStructure), GetModifiers(withChild.ContainingStructure, isOverride, withChild.Name), Ident(UpperFirstCharacter(withChild.Name)), ChildConstructorTypeRef(withChild)) _writer.WriteLine(" Ensures(Result(Of {0}) IsNot Nothing)", StructureTypeName(withChild.ContainingStructure)) _writer.Write(" return New {0}(", StructureTypeName(nodeStructure)) _writer.Write("Kind, Green.Errors") Dim allFields = GetAllFieldsOfStructure(nodeStructure) If allFields.Count > 0 Then For i = 0 To allFields.Count - 1 _writer.Write(", {0}", FieldParamName(allFields(i))) Next End If For Each child In nodeStructure.Children If child IsNot withChild Then _writer.Write(", {0}", ChildParamName(child)) Else _writer.Write(", {0}", Ident(UpperFirstCharacter(child.Name))) End If Next _writer.WriteLine(")") _writer.WriteLine(" End Function") ElseIf nodeStructure.Children.Contains(withChild) Then ' XML comment GenerateWithXmlComment(_writer, withChild, 8) _writer.WriteLine(" Friend {2} Function {0}({3} as {4}) As {1}", ChildWithFunctionName(withChild), StructureTypeName(withChild.ContainingStructure), "MustOverride", Ident(UpperFirstCharacter(withChild.Name)), ChildConstructorTypeRef(withChild)) End If _writer.WriteLine("") End If End Sub ' Generate public properties for a child that is a separated list Private Sub GenerateAccept(nodeStructure As ParseNodeStructure) If nodeStructure.ParentStructure IsNot Nothing AndAlso (_parseTree.IsAbstract(nodeStructure) OrElse nodeStructure.IsToken OrElse nodeStructure.IsTrivia) Then Return End If _writer.WriteLine(" Public {0} Function Accept(ByVal visitor As {1}) As VisualBasicSyntaxNode", If(IsRoot(nodeStructure), "Overridable", "Overrides"), _parseTree.VisitorName) _writer.WriteLine(" Return visitor.{0}(Me)", VisitorMethodName(nodeStructure)) _writer.WriteLine(" End Function") _writer.WriteLine() End Sub ' Generate special methods and properties for the root node. These only appear in the root node. Private Sub GenerateRootNodeSpecialMethods(nodeStructure As ParseNodeStructure) _writer.WriteLine() End Sub ' Generate the Visitor class definition Private Sub GenerateVisitorClass() _writer.WriteLine(" Friend MustInherit Class {0}", Ident(_parseTree.VisitorName)) ' Basic Visit method that dispatches. _writer.WriteLine(" Public Overridable Function Visit(ByVal node As {0}) As VisualBasicSyntaxNode", StructureTypeName(_parseTree.RootStructure)) _writer.WriteLine(" If node IsNot Nothing") _writer.WriteLine(" Return node.Accept(Me)") _writer.WriteLine(" Else") _writer.WriteLine(" Return Nothing") _writer.WriteLine(" End If") _writer.WriteLine(" End Function") For Each nodeStructure In _parseTree.NodeStructures.Values GenerateVisitorMethod(nodeStructure) Next _writer.WriteLine(" End Class") _writer.WriteLine() End Sub ' Generate a method in the Visitor class Private Sub GenerateVisitorMethod(nodeStructure As ParseNodeStructure) If nodeStructure.IsToken OrElse nodeStructure.IsTrivia Then Return End If Dim methodName = VisitorMethodName(nodeStructure) Dim structureName = StructureTypeName(nodeStructure) _writer.WriteLine(" Public Overridable Function {0}(ByVal node As {1}) As VisualBasicSyntaxNode", methodName, structureName) _writer.WriteLine(" Debug.Assert(node IsNot Nothing)") If Not IsRoot(nodeStructure) Then _writer.WriteLine(" Return {0}(node)", VisitorMethodName(nodeStructure.ParentStructure)) Else _writer.WriteLine(" Return node") End If _writer.WriteLine(" End Function") End Sub ' Generate the RewriteVisitor class definition Private Sub GenerateRewriteVisitorClass() _writer.WriteLine(" Friend MustInherit Class {0}", Ident(_parseTree.RewriteVisitorName)) _writer.WriteLine(" Inherits {0}", Ident(_parseTree.VisitorName), StructureTypeName(_parseTree.RootStructure)) _writer.WriteLine() For Each nodeStructure In _parseTree.NodeStructures.Values GenerateRewriteVisitorMethod(nodeStructure) Next _writer.WriteLine(" End Class") _writer.WriteLine() End Sub ' Generate a method in the RewriteVisitor class Private Sub GenerateRewriteVisitorMethod(nodeStructure As ParseNodeStructure) If nodeStructure.IsToken OrElse nodeStructure.IsTrivia Then Return End If If nodeStructure.Abstract Then ' do nothing for abstract nodes Return End If Dim methodName = VisitorMethodName(nodeStructure) Dim structureName = StructureTypeName(nodeStructure) _writer.WriteLine(" Public Overrides Function {0}(ByVal node As {1}) As {2}", methodName, structureName, StructureTypeName(_parseTree.RootStructure)) ' non-abstract non-terminals need to rewrite their children and recreate as needed. Dim allFields = GetAllFieldsOfStructure(nodeStructure) Dim allChildren = GetAllChildrenOfStructure(nodeStructure) ' create anyChanges variable _writer.WriteLine(" Dim anyChanges As Boolean = False") _writer.WriteLine() ' visit all children For i = 0 To allChildren.Count - 1 If allChildren(i).IsList Then _writer.WriteLine(" Dim {0} = VisitList(node.{1})" + Environment.NewLine + " If node.{2} IsNot {0}.Node Then anyChanges = True", ChildNewVarName(allChildren(i)), ChildPropertyName(allChildren(i)), ChildVarName(allChildren(i))) ElseIf KindTypeStructure(allChildren(i).ChildKind).IsToken Then _writer.WriteLine(" Dim {0} = DirectCast(Visit(node.{2}), {1})" + Environment.NewLine + " If node.{3} IsNot {0} Then anyChanges = True", ChildNewVarName(allChildren(i)), BaseTypeReference(allChildren(i)), ChildPropertyName(allChildren(i)), ChildVarName(allChildren(i))) Else _writer.WriteLine(" Dim {0} = DirectCast(Visit(node.{2}), {1})" + Environment.NewLine + " If node.{2} IsNot {0} Then anyChanges = True", ChildNewVarName(allChildren(i)), ChildPropertyTypeRef(nodeStructure, allChildren(i)), ChildVarName(allChildren(i))) End If Next _writer.WriteLine() ' check if any changes. _writer.WriteLine(" If anyChanges Then") _writer.Write(" Return New {0}(node.Kind", StructureTypeName(nodeStructure)) _writer.Write(", node.GetDiagnostics, node.GetAnnotations") For Each field In allFields _writer.Write(", node.{0}", FieldPropertyName(field)) Next For Each child In allChildren If child.IsList Then _writer.Write(", {0}.Node", ChildNewVarName(child)) ElseIf KindTypeStructure(child.ChildKind).IsToken Then _writer.Write(", {0}", ChildNewVarName(child)) Else _writer.Write(", {0}", ChildNewVarName(child)) End If Next _writer.WriteLine(")") _writer.WriteLine(" Else") _writer.WriteLine(" Return node") _writer.WriteLine(" End If") _writer.WriteLine(" End Function") _writer.WriteLine() End Sub End Class
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Queries/DistinctKeywordRecommender.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Queries ''' <summary> ''' Recommends the "Distinct" query operator. ''' </summary> Friend Class DistinctKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("Distinct", VBFeaturesResources.Restricts_the_values_of_a_query_result_to_eliminate_duplicate_values)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, CancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) Return If(context.IsQueryOperatorContext, s_keywords, ImmutableArray(Of RecommendedKeyword).Empty) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Queries ''' <summary> ''' Recommends the "Distinct" query operator. ''' </summary> Friend Class DistinctKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("Distinct", VBFeaturesResources.Restricts_the_values_of_a_query_result_to_eliminate_duplicate_values)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, CancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) Return If(context.IsQueryOperatorContext, s_keywords, ImmutableArray(Of RecommendedKeyword).Empty) End Function End Class End Namespace
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/ExpressionEvaluator/Core/Source/ExpressionCompiler/DkmExceptionUtilities.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Debugging { internal static partial class DkmExceptionUtilities { internal const int COR_E_BADIMAGEFORMAT = unchecked((int)0x8007000b); internal const int CORDBG_E_MISSING_METADATA = unchecked((int)0x80131c35); internal static bool IsBadOrMissingMetadataException(Exception e) { return e is ObjectDisposedException || e.HResult == COR_E_BADIMAGEFORMAT || e.HResult == CORDBG_E_MISSING_METADATA; } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Debugging { internal static partial class DkmExceptionUtilities { internal const int COR_E_BADIMAGEFORMAT = unchecked((int)0x8007000b); internal const int CORDBG_E_MISSING_METADATA = unchecked((int)0x80131c35); internal static bool IsBadOrMissingMetadataException(Exception e) { return e is ObjectDisposedException || e.HResult == COR_E_BADIMAGEFORMAT || e.HResult == CORDBG_E_MISSING_METADATA; } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/Core/Portable/Text/LinePosition.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.Serialization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Text { /// <summary> /// Immutable representation of a line number and position within a SourceText instance. /// </summary> [DataContract] public readonly struct LinePosition : IEquatable<LinePosition>, IComparable<LinePosition> { /// <summary> /// A <see cref="LinePosition"/> that represents position 0 at line 0. /// </summary> public static LinePosition Zero => default(LinePosition); [DataMember(Order = 0)] private readonly int _line; [DataMember(Order = 1)] private readonly int _character; /// <summary> /// Initializes a new instance of a <see cref="LinePosition"/> with the given line and character. /// </summary> /// <param name="line"> /// The line of the line position. The first line in a file is defined as line 0 (zero based line numbering). /// </param> /// <param name="character"> /// The character position in the line. /// </param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="line"/> or <paramref name="character"/> is less than zero. </exception> public LinePosition(int line, int character) { if (line < 0) { throw new ArgumentOutOfRangeException(nameof(line)); } if (character < 0) { throw new ArgumentOutOfRangeException(nameof(character)); } _line = line; _character = character; } // internal constructor that supports a line number == -1. // VB allows users to specify a 1-based line number of 0 when processing // externalsource directives, which get decremented during conversion to 0-based line numbers. // in this case the line number can be -1. internal LinePosition(int character) { if (character < 0) { throw new ArgumentOutOfRangeException(nameof(character)); } _line = -1; _character = character; } /// <summary> /// The line number. The first line in a file is defined as line 0 (zero based line numbering). /// </summary> public int Line { get { return _line; } } /// <summary> /// The character position within the line. /// </summary> public int Character { get { return _character; } } /// <summary> /// Determines whether two <see cref="LinePosition"/> are the same. /// </summary> public static bool operator ==(LinePosition left, LinePosition right) { return left.Equals(right); } /// <summary> /// Determines whether two <see cref="LinePosition"/> are different. /// </summary> public static bool operator !=(LinePosition left, LinePosition right) { return !left.Equals(right); } /// <summary> /// Determines whether two <see cref="LinePosition"/> are the same. /// </summary> /// <param name="other">The object to compare.</param> public bool Equals(LinePosition other) { return other.Line == this.Line && other.Character == this.Character; } /// <summary> /// Determines whether two <see cref="LinePosition"/> are the same. /// </summary> /// <param name="obj">The object to compare.</param> public override bool Equals(object? obj) { return obj is LinePosition && Equals((LinePosition)obj); } /// <summary> /// Provides a hash function for <see cref="LinePosition"/>. /// </summary> public override int GetHashCode() { return Hash.Combine(Line, Character); } /// <summary> /// Provides a string representation for <see cref="LinePosition"/>. /// </summary> /// <example>0,10</example> public override string ToString() { return Line + "," + Character; } public int CompareTo(LinePosition other) { int result = _line.CompareTo(other._line); return (result != 0) ? result : _character.CompareTo(other.Character); } public static bool operator >(LinePosition left, LinePosition right) { return left.CompareTo(right) > 0; } public static bool operator >=(LinePosition left, LinePosition right) { return left.CompareTo(right) >= 0; } public static bool operator <(LinePosition left, LinePosition right) { return left.CompareTo(right) < 0; } public static bool operator <=(LinePosition left, LinePosition right) { return left.CompareTo(right) <= 0; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.Serialization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Text { /// <summary> /// Immutable representation of a line number and position within a SourceText instance. /// </summary> [DataContract] public readonly struct LinePosition : IEquatable<LinePosition>, IComparable<LinePosition> { /// <summary> /// A <see cref="LinePosition"/> that represents position 0 at line 0. /// </summary> public static LinePosition Zero => default(LinePosition); [DataMember(Order = 0)] private readonly int _line; [DataMember(Order = 1)] private readonly int _character; /// <summary> /// Initializes a new instance of a <see cref="LinePosition"/> with the given line and character. /// </summary> /// <param name="line"> /// The line of the line position. The first line in a file is defined as line 0 (zero based line numbering). /// </param> /// <param name="character"> /// The character position in the line. /// </param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="line"/> or <paramref name="character"/> is less than zero. </exception> public LinePosition(int line, int character) { if (line < 0) { throw new ArgumentOutOfRangeException(nameof(line)); } if (character < 0) { throw new ArgumentOutOfRangeException(nameof(character)); } _line = line; _character = character; } // internal constructor that supports a line number == -1. // VB allows users to specify a 1-based line number of 0 when processing // externalsource directives, which get decremented during conversion to 0-based line numbers. // in this case the line number can be -1. internal LinePosition(int character) { if (character < 0) { throw new ArgumentOutOfRangeException(nameof(character)); } _line = -1; _character = character; } /// <summary> /// The line number. The first line in a file is defined as line 0 (zero based line numbering). /// </summary> public int Line { get { return _line; } } /// <summary> /// The character position within the line. /// </summary> public int Character { get { return _character; } } /// <summary> /// Determines whether two <see cref="LinePosition"/> are the same. /// </summary> public static bool operator ==(LinePosition left, LinePosition right) { return left.Equals(right); } /// <summary> /// Determines whether two <see cref="LinePosition"/> are different. /// </summary> public static bool operator !=(LinePosition left, LinePosition right) { return !left.Equals(right); } /// <summary> /// Determines whether two <see cref="LinePosition"/> are the same. /// </summary> /// <param name="other">The object to compare.</param> public bool Equals(LinePosition other) { return other.Line == this.Line && other.Character == this.Character; } /// <summary> /// Determines whether two <see cref="LinePosition"/> are the same. /// </summary> /// <param name="obj">The object to compare.</param> public override bool Equals(object? obj) { return obj is LinePosition && Equals((LinePosition)obj); } /// <summary> /// Provides a hash function for <see cref="LinePosition"/>. /// </summary> public override int GetHashCode() { return Hash.Combine(Line, Character); } /// <summary> /// Provides a string representation for <see cref="LinePosition"/>. /// </summary> /// <example>0,10</example> public override string ToString() { return Line + "," + Character; } public int CompareTo(LinePosition other) { int result = _line.CompareTo(other._line); return (result != 0) ? result : _character.CompareTo(other.Character); } public static bool operator >(LinePosition left, LinePosition right) { return left.CompareTo(right) > 0; } public static bool operator >=(LinePosition left, LinePosition right) { return left.CompareTo(right) >= 0; } public static bool operator <(LinePosition left, LinePosition right) { return left.CompareTo(right) < 0; } public static bool operator <=(LinePosition left, LinePosition right) { return left.CompareTo(right) <= 0; } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/VisualBasic/Portable/Analysis/FlowAnalysis/EntryPointsWalker.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports System.Linq Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' A region analysis walker that records jumps into the region. Works by overriding NoteBranch, which is ''' invoked by a superclass when the two endpoints of a jump have been identified. ''' </summary> ''' <remarks></remarks> Friend Class EntryPointsWalker Inherits AbstractRegionControlFlowPass Friend Overloads Shared Function Analyze(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo, ByRef succeeded As Boolean?) As IEnumerable(Of LabelStatementSyntax) Dim walker = New EntryPointsWalker(info, region) Try succeeded = walker.Analyze() Return If(succeeded, walker._entryPoints, SpecializedCollections.EmptyEnumerable(Of LabelStatementSyntax)()) Finally walker.Free() End Try End Function Private ReadOnly _entryPoints As HashSet(Of LabelStatementSyntax) = New HashSet(Of LabelStatementSyntax)() Private Overloads Function Analyze() As Boolean ' We only need to scan in a single pass. Return Scan() End Function Private Sub New(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo) MyBase.New(info, region) End Sub Protected Overrides Sub Free() MyBase.Free() End Sub Protected Overrides Sub NoteBranch(pending As PendingBranch, stmt As BoundStatement, labelStmt As BoundLabelStatement) If stmt.Syntax IsNot Nothing AndAlso labelStmt.Syntax IsNot Nothing AndAlso IsInsideRegion(labelStmt.Syntax.Span) AndAlso Not IsInsideRegion(stmt.Syntax.Span) Then Select Case stmt.Kind Case BoundKind.GotoStatement _entryPoints.Add(DirectCast(labelStmt.Syntax, LabelStatementSyntax)) Case BoundKind.ReturnStatement ' Do nothing Case Else Throw ExceptionUtilities.UnexpectedValue(stmt.Kind) End Select End If End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports System.Linq Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' A region analysis walker that records jumps into the region. Works by overriding NoteBranch, which is ''' invoked by a superclass when the two endpoints of a jump have been identified. ''' </summary> ''' <remarks></remarks> Friend Class EntryPointsWalker Inherits AbstractRegionControlFlowPass Friend Overloads Shared Function Analyze(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo, ByRef succeeded As Boolean?) As IEnumerable(Of LabelStatementSyntax) Dim walker = New EntryPointsWalker(info, region) Try succeeded = walker.Analyze() Return If(succeeded, walker._entryPoints, SpecializedCollections.EmptyEnumerable(Of LabelStatementSyntax)()) Finally walker.Free() End Try End Function Private ReadOnly _entryPoints As HashSet(Of LabelStatementSyntax) = New HashSet(Of LabelStatementSyntax)() Private Overloads Function Analyze() As Boolean ' We only need to scan in a single pass. Return Scan() End Function Private Sub New(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo) MyBase.New(info, region) End Sub Protected Overrides Sub Free() MyBase.Free() End Sub Protected Overrides Sub NoteBranch(pending As PendingBranch, stmt As BoundStatement, labelStmt As BoundLabelStatement) If stmt.Syntax IsNot Nothing AndAlso labelStmt.Syntax IsNot Nothing AndAlso IsInsideRegion(labelStmt.Syntax.Span) AndAlso Not IsInsideRegion(stmt.Syntax.Span) Then Select Case stmt.Kind Case BoundKind.GotoStatement _entryPoints.Add(DirectCast(labelStmt.Syntax, LabelStatementSyntax)) Case BoundKind.ReturnStatement ' Do nothing Case Else Throw ExceptionUtilities.UnexpectedValue(stmt.Kind) End Select End If End Sub End Class End Namespace
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EmbeddedLanguages/Common/EmbeddedSyntaxTree.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.Common { internal abstract class EmbeddedSyntaxTree<TSyntaxKind, TSyntaxNode, TCompilationUnitSyntax> where TSyntaxKind : struct where TSyntaxNode : EmbeddedSyntaxNode<TSyntaxKind, TSyntaxNode> where TCompilationUnitSyntax : TSyntaxNode { public readonly VirtualCharSequence Text; public readonly TCompilationUnitSyntax Root; public readonly ImmutableArray<EmbeddedDiagnostic> Diagnostics; protected EmbeddedSyntaxTree( VirtualCharSequence text, TCompilationUnitSyntax root, ImmutableArray<EmbeddedDiagnostic> diagnostics) { Text = text; Root = root; Diagnostics = diagnostics; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.Common { internal abstract class EmbeddedSyntaxTree<TSyntaxKind, TSyntaxNode, TCompilationUnitSyntax> where TSyntaxKind : struct where TSyntaxNode : EmbeddedSyntaxNode<TSyntaxKind, TSyntaxNode> where TCompilationUnitSyntax : TSyntaxNode { public readonly VirtualCharSequence Text; public readonly TCompilationUnitSyntax Root; public readonly ImmutableArray<EmbeddedDiagnostic> Diagnostics; protected EmbeddedSyntaxTree( VirtualCharSequence text, TCompilationUnitSyntax root, ImmutableArray<EmbeddedDiagnostic> diagnostics) { Text = text; Root = root; Diagnostics = diagnostics; } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/Core/Portable/Symbols/IEventSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents an event. /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> public interface IEventSymbol : ISymbol { /// <summary> /// The type of the event. /// </summary> ITypeSymbol Type { get; } /// <summary> /// The top-level nullability of the event. /// </summary> NullableAnnotation NullableAnnotation { get; } /// <summary> /// Returns true if the event is a WinRT type event. /// </summary> bool IsWindowsRuntimeEvent { get; } /// <summary> /// The 'add' accessor of the event. Null only in error scenarios. /// </summary> IMethodSymbol? AddMethod { get; } /// <summary> /// The 'remove' accessor of the event. Null only in error scenarios. /// </summary> IMethodSymbol? RemoveMethod { get; } /// <summary> /// The 'raise' accessor of the event. Null if there is no raise method. /// </summary> IMethodSymbol? RaiseMethod { get; } /// <summary> /// The original definition of the event. If the event is constructed from another /// symbol by type substitution, OriginalDefinition gets the original symbol, as it was /// defined in source or metadata. /// </summary> new IEventSymbol OriginalDefinition { get; } /// <summary> /// Returns the overridden event, or null. /// </summary> IEventSymbol? OverriddenEvent { get; } /// <summary> /// Returns interface properties explicitly implemented by this event. /// </summary> /// <remarks> /// Properties imported from metadata can explicitly implement more than one event. /// </remarks> ImmutableArray<IEventSymbol> ExplicitInterfaceImplementations { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents an event. /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> public interface IEventSymbol : ISymbol { /// <summary> /// The type of the event. /// </summary> ITypeSymbol Type { get; } /// <summary> /// The top-level nullability of the event. /// </summary> NullableAnnotation NullableAnnotation { get; } /// <summary> /// Returns true if the event is a WinRT type event. /// </summary> bool IsWindowsRuntimeEvent { get; } /// <summary> /// The 'add' accessor of the event. Null only in error scenarios. /// </summary> IMethodSymbol? AddMethod { get; } /// <summary> /// The 'remove' accessor of the event. Null only in error scenarios. /// </summary> IMethodSymbol? RemoveMethod { get; } /// <summary> /// The 'raise' accessor of the event. Null if there is no raise method. /// </summary> IMethodSymbol? RaiseMethod { get; } /// <summary> /// The original definition of the event. If the event is constructed from another /// symbol by type substitution, OriginalDefinition gets the original symbol, as it was /// defined in source or metadata. /// </summary> new IEventSymbol OriginalDefinition { get; } /// <summary> /// Returns the overridden event, or null. /// </summary> IEventSymbol? OverriddenEvent { get; } /// <summary> /// Returns interface properties explicitly implemented by this event. /// </summary> /// <remarks> /// Properties imported from metadata can explicitly implement more than one event. /// </remarks> ImmutableArray<IEventSymbol> ExplicitInterfaceImplementations { get; } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Utilities/ImportsClauseComparer.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 ImportsClauseComparer Implements IComparer(Of ImportsClauseSyntax) Public Shared ReadOnly NormalInstance As IComparer(Of ImportsClauseSyntax) = New ImportsClauseComparer() Private ReadOnly _nameComparer As IComparer(Of NameSyntax) Private ReadOnly _tokenComparer As IComparer(Of SyntaxToken) Private Sub New() _nameComparer = NameSyntaxComparer.Create(TokenComparer.NormalInstance) _tokenComparer = TokenComparer.NormalInstance End Sub Public Sub New(tokenComparer As IComparer(Of SyntaxToken)) _nameComparer = NameSyntaxComparer.Create(tokenComparer) _tokenComparer = tokenComparer End Sub Friend Function Compare(x As ImportsClauseSyntax, y As ImportsClauseSyntax) As Integer Implements IComparer(Of ImportsClauseSyntax).Compare Dim imports1 = TryCast(x, SimpleImportsClauseSyntax) Dim imports2 = TryCast(y, SimpleImportsClauseSyntax) Dim xml1 = TryCast(x, XmlNamespaceImportsClauseSyntax) Dim xml2 = TryCast(y, XmlNamespaceImportsClauseSyntax) If xml1 IsNot Nothing AndAlso xml2 Is Nothing Then Return 1 ElseIf xml1 Is Nothing AndAlso xml2 IsNot Nothing Then Return -1 ElseIf xml1 IsNot Nothing AndAlso xml2 IsNot Nothing Then Return CompareXmlNames( DirectCast(xml1.XmlNamespace.Name, XmlNameSyntax), DirectCast(xml2.XmlNamespace.Name, XmlNameSyntax)) ElseIf imports1 IsNot Nothing AndAlso imports2 IsNot Nothing Then If imports1.Alias IsNot Nothing AndAlso imports2.Alias Is Nothing Then Return 1 ElseIf imports1.Alias Is Nothing AndAlso imports2.Alias IsNot Nothing Then Return -1 ElseIf imports1.Alias IsNot Nothing AndAlso imports2.Alias IsNot Nothing Then Return _tokenComparer.Compare(imports1.Alias.Identifier, imports2.Alias.Identifier) Else Return _nameComparer.Compare(imports1.Name, imports2.Name) End If End If Return 0 End Function Private Function CompareXmlNames(xmlName1 As XmlNameSyntax, xmlName2 As XmlNameSyntax) As Integer Dim tokens1 = xmlName1.DescendantTokens().Where(Function(t) t.Kind = SyntaxKind.IdentifierToken).ToList() Dim tokens2 = xmlName2.DescendantTokens().Where(Function(t) t.Kind = SyntaxKind.IdentifierToken).ToList() For i = 0 To Math.Min(tokens1.Count - 1, tokens2.Count - 1) Dim compare = _tokenComparer.Compare(tokens1(i), tokens2(i)) If compare <> 0 Then Return compare End If Next Return tokens1.Count - tokens2.Count 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 ImportsClauseComparer Implements IComparer(Of ImportsClauseSyntax) Public Shared ReadOnly NormalInstance As IComparer(Of ImportsClauseSyntax) = New ImportsClauseComparer() Private ReadOnly _nameComparer As IComparer(Of NameSyntax) Private ReadOnly _tokenComparer As IComparer(Of SyntaxToken) Private Sub New() _nameComparer = NameSyntaxComparer.Create(TokenComparer.NormalInstance) _tokenComparer = TokenComparer.NormalInstance End Sub Public Sub New(tokenComparer As IComparer(Of SyntaxToken)) _nameComparer = NameSyntaxComparer.Create(tokenComparer) _tokenComparer = tokenComparer End Sub Friend Function Compare(x As ImportsClauseSyntax, y As ImportsClauseSyntax) As Integer Implements IComparer(Of ImportsClauseSyntax).Compare Dim imports1 = TryCast(x, SimpleImportsClauseSyntax) Dim imports2 = TryCast(y, SimpleImportsClauseSyntax) Dim xml1 = TryCast(x, XmlNamespaceImportsClauseSyntax) Dim xml2 = TryCast(y, XmlNamespaceImportsClauseSyntax) If xml1 IsNot Nothing AndAlso xml2 Is Nothing Then Return 1 ElseIf xml1 Is Nothing AndAlso xml2 IsNot Nothing Then Return -1 ElseIf xml1 IsNot Nothing AndAlso xml2 IsNot Nothing Then Return CompareXmlNames( DirectCast(xml1.XmlNamespace.Name, XmlNameSyntax), DirectCast(xml2.XmlNamespace.Name, XmlNameSyntax)) ElseIf imports1 IsNot Nothing AndAlso imports2 IsNot Nothing Then If imports1.Alias IsNot Nothing AndAlso imports2.Alias Is Nothing Then Return 1 ElseIf imports1.Alias Is Nothing AndAlso imports2.Alias IsNot Nothing Then Return -1 ElseIf imports1.Alias IsNot Nothing AndAlso imports2.Alias IsNot Nothing Then Return _tokenComparer.Compare(imports1.Alias.Identifier, imports2.Alias.Identifier) Else Return _nameComparer.Compare(imports1.Name, imports2.Name) End If End If Return 0 End Function Private Function CompareXmlNames(xmlName1 As XmlNameSyntax, xmlName2 As XmlNameSyntax) As Integer Dim tokens1 = xmlName1.DescendantTokens().Where(Function(t) t.Kind = SyntaxKind.IdentifierToken).ToList() Dim tokens2 = xmlName2.DescendantTokens().Where(Function(t) t.Kind = SyntaxKind.IdentifierToken).ToList() For i = 0 To Math.Min(tokens1.Count - 1, tokens2.Count - 1) Dim compare = _tokenComparer.Compare(tokens1(i), tokens2(i)) If compare <> 0 Then Return compare End If Next Return tokens1.Count - tokens2.Count End Function End Class End Namespace
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpFormatting.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpFormatting : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; public CSharpFormatting(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpFormatting)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void AlignOpenBraceWithMethodDeclaration() { using (var telemetry = VisualStudio.EnableTestTelemetryChannel()) { SetUpEditor(@" $$class C { void Main() { } }"); VisualStudio.Editor.FormatDocument(); VisualStudio.Editor.Verify.TextContains(@" class C { void Main() { } }"); telemetry.VerifyFired("vs/ide/vbcs/commandhandler/formatcommand"); } } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatOnSemicolon() { SetUpEditor(@" public class C { void Goo() { var x = from a in new List<int>() where x % 2 = 0 select x ;$$ } }"); VisualStudio.Editor.SendKeys(VirtualKey.Backspace, ";"); VisualStudio.Editor.Verify.TextContains(@" public class C { void Goo() { var x = from a in new List<int>() where x % 2 = 0 select x; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatSelection() { SetUpEditor(@" public class C { public void M( ) {$$ } }"); VisualStudio.Editor.SelectTextInCurrentDocument("public void M( ) {"); VisualStudio.Editor.FormatSelection(); VisualStudio.Editor.Verify.TextContains(@" public class C { public void M() { } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void PasteCodeWithLambdaBody() { SetUpEditor(@" using System; class Program { static void Main() { Action a = () => { using (null) { $$ } }; } }"); VisualStudio.Editor.Paste(@" Action b = () => { };"); VisualStudio.Editor.Verify.TextContains(@" using System; class Program { static void Main() { Action a = () => { using (null) { Action b = () => { }; } }; } }"); // Undo should only undo the formatting VisualStudio.Editor.Undo(); VisualStudio.Editor.Verify.TextContains(@" using System; class Program { static void Main() { Action a = () => { using (null) { Action b = () => { }; } }; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void PasteCodeWithLambdaBody2() { SetUpEditor(@" using System; class Program { static void Main() { Action a = () => { using (null) { $$ } }; } }"); VisualStudio.Editor.Paste(@" Action<int> b = n => { Console.Writeline(n); };"); VisualStudio.Editor.Verify.TextContains(@" using System; class Program { static void Main() { Action a = () => { using (null) { Action<int> b = n => { Console.Writeline(n); }; } }; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void PasteCodeWithLambdaBody3() { SetUpEditor(@" using System; class Program { static void Main() { Action a = () => { using (null) { $$ } }; } }"); VisualStudio.Editor.Paste(@" D d = delegate(int x) { return 2 * x; };"); VisualStudio.Editor.Verify.TextContains(@" using System; class Program { static void Main() { Action a = () => { using (null) { D d = delegate (int x) { return 2 * x; }; } }; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void ShiftEnterWithIntelliSenseAndBraceMatching() { SetUpEditor(@" class Program { object M(object bar) { return M$$ } }"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); VisualStudio.Editor.SendKeys("(ba", new KeyPress(VirtualKey.Enter, ShiftState.Shift), "// comment"); VisualStudio.Editor.Verify.TextContains(@" class Program { object M(object bar) { return M(bar); // comment } }"); } [WpfFact] [Trait(Traits.Feature, Traits.Features.EditorConfig)] [Trait(Traits.Feature, Traits.Features.Formatting)] [WorkItem(15003, "https://github.com/dotnet/roslyn/issues/15003")] public void ApplyEditorConfigAndFormatDocument() { var markup = @" class C { public int X1 { get { $$return 3; } } }"; var expectedTextTwoSpaceIndent = @" class C { public int X1 { get { return 3; } } }"; VisualStudio.SolutionExplorer.OpenFile(new ProjectUtils.Project(ProjectName), "Class1.cs"); MarkupTestFile.GetSpans(markup, out var expectedTextFourSpaceIndent, out ImmutableArray<TextSpan> _); SetUpEditor(markup); /* * The first portion of this test verifies that Format Document uses the default indentation settings when * no .editorconfig is available. */ VisualStudio.Workspace.WaitForAllAsyncOperations( Helper.HangMitigatingTimeout, FeatureAttribute.Workspace, FeatureAttribute.SolutionCrawler, FeatureAttribute.DiagnosticService, FeatureAttribute.ErrorSquiggles); VisualStudio.Editor.FormatDocumentViaCommand(); Assert.Equal(expectedTextFourSpaceIndent, VisualStudio.Editor.GetText()); /* * The second portion of this test adds a .editorconfig file to configure the indentation behavior, and * verifies that the next Format Document operation adheres to the formatting. */ var editorConfig = @"root = true [*.cs] indent_size = 2 "; VisualStudio.SolutionExplorer.AddFile(new ProjectUtils.Project(ProjectName), ".editorconfig", editorConfig, open: false); VisualStudio.Workspace.WaitForAllAsyncOperations( Helper.HangMitigatingTimeout, FeatureAttribute.Workspace, FeatureAttribute.SolutionCrawler, FeatureAttribute.DiagnosticService, FeatureAttribute.ErrorSquiggles); VisualStudio.Editor.FormatDocumentViaCommand(); Assert.Equal(expectedTextTwoSpaceIndent, VisualStudio.Editor.GetText()); /* * The third portion of this test modifies the existing .editorconfig file with a new indentation behavior, * and verifies that the next Format Document operation adheres to the updated formatting. */ VisualStudio.SolutionExplorer.SetFileContents(new ProjectUtils.Project(ProjectName), ".editorconfig", editorConfig.Replace("2", "4")); VisualStudio.Workspace.WaitForAllAsyncOperations( Helper.HangMitigatingTimeout, FeatureAttribute.Workspace, FeatureAttribute.SolutionCrawler, FeatureAttribute.DiagnosticService, FeatureAttribute.ErrorSquiggles); VisualStudio.Editor.FormatDocumentViaCommand(); Assert.Equal(expectedTextFourSpaceIndent, VisualStudio.Editor.GetText()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpFormatting : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; public CSharpFormatting(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpFormatting)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void AlignOpenBraceWithMethodDeclaration() { using (var telemetry = VisualStudio.EnableTestTelemetryChannel()) { SetUpEditor(@" $$class C { void Main() { } }"); VisualStudio.Editor.FormatDocument(); VisualStudio.Editor.Verify.TextContains(@" class C { void Main() { } }"); telemetry.VerifyFired("vs/ide/vbcs/commandhandler/formatcommand"); } } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatOnSemicolon() { SetUpEditor(@" public class C { void Goo() { var x = from a in new List<int>() where x % 2 = 0 select x ;$$ } }"); VisualStudio.Editor.SendKeys(VirtualKey.Backspace, ";"); VisualStudio.Editor.Verify.TextContains(@" public class C { void Goo() { var x = from a in new List<int>() where x % 2 = 0 select x; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatSelection() { SetUpEditor(@" public class C { public void M( ) {$$ } }"); VisualStudio.Editor.SelectTextInCurrentDocument("public void M( ) {"); VisualStudio.Editor.FormatSelection(); VisualStudio.Editor.Verify.TextContains(@" public class C { public void M() { } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void PasteCodeWithLambdaBody() { SetUpEditor(@" using System; class Program { static void Main() { Action a = () => { using (null) { $$ } }; } }"); VisualStudio.Editor.Paste(@" Action b = () => { };"); VisualStudio.Editor.Verify.TextContains(@" using System; class Program { static void Main() { Action a = () => { using (null) { Action b = () => { }; } }; } }"); // Undo should only undo the formatting VisualStudio.Editor.Undo(); VisualStudio.Editor.Verify.TextContains(@" using System; class Program { static void Main() { Action a = () => { using (null) { Action b = () => { }; } }; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void PasteCodeWithLambdaBody2() { SetUpEditor(@" using System; class Program { static void Main() { Action a = () => { using (null) { $$ } }; } }"); VisualStudio.Editor.Paste(@" Action<int> b = n => { Console.Writeline(n); };"); VisualStudio.Editor.Verify.TextContains(@" using System; class Program { static void Main() { Action a = () => { using (null) { Action<int> b = n => { Console.Writeline(n); }; } }; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void PasteCodeWithLambdaBody3() { SetUpEditor(@" using System; class Program { static void Main() { Action a = () => { using (null) { $$ } }; } }"); VisualStudio.Editor.Paste(@" D d = delegate(int x) { return 2 * x; };"); VisualStudio.Editor.Verify.TextContains(@" using System; class Program { static void Main() { Action a = () => { using (null) { D d = delegate (int x) { return 2 * x; }; } }; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)] public void ShiftEnterWithIntelliSenseAndBraceMatching() { SetUpEditor(@" class Program { object M(object bar) { return M$$ } }"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); VisualStudio.Editor.SendKeys("(ba", new KeyPress(VirtualKey.Enter, ShiftState.Shift), "// comment"); VisualStudio.Editor.Verify.TextContains(@" class Program { object M(object bar) { return M(bar); // comment } }"); } [WpfFact] [Trait(Traits.Feature, Traits.Features.EditorConfig)] [Trait(Traits.Feature, Traits.Features.Formatting)] [WorkItem(15003, "https://github.com/dotnet/roslyn/issues/15003")] public void ApplyEditorConfigAndFormatDocument() { var markup = @" class C { public int X1 { get { $$return 3; } } }"; var expectedTextTwoSpaceIndent = @" class C { public int X1 { get { return 3; } } }"; VisualStudio.SolutionExplorer.OpenFile(new ProjectUtils.Project(ProjectName), "Class1.cs"); MarkupTestFile.GetSpans(markup, out var expectedTextFourSpaceIndent, out ImmutableArray<TextSpan> _); SetUpEditor(markup); /* * The first portion of this test verifies that Format Document uses the default indentation settings when * no .editorconfig is available. */ VisualStudio.Workspace.WaitForAllAsyncOperations( Helper.HangMitigatingTimeout, FeatureAttribute.Workspace, FeatureAttribute.SolutionCrawler, FeatureAttribute.DiagnosticService, FeatureAttribute.ErrorSquiggles); VisualStudio.Editor.FormatDocumentViaCommand(); Assert.Equal(expectedTextFourSpaceIndent, VisualStudio.Editor.GetText()); /* * The second portion of this test adds a .editorconfig file to configure the indentation behavior, and * verifies that the next Format Document operation adheres to the formatting. */ var editorConfig = @"root = true [*.cs] indent_size = 2 "; VisualStudio.SolutionExplorer.AddFile(new ProjectUtils.Project(ProjectName), ".editorconfig", editorConfig, open: false); VisualStudio.Workspace.WaitForAllAsyncOperations( Helper.HangMitigatingTimeout, FeatureAttribute.Workspace, FeatureAttribute.SolutionCrawler, FeatureAttribute.DiagnosticService, FeatureAttribute.ErrorSquiggles); VisualStudio.Editor.FormatDocumentViaCommand(); Assert.Equal(expectedTextTwoSpaceIndent, VisualStudio.Editor.GetText()); /* * The third portion of this test modifies the existing .editorconfig file with a new indentation behavior, * and verifies that the next Format Document operation adheres to the updated formatting. */ VisualStudio.SolutionExplorer.SetFileContents(new ProjectUtils.Project(ProjectName), ".editorconfig", editorConfig.Replace("2", "4")); VisualStudio.Workspace.WaitForAllAsyncOperations( Helper.HangMitigatingTimeout, FeatureAttribute.Workspace, FeatureAttribute.SolutionCrawler, FeatureAttribute.DiagnosticService, FeatureAttribute.ErrorSquiggles); VisualStudio.Editor.FormatDocumentViaCommand(); Assert.Equal(expectedTextFourSpaceIndent, VisualStudio.Editor.GetText()); } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_While.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.Diagnostics Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitWhileStatement(node As BoundWhileStatement) As BoundNode Dim generateUnstructuredExceptionHandlingResumeCode As Boolean = ShouldGenerateUnstructuredExceptionHandlingResumeCode(node) Dim loopResumeLabel As BoundLabelStatement = Nothing Dim conditionResumeTarget As ImmutableArray(Of BoundStatement) = Nothing If generateUnstructuredExceptionHandlingResumeCode Then loopResumeLabel = RegisterUnstructuredExceptionHandlingNonThrowingResumeTarget(node.Syntax) conditionResumeTarget = RegisterUnstructuredExceptionHandlingResumeTarget(node.Syntax, canThrow:=True) End If Dim rewrittenBody = DirectCast(Visit(node.Body), BoundStatement) Dim afterBodyResumeLabel As BoundLabelStatement = Nothing If generateUnstructuredExceptionHandlingResumeCode Then afterBodyResumeLabel = RegisterUnstructuredExceptionHandlingNonThrowingResumeTarget(node.Syntax) End If Return RewriteWhileStatement(node, VisitExpressionNode(node.Condition), rewrittenBody, node.ContinueLabel, node.ExitLabel, True, loopResumeLabel, conditionResumeTarget, afterBodyResumeLabel) End Function Protected Function RewriteWhileStatement( statement As BoundStatement, rewrittenCondition As BoundExpression, rewrittenBody As BoundStatement, continueLabel As LabelSymbol, exitLabel As LabelSymbol, Optional loopIfTrue As Boolean = True, Optional loopResumeLabelOpt As BoundLabelStatement = Nothing, Optional conditionResumeTargetOpt As ImmutableArray(Of BoundStatement) = Nothing, Optional afterBodyResumeTargetOpt As BoundStatement = Nothing ) As BoundNode Dim startLabel = GenerateLabel("start") Dim statementSyntax = statement.Syntax Dim instrument As Boolean = Me.Instrument(statement) If instrument Then Select Case statement.Kind Case BoundKind.WhileStatement afterBodyResumeTargetOpt = _instrumenterOpt.InstrumentWhileEpilogue(DirectCast(statement, BoundWhileStatement), afterBodyResumeTargetOpt) Case BoundKind.DoLoopStatement afterBodyResumeTargetOpt = _instrumenterOpt.InstrumentDoLoopEpilogue(DirectCast(statement, BoundDoLoopStatement), afterBodyResumeTargetOpt) Case BoundKind.ForEachStatement Case Else Throw ExceptionUtilities.UnexpectedValue(statement.Kind) End Select End If rewrittenBody = Concat(rewrittenBody, afterBodyResumeTargetOpt) ' EnC: We need to insert a hidden sequence point to handle function remapping in case ' the containing method is edited while methods invoked in the condition are being executed. If rewrittenCondition IsNot Nothing AndAlso instrument Then Select Case statement.Kind Case BoundKind.WhileStatement rewrittenCondition = _instrumenterOpt.InstrumentWhileStatementCondition(DirectCast(statement, BoundWhileStatement), rewrittenCondition, _currentMethodOrLambda) Case BoundKind.DoLoopStatement rewrittenCondition = _instrumenterOpt.InstrumentDoLoopStatementCondition(DirectCast(statement, BoundDoLoopStatement), rewrittenCondition, _currentMethodOrLambda) Case BoundKind.ForEachStatement rewrittenCondition = _instrumenterOpt.InstrumentForEachStatementCondition(DirectCast(statement, BoundForEachStatement), rewrittenCondition, _currentMethodOrLambda) Case Else Throw ExceptionUtilities.UnexpectedValue(statement.Kind) End Select End If Dim ifConditionGotoStart As BoundStatement = New BoundConditionalGoto( statementSyntax, rewrittenCondition, loopIfTrue, startLabel) If Not conditionResumeTargetOpt.IsDefaultOrEmpty Then ifConditionGotoStart = New BoundStatementList(ifConditionGotoStart.Syntax, conditionResumeTargetOpt.Add(ifConditionGotoStart)) End If If instrument Then Select Case statement.Kind Case BoundKind.WhileStatement ifConditionGotoStart = _instrumenterOpt.InstrumentWhileStatementConditionalGotoStart(DirectCast(statement, BoundWhileStatement), ifConditionGotoStart) Case BoundKind.DoLoopStatement ifConditionGotoStart = _instrumenterOpt.InstrumentDoLoopStatementEntryOrConditionalGotoStart(DirectCast(statement, BoundDoLoopStatement), ifConditionGotoStart) Case BoundKind.ForEachStatement ifConditionGotoStart = _instrumenterOpt.InstrumentForEachStatementConditionalGotoStart(DirectCast(statement, BoundForEachStatement), ifConditionGotoStart) Case Else Throw ExceptionUtilities.UnexpectedValue(statement.Kind) End Select End If ' While condition ' body ' End While ' ' becomes ' ' goto continue; ' start: ' body ' continue: ' {GotoIfTrue condition start} ' exit: 'mark the initial jump as hidden. 'We do not want to associate it with statement before. 'This jump may be a target of another jump (for example if loops are nested) and that will make 'impression of the previous statement being re-executed Dim gotoContinue As BoundStatement = New BoundGotoStatement(statementSyntax, continueLabel, Nothing) If loopResumeLabelOpt IsNot Nothing Then gotoContinue = Concat(loopResumeLabelOpt, gotoContinue) End If If instrument Then gotoContinue = SyntheticBoundNodeFactory.HiddenSequencePoint(gotoContinue) End If Return New BoundStatementList(statementSyntax, ImmutableArray.Create(Of BoundStatement)( gotoContinue, New BoundLabelStatement(statementSyntax, startLabel), rewrittenBody, New BoundLabelStatement(statementSyntax, continueLabel), ifConditionGotoStart, New BoundLabelStatement(statementSyntax, exitLabel) )) 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.Diagnostics Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitWhileStatement(node As BoundWhileStatement) As BoundNode Dim generateUnstructuredExceptionHandlingResumeCode As Boolean = ShouldGenerateUnstructuredExceptionHandlingResumeCode(node) Dim loopResumeLabel As BoundLabelStatement = Nothing Dim conditionResumeTarget As ImmutableArray(Of BoundStatement) = Nothing If generateUnstructuredExceptionHandlingResumeCode Then loopResumeLabel = RegisterUnstructuredExceptionHandlingNonThrowingResumeTarget(node.Syntax) conditionResumeTarget = RegisterUnstructuredExceptionHandlingResumeTarget(node.Syntax, canThrow:=True) End If Dim rewrittenBody = DirectCast(Visit(node.Body), BoundStatement) Dim afterBodyResumeLabel As BoundLabelStatement = Nothing If generateUnstructuredExceptionHandlingResumeCode Then afterBodyResumeLabel = RegisterUnstructuredExceptionHandlingNonThrowingResumeTarget(node.Syntax) End If Return RewriteWhileStatement(node, VisitExpressionNode(node.Condition), rewrittenBody, node.ContinueLabel, node.ExitLabel, True, loopResumeLabel, conditionResumeTarget, afterBodyResumeLabel) End Function Protected Function RewriteWhileStatement( statement As BoundStatement, rewrittenCondition As BoundExpression, rewrittenBody As BoundStatement, continueLabel As LabelSymbol, exitLabel As LabelSymbol, Optional loopIfTrue As Boolean = True, Optional loopResumeLabelOpt As BoundLabelStatement = Nothing, Optional conditionResumeTargetOpt As ImmutableArray(Of BoundStatement) = Nothing, Optional afterBodyResumeTargetOpt As BoundStatement = Nothing ) As BoundNode Dim startLabel = GenerateLabel("start") Dim statementSyntax = statement.Syntax Dim instrument As Boolean = Me.Instrument(statement) If instrument Then Select Case statement.Kind Case BoundKind.WhileStatement afterBodyResumeTargetOpt = _instrumenterOpt.InstrumentWhileEpilogue(DirectCast(statement, BoundWhileStatement), afterBodyResumeTargetOpt) Case BoundKind.DoLoopStatement afterBodyResumeTargetOpt = _instrumenterOpt.InstrumentDoLoopEpilogue(DirectCast(statement, BoundDoLoopStatement), afterBodyResumeTargetOpt) Case BoundKind.ForEachStatement Case Else Throw ExceptionUtilities.UnexpectedValue(statement.Kind) End Select End If rewrittenBody = Concat(rewrittenBody, afterBodyResumeTargetOpt) ' EnC: We need to insert a hidden sequence point to handle function remapping in case ' the containing method is edited while methods invoked in the condition are being executed. If rewrittenCondition IsNot Nothing AndAlso instrument Then Select Case statement.Kind Case BoundKind.WhileStatement rewrittenCondition = _instrumenterOpt.InstrumentWhileStatementCondition(DirectCast(statement, BoundWhileStatement), rewrittenCondition, _currentMethodOrLambda) Case BoundKind.DoLoopStatement rewrittenCondition = _instrumenterOpt.InstrumentDoLoopStatementCondition(DirectCast(statement, BoundDoLoopStatement), rewrittenCondition, _currentMethodOrLambda) Case BoundKind.ForEachStatement rewrittenCondition = _instrumenterOpt.InstrumentForEachStatementCondition(DirectCast(statement, BoundForEachStatement), rewrittenCondition, _currentMethodOrLambda) Case Else Throw ExceptionUtilities.UnexpectedValue(statement.Kind) End Select End If Dim ifConditionGotoStart As BoundStatement = New BoundConditionalGoto( statementSyntax, rewrittenCondition, loopIfTrue, startLabel) If Not conditionResumeTargetOpt.IsDefaultOrEmpty Then ifConditionGotoStart = New BoundStatementList(ifConditionGotoStart.Syntax, conditionResumeTargetOpt.Add(ifConditionGotoStart)) End If If instrument Then Select Case statement.Kind Case BoundKind.WhileStatement ifConditionGotoStart = _instrumenterOpt.InstrumentWhileStatementConditionalGotoStart(DirectCast(statement, BoundWhileStatement), ifConditionGotoStart) Case BoundKind.DoLoopStatement ifConditionGotoStart = _instrumenterOpt.InstrumentDoLoopStatementEntryOrConditionalGotoStart(DirectCast(statement, BoundDoLoopStatement), ifConditionGotoStart) Case BoundKind.ForEachStatement ifConditionGotoStart = _instrumenterOpt.InstrumentForEachStatementConditionalGotoStart(DirectCast(statement, BoundForEachStatement), ifConditionGotoStart) Case Else Throw ExceptionUtilities.UnexpectedValue(statement.Kind) End Select End If ' While condition ' body ' End While ' ' becomes ' ' goto continue; ' start: ' body ' continue: ' {GotoIfTrue condition start} ' exit: 'mark the initial jump as hidden. 'We do not want to associate it with statement before. 'This jump may be a target of another jump (for example if loops are nested) and that will make 'impression of the previous statement being re-executed Dim gotoContinue As BoundStatement = New BoundGotoStatement(statementSyntax, continueLabel, Nothing) If loopResumeLabelOpt IsNot Nothing Then gotoContinue = Concat(loopResumeLabelOpt, gotoContinue) End If If instrument Then gotoContinue = SyntheticBoundNodeFactory.HiddenSequencePoint(gotoContinue) End If Return New BoundStatementList(statementSyntax, ImmutableArray.Create(Of BoundStatement)( gotoContinue, New BoundLabelStatement(statementSyntax, startLabel), rewrittenBody, New BoundLabelStatement(statementSyntax, continueLabel), ifConditionGotoStart, New BoundLabelStatement(statementSyntax, exitLabel) )) End Function End Class End Namespace
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/VisualBasic/Portable/Binding/DocumentationCommentCrefBinder_TypeParameters.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 System.Runtime.InteropServices Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class DocumentationCommentCrefBinder Inherits DocumentationCommentBinder Private NotInheritable Class TypeParametersBinder Inherits Binder Friend ReadOnly _typeParameters As Dictionary(Of String, CrefTypeParameterSymbol) Public Sub New(containingBinder As Binder, typeParameters As Dictionary(Of String, CrefTypeParameterSymbol)) MyBase.New(containingBinder) Me._typeParameters = typeParameters End Sub Friend Overrides Sub LookupInSingleBinder(lookupResult As LookupResult, name As String, arity As Integer, options As LookupOptions, originalBinder As Binder, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(lookupResult.IsClear) Dim typeParameter As CrefTypeParameterSymbol = Nothing If Me._typeParameters.TryGetValue(name, typeParameter) Then lookupResult.SetFrom(CheckViability(typeParameter, arity, options Or LookupOptions.IgnoreAccessibility, Nothing, useSiteInfo)) End If End Sub Friend Overrides Sub AddLookupSymbolsInfoInSingleBinder(nameSet As LookupSymbolsInfo, options As LookupOptions, originalBinder As Binder) For Each typeParameter In _typeParameters.Values If originalBinder.CanAddLookupSymbolInfo(typeParameter, options, nameSet, Nothing) Then nameSet.AddSymbol(typeParameter, typeParameter.Name, 0) End If Next End Sub End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports System.Runtime.InteropServices Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class DocumentationCommentCrefBinder Inherits DocumentationCommentBinder Private NotInheritable Class TypeParametersBinder Inherits Binder Friend ReadOnly _typeParameters As Dictionary(Of String, CrefTypeParameterSymbol) Public Sub New(containingBinder As Binder, typeParameters As Dictionary(Of String, CrefTypeParameterSymbol)) MyBase.New(containingBinder) Me._typeParameters = typeParameters End Sub Friend Overrides Sub LookupInSingleBinder(lookupResult As LookupResult, name As String, arity As Integer, options As LookupOptions, originalBinder As Binder, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(lookupResult.IsClear) Dim typeParameter As CrefTypeParameterSymbol = Nothing If Me._typeParameters.TryGetValue(name, typeParameter) Then lookupResult.SetFrom(CheckViability(typeParameter, arity, options Or LookupOptions.IgnoreAccessibility, Nothing, useSiteInfo)) End If End Sub Friend Overrides Sub AddLookupSymbolsInfoInSingleBinder(nameSet As LookupSymbolsInfo, options As LookupOptions, originalBinder As Binder) For Each typeParameter In _typeParameters.Values If originalBinder.CanAddLookupSymbolInfo(typeParameter, options, nameSet, Nothing) Then nameSet.AddSymbol(typeParameter, typeParameter.Name, 0) End If Next End Sub End Class End Class End Namespace
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/EditorFeatures/Core/Undo/ISourceTextUndoTransaction.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.Undo { /// <summary> /// Represents undo transaction for a <see cref="Microsoft.CodeAnalysis.Text.SourceText"/> /// with a display string by which the IDE's undo stack UI refers to the transaction. /// </summary> internal interface ISourceTextUndoTransaction : IDisposable { /// <summary> /// The <see cref="Microsoft.CodeAnalysis.Text.SourceText"/> for this undo transaction. /// </summary> SourceText SourceText { get; } /// <summary> /// The display string by which the IDE's undo stack UI refers to the transaction. /// </summary> string Description { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.Undo { /// <summary> /// Represents undo transaction for a <see cref="Microsoft.CodeAnalysis.Text.SourceText"/> /// with a display string by which the IDE's undo stack UI refers to the transaction. /// </summary> internal interface ISourceTextUndoTransaction : IDisposable { /// <summary> /// The <see cref="Microsoft.CodeAnalysis.Text.SourceText"/> for this undo transaction. /// </summary> SourceText SourceText { get; } /// <summary> /// The display string by which the IDE's undo stack UI refers to the transaction. /// </summary> string Description { get; } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/VisualStudio/Core/Def/Implementation/Venus/VenusCommandFilter`2.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.Editor; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus { [Obsolete("This is a compatibility shim for LiveShare and TypeScript; please do not use it.")] internal class VenusCommandFilter<TPackage, TLanguageService> : VenusCommandFilter where TPackage : AbstractPackage<TPackage, TLanguageService> where TLanguageService : AbstractLanguageService<TPackage, TLanguageService> { [Obsolete("This is a compatibility shim for TypeScript; please do not use it.")] public VenusCommandFilter( TLanguageService languageService, IWpfTextView wpfTextView, ICommandHandlerServiceFactory commandHandlerServiceFactory, ITextBuffer subjectBuffer, IOleCommandTarget nextCommandTarget, IVsEditorAdaptersFactoryService editorAdaptersFactoryService) : base(wpfTextView, subjectBuffer, nextCommandTarget, languageService.Package.ComponentModel) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.Editor; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus { [Obsolete("This is a compatibility shim for LiveShare and TypeScript; please do not use it.")] internal class VenusCommandFilter<TPackage, TLanguageService> : VenusCommandFilter where TPackage : AbstractPackage<TPackage, TLanguageService> where TLanguageService : AbstractLanguageService<TPackage, TLanguageService> { [Obsolete("This is a compatibility shim for TypeScript; please do not use it.")] public VenusCommandFilter( TLanguageService languageService, IWpfTextView wpfTextView, ICommandHandlerServiceFactory commandHandlerServiceFactory, ITextBuffer subjectBuffer, IOleCommandTarget nextCommandTarget, IVsEditorAdaptersFactoryService editorAdaptersFactoryService) : base(wpfTextView, subjectBuffer, nextCommandTarget, languageService.Package.ComponentModel) { } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Extensions/NameSyntaxExtensions.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions Friend Module NameSyntaxExtensions <Extension()> Public Function GetNameParts(nameSyntax As NameSyntax) As IList(Of NameSyntax) Return New NameSyntaxIterator(nameSyntax).ToList() End Function <Extension()> Public Function GetLastDottedName(nameSyntax As NameSyntax) As NameSyntax Dim parts = nameSyntax.GetNameParts() Return parts(parts.Count - 1) End Function <Extension> Public Function CanBeReplacedWithAnyName(nameSyntax As NameSyntax) As Boolean If nameSyntax.CheckParent(Of SimpleArgumentSyntax)(Function(a) a.IsNamed AndAlso a.NameColonEquals.Name Is nameSyntax) OrElse nameSyntax.CheckParent(Of HandlesClauseItemSyntax)(Function(h) h.EventMember Is nameSyntax) OrElse nameSyntax.CheckParent(Of InferredFieldInitializerSyntax)(Function(i) i.Expression Is nameSyntax) OrElse nameSyntax.CheckParent(Of NamedFieldInitializerSyntax)(Function(n) n.Name Is nameSyntax) OrElse nameSyntax.CheckParent(Of CatchStatementSyntax)(Function(c) c.IdentifierName Is nameSyntax) OrElse nameSyntax.CheckParent(Of RaiseEventStatementSyntax)(Function(r) r.Name Is nameSyntax) OrElse nameSyntax.CheckParent(Of QualifiedNameSyntax)(Function(q) q.Right Is nameSyntax) OrElse nameSyntax.CheckParent(Of MemberAccessExpressionSyntax)(Function(m) m.Name Is nameSyntax) Then Return False End If ' TODO(cyrusn): Add cases as appropriate as the language changes. Return True End Function End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions Friend Module NameSyntaxExtensions <Extension()> Public Function GetNameParts(nameSyntax As NameSyntax) As IList(Of NameSyntax) Return New NameSyntaxIterator(nameSyntax).ToList() End Function <Extension()> Public Function GetLastDottedName(nameSyntax As NameSyntax) As NameSyntax Dim parts = nameSyntax.GetNameParts() Return parts(parts.Count - 1) End Function <Extension> Public Function CanBeReplacedWithAnyName(nameSyntax As NameSyntax) As Boolean If nameSyntax.CheckParent(Of SimpleArgumentSyntax)(Function(a) a.IsNamed AndAlso a.NameColonEquals.Name Is nameSyntax) OrElse nameSyntax.CheckParent(Of HandlesClauseItemSyntax)(Function(h) h.EventMember Is nameSyntax) OrElse nameSyntax.CheckParent(Of InferredFieldInitializerSyntax)(Function(i) i.Expression Is nameSyntax) OrElse nameSyntax.CheckParent(Of NamedFieldInitializerSyntax)(Function(n) n.Name Is nameSyntax) OrElse nameSyntax.CheckParent(Of CatchStatementSyntax)(Function(c) c.IdentifierName Is nameSyntax) OrElse nameSyntax.CheckParent(Of RaiseEventStatementSyntax)(Function(r) r.Name Is nameSyntax) OrElse nameSyntax.CheckParent(Of QualifiedNameSyntax)(Function(q) q.Right Is nameSyntax) OrElse nameSyntax.CheckParent(Of MemberAccessExpressionSyntax)(Function(m) m.Name Is nameSyntax) Then Return False End If ' TODO(cyrusn): Add cases as appropriate as the language changes. Return True End Function End Module End Namespace
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Tools/ExternalAccess/Razor/Remote/RazorRemoteServiceCallbackIdWrapper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.Serialization; using Microsoft.CodeAnalysis.Remote; namespace Microsoft.CodeAnalysis.ExternalAccess.Razor { [DataContract] internal readonly struct RazorRemoteServiceCallbackIdWrapper { [DataMember(Order = 0)] internal RemoteServiceCallbackId UnderlyingObject { get; } public RazorRemoteServiceCallbackIdWrapper(RemoteServiceCallbackId underlyingObject) => UnderlyingObject = underlyingObject; public static implicit operator RazorRemoteServiceCallbackIdWrapper(RemoteServiceCallbackId id) => new(id); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.Serialization; using Microsoft.CodeAnalysis.Remote; namespace Microsoft.CodeAnalysis.ExternalAccess.Razor { [DataContract] internal readonly struct RazorRemoteServiceCallbackIdWrapper { [DataMember(Order = 0)] internal RemoteServiceCallbackId UnderlyingObject { get; } public RazorRemoteServiceCallbackIdWrapper(RemoteServiceCallbackId underlyingObject) => UnderlyingObject = underlyingObject; public static implicit operator RazorRemoteServiceCallbackIdWrapper(RemoteServiceCallbackId id) => new(id); } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/ExpressionEvaluator/CSharp/Source/ResultProvider/Helpers/Placeholders.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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; namespace Microsoft.CodeAnalysis { internal static class GreenNode { /// <summary> /// Required by <see cref="SyntaxKind"/>. /// </summary> public const int ListKind = 1; } } // This needs to be re-defined here to avoid ambiguity, because we allow this project to target .NET 4.0 on machines without 2.0 installed. namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal class ExtensionAttribute : Attribute { } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis { internal static class GreenNode { /// <summary> /// Required by <see cref="SyntaxKind"/>. /// </summary> public const int ListKind = 1; } } // This needs to be re-defined here to avoid ambiguity, because we allow this project to target .NET 4.0 on machines without 2.0 installed. namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal class ExtensionAttribute : Attribute { } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Features/Core/Portable/Shared/Utilities/ExtractTypeHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal static class ExtractTypeHelpers { public static async Task<(Document containingDocument, SyntaxAnnotation typeAnnotation)> AddTypeToExistingFileAsync(Document document, INamedTypeSymbol newType, AnnotatedSymbolMapping symbolMapping, CancellationToken cancellationToken) { var originalRoot = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var typeDeclaration = originalRoot.GetAnnotatedNodes(symbolMapping.TypeNodeAnnotation).Single(); var editor = new SyntaxEditor(originalRoot, symbolMapping.AnnotatedSolution.Workspace); var options = new CodeGenerationOptions( generateMethodBodies: true, options: await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false)); var codeGenService = document.GetRequiredLanguageService<ICodeGenerationService>(); var newTypeNode = codeGenService.CreateNamedTypeDeclaration(newType, options: options, cancellationToken: cancellationToken) .WithAdditionalAnnotations(SimplificationHelpers.SimplifyModuleNameAnnotation); var typeAnnotation = new SyntaxAnnotation(); newTypeNode = newTypeNode.WithAdditionalAnnotations(typeAnnotation); editor.InsertBefore(typeDeclaration, newTypeNode); var newDocument = document.WithSyntaxRoot(editor.GetChangedRoot()); return (newDocument, typeAnnotation); } public static async Task<(Document containingDocument, SyntaxAnnotation typeAnnotation)> AddTypeToNewFileAsync( Solution solution, string containingNamespaceDisplay, string fileName, ProjectId projectId, IEnumerable<string> folders, INamedTypeSymbol newSymbol, Document hintDocument, CancellationToken cancellationToken) { var newDocumentId = DocumentId.CreateNewId(projectId, debugName: fileName); var newDocumentPath = PathUtilities.CombinePaths(PathUtilities.GetDirectoryName(hintDocument.FilePath), fileName); var solutionWithInterfaceDocument = solution.AddDocument(newDocumentId, fileName, text: "", folders: folders, filePath: newDocumentPath); var newDocument = solutionWithInterfaceDocument.GetRequiredDocument(newDocumentId); var newSemanticModel = await newDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var options = new CodeGenerationOptions( contextLocation: newSemanticModel.SyntaxTree.GetLocation(new TextSpan()), generateMethodBodies: true, options: await newDocument.GetOptionsAsync(cancellationToken).ConfigureAwait(false)); var namespaceParts = containingNamespaceDisplay.Split('.').Where(s => !string.IsNullOrEmpty(s)); var newTypeDocument = await CodeGenerator.AddNamespaceOrTypeDeclarationAsync( newDocument.Project.Solution, newSemanticModel.GetEnclosingNamespace(0, cancellationToken), newSymbol.GenerateRootNamespaceOrType(namespaceParts.ToArray()), options: options, cancellationToken: cancellationToken).ConfigureAwait(false); var formattingSerivce = newTypeDocument.GetLanguageService<INewDocumentFormattingService>(); if (formattingSerivce is not null) { newTypeDocument = await formattingSerivce.FormatNewDocumentAsync(newTypeDocument, hintDocument, cancellationToken).ConfigureAwait(false); } var syntaxRoot = await newTypeDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var typeAnnotation = new SyntaxAnnotation(); var syntaxFacts = newTypeDocument.GetRequiredLanguageService<ISyntaxFactsService>(); var declarationNode = syntaxRoot.DescendantNodes().First(syntaxFacts.IsTypeDeclaration); var annotatedRoot = syntaxRoot.ReplaceNode(declarationNode, declarationNode.WithAdditionalAnnotations(typeAnnotation)); newTypeDocument = newTypeDocument.WithSyntaxRoot(annotatedRoot); var simplified = await Simplifier.ReduceAsync(newTypeDocument, cancellationToken: cancellationToken).ConfigureAwait(false); var formattedDocument = await Formatter.FormatAsync(simplified, cancellationToken: cancellationToken).ConfigureAwait(false); return (formattedDocument, typeAnnotation); } public static string GetTypeParameterSuffix(Document document, INamedTypeSymbol type, IEnumerable<ISymbol> extractableMembers) { var typeParameters = GetRequiredTypeParametersForMembers(type, extractableMembers); if (type.TypeParameters.Length == 0) { return string.Empty; } var typeParameterNames = typeParameters.SelectAsArray(p => p.Name); var syntaxGenerator = SyntaxGenerator.GetGenerator(document); return Formatter.Format(syntaxGenerator.SyntaxGeneratorInternal.TypeParameterList(typeParameterNames), document.Project.Solution.Workspace).ToString(); } public static ImmutableArray<ITypeParameterSymbol> GetRequiredTypeParametersForMembers(INamedTypeSymbol type, IEnumerable<ISymbol> includedMembers) { var potentialTypeParameters = GetPotentialTypeParameters(type); var directlyReferencedTypeParameters = GetDirectlyReferencedTypeParameters(potentialTypeParameters, includedMembers); // The directly referenced TypeParameters may have constraints that reference other // type parameters. var allReferencedTypeParameters = new HashSet<ITypeParameterSymbol>(directlyReferencedTypeParameters); var unanalyzedTypeParameters = new Queue<ITypeParameterSymbol>(directlyReferencedTypeParameters); while (!unanalyzedTypeParameters.IsEmpty()) { var typeParameter = unanalyzedTypeParameters.Dequeue(); foreach (var constraint in typeParameter.ConstraintTypes) { foreach (var originalTypeParameter in potentialTypeParameters) { if (!allReferencedTypeParameters.Contains(originalTypeParameter) && DoesTypeReferenceTypeParameter(constraint, originalTypeParameter, new HashSet<ITypeSymbol>())) { allReferencedTypeParameters.Add(originalTypeParameter); unanalyzedTypeParameters.Enqueue(originalTypeParameter); } } } } return potentialTypeParameters.WhereAsArray(allReferencedTypeParameters.Contains); } private static ImmutableArray<ITypeParameterSymbol> GetPotentialTypeParameters(INamedTypeSymbol type) { using var _ = ArrayBuilder<ITypeParameterSymbol>.GetInstance(out var typeParameters); var typesToVisit = new Stack<INamedTypeSymbol>(); var currentType = type; while (currentType != null) { typesToVisit.Push(currentType); currentType = currentType.ContainingType; } while (typesToVisit.Any()) { typeParameters.AddRange(typesToVisit.Pop().TypeParameters); } return typeParameters.ToImmutable(); } private static ImmutableArray<ITypeParameterSymbol> GetDirectlyReferencedTypeParameters(IEnumerable<ITypeParameterSymbol> potentialTypeParameters, IEnumerable<ISymbol> includedMembers) { using var _ = ArrayBuilder<ITypeParameterSymbol>.GetInstance(out var directlyReferencedTypeParameters); foreach (var typeParameter in potentialTypeParameters) { if (includedMembers.Any(m => DoesMemberReferenceTypeParameter(m, typeParameter, new HashSet<ITypeSymbol>()))) { directlyReferencedTypeParameters.Add(typeParameter); } } return directlyReferencedTypeParameters.ToImmutable(); } private static bool DoesMemberReferenceTypeParameter(ISymbol member, ITypeParameterSymbol typeParameter, HashSet<ITypeSymbol> checkedTypes) { switch (member.Kind) { case SymbolKind.Event: var @event = member as IEventSymbol; return DoesTypeReferenceTypeParameter(@event.Type, typeParameter, checkedTypes); case SymbolKind.Method: var method = member as IMethodSymbol; return method.Parameters.Any(t => DoesTypeReferenceTypeParameter(t.Type, typeParameter, checkedTypes)) || method.TypeParameters.Any(t => t.ConstraintTypes.Any(c => DoesTypeReferenceTypeParameter(c, typeParameter, checkedTypes))) || DoesTypeReferenceTypeParameter(method.ReturnType, typeParameter, checkedTypes); case SymbolKind.Property: var property = member as IPropertySymbol; return property.Parameters.Any(t => DoesTypeReferenceTypeParameter(t.Type, typeParameter, checkedTypes)) || DoesTypeReferenceTypeParameter(property.Type, typeParameter, checkedTypes); default: Debug.Assert(false, string.Format(FeaturesResources.Unexpected_interface_member_kind_colon_0, member.Kind.ToString())); return false; } } private static bool DoesTypeReferenceTypeParameter(ITypeSymbol type, ITypeParameterSymbol typeParameter, HashSet<ITypeSymbol> checkedTypes) { if (!checkedTypes.Add(type)) { return false; } // We want to ignore nullability when comparing as T and T? both are references to the type parameter if (type.Equals(typeParameter, SymbolEqualityComparer.Default) || type.GetTypeArguments().Any(t => DoesTypeReferenceTypeParameter(t, typeParameter, checkedTypes))) { return true; } if (type.ContainingType != null && type.Kind != SymbolKind.TypeParameter && DoesTypeReferenceTypeParameter(type.ContainingType, typeParameter, checkedTypes)) { return true; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal static class ExtractTypeHelpers { public static async Task<(Document containingDocument, SyntaxAnnotation typeAnnotation)> AddTypeToExistingFileAsync(Document document, INamedTypeSymbol newType, AnnotatedSymbolMapping symbolMapping, CancellationToken cancellationToken) { var originalRoot = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var typeDeclaration = originalRoot.GetAnnotatedNodes(symbolMapping.TypeNodeAnnotation).Single(); var editor = new SyntaxEditor(originalRoot, symbolMapping.AnnotatedSolution.Workspace); var options = new CodeGenerationOptions( generateMethodBodies: true, options: await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false)); var codeGenService = document.GetRequiredLanguageService<ICodeGenerationService>(); var newTypeNode = codeGenService.CreateNamedTypeDeclaration(newType, options: options, cancellationToken: cancellationToken) .WithAdditionalAnnotations(SimplificationHelpers.SimplifyModuleNameAnnotation); var typeAnnotation = new SyntaxAnnotation(); newTypeNode = newTypeNode.WithAdditionalAnnotations(typeAnnotation); editor.InsertBefore(typeDeclaration, newTypeNode); var newDocument = document.WithSyntaxRoot(editor.GetChangedRoot()); return (newDocument, typeAnnotation); } public static async Task<(Document containingDocument, SyntaxAnnotation typeAnnotation)> AddTypeToNewFileAsync( Solution solution, string containingNamespaceDisplay, string fileName, ProjectId projectId, IEnumerable<string> folders, INamedTypeSymbol newSymbol, Document hintDocument, CancellationToken cancellationToken) { var newDocumentId = DocumentId.CreateNewId(projectId, debugName: fileName); var newDocumentPath = PathUtilities.CombinePaths(PathUtilities.GetDirectoryName(hintDocument.FilePath), fileName); var solutionWithInterfaceDocument = solution.AddDocument(newDocumentId, fileName, text: "", folders: folders, filePath: newDocumentPath); var newDocument = solutionWithInterfaceDocument.GetRequiredDocument(newDocumentId); var newSemanticModel = await newDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var options = new CodeGenerationOptions( contextLocation: newSemanticModel.SyntaxTree.GetLocation(new TextSpan()), generateMethodBodies: true, options: await newDocument.GetOptionsAsync(cancellationToken).ConfigureAwait(false)); var namespaceParts = containingNamespaceDisplay.Split('.').Where(s => !string.IsNullOrEmpty(s)); var newTypeDocument = await CodeGenerator.AddNamespaceOrTypeDeclarationAsync( newDocument.Project.Solution, newSemanticModel.GetEnclosingNamespace(0, cancellationToken), newSymbol.GenerateRootNamespaceOrType(namespaceParts.ToArray()), options: options, cancellationToken: cancellationToken).ConfigureAwait(false); var formattingSerivce = newTypeDocument.GetLanguageService<INewDocumentFormattingService>(); if (formattingSerivce is not null) { newTypeDocument = await formattingSerivce.FormatNewDocumentAsync(newTypeDocument, hintDocument, cancellationToken).ConfigureAwait(false); } var syntaxRoot = await newTypeDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var typeAnnotation = new SyntaxAnnotation(); var syntaxFacts = newTypeDocument.GetRequiredLanguageService<ISyntaxFactsService>(); var declarationNode = syntaxRoot.DescendantNodes().First(syntaxFacts.IsTypeDeclaration); var annotatedRoot = syntaxRoot.ReplaceNode(declarationNode, declarationNode.WithAdditionalAnnotations(typeAnnotation)); newTypeDocument = newTypeDocument.WithSyntaxRoot(annotatedRoot); var simplified = await Simplifier.ReduceAsync(newTypeDocument, cancellationToken: cancellationToken).ConfigureAwait(false); var formattedDocument = await Formatter.FormatAsync(simplified, cancellationToken: cancellationToken).ConfigureAwait(false); return (formattedDocument, typeAnnotation); } public static string GetTypeParameterSuffix(Document document, INamedTypeSymbol type, IEnumerable<ISymbol> extractableMembers) { var typeParameters = GetRequiredTypeParametersForMembers(type, extractableMembers); if (type.TypeParameters.Length == 0) { return string.Empty; } var typeParameterNames = typeParameters.SelectAsArray(p => p.Name); var syntaxGenerator = SyntaxGenerator.GetGenerator(document); return Formatter.Format(syntaxGenerator.SyntaxGeneratorInternal.TypeParameterList(typeParameterNames), document.Project.Solution.Workspace).ToString(); } public static ImmutableArray<ITypeParameterSymbol> GetRequiredTypeParametersForMembers(INamedTypeSymbol type, IEnumerable<ISymbol> includedMembers) { var potentialTypeParameters = GetPotentialTypeParameters(type); var directlyReferencedTypeParameters = GetDirectlyReferencedTypeParameters(potentialTypeParameters, includedMembers); // The directly referenced TypeParameters may have constraints that reference other // type parameters. var allReferencedTypeParameters = new HashSet<ITypeParameterSymbol>(directlyReferencedTypeParameters); var unanalyzedTypeParameters = new Queue<ITypeParameterSymbol>(directlyReferencedTypeParameters); while (!unanalyzedTypeParameters.IsEmpty()) { var typeParameter = unanalyzedTypeParameters.Dequeue(); foreach (var constraint in typeParameter.ConstraintTypes) { foreach (var originalTypeParameter in potentialTypeParameters) { if (!allReferencedTypeParameters.Contains(originalTypeParameter) && DoesTypeReferenceTypeParameter(constraint, originalTypeParameter, new HashSet<ITypeSymbol>())) { allReferencedTypeParameters.Add(originalTypeParameter); unanalyzedTypeParameters.Enqueue(originalTypeParameter); } } } } return potentialTypeParameters.WhereAsArray(allReferencedTypeParameters.Contains); } private static ImmutableArray<ITypeParameterSymbol> GetPotentialTypeParameters(INamedTypeSymbol type) { using var _ = ArrayBuilder<ITypeParameterSymbol>.GetInstance(out var typeParameters); var typesToVisit = new Stack<INamedTypeSymbol>(); var currentType = type; while (currentType != null) { typesToVisit.Push(currentType); currentType = currentType.ContainingType; } while (typesToVisit.Any()) { typeParameters.AddRange(typesToVisit.Pop().TypeParameters); } return typeParameters.ToImmutable(); } private static ImmutableArray<ITypeParameterSymbol> GetDirectlyReferencedTypeParameters(IEnumerable<ITypeParameterSymbol> potentialTypeParameters, IEnumerable<ISymbol> includedMembers) { using var _ = ArrayBuilder<ITypeParameterSymbol>.GetInstance(out var directlyReferencedTypeParameters); foreach (var typeParameter in potentialTypeParameters) { if (includedMembers.Any(m => DoesMemberReferenceTypeParameter(m, typeParameter, new HashSet<ITypeSymbol>()))) { directlyReferencedTypeParameters.Add(typeParameter); } } return directlyReferencedTypeParameters.ToImmutable(); } private static bool DoesMemberReferenceTypeParameter(ISymbol member, ITypeParameterSymbol typeParameter, HashSet<ITypeSymbol> checkedTypes) { switch (member.Kind) { case SymbolKind.Event: var @event = member as IEventSymbol; return DoesTypeReferenceTypeParameter(@event.Type, typeParameter, checkedTypes); case SymbolKind.Method: var method = member as IMethodSymbol; return method.Parameters.Any(t => DoesTypeReferenceTypeParameter(t.Type, typeParameter, checkedTypes)) || method.TypeParameters.Any(t => t.ConstraintTypes.Any(c => DoesTypeReferenceTypeParameter(c, typeParameter, checkedTypes))) || DoesTypeReferenceTypeParameter(method.ReturnType, typeParameter, checkedTypes); case SymbolKind.Property: var property = member as IPropertySymbol; return property.Parameters.Any(t => DoesTypeReferenceTypeParameter(t.Type, typeParameter, checkedTypes)) || DoesTypeReferenceTypeParameter(property.Type, typeParameter, checkedTypes); default: Debug.Assert(false, string.Format(FeaturesResources.Unexpected_interface_member_kind_colon_0, member.Kind.ToString())); return false; } } private static bool DoesTypeReferenceTypeParameter(ITypeSymbol type, ITypeParameterSymbol typeParameter, HashSet<ITypeSymbol> checkedTypes) { if (!checkedTypes.Add(type)) { return false; } // We want to ignore nullability when comparing as T and T? both are references to the type parameter if (type.Equals(typeParameter, SymbolEqualityComparer.Default) || type.GetTypeArguments().Any(t => DoesTypeReferenceTypeParameter(t, typeParameter, checkedTypes))) { return true; } if (type.ContainingType != null && type.Kind != SymbolKind.TypeParameter && DoesTypeReferenceTypeParameter(type.ContainingType, typeParameter, checkedTypes)) { return true; } return false; } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxTokenFactoryTests.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.Xml.Linq Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SyntaxTokenFactoryTests <Fact> Public Sub TestKeywordToken() ' test if keyword tokens can be created Dim keywordToken = SyntaxFactory.Token(SyntaxKind.AddHandlerKeyword) Assert.Equal(keywordToken.ToString(), SyntaxFacts.GetText(SyntaxKind.AddHandlerKeyword)) Assert.Equal(keywordToken.LeadingTrivia.Count, 1) Assert.Equal(keywordToken.TrailingTrivia.Count, 1) keywordToken = SyntaxFactory.Token(SyntaxKind.XmlKeyword) Assert.Equal(keywordToken.ToString(), SyntaxFacts.GetText(SyntaxKind.XmlKeyword)) Assert.Equal(keywordToken.LeadingTrivia.Count, 1) Assert.Equal(keywordToken.TrailingTrivia.Count, 1) ' check that trivia works keywordToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.AddHandlerKeyword) Assert.Equal(keywordToken.LeadingTrivia.Count, 1) Assert.Equal(keywordToken.TrailingTrivia.Count, 1) keywordToken = SyntaxFactory.Token(SyntaxKind.AddHandlerKeyword, trailing:=New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" "))) Assert.Equal(keywordToken.LeadingTrivia.Count, 1) Assert.Equal(keywordToken.TrailingTrivia.Count, 1) keywordToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.AddHandlerKeyword, trailing:=New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" "))) Assert.Equal(keywordToken.LeadingTrivia.Count, 1) Assert.Equal(keywordToken.TrailingTrivia.Count, 1) ' check that trivia works keywordToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.AddHandlerKeyword, SyntaxFacts.GetText(SyntaxKind.AddHandlerKeyword).ToUpperInvariant) Assert.Equal(keywordToken.ToString(), SyntaxFacts.GetText(SyntaxKind.AddHandlerKeyword).ToUpperInvariant) Assert.Equal(keywordToken.LeadingTrivia.Count, 1) Assert.Equal(keywordToken.TrailingTrivia.Count, 1) keywordToken = SyntaxFactory.Token(SyntaxKind.AddHandlerKeyword, New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxFacts.GetText(SyntaxKind.AddHandlerKeyword).ToUpperInvariant) Assert.Equal(keywordToken.ToString(), SyntaxFacts.GetText(SyntaxKind.AddHandlerKeyword).ToUpperInvariant) Assert.Equal(keywordToken.LeadingTrivia.Count, 1) Assert.Equal(keywordToken.TrailingTrivia.Count, 1) keywordToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.AddHandlerKeyword, New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxFacts.GetText(SyntaxKind.AddHandlerKeyword).ToUpperInvariant) Assert.Equal(keywordToken.ToString(), SyntaxFacts.GetText(SyntaxKind.AddHandlerKeyword).ToUpperInvariant) Assert.Equal(keywordToken.LeadingTrivia.Count, 1) Assert.Equal(keywordToken.TrailingTrivia.Count, 1) End Sub <Fact> Public Sub TestPunctuationToken() ' test if keyword tokens can be created Dim punctuationToken = SyntaxFactory.Token(SyntaxKind.ExclamationToken) Assert.Equal(punctuationToken.ToString(), SyntaxFacts.GetText(SyntaxKind.ExclamationToken)) Assert.Equal(punctuationToken.LeadingTrivia.Count, 1) Assert.Equal(punctuationToken.TrailingTrivia.Count, 1) punctuationToken = SyntaxFactory.Token(SyntaxKind.XmlKeyword) Assert.Equal(punctuationToken.ToString(), SyntaxFacts.GetText(SyntaxKind.XmlKeyword)) Assert.Equal(punctuationToken.LeadingTrivia.Count, 1) Assert.Equal(punctuationToken.TrailingTrivia.Count, 1) ' check that trivia works punctuationToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.ExclamationToken) Assert.Equal(punctuationToken.LeadingTrivia.Count, 1) Assert.Equal(punctuationToken.TrailingTrivia.Count, 1) punctuationToken = SyntaxFactory.Token(SyntaxKind.ExclamationToken, trailing:=New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" "))) Assert.Equal(punctuationToken.LeadingTrivia.Count, 1) Assert.Equal(punctuationToken.TrailingTrivia.Count, 1) punctuationToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.ExclamationToken, trailing:=New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" "))) Assert.Equal(punctuationToken.LeadingTrivia.Count, 1) Assert.Equal(punctuationToken.TrailingTrivia.Count, 1) ' check that trivia works punctuationToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.ExclamationToken, SyntaxFacts.GetText(SyntaxKind.ExclamationToken).ToUpperInvariant) Assert.Equal(punctuationToken.ToString(), SyntaxFacts.GetText(SyntaxKind.ExclamationToken).ToUpperInvariant) Assert.Equal(punctuationToken.LeadingTrivia.Count, 1) Assert.Equal(punctuationToken.TrailingTrivia.Count, 1) punctuationToken = SyntaxFactory.Token(SyntaxKind.ExclamationToken, New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxFacts.GetText(SyntaxKind.ExclamationToken).ToUpperInvariant) Assert.Equal(punctuationToken.ToString(), SyntaxFacts.GetText(SyntaxKind.ExclamationToken).ToUpperInvariant) Assert.Equal(punctuationToken.LeadingTrivia.Count, 1) Assert.Equal(punctuationToken.TrailingTrivia.Count, 1) punctuationToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.ExclamationToken, New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxFacts.GetText(SyntaxKind.ExclamationToken).ToUpperInvariant) Assert.Equal(punctuationToken.ToString(), SyntaxFacts.GetText(SyntaxKind.ExclamationToken).ToUpperInvariant) Assert.Equal(punctuationToken.LeadingTrivia.Count, 1) Assert.Equal(punctuationToken.TrailingTrivia.Count, 1) End Sub <Fact> Public Sub TestAllFactoryCalls() Dim token As SyntaxToken For k = CInt(SyntaxKind.None) To CInt(SyntaxKind.BadDirectiveTrivia) ' keywords or punctuation If (k >= CInt(SyntaxKind.AddHandlerKeyword) AndAlso k <= CInt(SyntaxKind.YieldKeyword)) OrElse (k >= CInt(SyntaxKind.ExclamationToken) AndAlso k <= CInt(SyntaxKind.EndOfXmlToken)) OrElse k = SyntaxKind.NameOfKeyword OrElse k = SyntaxKind.DollarSignDoubleQuoteToken OrElse k = SyntaxKind.EndOfInterpolatedStringToken _ Then token = SyntaxFactory.Token(CType(k, SyntaxKind)) ' no exception during execution Assert.Equal(token.Kind, CType(k, SyntaxKind)) token = SyntaxFactory.Token(CType(k, SyntaxKind), text:=Nothing) ' check default text is there Assert.Equal(token.ToString(), SyntaxFacts.GetText(CType(k, SyntaxKind))) token = SyntaxFactory.Token(CType(k, SyntaxKind), SyntaxFacts.GetText(CType(k, SyntaxKind)).ToUpperInvariant) ' check default text is there Assert.Equal(token.ToString(), SyntaxFacts.GetText(CType(k, SyntaxKind)).ToUpperInvariant) token = SyntaxFactory.Token(CType(k, SyntaxKind), String.Empty) ' check default text is there Assert.Equal(token.ToString(), String.Empty) Else Dim localKind = k Assert.Throws(Of ArgumentOutOfRangeException)(Function() SyntaxFactory.Token(CType(localKind, SyntaxKind))) End If Next End Sub <Fact()> Public Sub TestReplaceTriviaDeep() ' The parser for VB will stop when it sees the #end if directive which is a different ' behavior from the C# compiler. That said the whitespace trivia was only turned to double for the ' DirectiveTrivia and not the whitespace between the identifier and operators. ' Added for parity of scenario with Directives but capturing difference in behavior Dim SourceText = "#if true then" & Environment.NewLine & "a + " & Environment.NewLine & "#end if" & Environment.NewLine & " + b" Dim expr As ExpressionSyntax = SyntaxFactory.ParseExpression(SourceText, consumeFullText:=False) ' get whitespace trivia inside structured directive trivia Dim deepTrivia = From d In expr.GetDirectives().SelectMany(Function(d) Return d.DescendantTrivia.Where(Function(tr) tr.Kind = SyntaxKind.WhitespaceTrivia) End Function).ToList ' replace deep trivia with double-whitespace trivia Dim twoSpace = SyntaxFactory.Whitespace(" ") Dim expr2 = expr.ReplaceTrivia(deepTrivia, Function(tr, tr2) twoSpace) Assert.Equal("#if true then" & Environment.NewLine & "a + " & Environment.NewLine, expr2.ToFullString()) End Sub <Fact()> Public Sub TestReplaceSingleTriviaInNode() Dim expr = SyntaxFactory.ParseExpression("a + b") Assert.NotNull(expr) Assert.Equal(SyntaxKind.AddExpression, expr.Kind) Dim bex = CType(expr, BinaryExpressionSyntax) Assert.Equal(SyntaxKind.IdentifierName, bex.Left.Kind) Dim id = (CType(bex.Left, IdentifierNameSyntax)).Identifier Assert.Equal("a", id.ValueText) Assert.Equal(1, id.TrailingTrivia.Count) Dim trivia = id.TrailingTrivia(0) Assert.Equal(1, trivia.Width) Dim bex2 = bex.ReplaceTrivia(trivia, SyntaxFactory.Whitespace(" ")) Assert.Equal(SyntaxKind.AddExpression, bex2.Kind) Assert.Equal("a + b", bex2.ToFullString()) Assert.Equal("a + b", bex.ToFullString()) End Sub <Fact()> Public Sub TestReplaceMultipleTriviaInNode() Dim expr = SyntaxFactory.ParseExpression("a + b") Dim twoSpaces = SyntaxFactory.Whitespace(" ") Dim trivia = (From tr In expr.DescendantTrivia() Where tr.Kind = SyntaxKind.WhitespaceTrivia Select tr).ToList Dim replaced As ExpressionSyntax = expr.ReplaceTrivia(trivia, Function(tr, tr2) twoSpaces) Dim rtext = replaced.ToFullString() Assert.Equal("a + b", rtext) End Sub <Fact()> Public Sub TestReplaceMultipleTriviaInNodeWithNestedExpression() Dim expr = SyntaxFactory.ParseExpression("a + (c - b)") Dim twoSpaces = SyntaxFactory.Whitespace(" ") Dim trivia = (From tr In expr.DescendantTrivia() Where tr.Kind = SyntaxKind.WhitespaceTrivia Select tr).ToList Dim replaced As ExpressionSyntax = expr.ReplaceTrivia(trivia, Function(tr, tr2) twoSpaces) Dim rtext = replaced.ToFullString() Assert.Equal("a + (c - b)", rtext) End Sub <Fact()> Public Sub TestReplaceSingleTriviaForMultipleTriviaInNode() Dim expr = SyntaxFactory.ParseExpression("a + b") Dim tr = expr.DescendantTrivia().First() Dim replaced = expr.ReplaceTrivia(tr, {SyntaxFactory.Space, SyntaxFactory.CommentTrivia("' goo "), SyntaxFactory.Space}) Dim rtext = replaced.ToFullString() Assert.Equal("a ' goo + b", rtext) End Sub <Fact()> Public Sub TestReplaceSingleTriviaInToken() Dim id = SyntaxFactory.ParseToken("a ") Assert.Equal(SyntaxKind.IdentifierToken, id.Kind) Dim trivia = id.TrailingTrivia(0) Assert.Equal(1, trivia.Width) Dim id2 = id.ReplaceTrivia(trivia, SyntaxFactory.Whitespace(" ")) Assert.Equal("a ", id2.ToFullString()) Assert.Equal("a ", id.ToFullString()) End Sub <Fact()> Public Sub TestReplaceMultipleTriviaInToken() Dim id = SyntaxFactory.ParseToken("a ' goo " & Environment.NewLine) ' replace each trivia with a single space Dim id2 = id.ReplaceTrivia(id.GetAllTrivia(), Function(tr, tr2) SyntaxFactory.Space) Assert.Equal("a ", id2.ToFullString()) 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 Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SyntaxTokenFactoryTests <Fact> Public Sub TestKeywordToken() ' test if keyword tokens can be created Dim keywordToken = SyntaxFactory.Token(SyntaxKind.AddHandlerKeyword) Assert.Equal(keywordToken.ToString(), SyntaxFacts.GetText(SyntaxKind.AddHandlerKeyword)) Assert.Equal(keywordToken.LeadingTrivia.Count, 1) Assert.Equal(keywordToken.TrailingTrivia.Count, 1) keywordToken = SyntaxFactory.Token(SyntaxKind.XmlKeyword) Assert.Equal(keywordToken.ToString(), SyntaxFacts.GetText(SyntaxKind.XmlKeyword)) Assert.Equal(keywordToken.LeadingTrivia.Count, 1) Assert.Equal(keywordToken.TrailingTrivia.Count, 1) ' check that trivia works keywordToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.AddHandlerKeyword) Assert.Equal(keywordToken.LeadingTrivia.Count, 1) Assert.Equal(keywordToken.TrailingTrivia.Count, 1) keywordToken = SyntaxFactory.Token(SyntaxKind.AddHandlerKeyword, trailing:=New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" "))) Assert.Equal(keywordToken.LeadingTrivia.Count, 1) Assert.Equal(keywordToken.TrailingTrivia.Count, 1) keywordToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.AddHandlerKeyword, trailing:=New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" "))) Assert.Equal(keywordToken.LeadingTrivia.Count, 1) Assert.Equal(keywordToken.TrailingTrivia.Count, 1) ' check that trivia works keywordToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.AddHandlerKeyword, SyntaxFacts.GetText(SyntaxKind.AddHandlerKeyword).ToUpperInvariant) Assert.Equal(keywordToken.ToString(), SyntaxFacts.GetText(SyntaxKind.AddHandlerKeyword).ToUpperInvariant) Assert.Equal(keywordToken.LeadingTrivia.Count, 1) Assert.Equal(keywordToken.TrailingTrivia.Count, 1) keywordToken = SyntaxFactory.Token(SyntaxKind.AddHandlerKeyword, New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxFacts.GetText(SyntaxKind.AddHandlerKeyword).ToUpperInvariant) Assert.Equal(keywordToken.ToString(), SyntaxFacts.GetText(SyntaxKind.AddHandlerKeyword).ToUpperInvariant) Assert.Equal(keywordToken.LeadingTrivia.Count, 1) Assert.Equal(keywordToken.TrailingTrivia.Count, 1) keywordToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.AddHandlerKeyword, New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxFacts.GetText(SyntaxKind.AddHandlerKeyword).ToUpperInvariant) Assert.Equal(keywordToken.ToString(), SyntaxFacts.GetText(SyntaxKind.AddHandlerKeyword).ToUpperInvariant) Assert.Equal(keywordToken.LeadingTrivia.Count, 1) Assert.Equal(keywordToken.TrailingTrivia.Count, 1) End Sub <Fact> Public Sub TestPunctuationToken() ' test if keyword tokens can be created Dim punctuationToken = SyntaxFactory.Token(SyntaxKind.ExclamationToken) Assert.Equal(punctuationToken.ToString(), SyntaxFacts.GetText(SyntaxKind.ExclamationToken)) Assert.Equal(punctuationToken.LeadingTrivia.Count, 1) Assert.Equal(punctuationToken.TrailingTrivia.Count, 1) punctuationToken = SyntaxFactory.Token(SyntaxKind.XmlKeyword) Assert.Equal(punctuationToken.ToString(), SyntaxFacts.GetText(SyntaxKind.XmlKeyword)) Assert.Equal(punctuationToken.LeadingTrivia.Count, 1) Assert.Equal(punctuationToken.TrailingTrivia.Count, 1) ' check that trivia works punctuationToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.ExclamationToken) Assert.Equal(punctuationToken.LeadingTrivia.Count, 1) Assert.Equal(punctuationToken.TrailingTrivia.Count, 1) punctuationToken = SyntaxFactory.Token(SyntaxKind.ExclamationToken, trailing:=New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" "))) Assert.Equal(punctuationToken.LeadingTrivia.Count, 1) Assert.Equal(punctuationToken.TrailingTrivia.Count, 1) punctuationToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.ExclamationToken, trailing:=New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" "))) Assert.Equal(punctuationToken.LeadingTrivia.Count, 1) Assert.Equal(punctuationToken.TrailingTrivia.Count, 1) ' check that trivia works punctuationToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.ExclamationToken, SyntaxFacts.GetText(SyntaxKind.ExclamationToken).ToUpperInvariant) Assert.Equal(punctuationToken.ToString(), SyntaxFacts.GetText(SyntaxKind.ExclamationToken).ToUpperInvariant) Assert.Equal(punctuationToken.LeadingTrivia.Count, 1) Assert.Equal(punctuationToken.TrailingTrivia.Count, 1) punctuationToken = SyntaxFactory.Token(SyntaxKind.ExclamationToken, New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxFacts.GetText(SyntaxKind.ExclamationToken).ToUpperInvariant) Assert.Equal(punctuationToken.ToString(), SyntaxFacts.GetText(SyntaxKind.ExclamationToken).ToUpperInvariant) Assert.Equal(punctuationToken.LeadingTrivia.Count, 1) Assert.Equal(punctuationToken.TrailingTrivia.Count, 1) punctuationToken = SyntaxFactory.Token(New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.ExclamationToken, New SyntaxTriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxFacts.GetText(SyntaxKind.ExclamationToken).ToUpperInvariant) Assert.Equal(punctuationToken.ToString(), SyntaxFacts.GetText(SyntaxKind.ExclamationToken).ToUpperInvariant) Assert.Equal(punctuationToken.LeadingTrivia.Count, 1) Assert.Equal(punctuationToken.TrailingTrivia.Count, 1) End Sub <Fact> Public Sub TestAllFactoryCalls() Dim token As SyntaxToken For k = CInt(SyntaxKind.None) To CInt(SyntaxKind.BadDirectiveTrivia) ' keywords or punctuation If (k >= CInt(SyntaxKind.AddHandlerKeyword) AndAlso k <= CInt(SyntaxKind.YieldKeyword)) OrElse (k >= CInt(SyntaxKind.ExclamationToken) AndAlso k <= CInt(SyntaxKind.EndOfXmlToken)) OrElse k = SyntaxKind.NameOfKeyword OrElse k = SyntaxKind.DollarSignDoubleQuoteToken OrElse k = SyntaxKind.EndOfInterpolatedStringToken _ Then token = SyntaxFactory.Token(CType(k, SyntaxKind)) ' no exception during execution Assert.Equal(token.Kind, CType(k, SyntaxKind)) token = SyntaxFactory.Token(CType(k, SyntaxKind), text:=Nothing) ' check default text is there Assert.Equal(token.ToString(), SyntaxFacts.GetText(CType(k, SyntaxKind))) token = SyntaxFactory.Token(CType(k, SyntaxKind), SyntaxFacts.GetText(CType(k, SyntaxKind)).ToUpperInvariant) ' check default text is there Assert.Equal(token.ToString(), SyntaxFacts.GetText(CType(k, SyntaxKind)).ToUpperInvariant) token = SyntaxFactory.Token(CType(k, SyntaxKind), String.Empty) ' check default text is there Assert.Equal(token.ToString(), String.Empty) Else Dim localKind = k Assert.Throws(Of ArgumentOutOfRangeException)(Function() SyntaxFactory.Token(CType(localKind, SyntaxKind))) End If Next End Sub <Fact()> Public Sub TestReplaceTriviaDeep() ' The parser for VB will stop when it sees the #end if directive which is a different ' behavior from the C# compiler. That said the whitespace trivia was only turned to double for the ' DirectiveTrivia and not the whitespace between the identifier and operators. ' Added for parity of scenario with Directives but capturing difference in behavior Dim SourceText = "#if true then" & Environment.NewLine & "a + " & Environment.NewLine & "#end if" & Environment.NewLine & " + b" Dim expr As ExpressionSyntax = SyntaxFactory.ParseExpression(SourceText, consumeFullText:=False) ' get whitespace trivia inside structured directive trivia Dim deepTrivia = From d In expr.GetDirectives().SelectMany(Function(d) Return d.DescendantTrivia.Where(Function(tr) tr.Kind = SyntaxKind.WhitespaceTrivia) End Function).ToList ' replace deep trivia with double-whitespace trivia Dim twoSpace = SyntaxFactory.Whitespace(" ") Dim expr2 = expr.ReplaceTrivia(deepTrivia, Function(tr, tr2) twoSpace) Assert.Equal("#if true then" & Environment.NewLine & "a + " & Environment.NewLine, expr2.ToFullString()) End Sub <Fact()> Public Sub TestReplaceSingleTriviaInNode() Dim expr = SyntaxFactory.ParseExpression("a + b") Assert.NotNull(expr) Assert.Equal(SyntaxKind.AddExpression, expr.Kind) Dim bex = CType(expr, BinaryExpressionSyntax) Assert.Equal(SyntaxKind.IdentifierName, bex.Left.Kind) Dim id = (CType(bex.Left, IdentifierNameSyntax)).Identifier Assert.Equal("a", id.ValueText) Assert.Equal(1, id.TrailingTrivia.Count) Dim trivia = id.TrailingTrivia(0) Assert.Equal(1, trivia.Width) Dim bex2 = bex.ReplaceTrivia(trivia, SyntaxFactory.Whitespace(" ")) Assert.Equal(SyntaxKind.AddExpression, bex2.Kind) Assert.Equal("a + b", bex2.ToFullString()) Assert.Equal("a + b", bex.ToFullString()) End Sub <Fact()> Public Sub TestReplaceMultipleTriviaInNode() Dim expr = SyntaxFactory.ParseExpression("a + b") Dim twoSpaces = SyntaxFactory.Whitespace(" ") Dim trivia = (From tr In expr.DescendantTrivia() Where tr.Kind = SyntaxKind.WhitespaceTrivia Select tr).ToList Dim replaced As ExpressionSyntax = expr.ReplaceTrivia(trivia, Function(tr, tr2) twoSpaces) Dim rtext = replaced.ToFullString() Assert.Equal("a + b", rtext) End Sub <Fact()> Public Sub TestReplaceMultipleTriviaInNodeWithNestedExpression() Dim expr = SyntaxFactory.ParseExpression("a + (c - b)") Dim twoSpaces = SyntaxFactory.Whitespace(" ") Dim trivia = (From tr In expr.DescendantTrivia() Where tr.Kind = SyntaxKind.WhitespaceTrivia Select tr).ToList Dim replaced As ExpressionSyntax = expr.ReplaceTrivia(trivia, Function(tr, tr2) twoSpaces) Dim rtext = replaced.ToFullString() Assert.Equal("a + (c - b)", rtext) End Sub <Fact()> Public Sub TestReplaceSingleTriviaForMultipleTriviaInNode() Dim expr = SyntaxFactory.ParseExpression("a + b") Dim tr = expr.DescendantTrivia().First() Dim replaced = expr.ReplaceTrivia(tr, {SyntaxFactory.Space, SyntaxFactory.CommentTrivia("' goo "), SyntaxFactory.Space}) Dim rtext = replaced.ToFullString() Assert.Equal("a ' goo + b", rtext) End Sub <Fact()> Public Sub TestReplaceSingleTriviaInToken() Dim id = SyntaxFactory.ParseToken("a ") Assert.Equal(SyntaxKind.IdentifierToken, id.Kind) Dim trivia = id.TrailingTrivia(0) Assert.Equal(1, trivia.Width) Dim id2 = id.ReplaceTrivia(trivia, SyntaxFactory.Whitespace(" ")) Assert.Equal("a ", id2.ToFullString()) Assert.Equal("a ", id.ToFullString()) End Sub <Fact()> Public Sub TestReplaceMultipleTriviaInToken() Dim id = SyntaxFactory.ParseToken("a ' goo " & Environment.NewLine) ' replace each trivia with a single space Dim id2 = id.ReplaceTrivia(id.GetAllTrivia(), Function(tr, tr2) SyntaxFactory.Space) Assert.Equal("a ", id2.ToFullString()) End Sub End Class End Namespace
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/Test/Resources/Core/MetadataTests/Invalid/CustomAttributeTableUnsorted.dll
MZ@ !L!This program cannot be run in DOS mode. $PEL}<! $NC ` BS`H H(  H.textT# $ `.rsrcH`&@@.reloc *@B0CH(@'0( }*0 { +*0# s {(;&o +*0 {(>*0( }*0 { +*0}( }*0 { +*0 { +*0}*0~ }"( *0 {! +*0 {#~ ( ,s z}!*0 {$ +*0={"~ ( ,~ +! s {"(;&o +*0 {% +*0}%*0 {!}- s },.s0}/{%}.{"~ ( , {"(>(:% }"~ ( , {,}$~ }# +*0={#~ ( ,s z , o }*( +*0 ( ( +*0S{#~ ( ,s z( o . d+ h ( {#~ (<&( *0A{#~ ( ,s z-~ +s {# e~ (<&*0T{#~ ( ,s z( o . g+ f ( {#s (<&( *0>{#~ ( ,s z( {# is (<&( *0&( {# js (<&( *0{&( t }&*0{&( t }&*0{'( t}'*0{'( t}'*0{(( t}(*0{(( t}(*0{)( t})*0{)( t})*0 YEJh&8}#{&, {&o 8{(,{(( s o 8{',s {'o+b{),'( s {)oo-+ +1{),'( s {) o o-+ ++*0){"~ ( ,{"(>~ }"*0 (=-t  o6*0( *)System.Resources.ResourceReader, mscorlibsSystem.Resources.RuntimeResourceSet, mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089PA}<Rd(d RSDSFpzCxekdG:\wksrc\FolderBrowser\Source\obj\Debug\FolderBrowser.pdbBSJB v1.0.3705` #-H #Strings#GUIDT#BlobW? 3# 0?S$   ,%N%X%~%% 4d%%%'% dQ%%%%(A%M%k%% Z r          X 1=d= ==  = ==>=Q=*0n=*4y=14=1: V V V V V V V V V V V/ VA VR V_ mW 5AQ Q Q Q Q Q Q Q Q! Q2 QB QW Ql zWW '1;+EWWz nWP {Zl _ c g{sy {  {s !{$!Oc<!_T!q{sh!{g !c ! !c!!c!0"!H"!\"""4!#H#4$d#?$#M%$\&t$i'$y($ +)% +*<% 5+`% 5,% ?-% ?.% :I/% MI0&cO1'5{s6O8\<hBrCwDZFrG}HgI I J /M ;RL'GSt'{gTm 5<<    P    o    o        7 <   o   O e  i{q{g{ga{ac){gyW1{gy{gy{Q_-]vy{ Y  1 A {{{{g{{/ {g{{g  %* /$4(9,>0C4H8M<RPTX\`dhlptx|  M 0  6C0. MXZ^??AW  (,CI -+  ko)oloroo1W'&()*+ ,-     + D uwy/{;x  % i <Module>FolderBrowser.dllmscorlibSystemEnumBrowseFlagsCP.Windows.FormsEventArgsIDisposableFolderSelChangedEventArgsMulticastDelegateFolderSelChangedEventHandlerIUnknownObtainedEventArgsIUnknownObtainedEventHandlerObjectValidateFailedEventArgsValidateFailedEventHandlerSystem.ComponentModelComponentShellFolderBrowserBrowseCallBackProcValueTypeBrowseInfoIMallocUnManagedMethodsvalue__ReturnOnlyFSDirsDontGoBelowDomainShowStatusTextReturnFSancestorsEditBoxValidateNewDialogStyleBrowseIncludeURLsAddUsageHintNoNewFolderButtonBrowseForComputerBrowseForPrinterIncludeFilesShowShareablepidlNewSelect.ctorget_CurSelFolderPidlget_CurSelFolderPathDisposeCurSelFolderPidlCurSelFolderPathInvokeIAsyncResultAsyncCallbackBeginInvokeEndInvokesiteUnknownget_SiteUnknownSiteUnknowninvalidTextdismissDialogget_InvalidTextget_DismissDialogset_DismissDialogInvalidTextDismissDialogWM_USERBFFM_SETSTATUSTEXTABFFM_SETSTATUSTEXTWBFFM_ENABLEOKBFFM_SETSELECTIONABFFM_SETSELECTIONWBFFM_SETOKTEXTBFFM_SETEXPANDEDBFFM_INITIALIZEDBFFM_SELCHANGEDBFFM_VALIDATEFAILEDABFFM_VALIDATEFAILEDWBFFM_IUNKNOWNtitlepidlReturnedhandledisplayNameflagsget_Titleset_Titleget_FolderDisplayNameget_FolderPathget_BrowseFlagsset_BrowseFlagsShowDialogInternalSystem.Windows.FormsIWin32WindowShowDialogSetStatusTextEnableOkButtonSetSelectionSetOkButtonTextSetExpandedEventHandlerInitializedadd_Initializedremove_InitializedSelChangedadd_SelChangedremove_SelChangedIUnknownObtainedadd_IUnknownObtainedremove_IUnknownObtainedValidateFailedadd_ValidateFailedremove_ValidateFailedCallBackTitleFolderDisplayNameFolderPathhwndOwnerpidlRootdisplaynamecallbacklparamAllocReallocFreeGetSizeDidAllocHeapMinimizeSHBrowseForFolderSystem.TextStringBuilderSHGetPathFromIDListSendMessageSHGetMallocSHMemFreeSystem.DiagnosticsDebuggableAttributeFolderBrowserFlagsAttributeToStringobjectmethodsendereresultargsvalueIntPtrZeroop_InequalityInvalidOperationExceptionop_EqualityStringEmptybiownerget_HandleFormget_ActiveFormtextEnvironmentOperatingSystemget_OSVersionPlatformIDget_PlatformSystem.Runtime.InteropServicesMarshalStringToHGlobalAutoFreeHGlobalbEnablenewselStringToHGlobalUnipathDelegateCombineRemovehwndmsglplpDataGetObjectForIUnknownPtrToStringAnsiPtrToStringUnidisposingDescriptionAttributewpStructLayoutAttributeLayoutKindMarshalAsAttributeUnmanagedTypeComImportAttributeGuidAttributeInterfaceTypeAttributeComInterfaceTypePreserveSigAttributecbpvDllImportAttributeShell32.dllpidlpszPathUser32.DllshmallocOutAttributeptrCP.Windows.Forms.FolderBrowser.resources 4>NEwb2z\V4 @ @    ((   ! % !  (  !%   (  !%dhefgij   , )- -      ( !% !(   ,1  11 ,,IQ U]]]     String that is displayed above the tree view control in the dialog box. This string can be used to specify instructions to the user.83The display name of the folder selected by the user i q&)$00000002-0000-0000-C000-000000000046 00 C>C 0C_CorDllMainmscoree.dll% 0HX`4VS_VERSION_INFO?DVarFileInfo$TranslationLStringFileInfo(000004b0Comments $CompanyName ,FileDescription 0FileVersion0.0.0.0DInternalNameFolderBrowser.dll(LegalCopyright ,LegalTrademarks LOriginalFilenameFolderBrowser.dll$ProductName 4ProductVersion0.0.0.08Assembly Version0.0.0.0@ P3
MZ@ !L!This program cannot be run in DOS mode. $PEL}<! $NC ` BS`H H(  H.textT# $ `.rsrcH`&@@.reloc *@B0CH(@'0( }*0 { +*0# s {(;&o +*0 {(>*0( }*0 { +*0}( }*0 { +*0 { +*0}*0~ }"( *0 {! +*0 {#~ ( ,s z}!*0 {$ +*0={"~ ( ,~ +! s {"(;&o +*0 {% +*0}%*0 {!}- s },.s0}/{%}.{"~ ( , {"(>(:% }"~ ( , {,}$~ }# +*0={#~ ( ,s z , o }*( +*0 ( ( +*0S{#~ ( ,s z( o . d+ h ( {#~ (<&( *0A{#~ ( ,s z-~ +s {# e~ (<&*0T{#~ ( ,s z( o . g+ f ( {#s (<&( *0>{#~ ( ,s z( {# is (<&( *0&( {# js (<&( *0{&( t }&*0{&( t }&*0{'( t}'*0{'( t}'*0{(( t}(*0{(( t}(*0{)( t})*0{)( t})*0 YEJh&8}#{&, {&o 8{(,{(( s o 8{',s {'o+b{),'( s {)oo-+ +1{),'( s {) o o-+ ++*0){"~ ( ,{"(>~ }"*0 (=-t  o6*0( *)System.Resources.ResourceReader, mscorlibsSystem.Resources.RuntimeResourceSet, mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089PA}<Rd(d RSDSFpzCxekdG:\wksrc\FolderBrowser\Source\obj\Debug\FolderBrowser.pdbBSJB v1.0.3705` #-H #Strings#GUIDT#BlobW? 3# 0?S$   ,%N%X%~%% 4d%%%'% dQ%%%%(A%M%k%% Z r          X 1=d= ==  = ==>=Q=*0n=*4y=14=1: V V V V V V V V V V V/ VA VR V_ mW 5AQ Q Q Q Q Q Q Q Q! Q2 QB QW Ql zWW '1;+EWWz nWP {Zl _ c g{sy {  {s !{$!Oc<!_T!q{sh!{g !c ! !c!!c!0"!H"!\"""4!#H#4$d#?$#M%$\&t$i'$y($ +)% +*<% 5+`% 5,% ?-% ?.% :I/% MI0&cO1'5{s6O8\<hBrCwDZFrG}HgI I J /M ;RL'GSt'{gTm 5<<    P    o    o        7 <   o   O e  i{q{g{ga{ac){gyW1{gy{gy{Q_-]vy{ Y  1 A {{{{g{{/ {g{{g  %* /$4(9,>0C4H8M<RPTX\`dhlptx|  M 0  6C0. MXZ^??AW  (,CI -+  ko)oloroo1W'&()*+ ,-     + D uwy/{;x  % i <Module>FolderBrowser.dllmscorlibSystemEnumBrowseFlagsCP.Windows.FormsEventArgsIDisposableFolderSelChangedEventArgsMulticastDelegateFolderSelChangedEventHandlerIUnknownObtainedEventArgsIUnknownObtainedEventHandlerObjectValidateFailedEventArgsValidateFailedEventHandlerSystem.ComponentModelComponentShellFolderBrowserBrowseCallBackProcValueTypeBrowseInfoIMallocUnManagedMethodsvalue__ReturnOnlyFSDirsDontGoBelowDomainShowStatusTextReturnFSancestorsEditBoxValidateNewDialogStyleBrowseIncludeURLsAddUsageHintNoNewFolderButtonBrowseForComputerBrowseForPrinterIncludeFilesShowShareablepidlNewSelect.ctorget_CurSelFolderPidlget_CurSelFolderPathDisposeCurSelFolderPidlCurSelFolderPathInvokeIAsyncResultAsyncCallbackBeginInvokeEndInvokesiteUnknownget_SiteUnknownSiteUnknowninvalidTextdismissDialogget_InvalidTextget_DismissDialogset_DismissDialogInvalidTextDismissDialogWM_USERBFFM_SETSTATUSTEXTABFFM_SETSTATUSTEXTWBFFM_ENABLEOKBFFM_SETSELECTIONABFFM_SETSELECTIONWBFFM_SETOKTEXTBFFM_SETEXPANDEDBFFM_INITIALIZEDBFFM_SELCHANGEDBFFM_VALIDATEFAILEDABFFM_VALIDATEFAILEDWBFFM_IUNKNOWNtitlepidlReturnedhandledisplayNameflagsget_Titleset_Titleget_FolderDisplayNameget_FolderPathget_BrowseFlagsset_BrowseFlagsShowDialogInternalSystem.Windows.FormsIWin32WindowShowDialogSetStatusTextEnableOkButtonSetSelectionSetOkButtonTextSetExpandedEventHandlerInitializedadd_Initializedremove_InitializedSelChangedadd_SelChangedremove_SelChangedIUnknownObtainedadd_IUnknownObtainedremove_IUnknownObtainedValidateFailedadd_ValidateFailedremove_ValidateFailedCallBackTitleFolderDisplayNameFolderPathhwndOwnerpidlRootdisplaynamecallbacklparamAllocReallocFreeGetSizeDidAllocHeapMinimizeSHBrowseForFolderSystem.TextStringBuilderSHGetPathFromIDListSendMessageSHGetMallocSHMemFreeSystem.DiagnosticsDebuggableAttributeFolderBrowserFlagsAttributeToStringobjectmethodsendereresultargsvalueIntPtrZeroop_InequalityInvalidOperationExceptionop_EqualityStringEmptybiownerget_HandleFormget_ActiveFormtextEnvironmentOperatingSystemget_OSVersionPlatformIDget_PlatformSystem.Runtime.InteropServicesMarshalStringToHGlobalAutoFreeHGlobalbEnablenewselStringToHGlobalUnipathDelegateCombineRemovehwndmsglplpDataGetObjectForIUnknownPtrToStringAnsiPtrToStringUnidisposingDescriptionAttributewpStructLayoutAttributeLayoutKindMarshalAsAttributeUnmanagedTypeComImportAttributeGuidAttributeInterfaceTypeAttributeComInterfaceTypePreserveSigAttributecbpvDllImportAttributeShell32.dllpidlpszPathUser32.DllshmallocOutAttributeptrCP.Windows.Forms.FolderBrowser.resources 4>NEwb2z\V4 @ @    ((   ! % !  (  !%   (  !%dhefgij   , )- -      ( !% !(   ,1  11 ,,IQ U]]]     String that is displayed above the tree view control in the dialog box. This string can be used to specify instructions to the user.83The display name of the folder selected by the user i q&)$00000002-0000-0000-C000-000000000046 00 C>C 0C_CorDllMainmscoree.dll% 0HX`4VS_VERSION_INFO?DVarFileInfo$TranslationLStringFileInfo(000004b0Comments $CompanyName ,FileDescription 0FileVersion0.0.0.0DInternalNameFolderBrowser.dll(LegalCopyright ,LegalTrademarks LOriginalFilenameFolderBrowser.dll$ProductName 4ProductVersion0.0.0.08Assembly Version0.0.0.0@ P3
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/AbstractContextTests.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 Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders Public MustInherit Class AbstractContextTests Protected MustOverride Function CheckResultAsync(validLocation As Boolean, position As Integer, syntaxTree As SyntaxTree) As Task Private Async Function VerifyWorkerAsync(markup As String, validLocation As Boolean) As Threading.Tasks.Task Dim text As String = Nothing Dim position As Integer = Nothing MarkupTestFile.GetPosition(markup, text, position) 'VerifyWithPlaceHolderRemoved(text, validLocation) 'VerifyAtEndOfFile(text, validLocation) Await VerifyAtPosition_TypePartiallyWrittenAsync(text, position, validLocation) Await VerifyAtEndOfFile_TypePartiallyWrittenAsync(text, position, validLocation) End Function Private Function VerifyAtPositionAsync(text As String, position As Integer, validLocation As Boolean, insertText As String) As Threading.Tasks.Task text = text.Substring(0, position) & insertText & text.Substring(position) position += insertText.Length Dim tree = SyntaxFactory.ParseSyntaxTree(SourceText.From(text)) Return CheckResultAsync(validLocation, position, tree) End Function Private Function VerifyAtPosition_TypePartiallyWrittenAsync(text As String, position As Integer, validLocation As Boolean) As Threading.Tasks.Task Return VerifyAtPositionAsync(text, position, validLocation, "Str") End Function Private Async Function VerifyAtEndOfFileAsync(text As String, position As Integer, validLocation As Boolean, insertText As String) As Task ' only do this if the placeholder was at the end of the text. If text.Length <> position Then Return End If text = text.Substring(startIndex:=0, length:=position) & insertText position += insertText.Length Dim tree = SyntaxFactory.ParseSyntaxTree(SourceText.From(text)) Await CheckResultAsync(validLocation, position, tree) End Function Private Function VerifyAtEndOfFile_TypePartiallyWrittenAsync(text As String, position As Integer, validLocation As Boolean) As Task Return VerifyAtEndOfFileAsync(text, position, validLocation, "Str") End Function Protected Function VerifyTrueAsync(text As String) As Threading.Tasks.Task Return VerifyWorkerAsync(text, validLocation:=True) End Function Protected Function VerifyFalseAsync(text As String) As Threading.Tasks.Task Return VerifyWorkerAsync(text, validLocation:=False) End Function Protected Shared Function AddInsideMethod(text As String) As String Return "Class C" & vbCrLf & " Function F()" & vbCrLf & " " & text & vbCrLf & " End Function" & vbCrLf & "End Class" End Function Protected Shared Function CreateContent(ParamArray contents As String()) As String Return String.Join(vbCrLf, contents) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders Public MustInherit Class AbstractContextTests Protected MustOverride Function CheckResultAsync(validLocation As Boolean, position As Integer, syntaxTree As SyntaxTree) As Task Private Async Function VerifyWorkerAsync(markup As String, validLocation As Boolean) As Threading.Tasks.Task Dim text As String = Nothing Dim position As Integer = Nothing MarkupTestFile.GetPosition(markup, text, position) 'VerifyWithPlaceHolderRemoved(text, validLocation) 'VerifyAtEndOfFile(text, validLocation) Await VerifyAtPosition_TypePartiallyWrittenAsync(text, position, validLocation) Await VerifyAtEndOfFile_TypePartiallyWrittenAsync(text, position, validLocation) End Function Private Function VerifyAtPositionAsync(text As String, position As Integer, validLocation As Boolean, insertText As String) As Threading.Tasks.Task text = text.Substring(0, position) & insertText & text.Substring(position) position += insertText.Length Dim tree = SyntaxFactory.ParseSyntaxTree(SourceText.From(text)) Return CheckResultAsync(validLocation, position, tree) End Function Private Function VerifyAtPosition_TypePartiallyWrittenAsync(text As String, position As Integer, validLocation As Boolean) As Threading.Tasks.Task Return VerifyAtPositionAsync(text, position, validLocation, "Str") End Function Private Async Function VerifyAtEndOfFileAsync(text As String, position As Integer, validLocation As Boolean, insertText As String) As Task ' only do this if the placeholder was at the end of the text. If text.Length <> position Then Return End If text = text.Substring(startIndex:=0, length:=position) & insertText position += insertText.Length Dim tree = SyntaxFactory.ParseSyntaxTree(SourceText.From(text)) Await CheckResultAsync(validLocation, position, tree) End Function Private Function VerifyAtEndOfFile_TypePartiallyWrittenAsync(text As String, position As Integer, validLocation As Boolean) As Task Return VerifyAtEndOfFileAsync(text, position, validLocation, "Str") End Function Protected Function VerifyTrueAsync(text As String) As Threading.Tasks.Task Return VerifyWorkerAsync(text, validLocation:=True) End Function Protected Function VerifyFalseAsync(text As String) As Threading.Tasks.Task Return VerifyWorkerAsync(text, validLocation:=False) End Function Protected Shared Function AddInsideMethod(text As String) As String Return "Class C" & vbCrLf & " Function F()" & vbCrLf & " " & text & vbCrLf & " End Function" & vbCrLf & "End Class" End Function Protected Shared Function CreateContent(ParamArray contents As String()) As String Return String.Join(vbCrLf, contents) End Function End Class End Namespace
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/EditorFeatures/VisualBasicTest/EncapsulateField/EncapsulateFieldTestState.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.Shared Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.EncapsulateField Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Microsoft.CodeAnalysis.VisualBasic.EncapsulateField Imports Microsoft.VisualStudio.Composition Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands Imports Microsoft.VisualStudio.Text.Operations Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EncapsulateField Friend Class EncapsulateFieldTestState Implements IDisposable Private ReadOnly _testDocument As TestHostDocument Public Workspace As TestWorkspace Public TargetDocument As Document Private Sub New(workspace As TestWorkspace) Me.Workspace = workspace _testDocument = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue OrElse d.SelectedSpans.Any()) TargetDocument = workspace.CurrentSolution.GetDocument(_testDocument.Id) End Sub Public Shared Function Create(markup As String) As EncapsulateFieldTestState Dim workspace = TestWorkspace.CreateVisualBasic(markup, composition:=EditorTestCompositions.EditorFeatures) Return New EncapsulateFieldTestState(workspace) End Function Public Sub Encapsulate() Dim args = New EncapsulateFieldCommandArgs(_testDocument.GetTextView(), _testDocument.GetTextBuffer()) Dim commandHandler = New EncapsulateFieldCommandHandler( Workspace.ExportProvider.GetExportedValue(Of IThreadingContext)(), Workspace.GetService(Of ITextBufferUndoManagerProvider)(), Workspace.ExportProvider.GetExportedValue(Of IAsynchronousOperationListenerProvider)) commandHandler.ExecuteCommand(args, TestCommandExecutionContext.Create()) End Sub Public Sub AssertEncapsulateAs(expected As String) Encapsulate() Assert.Equal(expected, _testDocument.GetTextBuffer().CurrentSnapshot.GetText().ToString()) End Sub Public Sub Dispose() Implements IDisposable.Dispose If Workspace IsNot Nothing Then Workspace.Dispose() End If End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.Shared Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.EncapsulateField Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Microsoft.CodeAnalysis.VisualBasic.EncapsulateField Imports Microsoft.VisualStudio.Composition Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands Imports Microsoft.VisualStudio.Text.Operations Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EncapsulateField Friend Class EncapsulateFieldTestState Implements IDisposable Private ReadOnly _testDocument As TestHostDocument Public Workspace As TestWorkspace Public TargetDocument As Document Private Sub New(workspace As TestWorkspace) Me.Workspace = workspace _testDocument = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue OrElse d.SelectedSpans.Any()) TargetDocument = workspace.CurrentSolution.GetDocument(_testDocument.Id) End Sub Public Shared Function Create(markup As String) As EncapsulateFieldTestState Dim workspace = TestWorkspace.CreateVisualBasic(markup, composition:=EditorTestCompositions.EditorFeatures) Return New EncapsulateFieldTestState(workspace) End Function Public Sub Encapsulate() Dim args = New EncapsulateFieldCommandArgs(_testDocument.GetTextView(), _testDocument.GetTextBuffer()) Dim commandHandler = New EncapsulateFieldCommandHandler( Workspace.ExportProvider.GetExportedValue(Of IThreadingContext)(), Workspace.GetService(Of ITextBufferUndoManagerProvider)(), Workspace.ExportProvider.GetExportedValue(Of IAsynchronousOperationListenerProvider)) commandHandler.ExecuteCommand(args, TestCommandExecutionContext.Create()) End Sub Public Sub AssertEncapsulateAs(expected As String) Encapsulate() Assert.Equal(expected, _testDocument.GetTextBuffer().CurrentSnapshot.GetText().ToString()) End Sub Public Sub Dispose() Implements IDisposable.Dispose If Workspace IsNot Nothing Then Workspace.Dispose() End If End Sub End Class End Namespace
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/Core/Portable/IVTConclusion.cs
// Licensed to the .NET Foundation under one or more agreements. // 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; namespace Microsoft.CodeAnalysis { /// <summary> /// The result of <see cref="ISymbolExtensions.PerformIVTCheck(AssemblyIdentity, ImmutableArray{byte}, ImmutableArray{byte})"/> /// </summary> internal enum IVTConclusion { /// <summary> /// This indicates that friend access should be granted. /// </summary> Match, /// <summary> /// This indicates that friend access should be granted for the purposes of error recovery, /// but the program is wrong. /// /// That's because this indicates that a strong-named assembly has referred to a weak-named assembly /// which has extended friend access to the strong-named assembly. This will ultimately /// result in an error because strong-named assemblies may not refer to weak-named assemblies. /// In Roslyn we give a new error, CS7029, before emit time. In the dev10 compiler we error at /// emit time. /// </summary> OneSignedOneNot, /// <summary> /// This indicates that friend access should not be granted because the other assembly grants /// friend access to a strong-named assembly, and either this assembly is weak-named, or /// it is strong-named and the names don't match. /// </summary> PublicKeyDoesntMatch, /// <summary> /// This indicates that friend access should not be granted because the other assembly /// does not name this assembly as a friend in any way whatsoever. /// </summary> NoRelationshipClaimed } }
// Licensed to the .NET Foundation under one or more agreements. // 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; namespace Microsoft.CodeAnalysis { /// <summary> /// The result of <see cref="ISymbolExtensions.PerformIVTCheck(AssemblyIdentity, ImmutableArray{byte}, ImmutableArray{byte})"/> /// </summary> internal enum IVTConclusion { /// <summary> /// This indicates that friend access should be granted. /// </summary> Match, /// <summary> /// This indicates that friend access should be granted for the purposes of error recovery, /// but the program is wrong. /// /// That's because this indicates that a strong-named assembly has referred to a weak-named assembly /// which has extended friend access to the strong-named assembly. This will ultimately /// result in an error because strong-named assemblies may not refer to weak-named assemblies. /// In Roslyn we give a new error, CS7029, before emit time. In the dev10 compiler we error at /// emit time. /// </summary> OneSignedOneNot, /// <summary> /// This indicates that friend access should not be granted because the other assembly grants /// friend access to a strong-named assembly, and either this assembly is weak-named, or /// it is strong-named and the names don't match. /// </summary> PublicKeyDoesntMatch, /// <summary> /// This indicates that friend access should not be granted because the other assembly /// does not name this assembly as a friend in any way whatsoever. /// </summary> NoRelationshipClaimed } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/VisualStudio/CSharp/Impl/Interactive/xlf/Commands.vsct.es.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="es" original="../Commands.vsct"> <body> <trans-unit id="cmdidCSharpInteractiveToolWindow|ButtonText"> <source>C# Interactive</source> <target state="translated">C# interactivo</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="es" original="../Commands.vsct"> <body> <trans-unit id="cmdidCSharpInteractiveToolWindow|ButtonText"> <source>C# Interactive</source> <target state="translated">C# interactivo</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/Core/Portable/InternalUtilities/FatalError.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Threading; #if NET20 // Some APIs referenced by documentation comments are not available on .NET Framework 2.0. #pragma warning disable CS1574 // XML comment has cref attribute that could not be resolved #endif #if COMPILERCORE namespace Microsoft.CodeAnalysis #else namespace Microsoft.CodeAnalysis.ErrorReporting #endif { internal static class FatalError { private static Action<Exception>? s_fatalHandler; private static Action<Exception>? s_nonFatalHandler; #pragma warning disable IDE0052 // Remove unread private members - We want to hold onto last exception to make investigation easier private static Exception? s_reportedException; private static string? s_reportedExceptionMessage; #pragma warning restore IDE0052 /// <summary> /// Set by the host to a fail fast trigger, /// if the host desires to crash the process on a fatal exception. /// </summary> [DisallowNull] public static Action<Exception>? Handler { get { return s_fatalHandler; } set { if (s_fatalHandler != value) { Debug.Assert(s_fatalHandler == null, "Handler already set"); s_fatalHandler = value; } } } /// <summary> /// Set by the host to a fail fast trigger, /// if the host desires to NOT crash the process on a non fatal exception. /// </summary> [DisallowNull] public static Action<Exception>? NonFatalHandler { get { return s_nonFatalHandler; } set { if (s_nonFatalHandler != value) { Debug.Assert(s_nonFatalHandler == null, "Handler already set"); s_nonFatalHandler = value; } } } // Same as setting the Handler property except that it avoids the assert. This is useful in // test code which needs to verify the handler is called in specific cases and will continually // overwrite this value. public static void OverwriteHandler(Action<Exception>? value) { s_fatalHandler = value; } private static bool IsCurrentOperationBeingCancelled(Exception exception, CancellationToken cancellationToken) => exception is OperationCanceledException && cancellationToken.IsCancellationRequested; /// <summary> /// Use in an exception filter to report a fatal error (by calling <see cref="Handler"/>), unless the /// operation has been cancelled. The exception is never caught. /// </summary> /// <returns><see langword="false"/> to avoid catching the exception.</returns> [DebuggerHidden] public static bool ReportAndPropagateUnlessCanceled(Exception exception) { if (exception is OperationCanceledException) { return false; } return ReportAndPropagate(exception); } /// <summary> /// <para>Use in an exception filter to report a fatal error (by calling <see cref="Handler"/>), unless the /// operation has been cancelled at the request of <paramref name="contextCancellationToken"/>. The exception is /// never caught.</para> /// /// <para>Cancellable operations are only expected to throw <see cref="OperationCanceledException"/> if the /// applicable <paramref name="contextCancellationToken"/> indicates cancellation is requested by setting /// <see cref="CancellationToken.IsCancellationRequested"/>. Unexpected cancellation, i.e. an /// <see cref="OperationCanceledException"/> which occurs without <paramref name="contextCancellationToken"/> /// requesting cancellation, is treated as an error by this method.</para> /// /// <para>This method does not require <see cref="OperationCanceledException.CancellationToken"/> to match /// <paramref name="contextCancellationToken"/>, provided cancellation is expected per the previous /// paragraph.</para> /// </summary> /// <param name="contextCancellationToken">A <see cref="CancellationToken"/> which will have /// <see cref="CancellationToken.IsCancellationRequested"/> set if cancellation is expected.</param> /// <returns><see langword="false"/> to avoid catching the exception.</returns> [DebuggerHidden] public static bool ReportAndPropagateUnlessCanceled(Exception exception, CancellationToken contextCancellationToken) { if (IsCurrentOperationBeingCancelled(exception, contextCancellationToken)) { return false; } return ReportAndPropagate(exception); } /// <summary> /// Use in an exception filter to report a non-fatal error (by calling <see cref="NonFatalHandler"/>) and catch /// the exception, unless the operation was cancelled. /// </summary> /// <returns><see langword="true"/> to catch the exception if the non-fatal error was reported; otherwise, /// <see langword="false"/> to propagate the exception if the operation was cancelled.</returns> [DebuggerHidden] public static bool ReportAndCatchUnlessCanceled(Exception exception) { if (exception is OperationCanceledException) { return false; } return ReportAndCatch(exception); } /// <summary> /// <para>Use in an exception filter to report a non-fatal error (by calling <see cref="NonFatalHandler"/>) and /// catch the exception, unless the operation was cancelled at the request of /// <paramref name="contextCancellationToken"/>.</para> /// /// <para>Cancellable operations are only expected to throw <see cref="OperationCanceledException"/> if the /// applicable <paramref name="contextCancellationToken"/> indicates cancellation is requested by setting /// <see cref="CancellationToken.IsCancellationRequested"/>. Unexpected cancellation, i.e. an /// <see cref="OperationCanceledException"/> which occurs without <paramref name="contextCancellationToken"/> /// requesting cancellation, is treated as an error by this method.</para> /// /// <para>This method does not require <see cref="OperationCanceledException.CancellationToken"/> to match /// <paramref name="contextCancellationToken"/>, provided cancellation is expected per the previous /// paragraph.</para> /// </summary> /// <param name="contextCancellationToken">A <see cref="CancellationToken"/> which will have /// <see cref="CancellationToken.IsCancellationRequested"/> set if cancellation is expected.</param> /// <returns><see langword="true"/> to catch the exception if the non-fatal error was reported; otherwise, /// <see langword="false"/> to propagate the exception if the operation was cancelled.</returns> [DebuggerHidden] public static bool ReportAndCatchUnlessCanceled(Exception exception, CancellationToken contextCancellationToken) { if (IsCurrentOperationBeingCancelled(exception, contextCancellationToken)) { return false; } return ReportAndCatch(exception); } /// <summary> /// Use in an exception filter to report a fatal error without catching the exception. /// The error is reported by calling <see cref="Handler"/>. /// </summary> /// <returns><see langword="false"/> to avoid catching the exception.</returns> [DebuggerHidden] public static bool ReportAndPropagate(Exception exception) { Report(exception, s_fatalHandler); return false; } /// <summary> /// Report a non-fatal error. /// Calls <see cref="NonFatalHandler"/> and doesn't pass the exception through (the method returns true). /// This is generally expected to be used within an exception filter as that allows us to /// capture data at the point the exception is thrown rather than when it is handled. /// However, it can also be used outside of an exception filter. If the exception has not /// already been thrown the method will throw and catch it itself to ensure we get a useful /// stack trace. /// </summary> /// <returns>True to catch the exception.</returns> [DebuggerHidden] public static bool ReportAndCatch(Exception exception) { Report(exception, s_nonFatalHandler); return true; } private static readonly object s_reportedMarker = new(); private static void Report(Exception exception, Action<Exception>? handler) { // hold onto last exception to make investigation easier s_reportedException = exception; s_reportedExceptionMessage = exception.ToString(); if (handler == null) { return; } // only report exception once if (exception.Data[s_reportedMarker] != null) { return; } #if !NET20 if (exception is AggregateException aggregate && aggregate.InnerExceptions.Count == 1 && aggregate.InnerExceptions[0].Data[s_reportedMarker] != null) { return; } #endif if (!exception.Data.IsReadOnly) { exception.Data[s_reportedMarker] = s_reportedMarker; } handler.Invoke(exception); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Threading; #if NET20 // Some APIs referenced by documentation comments are not available on .NET Framework 2.0. #pragma warning disable CS1574 // XML comment has cref attribute that could not be resolved #endif #if COMPILERCORE namespace Microsoft.CodeAnalysis #else namespace Microsoft.CodeAnalysis.ErrorReporting #endif { internal static class FatalError { private static Action<Exception>? s_fatalHandler; private static Action<Exception>? s_nonFatalHandler; #pragma warning disable IDE0052 // Remove unread private members - We want to hold onto last exception to make investigation easier private static Exception? s_reportedException; private static string? s_reportedExceptionMessage; #pragma warning restore IDE0052 /// <summary> /// Set by the host to a fail fast trigger, /// if the host desires to crash the process on a fatal exception. /// </summary> [DisallowNull] public static Action<Exception>? Handler { get { return s_fatalHandler; } set { if (s_fatalHandler != value) { Debug.Assert(s_fatalHandler == null, "Handler already set"); s_fatalHandler = value; } } } /// <summary> /// Set by the host to a fail fast trigger, /// if the host desires to NOT crash the process on a non fatal exception. /// </summary> [DisallowNull] public static Action<Exception>? NonFatalHandler { get { return s_nonFatalHandler; } set { if (s_nonFatalHandler != value) { Debug.Assert(s_nonFatalHandler == null, "Handler already set"); s_nonFatalHandler = value; } } } // Same as setting the Handler property except that it avoids the assert. This is useful in // test code which needs to verify the handler is called in specific cases and will continually // overwrite this value. public static void OverwriteHandler(Action<Exception>? value) { s_fatalHandler = value; } private static bool IsCurrentOperationBeingCancelled(Exception exception, CancellationToken cancellationToken) => exception is OperationCanceledException && cancellationToken.IsCancellationRequested; /// <summary> /// Use in an exception filter to report a fatal error (by calling <see cref="Handler"/>), unless the /// operation has been cancelled. The exception is never caught. /// </summary> /// <returns><see langword="false"/> to avoid catching the exception.</returns> [DebuggerHidden] public static bool ReportAndPropagateUnlessCanceled(Exception exception) { if (exception is OperationCanceledException) { return false; } return ReportAndPropagate(exception); } /// <summary> /// <para>Use in an exception filter to report a fatal error (by calling <see cref="Handler"/>), unless the /// operation has been cancelled at the request of <paramref name="contextCancellationToken"/>. The exception is /// never caught.</para> /// /// <para>Cancellable operations are only expected to throw <see cref="OperationCanceledException"/> if the /// applicable <paramref name="contextCancellationToken"/> indicates cancellation is requested by setting /// <see cref="CancellationToken.IsCancellationRequested"/>. Unexpected cancellation, i.e. an /// <see cref="OperationCanceledException"/> which occurs without <paramref name="contextCancellationToken"/> /// requesting cancellation, is treated as an error by this method.</para> /// /// <para>This method does not require <see cref="OperationCanceledException.CancellationToken"/> to match /// <paramref name="contextCancellationToken"/>, provided cancellation is expected per the previous /// paragraph.</para> /// </summary> /// <param name="contextCancellationToken">A <see cref="CancellationToken"/> which will have /// <see cref="CancellationToken.IsCancellationRequested"/> set if cancellation is expected.</param> /// <returns><see langword="false"/> to avoid catching the exception.</returns> [DebuggerHidden] public static bool ReportAndPropagateUnlessCanceled(Exception exception, CancellationToken contextCancellationToken) { if (IsCurrentOperationBeingCancelled(exception, contextCancellationToken)) { return false; } return ReportAndPropagate(exception); } /// <summary> /// Use in an exception filter to report a non-fatal error (by calling <see cref="NonFatalHandler"/>) and catch /// the exception, unless the operation was cancelled. /// </summary> /// <returns><see langword="true"/> to catch the exception if the non-fatal error was reported; otherwise, /// <see langword="false"/> to propagate the exception if the operation was cancelled.</returns> [DebuggerHidden] public static bool ReportAndCatchUnlessCanceled(Exception exception) { if (exception is OperationCanceledException) { return false; } return ReportAndCatch(exception); } /// <summary> /// <para>Use in an exception filter to report a non-fatal error (by calling <see cref="NonFatalHandler"/>) and /// catch the exception, unless the operation was cancelled at the request of /// <paramref name="contextCancellationToken"/>.</para> /// /// <para>Cancellable operations are only expected to throw <see cref="OperationCanceledException"/> if the /// applicable <paramref name="contextCancellationToken"/> indicates cancellation is requested by setting /// <see cref="CancellationToken.IsCancellationRequested"/>. Unexpected cancellation, i.e. an /// <see cref="OperationCanceledException"/> which occurs without <paramref name="contextCancellationToken"/> /// requesting cancellation, is treated as an error by this method.</para> /// /// <para>This method does not require <see cref="OperationCanceledException.CancellationToken"/> to match /// <paramref name="contextCancellationToken"/>, provided cancellation is expected per the previous /// paragraph.</para> /// </summary> /// <param name="contextCancellationToken">A <see cref="CancellationToken"/> which will have /// <see cref="CancellationToken.IsCancellationRequested"/> set if cancellation is expected.</param> /// <returns><see langword="true"/> to catch the exception if the non-fatal error was reported; otherwise, /// <see langword="false"/> to propagate the exception if the operation was cancelled.</returns> [DebuggerHidden] public static bool ReportAndCatchUnlessCanceled(Exception exception, CancellationToken contextCancellationToken) { if (IsCurrentOperationBeingCancelled(exception, contextCancellationToken)) { return false; } return ReportAndCatch(exception); } /// <summary> /// Use in an exception filter to report a fatal error without catching the exception. /// The error is reported by calling <see cref="Handler"/>. /// </summary> /// <returns><see langword="false"/> to avoid catching the exception.</returns> [DebuggerHidden] public static bool ReportAndPropagate(Exception exception) { Report(exception, s_fatalHandler); return false; } /// <summary> /// Report a non-fatal error. /// Calls <see cref="NonFatalHandler"/> and doesn't pass the exception through (the method returns true). /// This is generally expected to be used within an exception filter as that allows us to /// capture data at the point the exception is thrown rather than when it is handled. /// However, it can also be used outside of an exception filter. If the exception has not /// already been thrown the method will throw and catch it itself to ensure we get a useful /// stack trace. /// </summary> /// <returns>True to catch the exception.</returns> [DebuggerHidden] public static bool ReportAndCatch(Exception exception) { Report(exception, s_nonFatalHandler); return true; } private static readonly object s_reportedMarker = new(); private static void Report(Exception exception, Action<Exception>? handler) { // hold onto last exception to make investigation easier s_reportedException = exception; s_reportedExceptionMessage = exception.ToString(); if (handler == null) { return; } // only report exception once if (exception.Data[s_reportedMarker] != null) { return; } #if !NET20 if (exception is AggregateException aggregate && aggregate.InnerExceptions.Count == 1 && aggregate.InnerExceptions[0].Data[s_reportedMarker] != null) { return; } #endif if (!exception.Data.IsReadOnly) { exception.Data[s_reportedMarker] = s_reportedMarker; } handler.Invoke(exception); } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/VisualStudio/IntegrationTest/TestUtilities/InProcess/PickMembersDialog_InProc.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls.Primitives; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Microsoft.VisualStudio.LanguageServices.Implementation.PickMembers; using Roslyn.Utilities; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess { internal class PickMembersDialog_InProc : InProcComponent { private PickMembersDialog_InProc() { } public static PickMembersDialog_InProc Create() => new PickMembersDialog_InProc(); public void VerifyOpen() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { var cancellationToken = cancellationTokenSource.Token; while (true) { cancellationToken.ThrowIfCancellationRequested(); var window = JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationToken)); if (window is null) { // Thread.Yield is insufficient; something in the light bulb must be relying on a UI thread // message at lower priority than the Background priority used in testing. WaitForApplicationIdle(Helper.HangMitigatingTimeout); continue; } WaitForApplicationIdle(Helper.HangMitigatingTimeout); return; } } } public void VerifyClosed() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { var cancellationToken = cancellationTokenSource.Token; while (true) { cancellationToken.ThrowIfCancellationRequested(); var window = JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationToken)); if (window is null) { return; } Thread.Yield(); } } } public bool CloseWindow() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { if (JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationTokenSource.Token)) is null) { return false; } } ClickCancel(); return true; } public void ClickOK() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.OKButton, cancellationTokenSource.Token)); } } public void ClickCancel() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.CancelButton, cancellationTokenSource.Token)); } } public void ClickDown() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.DownButton, cancellationTokenSource.Token)); } } private async Task<PickMembersDialog> GetDialogAsync(CancellationToken cancellationToken) { await JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, cancellationToken); return Application.Current.Windows.OfType<PickMembersDialog>().Single(); } private async Task<PickMembersDialog> TryGetDialogAsync(CancellationToken cancellationToken) { await JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, cancellationToken); return Application.Current.Windows.OfType<PickMembersDialog>().SingleOrDefault(); } private async Task ClickAsync(Func<PickMembersDialog.TestAccessor, ButtonBase> buttonSelector, CancellationToken cancellationToken) { await JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, cancellationToken); var dialog = await GetDialogAsync(cancellationToken); var button = buttonSelector(dialog.GetTestAccessor()); Contract.ThrowIfFalse(await button.SimulateClickAsync(JoinableTaskFactory)); } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls.Primitives; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Microsoft.VisualStudio.LanguageServices.Implementation.PickMembers; using Roslyn.Utilities; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess { internal class PickMembersDialog_InProc : InProcComponent { private PickMembersDialog_InProc() { } public static PickMembersDialog_InProc Create() => new PickMembersDialog_InProc(); public void VerifyOpen() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { var cancellationToken = cancellationTokenSource.Token; while (true) { cancellationToken.ThrowIfCancellationRequested(); var window = JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationToken)); if (window is null) { // Thread.Yield is insufficient; something in the light bulb must be relying on a UI thread // message at lower priority than the Background priority used in testing. WaitForApplicationIdle(Helper.HangMitigatingTimeout); continue; } WaitForApplicationIdle(Helper.HangMitigatingTimeout); return; } } } public void VerifyClosed() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { var cancellationToken = cancellationTokenSource.Token; while (true) { cancellationToken.ThrowIfCancellationRequested(); var window = JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationToken)); if (window is null) { return; } Thread.Yield(); } } } public bool CloseWindow() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { if (JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationTokenSource.Token)) is null) { return false; } } ClickCancel(); return true; } public void ClickOK() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.OKButton, cancellationTokenSource.Token)); } } public void ClickCancel() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.CancelButton, cancellationTokenSource.Token)); } } public void ClickDown() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.DownButton, cancellationTokenSource.Token)); } } private async Task<PickMembersDialog> GetDialogAsync(CancellationToken cancellationToken) { await JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, cancellationToken); return Application.Current.Windows.OfType<PickMembersDialog>().Single(); } private async Task<PickMembersDialog> TryGetDialogAsync(CancellationToken cancellationToken) { await JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, cancellationToken); return Application.Current.Windows.OfType<PickMembersDialog>().SingleOrDefault(); } private async Task ClickAsync(Func<PickMembersDialog.TestAccessor, ButtonBase> buttonSelector, CancellationToken cancellationToken) { await JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, cancellationToken); var dialog = await GetDialogAsync(cancellationToken); var button = buttonSelector(dialog.GetTestAccessor()); Contract.ThrowIfFalse(await button.SimulateClickAsync(JoinableTaskFactory)); } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./docs/features/tuples.md
Quickstart guide for tuples (C# 7.0 and Visual Basic 15) ------------------------------------ 1. Install VS2017 2. Start a C# or VB project 3. Add a reference to the `System.ValueTuple` package from NuGet ![Install the ValueTuple package](img/install-valuetuple.png) 4. Use tuples in C#: ```C# public class C { public static (int code, string message) Method((int, string) x) { return x; } public static void Main() { var pair1 = (42, "hello"); System.Console.Write(Method(pair1).message); var pair2 = (code: 43, message: "world"); System.Console.Write(pair2.message); } } ``` 5. Or use tuples in VB: ```VB Public Class C Public Shared Function Method(x As (Integer, String)) As (code As Integer, message As String) Return x End Function Public Shared Sub Main() Dim x = (42, "hello") System.Console.Write(C.Method(x).message) Dim pair2 = (code:=43, message:="world") System.Console.Write(pair2.message) End Sub End Class ``` 6. Use deconstructions (C# only): see the [deconstruction page](deconstruction.md) Without the `System.ValueTuple` package from NuGet, the compiler will produce an error: ``error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported`` Design ------ The goal of this document is capture what is being implemented. As design evolves, the document will undergo adjustments. Changes in design will be applied to this document as the changes are implemented. Tuple types ----------- Tuple types would be introduced with syntax very similar to a parameter list: ```C# public (int sum, int count) Tally(IEnumerable<int> values) { ... } var t = Tally(myValues); Console.WriteLine($"Sum: {t.sum}, count: {t.count}"); ``` The syntax `(int sum, int count)` indicates an anonymous data structure with public fields of the given names and types, also referred to as *tuple*. With no further syntax additions to C#, tuple values could be created as ```C# var t1 = new (int sum, int count) (0, 1); var t2 = new (int sum, int count) { sum = 0, count = 0 }; var t3 = new (int, int) (0, 1); // field names are optional ``` Note that specifying field names is optional, however when names are provided, all fields must be named. Duplicate names are disallowed. Tuple literals -------------- ```C# var t1 = (0, 2); // infer tuple type from values var t2 = (sum: 0, count: 1); // infer tuple type from names and values ``` Creating a tuple value of a known target type: ```C# public (int sum, int count) Tally(IEnumerable<int> values) { var s = 0; var c = 0; foreach (var value in values) { s += value; c++; } return (s, c); // target typed to (int sum, int count) } ``` Note that specifying field names is optional, however when names are provided, all fields must be named. Duplicate names are disallowed. ```C# var t1 = (sum: 0, 1); // error! some fields are named some are not. var t2 = (sum: 0, sum: 1); // error! duplicate names. ``` Duality with underlying type -------------- Tuples map to underlying types of particular names - ``` System.ValueTuple<T1, T2> System.ValueTuple<T1, T2, T3> ... System.ValueTuple<T1, T2, T3,..., T7, TRest> ``` In all scenarios tuple types behave exactly like underlying types with only additional optional enhancement of the more expressive field names given by the programmer. ```C# var t = (sum: 0, count: 1); t.sum = 1; // sum is the name for the field #1 t.Item1 = 1; // Item1 is the name of underlying field #1 and is also available var t1 = (0, 1); // tuple omits the field names. t.Item1 = 1; // underlying field name is still available t.ToString() // ToString on the underlying tuple type is called. System.ValueTuple<int, int> vt = t; // identity conversion (int moo, int boo) t2 = vt; // identity conversion ``` Because of the dual nature of tuples, it is not allowed to assign field names that overlap with preexisting member names of the underlying type. The only exception is the use of predefined "Item1", "Item2",..."ItemN" at corresponding position N, since that would not be ambiguous. ```C# var t = (ToString: 0, ObjectEquals: 1); // error: names match underlying member names var t1 = (Item1: 0, Item2: 1); // valid var t2 = (misc: 0, Item1: 1); // error: "Item1" was used in a wrong position ``` Example of underlying tuple type implementation: https://github.com/dotnet/roslyn/blob/features/tuples/docs/features/ValueTuples.cs To be replaced by the actual tuple implementation in FX Core. Identity conversion -------------- Element names are immaterial to tuple conversions. Tuples with the same types in the same order are identity convertible to each other or to and from corresponding underlying ValueTuple types, regardless of the names. ```C# var t = (sum: 0, count: 1); System.ValueTuple<int, int> vt = t; // identity conversion (int moo, int boo) t2 = vt; // identity conversion t2.moo = 1; ``` That said, if you have an element name at *one* position on one side of a conversion, and the same name at *another* position on the other side. That would be indication that the code almost certainly contains a bug: ```C# (int sum, int count) moo () { return (count: 1, sum: 3); // warning!! } ``` Overloading, Overriding, Hiding -------------- For the purpose of Overloading Overriding Hiding, tuples of the same types and lengths as well as their underlying ValueTuple types are considered equivalent. All other differences are immaterial. When overriding a member it is permitted to use tuple types with same or different field names than in the base member. A situation where same field names are used for non-matching fields between base and derived member signatures, a warning is reported by the compiler. ```C# class Base { virtual void M1(ValueTuple<int, int> arg){...} } class Derived : Base { override void M1((int c, int d) arg){...} // valid override, signatures are equivalent } class Derived2 : Derived { override void M1((int c1, int c) arg){...} // also valid, warning on possible misuse of name 'c' } class InvalidOverloading { virtual void M1((int c, int d) arg){...} virtual void M1((int x, int y) arg){...} // invalid overload, signatures are eqivalent virtual void M1(ValueTuple<int, int> arg){...} // also invalid } ``` Name erasure at runtime -------------- Importantly, the tuple field names aren't part of the runtime representation of tuples, but are tracked only by the compiler. As a result, the field names will not be available to a 3rd party observer of a tuple instance - such as reflection or dynamic code. In alignment with the identity conversions, a boxed tuple does not retain the names of the fields and will unbox to any tuple type that has the same element types in the same order. ```C# object o = (a: 1, b: 2); // boxing conversion var t = ((int moo, int boo))o; // unboxing conversion ``` Target typing -------------- A tuple literal is "target typed" when used in a context specifying a tuple type. What that means is that the tuple literal has a "conversion from expression" to any tuple type, as long as the element expressions of the tuple literal have an implicit conversion to the element types of the tuple type. ```C# (string name, byte age) t = (null, 5); // Ok: the expressions null and 5 convert to string and byte ``` In cases where the tuple literal is not part of a conversion, a tuple is used by its "natural type", which means a tuple type where the element types are the types of the constituent expressions. Since not all expressions have types, not all tuple literals have a natural type either: ```C# var t = ("John", 5); // Ok: the type of t is (string, int) var t = (null, 5); // Error: tuple expression doesn't have a type because null does not have a type ((1,2, null), 5).ToString(); // Error: tuple expression doesn't have a type ImmutableArray.Create((()=>1, 1)); // Error: tuple expression doesn't have a type because lambda does not have a type ImmutableArray.Create(((Func<int>)(()=>1), 1)); // ok ``` A tuple literal may include names, in which case they become part of the natural type: ```C# var t = (name: "John", age: 5); // The type of t is (string name, int age) t.age++; // t has field named age. ``` A successful conversion from tuple expression to tuple type is classified as _ImplictTuple_ conversion, unless tuple's natural type matches the target type exactly, in such case it is an _Identity_ conversion. ```C# void M1((int x, int y) arg){...}; void M1((object x, object y) arg){...}; M1((1, 2)); // first overload is used. Identity conversion is better than implicit conversion. M1(("hi", "hello")); // second overload is used. Implicit tuple conversion is better than no conversion. ``` Target typing will "see through" nullable target types. A successful conversion from tuple expression to a nullable tuple type is classified as _ImplicitNullable_ conversion. ```C# ((int x, int y, int z)?, int t)? SpaceTime() { return ((1,2,3), 7); // valid, implicit nullable conversion } ``` Overload resolution and tuples with no natural types. -------------- A situation may arise during overload resolution where multiple equally qualified candidates could be available due to a tuple argument without natural type being implicitly convertible to the corresponding parameters. In such situations overload resolution employs _exact match_ rule where arguments without natural types are recursively matched to the types of the corresponding parameters in terms of constituent structural elements. Tuple expressions are no exception from this rule and the _exact match_ rule is based on the natural types of the constituent tuple arguments. The rule is mutually recursive with respect to other containing or contained expressions not in a possession of a natural type. ```C# void M1((int x, Func<(int, int)>) arg){...}; void M1((int x, Func<(int, byte)>) arg){...}; M1((1, ()=>(2, 3))); // the first overload is used due to "exact match" rule ``` Conversions -------------- Tuple types and expressions support a variety of conversions by "lifting" conversions of the elements into overal _tuple conversion_. For the classification purpose, all element conversions are considered recursively. For example: To have an implicit conversion, all element expressions/types must have implicit conversions to the corresponding element types. Typele conversions are *Standard Conversions* and therefore can stack with user-defined operators to form user-defined conversions. A tuple conversion can be classified as a valid instance conversion for an extension method invocation as long as all element conversions are applicable as instance conversions. Language grammar changes --------------------- This is based on the [ANTLR grammar](https://raw.githubusercontent.com/ljw1004/csharpspec/gh-pages/csharp.g4) from Lucian. For tuple type declarations: ```ANTLR struct_type : type_name | simple_type | nullable_type | tuple_type // new ; tuple_type : '(' tuple_type_element_list ')' ; tuple_type_element_list : tuple_type_element ',' tuple_type_element | tuple_type_element_list ',' tuple_type_element ; tuple_type_element : type identifier? ; ``` For tuple literals: ```ANTLR literal : boolean_literal | integer_literal | real_literal | character_literal | string_literal | null_literal | tuple_literal // new ; tuple_literal : '(' tuple_literal_element_list ')' ; tuple_literal_element_list : tuple_literal_element ',' tuple_literal_element | tuple_literal_element_list ',' tuple_literal_element ; tuple_literal_element : ( identifier ':' )? expression ; ``` Note that because it is not a constant expression, a tuple literal cannot be used as default value for an optional parameter. Open issues: ----------- - [ ] Provide more details on semantics of tuple type declarations, both static (Type rules, constraints, all-or-none names, can't be used on right-hand-side of a 'is', ...) and dynamic (what does it do at runtime?). - [ ] Provide more details on semantics of tuple literals, both static (new kind of conversion from expression, new kind of conversion from type, all-or-none, scrambled names, underlying types, underlying names, listing the members of this type, what it means to access, ) and dynamic (what happens when you do this conversion?). - [ ] Exactly matching expression References: ----------- A lot of details and motivation for the feature is given in [Proposal: Language support for Tuples](https://github.com/dotnet/roslyn/issues/347) [C# Design Notes for Apr 6, 2016](https://github.com/dotnet/roslyn/issues/10429)
Quickstart guide for tuples (C# 7.0 and Visual Basic 15) ------------------------------------ 1. Install VS2017 2. Start a C# or VB project 3. Add a reference to the `System.ValueTuple` package from NuGet ![Install the ValueTuple package](img/install-valuetuple.png) 4. Use tuples in C#: ```C# public class C { public static (int code, string message) Method((int, string) x) { return x; } public static void Main() { var pair1 = (42, "hello"); System.Console.Write(Method(pair1).message); var pair2 = (code: 43, message: "world"); System.Console.Write(pair2.message); } } ``` 5. Or use tuples in VB: ```VB Public Class C Public Shared Function Method(x As (Integer, String)) As (code As Integer, message As String) Return x End Function Public Shared Sub Main() Dim x = (42, "hello") System.Console.Write(C.Method(x).message) Dim pair2 = (code:=43, message:="world") System.Console.Write(pair2.message) End Sub End Class ``` 6. Use deconstructions (C# only): see the [deconstruction page](deconstruction.md) Without the `System.ValueTuple` package from NuGet, the compiler will produce an error: ``error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported`` Design ------ The goal of this document is capture what is being implemented. As design evolves, the document will undergo adjustments. Changes in design will be applied to this document as the changes are implemented. Tuple types ----------- Tuple types would be introduced with syntax very similar to a parameter list: ```C# public (int sum, int count) Tally(IEnumerable<int> values) { ... } var t = Tally(myValues); Console.WriteLine($"Sum: {t.sum}, count: {t.count}"); ``` The syntax `(int sum, int count)` indicates an anonymous data structure with public fields of the given names and types, also referred to as *tuple*. With no further syntax additions to C#, tuple values could be created as ```C# var t1 = new (int sum, int count) (0, 1); var t2 = new (int sum, int count) { sum = 0, count = 0 }; var t3 = new (int, int) (0, 1); // field names are optional ``` Note that specifying field names is optional, however when names are provided, all fields must be named. Duplicate names are disallowed. Tuple literals -------------- ```C# var t1 = (0, 2); // infer tuple type from values var t2 = (sum: 0, count: 1); // infer tuple type from names and values ``` Creating a tuple value of a known target type: ```C# public (int sum, int count) Tally(IEnumerable<int> values) { var s = 0; var c = 0; foreach (var value in values) { s += value; c++; } return (s, c); // target typed to (int sum, int count) } ``` Note that specifying field names is optional, however when names are provided, all fields must be named. Duplicate names are disallowed. ```C# var t1 = (sum: 0, 1); // error! some fields are named some are not. var t2 = (sum: 0, sum: 1); // error! duplicate names. ``` Duality with underlying type -------------- Tuples map to underlying types of particular names - ``` System.ValueTuple<T1, T2> System.ValueTuple<T1, T2, T3> ... System.ValueTuple<T1, T2, T3,..., T7, TRest> ``` In all scenarios tuple types behave exactly like underlying types with only additional optional enhancement of the more expressive field names given by the programmer. ```C# var t = (sum: 0, count: 1); t.sum = 1; // sum is the name for the field #1 t.Item1 = 1; // Item1 is the name of underlying field #1 and is also available var t1 = (0, 1); // tuple omits the field names. t.Item1 = 1; // underlying field name is still available t.ToString() // ToString on the underlying tuple type is called. System.ValueTuple<int, int> vt = t; // identity conversion (int moo, int boo) t2 = vt; // identity conversion ``` Because of the dual nature of tuples, it is not allowed to assign field names that overlap with preexisting member names of the underlying type. The only exception is the use of predefined "Item1", "Item2",..."ItemN" at corresponding position N, since that would not be ambiguous. ```C# var t = (ToString: 0, ObjectEquals: 1); // error: names match underlying member names var t1 = (Item1: 0, Item2: 1); // valid var t2 = (misc: 0, Item1: 1); // error: "Item1" was used in a wrong position ``` Example of underlying tuple type implementation: https://github.com/dotnet/roslyn/blob/features/tuples/docs/features/ValueTuples.cs To be replaced by the actual tuple implementation in FX Core. Identity conversion -------------- Element names are immaterial to tuple conversions. Tuples with the same types in the same order are identity convertible to each other or to and from corresponding underlying ValueTuple types, regardless of the names. ```C# var t = (sum: 0, count: 1); System.ValueTuple<int, int> vt = t; // identity conversion (int moo, int boo) t2 = vt; // identity conversion t2.moo = 1; ``` That said, if you have an element name at *one* position on one side of a conversion, and the same name at *another* position on the other side. That would be indication that the code almost certainly contains a bug: ```C# (int sum, int count) moo () { return (count: 1, sum: 3); // warning!! } ``` Overloading, Overriding, Hiding -------------- For the purpose of Overloading Overriding Hiding, tuples of the same types and lengths as well as their underlying ValueTuple types are considered equivalent. All other differences are immaterial. When overriding a member it is permitted to use tuple types with same or different field names than in the base member. A situation where same field names are used for non-matching fields between base and derived member signatures, a warning is reported by the compiler. ```C# class Base { virtual void M1(ValueTuple<int, int> arg){...} } class Derived : Base { override void M1((int c, int d) arg){...} // valid override, signatures are equivalent } class Derived2 : Derived { override void M1((int c1, int c) arg){...} // also valid, warning on possible misuse of name 'c' } class InvalidOverloading { virtual void M1((int c, int d) arg){...} virtual void M1((int x, int y) arg){...} // invalid overload, signatures are eqivalent virtual void M1(ValueTuple<int, int> arg){...} // also invalid } ``` Name erasure at runtime -------------- Importantly, the tuple field names aren't part of the runtime representation of tuples, but are tracked only by the compiler. As a result, the field names will not be available to a 3rd party observer of a tuple instance - such as reflection or dynamic code. In alignment with the identity conversions, a boxed tuple does not retain the names of the fields and will unbox to any tuple type that has the same element types in the same order. ```C# object o = (a: 1, b: 2); // boxing conversion var t = ((int moo, int boo))o; // unboxing conversion ``` Target typing -------------- A tuple literal is "target typed" when used in a context specifying a tuple type. What that means is that the tuple literal has a "conversion from expression" to any tuple type, as long as the element expressions of the tuple literal have an implicit conversion to the element types of the tuple type. ```C# (string name, byte age) t = (null, 5); // Ok: the expressions null and 5 convert to string and byte ``` In cases where the tuple literal is not part of a conversion, a tuple is used by its "natural type", which means a tuple type where the element types are the types of the constituent expressions. Since not all expressions have types, not all tuple literals have a natural type either: ```C# var t = ("John", 5); // Ok: the type of t is (string, int) var t = (null, 5); // Error: tuple expression doesn't have a type because null does not have a type ((1,2, null), 5).ToString(); // Error: tuple expression doesn't have a type ImmutableArray.Create((()=>1, 1)); // Error: tuple expression doesn't have a type because lambda does not have a type ImmutableArray.Create(((Func<int>)(()=>1), 1)); // ok ``` A tuple literal may include names, in which case they become part of the natural type: ```C# var t = (name: "John", age: 5); // The type of t is (string name, int age) t.age++; // t has field named age. ``` A successful conversion from tuple expression to tuple type is classified as _ImplictTuple_ conversion, unless tuple's natural type matches the target type exactly, in such case it is an _Identity_ conversion. ```C# void M1((int x, int y) arg){...}; void M1((object x, object y) arg){...}; M1((1, 2)); // first overload is used. Identity conversion is better than implicit conversion. M1(("hi", "hello")); // second overload is used. Implicit tuple conversion is better than no conversion. ``` Target typing will "see through" nullable target types. A successful conversion from tuple expression to a nullable tuple type is classified as _ImplicitNullable_ conversion. ```C# ((int x, int y, int z)?, int t)? SpaceTime() { return ((1,2,3), 7); // valid, implicit nullable conversion } ``` Overload resolution and tuples with no natural types. -------------- A situation may arise during overload resolution where multiple equally qualified candidates could be available due to a tuple argument without natural type being implicitly convertible to the corresponding parameters. In such situations overload resolution employs _exact match_ rule where arguments without natural types are recursively matched to the types of the corresponding parameters in terms of constituent structural elements. Tuple expressions are no exception from this rule and the _exact match_ rule is based on the natural types of the constituent tuple arguments. The rule is mutually recursive with respect to other containing or contained expressions not in a possession of a natural type. ```C# void M1((int x, Func<(int, int)>) arg){...}; void M1((int x, Func<(int, byte)>) arg){...}; M1((1, ()=>(2, 3))); // the first overload is used due to "exact match" rule ``` Conversions -------------- Tuple types and expressions support a variety of conversions by "lifting" conversions of the elements into overal _tuple conversion_. For the classification purpose, all element conversions are considered recursively. For example: To have an implicit conversion, all element expressions/types must have implicit conversions to the corresponding element types. Typele conversions are *Standard Conversions* and therefore can stack with user-defined operators to form user-defined conversions. A tuple conversion can be classified as a valid instance conversion for an extension method invocation as long as all element conversions are applicable as instance conversions. Language grammar changes --------------------- This is based on the [ANTLR grammar](https://raw.githubusercontent.com/ljw1004/csharpspec/gh-pages/csharp.g4) from Lucian. For tuple type declarations: ```ANTLR struct_type : type_name | simple_type | nullable_type | tuple_type // new ; tuple_type : '(' tuple_type_element_list ')' ; tuple_type_element_list : tuple_type_element ',' tuple_type_element | tuple_type_element_list ',' tuple_type_element ; tuple_type_element : type identifier? ; ``` For tuple literals: ```ANTLR literal : boolean_literal | integer_literal | real_literal | character_literal | string_literal | null_literal | tuple_literal // new ; tuple_literal : '(' tuple_literal_element_list ')' ; tuple_literal_element_list : tuple_literal_element ',' tuple_literal_element | tuple_literal_element_list ',' tuple_literal_element ; tuple_literal_element : ( identifier ':' )? expression ; ``` Note that because it is not a constant expression, a tuple literal cannot be used as default value for an optional parameter. Open issues: ----------- - [ ] Provide more details on semantics of tuple type declarations, both static (Type rules, constraints, all-or-none names, can't be used on right-hand-side of a 'is', ...) and dynamic (what does it do at runtime?). - [ ] Provide more details on semantics of tuple literals, both static (new kind of conversion from expression, new kind of conversion from type, all-or-none, scrambled names, underlying types, underlying names, listing the members of this type, what it means to access, ) and dynamic (what happens when you do this conversion?). - [ ] Exactly matching expression References: ----------- A lot of details and motivation for the feature is given in [Proposal: Language support for Tuples](https://github.com/dotnet/roslyn/issues/347) [C# Design Notes for Apr 6, 2016](https://github.com/dotnet/roslyn/issues/10429)
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Utilities/NameSyntaxIterator.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 NameSyntaxIterator Implements IEnumerable(Of NameSyntax) Private ReadOnly _name As NameSyntax Public Sub New(name As NameSyntax) If name Is Nothing Then Throw New ArgumentNullException(NameOf(name)) End If Me._name = name End Sub Public Function GetEnumerator() As IEnumerator(Of NameSyntax) Implements IEnumerable(Of NameSyntax).GetEnumerator Dim nodes = New LinkedList(Of NameSyntax) Dim current = _name While True If TypeOf current Is QualifiedNameSyntax Then Dim qualifiedName = DirectCast(current, QualifiedNameSyntax) nodes.AddFirst(qualifiedName.Right) current = qualifiedName.Left Else nodes.AddFirst(current) Exit While End If End While Return nodes.GetEnumerator() End Function Private Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator Return GetEnumerator() 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 NameSyntaxIterator Implements IEnumerable(Of NameSyntax) Private ReadOnly _name As NameSyntax Public Sub New(name As NameSyntax) If name Is Nothing Then Throw New ArgumentNullException(NameOf(name)) End If Me._name = name End Sub Public Function GetEnumerator() As IEnumerator(Of NameSyntax) Implements IEnumerable(Of NameSyntax).GetEnumerator Dim nodes = New LinkedList(Of NameSyntax) Dim current = _name While True If TypeOf current Is QualifiedNameSyntax Then Dim qualifiedName = DirectCast(current, QualifiedNameSyntax) nodes.AddFirst(qualifiedName.Right) current = qualifiedName.Left Else nodes.AddFirst(current) Exit While End If End While Return nodes.GetEnumerator() End Function Private Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator Return GetEnumerator() End Function End Class End Namespace
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/Test/Resources/Core/SymbolsTests/Versioning/EN_US.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. [assembly: System.Reflection.AssemblyCultureAttribute("en-US")] public class enUS { }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. [assembly: System.Reflection.AssemblyCultureAttribute("en-US")] public class enUS { }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Scripting/Core/Utilities/IListExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.Scripting { internal static class IListExtensions { public static void AddRange<T>(this IList<T> list, ImmutableArray<T> items) { foreach (var item in items) { list.Add(item); } } public static void AddRange<T>(this IList<T> list, T[] items) { foreach (var item in items) { list.Add(item); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.Scripting { internal static class IListExtensions { public static void AddRange<T>(this IList<T> list, ImmutableArray<T> items) { foreach (var item in items) { list.Add(item); } } public static void AddRange<T>(this IList<T> list, T[] items) { foreach (var item in items) { list.Add(item); } } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Features/Core/Portable/LanguageServices/AnonymousTypeDisplayService/IAnonymousTypeDisplayExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageServices { internal static class IAnonymousTypeDisplayExtensions { public static IList<SymbolDisplayPart> InlineDelegateAnonymousTypes( this IAnonymousTypeDisplayService service, IList<SymbolDisplayPart> parts, SemanticModel semanticModel, int position) { var result = parts; while (true) { var delegateAnonymousType = result.Select(p => p.Symbol).OfType<INamedTypeSymbol>().FirstOrDefault(s => s.IsAnonymousDelegateType()); if (delegateAnonymousType == null) { break; } result = result == parts ? new List<SymbolDisplayPart>(parts) : result; ReplaceAnonymousType(result, delegateAnonymousType, service.GetAnonymousTypeParts(delegateAnonymousType, semanticModel, position)); } return result; } private static void ReplaceAnonymousType( IList<SymbolDisplayPart> list, INamedTypeSymbol anonymousType, IEnumerable<SymbolDisplayPart> parts) { var index = list.IndexOf(p => anonymousType.Equals(p.Symbol)); if (index >= 0) { var result = list.Take(index).Concat(parts).Concat(list.Skip(index + 1)).ToList(); list.Clear(); list.AddRange(result); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageServices { internal static class IAnonymousTypeDisplayExtensions { public static IList<SymbolDisplayPart> InlineDelegateAnonymousTypes( this IAnonymousTypeDisplayService service, IList<SymbolDisplayPart> parts, SemanticModel semanticModel, int position) { var result = parts; while (true) { var delegateAnonymousType = result.Select(p => p.Symbol).OfType<INamedTypeSymbol>().FirstOrDefault(s => s.IsAnonymousDelegateType()); if (delegateAnonymousType == null) { break; } result = result == parts ? new List<SymbolDisplayPart>(parts) : result; ReplaceAnonymousType(result, delegateAnonymousType, service.GetAnonymousTypeParts(delegateAnonymousType, semanticModel, position)); } return result; } private static void ReplaceAnonymousType( IList<SymbolDisplayPart> list, INamedTypeSymbol anonymousType, IEnumerable<SymbolDisplayPart> parts) { var index = list.IndexOf(p => anonymousType.Equals(p.Symbol)); if (index >= 0) { var result = list.Take(index).Concat(parts).Concat(list.Skip(index + 1)).ToList(); list.Clear(); list.AddRange(result); } } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Workspaces/CSharpTest/Formatting/FormattingTests_FunctionPointers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Formatting { [Trait(Traits.Feature, Traits.Features.Formatting)] public class FormattingTests_FunctionPointers : CSharpFormattingTestBase { [Fact] public async Task FormatFunctionPointer() { var content = @" unsafe class C { delegate * < int , int > functionPointer; }"; var expected = @" unsafe class C { delegate*<int, int> functionPointer; }"; await AssertFormatAsync(expected, content); } [Fact] public async Task FormatFunctionPointerWithManagedCallingConvention() { var content = @" unsafe class C { delegate *managed < int , int > functionPointer; }"; var expected = @" unsafe class C { delegate* managed<int, int> functionPointer; }"; await AssertFormatAsync(expected, content); } [Fact] public async Task FormatFunctionPointerWithUnmanagedCallingConvention() { var content = @" unsafe class C { delegate *unmanaged < int , int > functionPointer; }"; var expected = @" unsafe class C { delegate* unmanaged<int, int> functionPointer; }"; await AssertFormatAsync(expected, content); } [Fact] public async Task FormatFunctionPointerWithUnmanagedCallingConventionAndSpecifiers() { var content = @" unsafe class C { delegate *unmanaged [ Cdecl , Thiscall ] < int , int > functionPointer; }"; var expected = @" unsafe class C { delegate* unmanaged[Cdecl, Thiscall]<int, int> functionPointer; }"; await AssertFormatAsync(expected, content); } [Fact] public async Task FormatFunctionPointerWithUnrecognizedCallingConvention() { var content = @" unsafe class C { delegate *invalid < int , int > functionPointer; }"; var expected = @" unsafe class C { delegate*invalid <int, int> functionPointer; }"; await AssertFormatAsync(expected, content); } [Fact] public async Task FormatFunctionPointerWithInvalidCallingConventionAndSpecifiers() { var content = @" unsafe class C { delegate *invalid [ Cdecl , Thiscall ] < int , int > functionPointer; }"; var expected = @" unsafe class C { delegate*invalid [Cdecl, Thiscall]<int, int> functionPointer; }"; await AssertFormatAsync(expected, content); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Formatting { [Trait(Traits.Feature, Traits.Features.Formatting)] public class FormattingTests_FunctionPointers : CSharpFormattingTestBase { [Fact] public async Task FormatFunctionPointer() { var content = @" unsafe class C { delegate * < int , int > functionPointer; }"; var expected = @" unsafe class C { delegate*<int, int> functionPointer; }"; await AssertFormatAsync(expected, content); } [Fact] public async Task FormatFunctionPointerWithManagedCallingConvention() { var content = @" unsafe class C { delegate *managed < int , int > functionPointer; }"; var expected = @" unsafe class C { delegate* managed<int, int> functionPointer; }"; await AssertFormatAsync(expected, content); } [Fact] public async Task FormatFunctionPointerWithUnmanagedCallingConvention() { var content = @" unsafe class C { delegate *unmanaged < int , int > functionPointer; }"; var expected = @" unsafe class C { delegate* unmanaged<int, int> functionPointer; }"; await AssertFormatAsync(expected, content); } [Fact] public async Task FormatFunctionPointerWithUnmanagedCallingConventionAndSpecifiers() { var content = @" unsafe class C { delegate *unmanaged [ Cdecl , Thiscall ] < int , int > functionPointer; }"; var expected = @" unsafe class C { delegate* unmanaged[Cdecl, Thiscall]<int, int> functionPointer; }"; await AssertFormatAsync(expected, content); } [Fact] public async Task FormatFunctionPointerWithUnrecognizedCallingConvention() { var content = @" unsafe class C { delegate *invalid < int , int > functionPointer; }"; var expected = @" unsafe class C { delegate*invalid <int, int> functionPointer; }"; await AssertFormatAsync(expected, content); } [Fact] public async Task FormatFunctionPointerWithInvalidCallingConventionAndSpecifiers() { var content = @" unsafe class C { delegate *invalid [ Cdecl , Thiscall ] < int , int > functionPointer; }"; var expected = @" unsafe class C { delegate*invalid [Cdecl, Thiscall]<int, int> functionPointer; }"; await AssertFormatAsync(expected, content); } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/Core/Portable/InternalUtilities/SpecializedCollections.ReadOnly.Set.cs
// Licensed to the .NET Foundation under one or more agreements. // 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; namespace Roslyn.Utilities { internal partial class SpecializedCollections { private partial class ReadOnly { internal class Set<TUnderlying, T> : Collection<TUnderlying, T>, ISet<T>, IReadOnlySet<T> where TUnderlying : ISet<T> { public Set(TUnderlying underlying) : base(underlying) { } public new bool Add(T item) { throw new NotSupportedException(); } public void ExceptWith(IEnumerable<T> other) { throw new NotSupportedException(); } public void IntersectWith(IEnumerable<T> other) { throw new NotSupportedException(); } public bool IsProperSubsetOf(IEnumerable<T> other) { return Underlying.IsProperSubsetOf(other); } public bool IsProperSupersetOf(IEnumerable<T> other) { return Underlying.IsProperSupersetOf(other); } public bool IsSubsetOf(IEnumerable<T> other) { return Underlying.IsSubsetOf(other); } public bool IsSupersetOf(IEnumerable<T> other) { return Underlying.IsSupersetOf(other); } public bool Overlaps(IEnumerable<T> other) { return Underlying.Overlaps(other); } public bool SetEquals(IEnumerable<T> other) { return Underlying.SetEquals(other); } public void SymmetricExceptWith(IEnumerable<T> other) { throw new NotSupportedException(); } public void UnionWith(IEnumerable<T> other) { throw new NotSupportedException(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // 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; namespace Roslyn.Utilities { internal partial class SpecializedCollections { private partial class ReadOnly { internal class Set<TUnderlying, T> : Collection<TUnderlying, T>, ISet<T>, IReadOnlySet<T> where TUnderlying : ISet<T> { public Set(TUnderlying underlying) : base(underlying) { } public new bool Add(T item) { throw new NotSupportedException(); } public void ExceptWith(IEnumerable<T> other) { throw new NotSupportedException(); } public void IntersectWith(IEnumerable<T> other) { throw new NotSupportedException(); } public bool IsProperSubsetOf(IEnumerable<T> other) { return Underlying.IsProperSubsetOf(other); } public bool IsProperSupersetOf(IEnumerable<T> other) { return Underlying.IsProperSupersetOf(other); } public bool IsSubsetOf(IEnumerable<T> other) { return Underlying.IsSubsetOf(other); } public bool IsSupersetOf(IEnumerable<T> other) { return Underlying.IsSupersetOf(other); } public bool Overlaps(IEnumerable<T> other) { return Underlying.Overlaps(other); } public bool SetEquals(IEnumerable<T> other) { return Underlying.SetEquals(other); } public void SymmetricExceptWith(IEnumerable<T> other) { throw new NotSupportedException(); } public void UnionWith(IEnumerable<T> other) { throw new NotSupportedException(); } } } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenSyncLock.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 CodeGenSyncLock Inherits BasicTestBase <Fact()> Public Sub SimpleSyncLock() Dim source = <compilation> <file name="a.vb"> Option Strict On Imports System Class C1 Public Shared Sub Main() SyncLock GetType(C1) Console.WriteLine("Inside SyncLock.") End SyncLock End Sub End Class </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ Inside SyncLock. ]]>).VerifyIL("C1.Main", <![CDATA[ { // Code size 44 (0x2c) .maxstack 2 .locals init (Object V_0, Boolean V_1) IL_0000: ldtoken "C1" IL_0005: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type" IL_000a: stloc.0 IL_000b: ldc.i4.0 IL_000c: stloc.1 .try { IL_000d: ldloc.0 IL_000e: ldloca.s V_1 IL_0010: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0015: ldstr "Inside SyncLock." IL_001a: call "Sub System.Console.WriteLine(String)" IL_001f: leave.s IL_002b } finally { IL_0021: ldloc.1 IL_0022: brfalse.s IL_002a IL_0024: ldloc.0 IL_0025: call "Sub System.Threading.Monitor.Exit(Object)" IL_002a: endfinally } IL_002b: ret } ]]>) End Sub <Fact()> Public Sub SimpleSyncLockOldMonitorEnter() Dim source = <compilation> <file name="a.vb"> Option Strict On Imports System Class C1 Public Shared Sub Main() SyncLock GetType(C1) Console.WriteLine("Inside SyncLock.") End SyncLock End Sub End Class </file> </compilation> Dim allReferences As MetadataReference() = { TestMetadata.Net20.mscorlib, SystemRef, MsvbRef} CompileAndVerify(source, allReferences, ).VerifyIL("C1.Main", <![CDATA[ { // Code size 37 (0x25) .maxstack 1 .locals init (Object V_0) IL_0000: ldtoken "C1" IL_0005: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type" IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: call "Sub System.Threading.Monitor.Enter(Object)" .try { IL_0011: ldstr "Inside SyncLock." IL_0016: call "Sub System.Console.WriteLine(String)" IL_001b: leave.s IL_0024 } finally { IL_001d: ldloc.0 IL_001e: call "Sub System.Threading.Monitor.Exit(Object)" IL_0023: endfinally } IL_0024: ret } ]]>) End Sub <Fact()> Public Sub SimpleSyncLockTypeParameter() Dim source = <compilation> <file name="a.vb"> Option Strict On Imports System Class C1 Public Shared Sub Main() DoStuff(Of C1)() End Sub Public Shared Sub DoStuff(Of T as Class)() Dim lock as T = TryCast(new C1(), T) SyncLock lock Console.WriteLine("Inside SyncLock.") End SyncLock End Sub End Class </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ Inside SyncLock. ]]> ).VerifyIL("C1.DoStuff", <![CDATA[ { // Code size 54 (0x36) .maxstack 2 .locals init (Object V_0, Boolean V_1) IL_0000: newobj "Sub C1..ctor()" IL_0005: isinst "T" IL_000a: unbox.any "T" IL_000f: box "T" IL_0014: stloc.0 IL_0015: ldc.i4.0 IL_0016: stloc.1 .try { IL_0017: ldloc.0 IL_0018: ldloca.s V_1 IL_001a: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_001f: ldstr "Inside SyncLock." IL_0024: call "Sub System.Console.WriteLine(String)" IL_0029: leave.s IL_0035 } finally { IL_002b: ldloc.1 IL_002c: brfalse.s IL_0034 IL_002e: ldloc.0 IL_002f: call "Sub System.Threading.Monitor.Exit(Object)" IL_0034: endfinally } IL_0035: ret } ]]>) End Sub <Fact()> Public Sub SimpleSyncLockObjectType() Dim source = <compilation> <file name="a.vb"> Option Strict On Imports System Class C1 Public Shared Sub Main() Dim lock as new Object() SyncLock lock Console.WriteLine("Inside SyncLock.") End SyncLock End Sub End Class </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ Inside SyncLock. ]]>).VerifyIL("C1.Main", <![CDATA[ { // Code size 50 (0x32) .maxstack 2 .locals init (Object V_0, Boolean V_1) IL_0000: newobj "Sub Object..ctor()" IL_0005: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: call "Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.CheckForSyncLockOnValueType(Object)" IL_0011: ldc.i4.0 IL_0012: stloc.1 .try { IL_0013: ldloc.0 IL_0014: ldloca.s V_1 IL_0016: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_001b: ldstr "Inside SyncLock." IL_0020: call "Sub System.Console.WriteLine(String)" IL_0025: leave.s IL_0031 } finally { IL_0027: ldloc.1 IL_0028: brfalse.s IL_0030 IL_002a: ldloc.0 IL_002b: call "Sub System.Threading.Monitor.Exit(Object)" IL_0030: endfinally } IL_0031: ret } ]]>) End Sub <Fact()> Public Sub SimpleSyncLockPropertyAccess() Dim source = <compilation> <file name="a.vb"> Option Strict On Imports System Class C1 Public Shared ReadOnly Property GetInstance() as C1 Get return new C1() End Get End Property Public Shared Sub Main() SyncLock GetInstance Console.WriteLine("Inside SyncLock.") End SyncLock End Sub End Class </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ Inside SyncLock. ]]>) End Sub <Fact()> Public Sub SimpleSyncLockNothing() Dim source = <compilation> <file name="a.vb"> Option Strict ON Imports System Class Program Shared Sub Main() SyncLock Nothing Exit Sub End SyncLock End Sub End Class </file> </compilation> CompileAndVerify(source).VerifyIL("Program.Main", <![CDATA[ { // Code size 31 (0x1f) .maxstack 2 .locals init (Object V_0, Boolean V_1) IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: call "Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.CheckForSyncLockOnValueType(Object)" IL_0008: ldc.i4.0 IL_0009: stloc.1 .try { IL_000a: ldloc.0 IL_000b: ldloca.s V_1 IL_000d: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0012: leave.s IL_001e } finally { IL_0014: ldloc.1 IL_0015: brfalse.s IL_001d IL_0017: ldloc.0 IL_0018: call "Sub System.Threading.Monitor.Exit(Object)" IL_001d: endfinally } IL_001e: ret } ]]>) End Sub <Fact()> Public Sub SimpleSyncLockInterface() Dim source = <compilation> <file name="a.vb"> Option Strict ON Module M1 Sub Main() SyncLock Goo End SyncLock End Sub Function Goo() As I1 Return Nothing End Function End Module Interface I1 End Interface </file> </compilation> CompileAndVerify(source).VerifyIL("M1.Main", <![CDATA[ { // Code size 29 (0x1d) .maxstack 2 .locals init (Object V_0, Boolean V_1) IL_0000: call "Function M1.Goo() As I1" IL_0005: stloc.0 IL_0006: ldc.i4.0 IL_0007: stloc.1 .try { IL_0008: ldloc.0 IL_0009: ldloca.s V_1 IL_000b: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0010: leave.s IL_001c } finally { IL_0012: ldloc.1 IL_0013: brfalse.s IL_001b IL_0015: ldloc.0 IL_0016: call "Sub System.Threading.Monitor.Exit(Object)" IL_001b: endfinally } IL_001c: ret } ]]>) End Sub <Fact()> Public Sub SimpleSyncLockSharedObject() Dim source = <compilation> <file name="a.vb"> Class Program Shared Key As Object Shared Sub Main() SyncLock Key End SyncLock End Sub End Class </file> </compilation> CompileAndVerify(source).VerifyIL("Program.Main", <![CDATA[ { // Code size 35 (0x23) .maxstack 2 .locals init (Object V_0, Boolean V_1) IL_0000: ldsfld "Program.Key As Object" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: call "Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.CheckForSyncLockOnValueType(Object)" IL_000c: ldc.i4.0 IL_000d: stloc.1 .try { IL_000e: ldloc.0 IL_000f: ldloca.s V_1 IL_0011: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0016: leave.s IL_0022 } finally { IL_0018: ldloc.1 IL_0019: brfalse.s IL_0021 IL_001b: ldloc.0 IL_001c: call "Sub System.Threading.Monitor.Exit(Object)" IL_0021: endfinally } IL_0022: ret } ]]>) End Sub <Fact()> Public Sub SimpleSyncLockDelegate() Dim source = <compilation> <file name="a.vb"> Delegate Sub D(p1 As Integer) Class Program Public Shared Sub Main(args As String()) SyncLock New D(AddressOf PM) End SyncLock End Sub Private Shared Sub PM(p1 As Integer) End Sub End Class </file> </compilation> CompileAndVerify(source).VerifyIL("Program.Main", <![CDATA[ { // Code size 36 (0x24) .maxstack 2 .locals init (Object V_0, Boolean V_1) IL_0000: ldnull IL_0001: ldftn "Sub Program.PM(Integer)" IL_0007: newobj "Sub D..ctor(Object, System.IntPtr)" IL_000c: stloc.0 IL_000d: ldc.i4.0 IL_000e: stloc.1 .try { IL_000f: ldloc.0 IL_0010: ldloca.s V_1 IL_0012: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0017: leave.s IL_0023 } finally { IL_0019: ldloc.1 IL_001a: brfalse.s IL_0022 IL_001c: ldloc.0 IL_001d: call "Sub System.Threading.Monitor.Exit(Object)" IL_0022: endfinally } IL_0023: ret } ]]>) End Sub <Fact()> Public Sub CallMonitorExitInSyncLock() Dim source = <compilation> <file name="a.vb"> Class Program Public Shared Sub Main(args As String()) SyncLock args System.Threading.Monitor.Exit(args) End SyncLock End Sub End Class </file> </compilation> CompileAndVerify(source).VerifyIL("Program.Main", <![CDATA[ { // Code size 31 (0x1f) .maxstack 2 .locals init (Object V_0, Boolean V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldc.i4.0 IL_0003: stloc.1 .try { IL_0004: ldloc.0 IL_0005: ldloca.s V_1 IL_0007: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_000c: ldarg.0 IL_000d: call "Sub System.Threading.Monitor.Exit(Object)" IL_0012: leave.s IL_001e } finally { IL_0014: ldloc.1 IL_0015: brfalse.s IL_001d IL_0017: ldloc.0 IL_0018: call "Sub System.Threading.Monitor.Exit(Object)" IL_001d: endfinally } IL_001e: ret } ]]>) End Sub <Fact()> Public Sub CallMonitorExitInSyncLock_1() Dim source = <compilation> <file name="a.vb"> Class Program Public Shared Sub Main(args As String()) End Sub Public Sub goo(obj As Object) SyncLock obj System.Threading.Monitor.Exit(obj) End SyncLock End Sub End Class </file> </compilation> CompileAndVerify(source).VerifyIL("Program.goo", <![CDATA[ { // Code size 42 (0x2a) .maxstack 2 .locals init (Object V_0, Boolean V_1) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: call "Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.CheckForSyncLockOnValueType(Object)" IL_0008: ldc.i4.0 IL_0009: stloc.1 .try { IL_000a: ldloc.0 IL_000b: ldloca.s V_1 IL_000d: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0012: ldarg.1 IL_0013: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0018: call "Sub System.Threading.Monitor.Exit(Object)" IL_001d: leave.s IL_0029 } finally { IL_001f: ldloc.1 IL_0020: brfalse.s IL_0028 IL_0022: ldloc.0 IL_0023: call "Sub System.Threading.Monitor.Exit(Object)" IL_0028: endfinally } IL_0029: ret } ]]>) End Sub <Fact()> Public Sub SyncLockMe() Dim source = <compilation> <file name="a.vb"> Class Program Sub goo() SyncLock Me End SyncLock End Sub End Class </file> </compilation> CompileAndVerify(source).VerifyIL("Program.goo", <![CDATA[ { // Code size 25 (0x19) .maxstack 2 .locals init (Object V_0, Boolean V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldc.i4.0 IL_0003: stloc.1 .try { IL_0004: ldloc.0 IL_0005: ldloca.s V_1 IL_0007: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_000c: leave.s IL_0018 } finally { IL_000e: ldloc.1 IL_000f: brfalse.s IL_0017 IL_0011: ldloc.0 IL_0012: call "Sub System.Threading.Monitor.Exit(Object)" IL_0017: endfinally } IL_0018: ret } ]]>) End Sub <Fact()> Public Sub SyncLockString() Dim source = <compilation> <file name="a.vb"> Class Program Sub goo() SyncLock "abc" End SyncLock End Sub End Class </file> </compilation> CompileAndVerify(source).VerifyIL("Program.goo", <![CDATA[ { // Code size 29 (0x1d) .maxstack 2 .locals init (Object V_0, Boolean V_1) IL_0000: ldstr "abc" IL_0005: stloc.0 IL_0006: ldc.i4.0 IL_0007: stloc.1 .try { IL_0008: ldloc.0 IL_0009: ldloca.s V_1 IL_000b: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0010: leave.s IL_001c } finally { IL_0012: ldloc.1 IL_0013: brfalse.s IL_001b IL_0015: ldloc.0 IL_0016: call "Sub System.Threading.Monitor.Exit(Object)" IL_001b: endfinally } IL_001c: ret } ]]>) End Sub <Fact()> Public Sub NestedSyncLock() Dim source = <compilation> <file name="a.vb"> Public Class Program Public Sub goo() Dim syncroot As Object = New Object SyncLock syncroot SyncLock syncroot.ToString() End SyncLock End SyncLock End Sub End Class </file> </compilation> CompileAndVerify(source).VerifyIL("Program.goo", <![CDATA[ { // Code size 71 (0x47) .maxstack 2 .locals init (Object V_0, //syncroot Object V_1, Boolean V_2, Object V_3, Boolean V_4) IL_0000: newobj "Sub Object..ctor()" IL_0005: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: stloc.1 IL_000d: ldloc.1 IL_000e: call "Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.CheckForSyncLockOnValueType(Object)" IL_0013: ldc.i4.0 IL_0014: stloc.2 .try { IL_0015: ldloc.1 IL_0016: ldloca.s V_2 IL_0018: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_001d: ldloc.0 IL_001e: callvirt "Function Object.ToString() As String" IL_0023: stloc.3 IL_0024: ldc.i4.0 IL_0025: stloc.s V_4 .try { IL_0027: ldloc.3 IL_0028: ldloca.s V_4 IL_002a: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_002f: leave.s IL_0046 } finally { IL_0031: ldloc.s V_4 IL_0033: brfalse.s IL_003b IL_0035: ldloc.3 IL_0036: call "Sub System.Threading.Monitor.Exit(Object)" IL_003b: endfinally } } finally { IL_003c: ldloc.2 IL_003d: brfalse.s IL_0045 IL_003f: ldloc.1 IL_0040: call "Sub System.Threading.Monitor.Exit(Object)" IL_0045: endfinally } IL_0046: ret } ]]>) End Sub <Fact()> Public Sub NestedSyncLock_1() Dim source = <compilation> <file name="a.vb"> Public Class Program Public Sub goo() Dim syncroot As Object = New Object SyncLock syncroot SyncLock syncroot End SyncLock End SyncLock End Sub End Class </file> </compilation> CompileAndVerify(source).VerifyIL("Program.goo", <![CDATA[ { // Code size 72 (0x48) .maxstack 2 .locals init (Object V_0, //syncroot Object V_1, Boolean V_2, Object V_3, Boolean V_4) IL_0000: newobj "Sub Object..ctor()" IL_0005: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: stloc.1 IL_000d: ldloc.1 IL_000e: call "Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.CheckForSyncLockOnValueType(Object)" IL_0013: ldc.i4.0 IL_0014: stloc.2 .try { IL_0015: ldloc.1 IL_0016: ldloca.s V_2 IL_0018: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_001d: ldloc.0 IL_001e: stloc.3 IL_001f: ldloc.3 IL_0020: call "Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.CheckForSyncLockOnValueType(Object)" IL_0025: ldc.i4.0 IL_0026: stloc.s V_4 .try { IL_0028: ldloc.3 IL_0029: ldloca.s V_4 IL_002b: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0030: leave.s IL_0047 } finally { IL_0032: ldloc.s V_4 IL_0034: brfalse.s IL_003c IL_0036: ldloc.3 IL_0037: call "Sub System.Threading.Monitor.Exit(Object)" IL_003c: endfinally } } finally { IL_003d: ldloc.2 IL_003e: brfalse.s IL_0046 IL_0040: ldloc.1 IL_0041: call "Sub System.Threading.Monitor.Exit(Object)" IL_0046: endfinally } IL_0047: ret } ]]>) End Sub <Fact()> Public Sub TryAndSyncLock() Dim source = <compilation> <file name="a.vb"> Imports System Module M1 Sub Main() Try System.Threading.Monitor.Enter(Nothing) SyncLock Nothing Exit Try End SyncLock Catch ex As Exception End Try End Sub End Module </file> </compilation> CompileAndVerify(source).VerifyIL("M1.Main", <![CDATA[ { // Code size 51 (0x33) .maxstack 2 .locals init (Object V_0, Boolean V_1, System.Exception V_2) //ex .try { IL_0000: ldnull IL_0001: call "Sub System.Threading.Monitor.Enter(Object)" IL_0006: ldnull IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: call "Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.CheckForSyncLockOnValueType(Object)" IL_000e: ldc.i4.0 IL_000f: stloc.1 .try { IL_0010: ldloc.0 IL_0011: ldloca.s V_1 IL_0013: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0018: leave.s IL_0032 } finally { IL_001a: ldloc.1 IL_001b: brfalse.s IL_0023 IL_001d: ldloc.0 IL_001e: call "Sub System.Threading.Monitor.Exit(Object)" IL_0023: endfinally } } catch System.Exception { IL_0024: dup IL_0025: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)" IL_002a: stloc.2 IL_002b: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()" IL_0030: leave.s IL_0032 } IL_0032: ret } ]]>) End Sub <Fact()> Public Sub TryAndSyncLock_1() Dim source = <compilation> <file name="a.vb"> Module M1 Sub Main() Try Dim o = Nothing Catch Finally lab1: SyncLock String.Empty GoTo lab1 End SyncLock End Try End Sub End Module </file> </compilation> CompileAndVerify(source).VerifyIL("M1.Main", <![CDATA[ { // Code size 44 (0x2c) .maxstack 2 .locals init (Object V_0, Boolean V_1) .try { .try { IL_0000: leave.s IL_002a } catch System.Exception { IL_0002: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)" IL_0007: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()" IL_000c: leave.s IL_002a } } finally { IL_000e: ldsfld "String.Empty As String" IL_0013: stloc.0 IL_0014: ldc.i4.0 IL_0015: stloc.1 .try { IL_0016: ldloc.0 IL_0017: ldloca.s V_1 IL_0019: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_001e: leave.s IL_000e } finally { IL_0020: ldloc.1 IL_0021: brfalse.s IL_0029 IL_0023: ldloc.0 IL_0024: call "Sub System.Threading.Monitor.Exit(Object)" IL_0029: endfinally } } IL_002a: br.s IL_002a } ]]>) End Sub <Fact()> Public Sub JumpFormOneCaseToAnotherCase() Dim source = <compilation> <file name="a.vb"> Option Infer On Imports System Class Program Shared Sub Main() Select "" Case "a" SyncLock Nothing GoTo lab1 End SyncLock Case "b" lab1: End Select End Sub End Class </file> </compilation> CompileAndVerify(source).VerifyIL("Program.Main", <![CDATA[ { // Code size 65 (0x41) .maxstack 3 .locals init (String V_0, Object V_1, Boolean V_2) IL_0000: ldstr "" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr "a" IL_000c: ldc.i4.0 IL_000d: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer" IL_0012: brfalse.s IL_0022 IL_0014: ldloc.0 IL_0015: ldstr "b" IL_001a: ldc.i4.0 IL_001b: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer" IL_0020: pop IL_0021: ret IL_0022: ldnull IL_0023: stloc.1 IL_0024: ldloc.1 IL_0025: call "Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.CheckForSyncLockOnValueType(Object)" IL_002a: ldc.i4.0 IL_002b: stloc.2 .try { IL_002c: ldloc.1 IL_002d: ldloca.s V_2 IL_002f: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0034: leave.s IL_0040 } finally { IL_0036: ldloc.2 IL_0037: brfalse.s IL_003f IL_0039: ldloc.1 IL_003a: call "Sub System.Threading.Monitor.Exit(Object)" IL_003f: endfinally } IL_0040: ret } ]]>) End Sub <Fact()> Public Sub CustomerApplication() Dim source = <compilation> <file name="a.vb"> Class C Public Shared Sub Main(args As String()) Dim p As New D() Dim t As System.Threading.Thread() = New System.Threading.Thread(19) {} For i As Integer = 0 To 19 t(i) = New System.Threading.Thread(AddressOf p.goo) t(i).Start() Next For i As Integer = 0 To 19 t(i).Join() Next System.Console.WriteLine(p.s) End Sub End Class Class D Private syncroot As New Object() Public s As Integer Public Sub goo() SyncLock syncroot For i As Integer = 0 To 49999 s = s + 1 Next End SyncLock Return End Sub End Class </file> </compilation> CompileAndVerify(source, expectedOutput:="1000000") End Sub <Fact()> Public Sub CustomerApplication_2() Dim source = <compilation> <file name="a.vb"> Imports System Class Test Public Shared Sub Main() Dim p As New D() Dim t As System.Threading.Thread() = New System.Threading.Thread(9) {} For i As Integer = 0 To 4 t(i) = New System.Threading.Thread(AddressOf p.goo) t(i).Start() Next For i As Integer = 0 To 4 t(i).Join() Next End Sub End Class Class D Private syncroot As New Object() Public Sub goo() Try SyncLock syncroot System.Console.Write("Lock") Throw New Exception() End SyncLock Catch System.Console.Write("Catch") End Try Return End Sub End Class </file> </compilation> CompileAndVerify(source).VerifyIL("D.goo", <![CDATA[ { // Code size 72 (0x48) .maxstack 2 .locals init (Object V_0, Boolean V_1) .try { IL_0000: ldarg.0 IL_0001: ldfld "D.syncroot As Object" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call "Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.CheckForSyncLockOnValueType(Object)" IL_000d: ldc.i4.0 IL_000e: stloc.1 .try { IL_000f: ldloc.0 IL_0010: ldloca.s V_1 IL_0012: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0017: ldstr "Lock" IL_001c: call "Sub System.Console.Write(String)" IL_0021: newobj "Sub System.Exception..ctor()" IL_0026: throw } finally { IL_0027: ldloc.1 IL_0028: brfalse.s IL_0030 IL_002a: ldloc.0 IL_002b: call "Sub System.Threading.Monitor.Exit(Object)" IL_0030: endfinally } } catch System.Exception { IL_0031: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)" IL_0036: ldstr "Catch" IL_003b: call "Sub System.Console.Write(String)" IL_0040: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()" IL_0045: leave.s IL_0047 } IL_0047: ret } ]]>) End Sub <Fact()> Public Sub SyncLockNoCheckForSyncLockOnValueType() Dim source = <compilation> <file name="a.vb"> Module Module1 Private SyncObj As Object = New Object() Sub Main() SyncLock SyncObj End SyncLock End Sub End Module </file> </compilation> CompileAndVerify(source, options:=TestOptions.ReleaseExe.WithEmbedVbCoreRuntime(True)).VerifyIL("Module1.Main", <![CDATA[ { // Code size 29 (0x1d) .maxstack 2 .locals init (Object V_0, Boolean V_1) IL_0000: ldsfld "Module1.SyncObj As Object" IL_0005: stloc.0 IL_0006: ldc.i4.0 IL_0007: stloc.1 .try { IL_0008: ldloc.0 IL_0009: ldloca.s V_1 IL_000b: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0010: leave.s IL_001c } finally { IL_0012: ldloc.1 IL_0013: brfalse.s IL_001b IL_0015: ldloc.0 IL_0016: call "Sub System.Threading.Monitor.Exit(Object)" IL_001b: endfinally } IL_001c: ret } ]]>) End Sub <Fact()> Public Sub SyncLockWithCheckForSyncLockOnValueType() Dim source = <compilation> <file name="a.vb"> Module Module1 Private SyncObj As Object = New Object() Sub Main() SyncLock SyncObj End SyncLock End Sub End Module </file> </compilation> CompileAndVerify(source, options:=TestOptions.ReleaseExe.WithEmbedVbCoreRuntime(False)).VerifyIL("Module1.Main", <![CDATA[ { // Code size 35 (0x23) .maxstack 2 .locals init (Object V_0, Boolean V_1) IL_0000: ldsfld "Module1.SyncObj As Object" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: call "Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.CheckForSyncLockOnValueType(Object)" IL_000c: ldc.i4.0 IL_000d: stloc.1 .try { IL_000e: ldloc.0 IL_000f: ldloca.s V_1 IL_0011: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0016: leave.s IL_0022 } finally { IL_0018: ldloc.1 IL_0019: brfalse.s IL_0021 IL_001b: ldloc.0 IL_001c: call "Sub System.Threading.Monitor.Exit(Object)" IL_0021: endfinally } IL_0022: ret } ]]>) End Sub <Fact, WorkItem(811916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/811916")> Public Sub VBLegacyThreading_VB7FreeThreading_SyncLock_SyncLock4() Dim source = <compilation> <file name="a.vb"> Module Module1 Dim x As New T1 Sub Main() SyncLock x x.goo() End SyncLock End Sub End Module Class T1 Public Sub goo() End Sub End Class </file> </compilation> CompileAndVerify(source, options:=TestOptions.ReleaseExe).VerifyIL("Module1.Main", <![CDATA[ { // Code size 39 (0x27) .maxstack 2 .locals init (Object V_0, Boolean V_1) IL_0000: ldsfld "Module1.x As T1" IL_0005: stloc.0 IL_0006: ldc.i4.0 IL_0007: stloc.1 .try { IL_0008: ldloc.0 IL_0009: ldloca.s V_1 IL_000b: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0010: ldsfld "Module1.x As T1" IL_0015: callvirt "Sub T1.goo()" IL_001a: leave.s IL_0026 } finally { IL_001c: ldloc.1 IL_001d: brfalse.s IL_0025 IL_001f: ldloc.0 IL_0020: call "Sub System.Threading.Monitor.Exit(Object)" IL_0025: endfinally } IL_0026: ret } ]]>) End Sub <Fact(), WorkItem(1106943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1106943")> Public Sub Bug1106943_01() Dim source = <compilation> <file name="a.vb"> Option Strict On Imports System Class C1 Public Shared Sub Main() SyncLock GetType(C1) Console.WriteLine("Inside SyncLock.") End SyncLock End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe) compilation.MakeMemberMissing(WellKnownMember.System_Threading_Monitor__Enter) CompileAndVerify(compilation, expectedOutput:="Inside SyncLock.") End Sub <Fact(), WorkItem(1106943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1106943")> Public Sub Bug1106943_02() Dim source = <compilation> <file name="a.vb"> Option Strict On Imports System Class C1 Public Shared Sub Main() SyncLock GetType(C1) Console.WriteLine("Inside SyncLock.") End SyncLock End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe) compilation.MakeMemberMissing(WellKnownMember.System_Threading_Monitor__Enter2) CompileAndVerify(compilation, expectedOutput:="Inside SyncLock.") End Sub <Fact(), WorkItem(1106943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1106943")> Public Sub Bug1106943_03() Dim source = <compilation> <file name="a.vb"> Option Strict On Imports System Class C1 Public Shared Sub Main() SyncLock GetType(C1) Console.WriteLine("Inside SyncLock.") End SyncLock End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe) compilation.MakeMemberMissing(WellKnownMember.System_Threading_Monitor__Enter) compilation.MakeMemberMissing(WellKnownMember.System_Threading_Monitor__Enter2) AssertTheseEmitDiagnostics(compilation, <expected> BC35000: Requested operation is not available because the runtime library function 'System.Threading.Monitor.Enter' is not defined. SyncLock GetType(C1) ~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(1106943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1106943")> Public Sub Bug1106943_04() Dim source = <compilation> <file name="a.vb"> Option Strict On Imports System Class C1 Public Shared Sub Main() SyncLock GetType(C1) Console.WriteLine("Inside SyncLock.") End SyncLock End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe) compilation.MakeMemberMissing(WellKnownMember.System_Threading_Monitor__Exit) AssertTheseEmitDiagnostics(compilation, <expected> BC35000: Requested operation is not available because the runtime library function 'System.Threading.Monitor.Exit' is not defined. SyncLock GetType(C1) ~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(1106943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1106943")> Public Sub Bug1106943_05() Dim source = <compilation> <file name="a.vb"> Option Strict On Imports System Class C1 Public Shared Sub Main() SyncLock GetType(C1) Console.WriteLine("Inside SyncLock.") End SyncLock End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe) compilation.MakeMemberMissing(WellKnownMember.System_Threading_Monitor__Enter) compilation.MakeMemberMissing(WellKnownMember.System_Threading_Monitor__Enter2) compilation.MakeMemberMissing(WellKnownMember.System_Threading_Monitor__Exit) AssertTheseEmitDiagnostics(compilation, <expected> BC35000: Requested operation is not available because the runtime library function 'System.Threading.Monitor.Exit' is not defined. SyncLock GetType(C1) ~~~~~~~~~~~~~~~~~~~~~ BC35000: Requested operation is not available because the runtime library function 'System.Threading.Monitor.Enter' is not defined. SyncLock GetType(C1) ~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(1106943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1106943")> Public Sub Bug1106943_06() Dim source = <compilation> <file name="a.vb"> Option Strict On Imports System Class C1 Public Shared Sub Main() SyncLock GetType(C1) Console.WriteLine("Inside SyncLock.") End SyncLock End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe) compilation.MakeTypeMissing(WellKnownType.System_Threading_Monitor) AssertTheseEmitDiagnostics(compilation, <expected> BC35000: Requested operation is not available because the runtime library function 'System.Threading.Monitor.Exit' is not defined. SyncLock GetType(C1) ~~~~~~~~~~~~~~~~~~~~~ BC35000: Requested operation is not available because the runtime library function 'System.Threading.Monitor.Enter' is not defined. SyncLock GetType(C1) ~~~~~~~~~~~ </expected>) 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 CodeGenSyncLock Inherits BasicTestBase <Fact()> Public Sub SimpleSyncLock() Dim source = <compilation> <file name="a.vb"> Option Strict On Imports System Class C1 Public Shared Sub Main() SyncLock GetType(C1) Console.WriteLine("Inside SyncLock.") End SyncLock End Sub End Class </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ Inside SyncLock. ]]>).VerifyIL("C1.Main", <![CDATA[ { // Code size 44 (0x2c) .maxstack 2 .locals init (Object V_0, Boolean V_1) IL_0000: ldtoken "C1" IL_0005: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type" IL_000a: stloc.0 IL_000b: ldc.i4.0 IL_000c: stloc.1 .try { IL_000d: ldloc.0 IL_000e: ldloca.s V_1 IL_0010: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0015: ldstr "Inside SyncLock." IL_001a: call "Sub System.Console.WriteLine(String)" IL_001f: leave.s IL_002b } finally { IL_0021: ldloc.1 IL_0022: brfalse.s IL_002a IL_0024: ldloc.0 IL_0025: call "Sub System.Threading.Monitor.Exit(Object)" IL_002a: endfinally } IL_002b: ret } ]]>) End Sub <Fact()> Public Sub SimpleSyncLockOldMonitorEnter() Dim source = <compilation> <file name="a.vb"> Option Strict On Imports System Class C1 Public Shared Sub Main() SyncLock GetType(C1) Console.WriteLine("Inside SyncLock.") End SyncLock End Sub End Class </file> </compilation> Dim allReferences As MetadataReference() = { TestMetadata.Net20.mscorlib, SystemRef, MsvbRef} CompileAndVerify(source, allReferences, ).VerifyIL("C1.Main", <![CDATA[ { // Code size 37 (0x25) .maxstack 1 .locals init (Object V_0) IL_0000: ldtoken "C1" IL_0005: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type" IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: call "Sub System.Threading.Monitor.Enter(Object)" .try { IL_0011: ldstr "Inside SyncLock." IL_0016: call "Sub System.Console.WriteLine(String)" IL_001b: leave.s IL_0024 } finally { IL_001d: ldloc.0 IL_001e: call "Sub System.Threading.Monitor.Exit(Object)" IL_0023: endfinally } IL_0024: ret } ]]>) End Sub <Fact()> Public Sub SimpleSyncLockTypeParameter() Dim source = <compilation> <file name="a.vb"> Option Strict On Imports System Class C1 Public Shared Sub Main() DoStuff(Of C1)() End Sub Public Shared Sub DoStuff(Of T as Class)() Dim lock as T = TryCast(new C1(), T) SyncLock lock Console.WriteLine("Inside SyncLock.") End SyncLock End Sub End Class </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ Inside SyncLock. ]]> ).VerifyIL("C1.DoStuff", <![CDATA[ { // Code size 54 (0x36) .maxstack 2 .locals init (Object V_0, Boolean V_1) IL_0000: newobj "Sub C1..ctor()" IL_0005: isinst "T" IL_000a: unbox.any "T" IL_000f: box "T" IL_0014: stloc.0 IL_0015: ldc.i4.0 IL_0016: stloc.1 .try { IL_0017: ldloc.0 IL_0018: ldloca.s V_1 IL_001a: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_001f: ldstr "Inside SyncLock." IL_0024: call "Sub System.Console.WriteLine(String)" IL_0029: leave.s IL_0035 } finally { IL_002b: ldloc.1 IL_002c: brfalse.s IL_0034 IL_002e: ldloc.0 IL_002f: call "Sub System.Threading.Monitor.Exit(Object)" IL_0034: endfinally } IL_0035: ret } ]]>) End Sub <Fact()> Public Sub SimpleSyncLockObjectType() Dim source = <compilation> <file name="a.vb"> Option Strict On Imports System Class C1 Public Shared Sub Main() Dim lock as new Object() SyncLock lock Console.WriteLine("Inside SyncLock.") End SyncLock End Sub End Class </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ Inside SyncLock. ]]>).VerifyIL("C1.Main", <![CDATA[ { // Code size 50 (0x32) .maxstack 2 .locals init (Object V_0, Boolean V_1) IL_0000: newobj "Sub Object..ctor()" IL_0005: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: call "Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.CheckForSyncLockOnValueType(Object)" IL_0011: ldc.i4.0 IL_0012: stloc.1 .try { IL_0013: ldloc.0 IL_0014: ldloca.s V_1 IL_0016: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_001b: ldstr "Inside SyncLock." IL_0020: call "Sub System.Console.WriteLine(String)" IL_0025: leave.s IL_0031 } finally { IL_0027: ldloc.1 IL_0028: brfalse.s IL_0030 IL_002a: ldloc.0 IL_002b: call "Sub System.Threading.Monitor.Exit(Object)" IL_0030: endfinally } IL_0031: ret } ]]>) End Sub <Fact()> Public Sub SimpleSyncLockPropertyAccess() Dim source = <compilation> <file name="a.vb"> Option Strict On Imports System Class C1 Public Shared ReadOnly Property GetInstance() as C1 Get return new C1() End Get End Property Public Shared Sub Main() SyncLock GetInstance Console.WriteLine("Inside SyncLock.") End SyncLock End Sub End Class </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ Inside SyncLock. ]]>) End Sub <Fact()> Public Sub SimpleSyncLockNothing() Dim source = <compilation> <file name="a.vb"> Option Strict ON Imports System Class Program Shared Sub Main() SyncLock Nothing Exit Sub End SyncLock End Sub End Class </file> </compilation> CompileAndVerify(source).VerifyIL("Program.Main", <![CDATA[ { // Code size 31 (0x1f) .maxstack 2 .locals init (Object V_0, Boolean V_1) IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: call "Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.CheckForSyncLockOnValueType(Object)" IL_0008: ldc.i4.0 IL_0009: stloc.1 .try { IL_000a: ldloc.0 IL_000b: ldloca.s V_1 IL_000d: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0012: leave.s IL_001e } finally { IL_0014: ldloc.1 IL_0015: brfalse.s IL_001d IL_0017: ldloc.0 IL_0018: call "Sub System.Threading.Monitor.Exit(Object)" IL_001d: endfinally } IL_001e: ret } ]]>) End Sub <Fact()> Public Sub SimpleSyncLockInterface() Dim source = <compilation> <file name="a.vb"> Option Strict ON Module M1 Sub Main() SyncLock Goo End SyncLock End Sub Function Goo() As I1 Return Nothing End Function End Module Interface I1 End Interface </file> </compilation> CompileAndVerify(source).VerifyIL("M1.Main", <![CDATA[ { // Code size 29 (0x1d) .maxstack 2 .locals init (Object V_0, Boolean V_1) IL_0000: call "Function M1.Goo() As I1" IL_0005: stloc.0 IL_0006: ldc.i4.0 IL_0007: stloc.1 .try { IL_0008: ldloc.0 IL_0009: ldloca.s V_1 IL_000b: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0010: leave.s IL_001c } finally { IL_0012: ldloc.1 IL_0013: brfalse.s IL_001b IL_0015: ldloc.0 IL_0016: call "Sub System.Threading.Monitor.Exit(Object)" IL_001b: endfinally } IL_001c: ret } ]]>) End Sub <Fact()> Public Sub SimpleSyncLockSharedObject() Dim source = <compilation> <file name="a.vb"> Class Program Shared Key As Object Shared Sub Main() SyncLock Key End SyncLock End Sub End Class </file> </compilation> CompileAndVerify(source).VerifyIL("Program.Main", <![CDATA[ { // Code size 35 (0x23) .maxstack 2 .locals init (Object V_0, Boolean V_1) IL_0000: ldsfld "Program.Key As Object" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: call "Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.CheckForSyncLockOnValueType(Object)" IL_000c: ldc.i4.0 IL_000d: stloc.1 .try { IL_000e: ldloc.0 IL_000f: ldloca.s V_1 IL_0011: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0016: leave.s IL_0022 } finally { IL_0018: ldloc.1 IL_0019: brfalse.s IL_0021 IL_001b: ldloc.0 IL_001c: call "Sub System.Threading.Monitor.Exit(Object)" IL_0021: endfinally } IL_0022: ret } ]]>) End Sub <Fact()> Public Sub SimpleSyncLockDelegate() Dim source = <compilation> <file name="a.vb"> Delegate Sub D(p1 As Integer) Class Program Public Shared Sub Main(args As String()) SyncLock New D(AddressOf PM) End SyncLock End Sub Private Shared Sub PM(p1 As Integer) End Sub End Class </file> </compilation> CompileAndVerify(source).VerifyIL("Program.Main", <![CDATA[ { // Code size 36 (0x24) .maxstack 2 .locals init (Object V_0, Boolean V_1) IL_0000: ldnull IL_0001: ldftn "Sub Program.PM(Integer)" IL_0007: newobj "Sub D..ctor(Object, System.IntPtr)" IL_000c: stloc.0 IL_000d: ldc.i4.0 IL_000e: stloc.1 .try { IL_000f: ldloc.0 IL_0010: ldloca.s V_1 IL_0012: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0017: leave.s IL_0023 } finally { IL_0019: ldloc.1 IL_001a: brfalse.s IL_0022 IL_001c: ldloc.0 IL_001d: call "Sub System.Threading.Monitor.Exit(Object)" IL_0022: endfinally } IL_0023: ret } ]]>) End Sub <Fact()> Public Sub CallMonitorExitInSyncLock() Dim source = <compilation> <file name="a.vb"> Class Program Public Shared Sub Main(args As String()) SyncLock args System.Threading.Monitor.Exit(args) End SyncLock End Sub End Class </file> </compilation> CompileAndVerify(source).VerifyIL("Program.Main", <![CDATA[ { // Code size 31 (0x1f) .maxstack 2 .locals init (Object V_0, Boolean V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldc.i4.0 IL_0003: stloc.1 .try { IL_0004: ldloc.0 IL_0005: ldloca.s V_1 IL_0007: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_000c: ldarg.0 IL_000d: call "Sub System.Threading.Monitor.Exit(Object)" IL_0012: leave.s IL_001e } finally { IL_0014: ldloc.1 IL_0015: brfalse.s IL_001d IL_0017: ldloc.0 IL_0018: call "Sub System.Threading.Monitor.Exit(Object)" IL_001d: endfinally } IL_001e: ret } ]]>) End Sub <Fact()> Public Sub CallMonitorExitInSyncLock_1() Dim source = <compilation> <file name="a.vb"> Class Program Public Shared Sub Main(args As String()) End Sub Public Sub goo(obj As Object) SyncLock obj System.Threading.Monitor.Exit(obj) End SyncLock End Sub End Class </file> </compilation> CompileAndVerify(source).VerifyIL("Program.goo", <![CDATA[ { // Code size 42 (0x2a) .maxstack 2 .locals init (Object V_0, Boolean V_1) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: call "Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.CheckForSyncLockOnValueType(Object)" IL_0008: ldc.i4.0 IL_0009: stloc.1 .try { IL_000a: ldloc.0 IL_000b: ldloca.s V_1 IL_000d: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0012: ldarg.1 IL_0013: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0018: call "Sub System.Threading.Monitor.Exit(Object)" IL_001d: leave.s IL_0029 } finally { IL_001f: ldloc.1 IL_0020: brfalse.s IL_0028 IL_0022: ldloc.0 IL_0023: call "Sub System.Threading.Monitor.Exit(Object)" IL_0028: endfinally } IL_0029: ret } ]]>) End Sub <Fact()> Public Sub SyncLockMe() Dim source = <compilation> <file name="a.vb"> Class Program Sub goo() SyncLock Me End SyncLock End Sub End Class </file> </compilation> CompileAndVerify(source).VerifyIL("Program.goo", <![CDATA[ { // Code size 25 (0x19) .maxstack 2 .locals init (Object V_0, Boolean V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldc.i4.0 IL_0003: stloc.1 .try { IL_0004: ldloc.0 IL_0005: ldloca.s V_1 IL_0007: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_000c: leave.s IL_0018 } finally { IL_000e: ldloc.1 IL_000f: brfalse.s IL_0017 IL_0011: ldloc.0 IL_0012: call "Sub System.Threading.Monitor.Exit(Object)" IL_0017: endfinally } IL_0018: ret } ]]>) End Sub <Fact()> Public Sub SyncLockString() Dim source = <compilation> <file name="a.vb"> Class Program Sub goo() SyncLock "abc" End SyncLock End Sub End Class </file> </compilation> CompileAndVerify(source).VerifyIL("Program.goo", <![CDATA[ { // Code size 29 (0x1d) .maxstack 2 .locals init (Object V_0, Boolean V_1) IL_0000: ldstr "abc" IL_0005: stloc.0 IL_0006: ldc.i4.0 IL_0007: stloc.1 .try { IL_0008: ldloc.0 IL_0009: ldloca.s V_1 IL_000b: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0010: leave.s IL_001c } finally { IL_0012: ldloc.1 IL_0013: brfalse.s IL_001b IL_0015: ldloc.0 IL_0016: call "Sub System.Threading.Monitor.Exit(Object)" IL_001b: endfinally } IL_001c: ret } ]]>) End Sub <Fact()> Public Sub NestedSyncLock() Dim source = <compilation> <file name="a.vb"> Public Class Program Public Sub goo() Dim syncroot As Object = New Object SyncLock syncroot SyncLock syncroot.ToString() End SyncLock End SyncLock End Sub End Class </file> </compilation> CompileAndVerify(source).VerifyIL("Program.goo", <![CDATA[ { // Code size 71 (0x47) .maxstack 2 .locals init (Object V_0, //syncroot Object V_1, Boolean V_2, Object V_3, Boolean V_4) IL_0000: newobj "Sub Object..ctor()" IL_0005: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: stloc.1 IL_000d: ldloc.1 IL_000e: call "Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.CheckForSyncLockOnValueType(Object)" IL_0013: ldc.i4.0 IL_0014: stloc.2 .try { IL_0015: ldloc.1 IL_0016: ldloca.s V_2 IL_0018: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_001d: ldloc.0 IL_001e: callvirt "Function Object.ToString() As String" IL_0023: stloc.3 IL_0024: ldc.i4.0 IL_0025: stloc.s V_4 .try { IL_0027: ldloc.3 IL_0028: ldloca.s V_4 IL_002a: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_002f: leave.s IL_0046 } finally { IL_0031: ldloc.s V_4 IL_0033: brfalse.s IL_003b IL_0035: ldloc.3 IL_0036: call "Sub System.Threading.Monitor.Exit(Object)" IL_003b: endfinally } } finally { IL_003c: ldloc.2 IL_003d: brfalse.s IL_0045 IL_003f: ldloc.1 IL_0040: call "Sub System.Threading.Monitor.Exit(Object)" IL_0045: endfinally } IL_0046: ret } ]]>) End Sub <Fact()> Public Sub NestedSyncLock_1() Dim source = <compilation> <file name="a.vb"> Public Class Program Public Sub goo() Dim syncroot As Object = New Object SyncLock syncroot SyncLock syncroot End SyncLock End SyncLock End Sub End Class </file> </compilation> CompileAndVerify(source).VerifyIL("Program.goo", <![CDATA[ { // Code size 72 (0x48) .maxstack 2 .locals init (Object V_0, //syncroot Object V_1, Boolean V_2, Object V_3, Boolean V_4) IL_0000: newobj "Sub Object..ctor()" IL_0005: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: stloc.1 IL_000d: ldloc.1 IL_000e: call "Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.CheckForSyncLockOnValueType(Object)" IL_0013: ldc.i4.0 IL_0014: stloc.2 .try { IL_0015: ldloc.1 IL_0016: ldloca.s V_2 IL_0018: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_001d: ldloc.0 IL_001e: stloc.3 IL_001f: ldloc.3 IL_0020: call "Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.CheckForSyncLockOnValueType(Object)" IL_0025: ldc.i4.0 IL_0026: stloc.s V_4 .try { IL_0028: ldloc.3 IL_0029: ldloca.s V_4 IL_002b: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0030: leave.s IL_0047 } finally { IL_0032: ldloc.s V_4 IL_0034: brfalse.s IL_003c IL_0036: ldloc.3 IL_0037: call "Sub System.Threading.Monitor.Exit(Object)" IL_003c: endfinally } } finally { IL_003d: ldloc.2 IL_003e: brfalse.s IL_0046 IL_0040: ldloc.1 IL_0041: call "Sub System.Threading.Monitor.Exit(Object)" IL_0046: endfinally } IL_0047: ret } ]]>) End Sub <Fact()> Public Sub TryAndSyncLock() Dim source = <compilation> <file name="a.vb"> Imports System Module M1 Sub Main() Try System.Threading.Monitor.Enter(Nothing) SyncLock Nothing Exit Try End SyncLock Catch ex As Exception End Try End Sub End Module </file> </compilation> CompileAndVerify(source).VerifyIL("M1.Main", <![CDATA[ { // Code size 51 (0x33) .maxstack 2 .locals init (Object V_0, Boolean V_1, System.Exception V_2) //ex .try { IL_0000: ldnull IL_0001: call "Sub System.Threading.Monitor.Enter(Object)" IL_0006: ldnull IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: call "Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.CheckForSyncLockOnValueType(Object)" IL_000e: ldc.i4.0 IL_000f: stloc.1 .try { IL_0010: ldloc.0 IL_0011: ldloca.s V_1 IL_0013: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0018: leave.s IL_0032 } finally { IL_001a: ldloc.1 IL_001b: brfalse.s IL_0023 IL_001d: ldloc.0 IL_001e: call "Sub System.Threading.Monitor.Exit(Object)" IL_0023: endfinally } } catch System.Exception { IL_0024: dup IL_0025: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)" IL_002a: stloc.2 IL_002b: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()" IL_0030: leave.s IL_0032 } IL_0032: ret } ]]>) End Sub <Fact()> Public Sub TryAndSyncLock_1() Dim source = <compilation> <file name="a.vb"> Module M1 Sub Main() Try Dim o = Nothing Catch Finally lab1: SyncLock String.Empty GoTo lab1 End SyncLock End Try End Sub End Module </file> </compilation> CompileAndVerify(source).VerifyIL("M1.Main", <![CDATA[ { // Code size 44 (0x2c) .maxstack 2 .locals init (Object V_0, Boolean V_1) .try { .try { IL_0000: leave.s IL_002a } catch System.Exception { IL_0002: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)" IL_0007: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()" IL_000c: leave.s IL_002a } } finally { IL_000e: ldsfld "String.Empty As String" IL_0013: stloc.0 IL_0014: ldc.i4.0 IL_0015: stloc.1 .try { IL_0016: ldloc.0 IL_0017: ldloca.s V_1 IL_0019: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_001e: leave.s IL_000e } finally { IL_0020: ldloc.1 IL_0021: brfalse.s IL_0029 IL_0023: ldloc.0 IL_0024: call "Sub System.Threading.Monitor.Exit(Object)" IL_0029: endfinally } } IL_002a: br.s IL_002a } ]]>) End Sub <Fact()> Public Sub JumpFormOneCaseToAnotherCase() Dim source = <compilation> <file name="a.vb"> Option Infer On Imports System Class Program Shared Sub Main() Select "" Case "a" SyncLock Nothing GoTo lab1 End SyncLock Case "b" lab1: End Select End Sub End Class </file> </compilation> CompileAndVerify(source).VerifyIL("Program.Main", <![CDATA[ { // Code size 65 (0x41) .maxstack 3 .locals init (String V_0, Object V_1, Boolean V_2) IL_0000: ldstr "" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr "a" IL_000c: ldc.i4.0 IL_000d: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer" IL_0012: brfalse.s IL_0022 IL_0014: ldloc.0 IL_0015: ldstr "b" IL_001a: ldc.i4.0 IL_001b: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer" IL_0020: pop IL_0021: ret IL_0022: ldnull IL_0023: stloc.1 IL_0024: ldloc.1 IL_0025: call "Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.CheckForSyncLockOnValueType(Object)" IL_002a: ldc.i4.0 IL_002b: stloc.2 .try { IL_002c: ldloc.1 IL_002d: ldloca.s V_2 IL_002f: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0034: leave.s IL_0040 } finally { IL_0036: ldloc.2 IL_0037: brfalse.s IL_003f IL_0039: ldloc.1 IL_003a: call "Sub System.Threading.Monitor.Exit(Object)" IL_003f: endfinally } IL_0040: ret } ]]>) End Sub <Fact()> Public Sub CustomerApplication() Dim source = <compilation> <file name="a.vb"> Class C Public Shared Sub Main(args As String()) Dim p As New D() Dim t As System.Threading.Thread() = New System.Threading.Thread(19) {} For i As Integer = 0 To 19 t(i) = New System.Threading.Thread(AddressOf p.goo) t(i).Start() Next For i As Integer = 0 To 19 t(i).Join() Next System.Console.WriteLine(p.s) End Sub End Class Class D Private syncroot As New Object() Public s As Integer Public Sub goo() SyncLock syncroot For i As Integer = 0 To 49999 s = s + 1 Next End SyncLock Return End Sub End Class </file> </compilation> CompileAndVerify(source, expectedOutput:="1000000") End Sub <Fact()> Public Sub CustomerApplication_2() Dim source = <compilation> <file name="a.vb"> Imports System Class Test Public Shared Sub Main() Dim p As New D() Dim t As System.Threading.Thread() = New System.Threading.Thread(9) {} For i As Integer = 0 To 4 t(i) = New System.Threading.Thread(AddressOf p.goo) t(i).Start() Next For i As Integer = 0 To 4 t(i).Join() Next End Sub End Class Class D Private syncroot As New Object() Public Sub goo() Try SyncLock syncroot System.Console.Write("Lock") Throw New Exception() End SyncLock Catch System.Console.Write("Catch") End Try Return End Sub End Class </file> </compilation> CompileAndVerify(source).VerifyIL("D.goo", <![CDATA[ { // Code size 72 (0x48) .maxstack 2 .locals init (Object V_0, Boolean V_1) .try { IL_0000: ldarg.0 IL_0001: ldfld "D.syncroot As Object" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call "Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.CheckForSyncLockOnValueType(Object)" IL_000d: ldc.i4.0 IL_000e: stloc.1 .try { IL_000f: ldloc.0 IL_0010: ldloca.s V_1 IL_0012: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0017: ldstr "Lock" IL_001c: call "Sub System.Console.Write(String)" IL_0021: newobj "Sub System.Exception..ctor()" IL_0026: throw } finally { IL_0027: ldloc.1 IL_0028: brfalse.s IL_0030 IL_002a: ldloc.0 IL_002b: call "Sub System.Threading.Monitor.Exit(Object)" IL_0030: endfinally } } catch System.Exception { IL_0031: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)" IL_0036: ldstr "Catch" IL_003b: call "Sub System.Console.Write(String)" IL_0040: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()" IL_0045: leave.s IL_0047 } IL_0047: ret } ]]>) End Sub <Fact()> Public Sub SyncLockNoCheckForSyncLockOnValueType() Dim source = <compilation> <file name="a.vb"> Module Module1 Private SyncObj As Object = New Object() Sub Main() SyncLock SyncObj End SyncLock End Sub End Module </file> </compilation> CompileAndVerify(source, options:=TestOptions.ReleaseExe.WithEmbedVbCoreRuntime(True)).VerifyIL("Module1.Main", <![CDATA[ { // Code size 29 (0x1d) .maxstack 2 .locals init (Object V_0, Boolean V_1) IL_0000: ldsfld "Module1.SyncObj As Object" IL_0005: stloc.0 IL_0006: ldc.i4.0 IL_0007: stloc.1 .try { IL_0008: ldloc.0 IL_0009: ldloca.s V_1 IL_000b: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0010: leave.s IL_001c } finally { IL_0012: ldloc.1 IL_0013: brfalse.s IL_001b IL_0015: ldloc.0 IL_0016: call "Sub System.Threading.Monitor.Exit(Object)" IL_001b: endfinally } IL_001c: ret } ]]>) End Sub <Fact()> Public Sub SyncLockWithCheckForSyncLockOnValueType() Dim source = <compilation> <file name="a.vb"> Module Module1 Private SyncObj As Object = New Object() Sub Main() SyncLock SyncObj End SyncLock End Sub End Module </file> </compilation> CompileAndVerify(source, options:=TestOptions.ReleaseExe.WithEmbedVbCoreRuntime(False)).VerifyIL("Module1.Main", <![CDATA[ { // Code size 35 (0x23) .maxstack 2 .locals init (Object V_0, Boolean V_1) IL_0000: ldsfld "Module1.SyncObj As Object" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: call "Sub Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.CheckForSyncLockOnValueType(Object)" IL_000c: ldc.i4.0 IL_000d: stloc.1 .try { IL_000e: ldloc.0 IL_000f: ldloca.s V_1 IL_0011: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0016: leave.s IL_0022 } finally { IL_0018: ldloc.1 IL_0019: brfalse.s IL_0021 IL_001b: ldloc.0 IL_001c: call "Sub System.Threading.Monitor.Exit(Object)" IL_0021: endfinally } IL_0022: ret } ]]>) End Sub <Fact, WorkItem(811916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/811916")> Public Sub VBLegacyThreading_VB7FreeThreading_SyncLock_SyncLock4() Dim source = <compilation> <file name="a.vb"> Module Module1 Dim x As New T1 Sub Main() SyncLock x x.goo() End SyncLock End Sub End Module Class T1 Public Sub goo() End Sub End Class </file> </compilation> CompileAndVerify(source, options:=TestOptions.ReleaseExe).VerifyIL("Module1.Main", <![CDATA[ { // Code size 39 (0x27) .maxstack 2 .locals init (Object V_0, Boolean V_1) IL_0000: ldsfld "Module1.x As T1" IL_0005: stloc.0 IL_0006: ldc.i4.0 IL_0007: stloc.1 .try { IL_0008: ldloc.0 IL_0009: ldloca.s V_1 IL_000b: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0010: ldsfld "Module1.x As T1" IL_0015: callvirt "Sub T1.goo()" IL_001a: leave.s IL_0026 } finally { IL_001c: ldloc.1 IL_001d: brfalse.s IL_0025 IL_001f: ldloc.0 IL_0020: call "Sub System.Threading.Monitor.Exit(Object)" IL_0025: endfinally } IL_0026: ret } ]]>) End Sub <Fact(), WorkItem(1106943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1106943")> Public Sub Bug1106943_01() Dim source = <compilation> <file name="a.vb"> Option Strict On Imports System Class C1 Public Shared Sub Main() SyncLock GetType(C1) Console.WriteLine("Inside SyncLock.") End SyncLock End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe) compilation.MakeMemberMissing(WellKnownMember.System_Threading_Monitor__Enter) CompileAndVerify(compilation, expectedOutput:="Inside SyncLock.") End Sub <Fact(), WorkItem(1106943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1106943")> Public Sub Bug1106943_02() Dim source = <compilation> <file name="a.vb"> Option Strict On Imports System Class C1 Public Shared Sub Main() SyncLock GetType(C1) Console.WriteLine("Inside SyncLock.") End SyncLock End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe) compilation.MakeMemberMissing(WellKnownMember.System_Threading_Monitor__Enter2) CompileAndVerify(compilation, expectedOutput:="Inside SyncLock.") End Sub <Fact(), WorkItem(1106943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1106943")> Public Sub Bug1106943_03() Dim source = <compilation> <file name="a.vb"> Option Strict On Imports System Class C1 Public Shared Sub Main() SyncLock GetType(C1) Console.WriteLine("Inside SyncLock.") End SyncLock End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe) compilation.MakeMemberMissing(WellKnownMember.System_Threading_Monitor__Enter) compilation.MakeMemberMissing(WellKnownMember.System_Threading_Monitor__Enter2) AssertTheseEmitDiagnostics(compilation, <expected> BC35000: Requested operation is not available because the runtime library function 'System.Threading.Monitor.Enter' is not defined. SyncLock GetType(C1) ~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(1106943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1106943")> Public Sub Bug1106943_04() Dim source = <compilation> <file name="a.vb"> Option Strict On Imports System Class C1 Public Shared Sub Main() SyncLock GetType(C1) Console.WriteLine("Inside SyncLock.") End SyncLock End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe) compilation.MakeMemberMissing(WellKnownMember.System_Threading_Monitor__Exit) AssertTheseEmitDiagnostics(compilation, <expected> BC35000: Requested operation is not available because the runtime library function 'System.Threading.Monitor.Exit' is not defined. SyncLock GetType(C1) ~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(1106943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1106943")> Public Sub Bug1106943_05() Dim source = <compilation> <file name="a.vb"> Option Strict On Imports System Class C1 Public Shared Sub Main() SyncLock GetType(C1) Console.WriteLine("Inside SyncLock.") End SyncLock End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe) compilation.MakeMemberMissing(WellKnownMember.System_Threading_Monitor__Enter) compilation.MakeMemberMissing(WellKnownMember.System_Threading_Monitor__Enter2) compilation.MakeMemberMissing(WellKnownMember.System_Threading_Monitor__Exit) AssertTheseEmitDiagnostics(compilation, <expected> BC35000: Requested operation is not available because the runtime library function 'System.Threading.Monitor.Exit' is not defined. SyncLock GetType(C1) ~~~~~~~~~~~~~~~~~~~~~ BC35000: Requested operation is not available because the runtime library function 'System.Threading.Monitor.Enter' is not defined. SyncLock GetType(C1) ~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(1106943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1106943")> Public Sub Bug1106943_06() Dim source = <compilation> <file name="a.vb"> Option Strict On Imports System Class C1 Public Shared Sub Main() SyncLock GetType(C1) Console.WriteLine("Inside SyncLock.") End SyncLock End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe) compilation.MakeTypeMissing(WellKnownType.System_Threading_Monitor) AssertTheseEmitDiagnostics(compilation, <expected> BC35000: Requested operation is not available because the runtime library function 'System.Threading.Monitor.Exit' is not defined. SyncLock GetType(C1) ~~~~~~~~~~~~~~~~~~~~~ BC35000: Requested operation is not available because the runtime library function 'System.Threading.Monitor.Enter' is not defined. SyncLock GetType(C1) ~~~~~~~~~~~ </expected>) End Sub End Class End Namespace
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Analyzers/CSharp/Analyzers/UseIsNullCheck/CSharpUseNullCheckOverTypeCheckDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.UseIsNullCheck { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class CSharpUseNullCheckOverTypeCheckDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public CSharpUseNullCheckOverTypeCheckDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseNullCheckOverTypeCheckDiagnosticId, EnforceOnBuildValues.UseNullCheckOverTypeCheck, CSharpCodeStyleOptions.PreferNullCheckOverTypeCheck, LanguageNames.CSharp, new LocalizableResourceString(nameof(CSharpAnalyzersResources.Prefer_null_check_over_type_check), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)), new LocalizableResourceString(nameof(CSharpAnalyzersResources.Null_check_can_be_clarified), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) { context.RegisterCompilationStartAction(context => { if (((CSharpCompilation)context.Compilation).LanguageVersion < LanguageVersion.CSharp9) { return; } context.RegisterOperationAction(c => AnalyzeIsTypeOperation(c), OperationKind.IsType); context.RegisterOperationAction(c => AnalyzeNegatedPatternOperation(c), OperationKind.NegatedPattern); }); } private static bool ShouldAnalyze(OperationAnalysisContext context, out ReportDiagnostic severity) { var option = context.Options.GetOption(CSharpCodeStyleOptions.PreferNullCheckOverTypeCheck, context.Operation.Syntax.SyntaxTree, context.CancellationToken); if (!option.Value) { severity = ReportDiagnostic.Default; return false; } severity = option.Notification.Severity; return true; } private void AnalyzeNegatedPatternOperation(OperationAnalysisContext context) { if (!ShouldAnalyze(context, out var severity) || context.Operation.Syntax is not UnaryPatternSyntax) { return; } var negatedPattern = (INegatedPatternOperation)context.Operation; // Matches 'x is not MyType' // InputType is the type of 'x' // MatchedType is 'MyType' // We check InheritsFromOrEquals so that we report a diagnostic on the following: // 1. x is not object (which is also equivalent to 'is null' check) // 2. derivedObj is parentObj (which is the same as the previous point). // 3. str is string (where str is a string, this is also equivalent to 'is null' check). // This doesn't match `x is not MyType y` because in such case, negatedPattern.Pattern will // be `DeclarationPattern`, not `TypePattern`. if (negatedPattern.Pattern is ITypePatternOperation typePatternOperation && typePatternOperation.InputType.InheritsFromOrEquals(typePatternOperation.MatchedType)) { context.ReportDiagnostic( DiagnosticHelper.Create( Descriptor, context.Operation.Syntax.GetLocation(), severity, additionalLocations: null, properties: null)); } } private void AnalyzeIsTypeOperation(OperationAnalysisContext context) { if (!ShouldAnalyze(context, out var severity) || context.Operation.Syntax is not BinaryExpressionSyntax) { return; } var isTypeOperation = (IIsTypeOperation)context.Operation; // Matches 'x is MyType' // isTypeOperation.TypeOperand is 'MyType' // isTypeOperation.ValueOperand.Type is the type of 'x'. // We check InheritsFromOrEquals for the same reason as stated in AnalyzeNegatedPatternOperation. // This doesn't match `x is MyType y` because in such case, we have an IsPattern instead of IsType operation. if (isTypeOperation.ValueOperand.Type is not null && isTypeOperation.ValueOperand.Type.InheritsFromOrEquals(isTypeOperation.TypeOperand)) { context.ReportDiagnostic( DiagnosticHelper.Create( Descriptor, context.Operation.Syntax.GetLocation(), severity, additionalLocations: null, properties: null)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.UseIsNullCheck { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class CSharpUseNullCheckOverTypeCheckDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public CSharpUseNullCheckOverTypeCheckDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseNullCheckOverTypeCheckDiagnosticId, EnforceOnBuildValues.UseNullCheckOverTypeCheck, CSharpCodeStyleOptions.PreferNullCheckOverTypeCheck, LanguageNames.CSharp, new LocalizableResourceString(nameof(CSharpAnalyzersResources.Prefer_null_check_over_type_check), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)), new LocalizableResourceString(nameof(CSharpAnalyzersResources.Null_check_can_be_clarified), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) { context.RegisterCompilationStartAction(context => { if (((CSharpCompilation)context.Compilation).LanguageVersion < LanguageVersion.CSharp9) { return; } context.RegisterOperationAction(c => AnalyzeIsTypeOperation(c), OperationKind.IsType); context.RegisterOperationAction(c => AnalyzeNegatedPatternOperation(c), OperationKind.NegatedPattern); }); } private static bool ShouldAnalyze(OperationAnalysisContext context, out ReportDiagnostic severity) { var option = context.Options.GetOption(CSharpCodeStyleOptions.PreferNullCheckOverTypeCheck, context.Operation.Syntax.SyntaxTree, context.CancellationToken); if (!option.Value) { severity = ReportDiagnostic.Default; return false; } severity = option.Notification.Severity; return true; } private void AnalyzeNegatedPatternOperation(OperationAnalysisContext context) { if (!ShouldAnalyze(context, out var severity) || context.Operation.Syntax is not UnaryPatternSyntax) { return; } var negatedPattern = (INegatedPatternOperation)context.Operation; // Matches 'x is not MyType' // InputType is the type of 'x' // MatchedType is 'MyType' // We check InheritsFromOrEquals so that we report a diagnostic on the following: // 1. x is not object (which is also equivalent to 'is null' check) // 2. derivedObj is parentObj (which is the same as the previous point). // 3. str is string (where str is a string, this is also equivalent to 'is null' check). // This doesn't match `x is not MyType y` because in such case, negatedPattern.Pattern will // be `DeclarationPattern`, not `TypePattern`. if (negatedPattern.Pattern is ITypePatternOperation typePatternOperation && typePatternOperation.InputType.InheritsFromOrEquals(typePatternOperation.MatchedType)) { context.ReportDiagnostic( DiagnosticHelper.Create( Descriptor, context.Operation.Syntax.GetLocation(), severity, additionalLocations: null, properties: null)); } } private void AnalyzeIsTypeOperation(OperationAnalysisContext context) { if (!ShouldAnalyze(context, out var severity) || context.Operation.Syntax is not BinaryExpressionSyntax) { return; } var isTypeOperation = (IIsTypeOperation)context.Operation; // Matches 'x is MyType' // isTypeOperation.TypeOperand is 'MyType' // isTypeOperation.ValueOperand.Type is the type of 'x'. // We check InheritsFromOrEquals for the same reason as stated in AnalyzeNegatedPatternOperation. // This doesn't match `x is MyType y` because in such case, we have an IsPattern instead of IsType operation. if (isTypeOperation.ValueOperand.Type is not null && isTypeOperation.ValueOperand.Type.InheritsFromOrEquals(isTypeOperation.TypeOperand)) { context.ReportDiagnostic( DiagnosticHelper.Create( Descriptor, context.Operation.Syntax.GetLocation(), severity, additionalLocations: null, properties: null)); } } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/EditorFeatures/Core/Shared/Utilities/WorkspaceThreadingService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities { [Export(typeof(IWorkspaceThreadingService))] [Shared] internal sealed class WorkspaceThreadingService : IWorkspaceThreadingService { private readonly IThreadingContext _threadingContext; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public WorkspaceThreadingService(IThreadingContext threadingContext) { _threadingContext = threadingContext; } public TResult Run<TResult>(Func<Task<TResult>> asyncMethod) { return _threadingContext.JoinableTaskFactory.Run(asyncMethod); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities { [Export(typeof(IWorkspaceThreadingService))] [Shared] internal sealed class WorkspaceThreadingService : IWorkspaceThreadingService { private readonly IThreadingContext _threadingContext; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public WorkspaceThreadingService(IThreadingContext threadingContext) { _threadingContext = threadingContext; } public TResult Run<TResult>(Func<Task<TResult>> asyncMethod) { return _threadingContext.JoinableTaskFactory.Run(asyncMethod); } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Tools/ExternalAccess/Razor/RazorPredefinedCodeRefactoringProviderNames.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CodeRefactorings; namespace Microsoft.CodeAnalysis.ExternalAccess.Razor { internal static class RazorPredefinedCodeRefactoringProviderNames { public static string AddAwait => PredefinedCodeRefactoringProviderNames.AddAwait; public static string AddConstructorParametersFromMembers => PredefinedCodeRefactoringProviderNames.AddConstructorParametersFromMembers; public static string AddFileBanner => PredefinedCodeRefactoringProviderNames.AddFileBanner; public static string AddMissingImports => PredefinedCodeRefactoringProviderNames.AddMissingImports; public static string ChangeSignature => PredefinedCodeRefactoringProviderNames.ChangeSignature; public static string ConvertAnonymousTypeToClass => PredefinedCodeRefactoringProviderNames.ConvertAnonymousTypeToClass; public static string ConvertDirectCastToTryCast => PredefinedCodeRefactoringProviderNames.ConvertDirectCastToTryCast; public static string ConvertTryCastToDirectCast => PredefinedCodeRefactoringProviderNames.ConvertTryCastToDirectCast; public static string ConvertToInterpolatedString => PredefinedCodeRefactoringProviderNames.ConvertToInterpolatedString; public static string ConvertTupleToStruct => PredefinedCodeRefactoringProviderNames.ConvertTupleToStruct; public static string EncapsulateField => PredefinedCodeRefactoringProviderNames.EncapsulateField; public static string ExtractClass => PredefinedCodeRefactoringProviderNames.ExtractClass; public static string ExtractInterface => PredefinedCodeRefactoringProviderNames.ExtractInterface; public static string ExtractMethod => PredefinedCodeRefactoringProviderNames.ExtractMethod; public static string GenerateConstructorFromMembers => PredefinedCodeRefactoringProviderNames.GenerateConstructorFromMembers; public static string GenerateDefaultConstructors => PredefinedCodeRefactoringProviderNames.GenerateDefaultConstructors; public static string GenerateEqualsAndGetHashCodeFromMembers => PredefinedCodeRefactoringProviderNames.GenerateEqualsAndGetHashCodeFromMembers; public static string GenerateOverrides => PredefinedCodeRefactoringProviderNames.GenerateOverrides; public static string InlineTemporary => PredefinedCodeRefactoringProviderNames.InlineTemporary; public static string IntroduceUsingStatement => PredefinedCodeRefactoringProviderNames.IntroduceUsingStatement; public static string IntroduceVariable => PredefinedCodeRefactoringProviderNames.IntroduceVariable; public static string InvertConditional => PredefinedCodeRefactoringProviderNames.InvertConditional; public static string InvertIf => PredefinedCodeRefactoringProviderNames.InvertIf; public static string InvertLogical => PredefinedCodeRefactoringProviderNames.InvertLogical; public static string MergeConsecutiveIfStatements => PredefinedCodeRefactoringProviderNames.MergeConsecutiveIfStatements; public static string MergeNestedIfStatements => PredefinedCodeRefactoringProviderNames.MergeNestedIfStatements; public static string MoveDeclarationNearReference => PredefinedCodeRefactoringProviderNames.MoveDeclarationNearReference; public static string MoveToNamespace => PredefinedCodeRefactoringProviderNames.MoveToNamespace; public static string MoveTypeToFile => PredefinedCodeRefactoringProviderNames.MoveTypeToFile; public static string PullMemberUp => PredefinedCodeRefactoringProviderNames.PullMemberUp; public static string InlineMethod => PredefinedCodeRefactoringProviderNames.InlineMethod; public static string ReplaceDocCommentTextWithTag => PredefinedCodeRefactoringProviderNames.ReplaceDocCommentTextWithTag; public static string SplitIntoConsecutiveIfStatements => PredefinedCodeRefactoringProviderNames.SplitIntoConsecutiveIfStatements; public static string SplitIntoNestedIfStatements => PredefinedCodeRefactoringProviderNames.SplitIntoNestedIfStatements; public static string SyncNamespace => PredefinedCodeRefactoringProviderNames.SyncNamespace; public static string UseExplicitType => PredefinedCodeRefactoringProviderNames.UseExplicitType; public static string UseExpressionBody => PredefinedCodeRefactoringProviderNames.UseExpressionBody; public static string UseImplicitType => PredefinedCodeRefactoringProviderNames.UseImplicitType; public static string Wrapping => PredefinedCodeRefactoringProviderNames.Wrapping; public static string MakeLocalFunctionStatic => PredefinedCodeRefactoringProviderNames.MakeLocalFunctionStatic; public static string GenerateComparisonOperators => PredefinedCodeRefactoringProviderNames.GenerateComparisonOperators; public static string ReplacePropertyWithMethods => PredefinedCodeRefactoringProviderNames.ReplacePropertyWithMethods; public static string ReplaceMethodWithProperty => PredefinedCodeRefactoringProviderNames.ReplaceMethodWithProperty; public static string AddDebuggerDisplay => PredefinedCodeRefactoringProviderNames.AddDebuggerDisplay; public static string ConvertAutoPropertyToFullProperty => PredefinedCodeRefactoringProviderNames.ConvertAutoPropertyToFullProperty; public static string ReverseForStatement => PredefinedCodeRefactoringProviderNames.ReverseForStatement; public static string ConvertLocalFunctionToMethod => PredefinedCodeRefactoringProviderNames.ConvertLocalFunctionToMethod; public static string ConvertForEachToFor => PredefinedCodeRefactoringProviderNames.ConvertForEachToFor; public static string ConvertLinqQueryToForEach => PredefinedCodeRefactoringProviderNames.ConvertLinqQueryToForEach; public static string ConvertForEachToLinqQuery => PredefinedCodeRefactoringProviderNames.ConvertForEachToLinqQuery; public static string ConvertNumericLiteral => PredefinedCodeRefactoringProviderNames.ConvertNumericLiteral; public static string IntroduceLocalForExpression => PredefinedCodeRefactoringProviderNames.IntroduceLocalForExpression; public static string AddParameterCheck => PredefinedCodeRefactoringProviderNames.AddParameterCheck; public static string InitializeMemberFromParameter => PredefinedCodeRefactoringProviderNames.InitializeMemberFromParameter; public static string NameTupleElement => PredefinedCodeRefactoringProviderNames.NameTupleElement; public static string UseNamedArguments => PredefinedCodeRefactoringProviderNames.UseNamedArguments; public static string ConvertForToForEach => PredefinedCodeRefactoringProviderNames.ConvertForToForEach; public static string ConvertIfToSwitch => PredefinedCodeRefactoringProviderNames.ConvertIfToSwitch; public static string ConvertBetweenRegularAndVerbatimString => PredefinedCodeRefactoringProviderNames.ConvertBetweenRegularAndVerbatimString; public static string ConvertBetweenRegularAndVerbatimInterpolatedString => PredefinedCodeRefactoringProviderNames.ConvertBetweenRegularAndVerbatimInterpolatedString; public static string RenameTracking => PredefinedCodeRefactoringProviderNames.RenameTracking; public static string UseExpressionBodyForLambda => PredefinedCodeRefactoringProviderNames.UseExpressionBodyForLambda; public static string ImplementInterfaceExplicitly => PredefinedCodeRefactoringProviderNames.ImplementInterfaceExplicitly; public static string ImplementInterfaceImplicitly => PredefinedCodeRefactoringProviderNames.ImplementInterfaceImplicitly; public static string ConvertPlaceholderToInterpolatedString => PredefinedCodeRefactoringProviderNames.ConvertPlaceholderToInterpolatedString; public static string ConvertConcatenationToInterpolatedString => PredefinedCodeRefactoringProviderNames.ConvertConcatenationToInterpolatedString; public static string InvertMultiLineIf => PredefinedCodeRefactoringProviderNames.InvertMultiLineIf; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CodeRefactorings; namespace Microsoft.CodeAnalysis.ExternalAccess.Razor { internal static class RazorPredefinedCodeRefactoringProviderNames { public static string AddAwait => PredefinedCodeRefactoringProviderNames.AddAwait; public static string AddConstructorParametersFromMembers => PredefinedCodeRefactoringProviderNames.AddConstructorParametersFromMembers; public static string AddFileBanner => PredefinedCodeRefactoringProviderNames.AddFileBanner; public static string AddMissingImports => PredefinedCodeRefactoringProviderNames.AddMissingImports; public static string ChangeSignature => PredefinedCodeRefactoringProviderNames.ChangeSignature; public static string ConvertAnonymousTypeToClass => PredefinedCodeRefactoringProviderNames.ConvertAnonymousTypeToClass; public static string ConvertDirectCastToTryCast => PredefinedCodeRefactoringProviderNames.ConvertDirectCastToTryCast; public static string ConvertTryCastToDirectCast => PredefinedCodeRefactoringProviderNames.ConvertTryCastToDirectCast; public static string ConvertToInterpolatedString => PredefinedCodeRefactoringProviderNames.ConvertToInterpolatedString; public static string ConvertTupleToStruct => PredefinedCodeRefactoringProviderNames.ConvertTupleToStruct; public static string EncapsulateField => PredefinedCodeRefactoringProviderNames.EncapsulateField; public static string ExtractClass => PredefinedCodeRefactoringProviderNames.ExtractClass; public static string ExtractInterface => PredefinedCodeRefactoringProviderNames.ExtractInterface; public static string ExtractMethod => PredefinedCodeRefactoringProviderNames.ExtractMethod; public static string GenerateConstructorFromMembers => PredefinedCodeRefactoringProviderNames.GenerateConstructorFromMembers; public static string GenerateDefaultConstructors => PredefinedCodeRefactoringProviderNames.GenerateDefaultConstructors; public static string GenerateEqualsAndGetHashCodeFromMembers => PredefinedCodeRefactoringProviderNames.GenerateEqualsAndGetHashCodeFromMembers; public static string GenerateOverrides => PredefinedCodeRefactoringProviderNames.GenerateOverrides; public static string InlineTemporary => PredefinedCodeRefactoringProviderNames.InlineTemporary; public static string IntroduceUsingStatement => PredefinedCodeRefactoringProviderNames.IntroduceUsingStatement; public static string IntroduceVariable => PredefinedCodeRefactoringProviderNames.IntroduceVariable; public static string InvertConditional => PredefinedCodeRefactoringProviderNames.InvertConditional; public static string InvertIf => PredefinedCodeRefactoringProviderNames.InvertIf; public static string InvertLogical => PredefinedCodeRefactoringProviderNames.InvertLogical; public static string MergeConsecutiveIfStatements => PredefinedCodeRefactoringProviderNames.MergeConsecutiveIfStatements; public static string MergeNestedIfStatements => PredefinedCodeRefactoringProviderNames.MergeNestedIfStatements; public static string MoveDeclarationNearReference => PredefinedCodeRefactoringProviderNames.MoveDeclarationNearReference; public static string MoveToNamespace => PredefinedCodeRefactoringProviderNames.MoveToNamespace; public static string MoveTypeToFile => PredefinedCodeRefactoringProviderNames.MoveTypeToFile; public static string PullMemberUp => PredefinedCodeRefactoringProviderNames.PullMemberUp; public static string InlineMethod => PredefinedCodeRefactoringProviderNames.InlineMethod; public static string ReplaceDocCommentTextWithTag => PredefinedCodeRefactoringProviderNames.ReplaceDocCommentTextWithTag; public static string SplitIntoConsecutiveIfStatements => PredefinedCodeRefactoringProviderNames.SplitIntoConsecutiveIfStatements; public static string SplitIntoNestedIfStatements => PredefinedCodeRefactoringProviderNames.SplitIntoNestedIfStatements; public static string SyncNamespace => PredefinedCodeRefactoringProviderNames.SyncNamespace; public static string UseExplicitType => PredefinedCodeRefactoringProviderNames.UseExplicitType; public static string UseExpressionBody => PredefinedCodeRefactoringProviderNames.UseExpressionBody; public static string UseImplicitType => PredefinedCodeRefactoringProviderNames.UseImplicitType; public static string Wrapping => PredefinedCodeRefactoringProviderNames.Wrapping; public static string MakeLocalFunctionStatic => PredefinedCodeRefactoringProviderNames.MakeLocalFunctionStatic; public static string GenerateComparisonOperators => PredefinedCodeRefactoringProviderNames.GenerateComparisonOperators; public static string ReplacePropertyWithMethods => PredefinedCodeRefactoringProviderNames.ReplacePropertyWithMethods; public static string ReplaceMethodWithProperty => PredefinedCodeRefactoringProviderNames.ReplaceMethodWithProperty; public static string AddDebuggerDisplay => PredefinedCodeRefactoringProviderNames.AddDebuggerDisplay; public static string ConvertAutoPropertyToFullProperty => PredefinedCodeRefactoringProviderNames.ConvertAutoPropertyToFullProperty; public static string ReverseForStatement => PredefinedCodeRefactoringProviderNames.ReverseForStatement; public static string ConvertLocalFunctionToMethod => PredefinedCodeRefactoringProviderNames.ConvertLocalFunctionToMethod; public static string ConvertForEachToFor => PredefinedCodeRefactoringProviderNames.ConvertForEachToFor; public static string ConvertLinqQueryToForEach => PredefinedCodeRefactoringProviderNames.ConvertLinqQueryToForEach; public static string ConvertForEachToLinqQuery => PredefinedCodeRefactoringProviderNames.ConvertForEachToLinqQuery; public static string ConvertNumericLiteral => PredefinedCodeRefactoringProviderNames.ConvertNumericLiteral; public static string IntroduceLocalForExpression => PredefinedCodeRefactoringProviderNames.IntroduceLocalForExpression; public static string AddParameterCheck => PredefinedCodeRefactoringProviderNames.AddParameterCheck; public static string InitializeMemberFromParameter => PredefinedCodeRefactoringProviderNames.InitializeMemberFromParameter; public static string NameTupleElement => PredefinedCodeRefactoringProviderNames.NameTupleElement; public static string UseNamedArguments => PredefinedCodeRefactoringProviderNames.UseNamedArguments; public static string ConvertForToForEach => PredefinedCodeRefactoringProviderNames.ConvertForToForEach; public static string ConvertIfToSwitch => PredefinedCodeRefactoringProviderNames.ConvertIfToSwitch; public static string ConvertBetweenRegularAndVerbatimString => PredefinedCodeRefactoringProviderNames.ConvertBetweenRegularAndVerbatimString; public static string ConvertBetweenRegularAndVerbatimInterpolatedString => PredefinedCodeRefactoringProviderNames.ConvertBetweenRegularAndVerbatimInterpolatedString; public static string RenameTracking => PredefinedCodeRefactoringProviderNames.RenameTracking; public static string UseExpressionBodyForLambda => PredefinedCodeRefactoringProviderNames.UseExpressionBodyForLambda; public static string ImplementInterfaceExplicitly => PredefinedCodeRefactoringProviderNames.ImplementInterfaceExplicitly; public static string ImplementInterfaceImplicitly => PredefinedCodeRefactoringProviderNames.ImplementInterfaceImplicitly; public static string ConvertPlaceholderToInterpolatedString => PredefinedCodeRefactoringProviderNames.ConvertPlaceholderToInterpolatedString; public static string ConvertConcatenationToInterpolatedString => PredefinedCodeRefactoringProviderNames.ConvertConcatenationToInterpolatedString; public static string InvertMultiLineIf => PredefinedCodeRefactoringProviderNames.InvertMultiLineIf; } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Features/CSharp/Portable/ConvertBetweenRegularAndVerbatimString/ConvertBetweenRegularAndVerbatimStringCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Composition; using System.Diagnostics.CodeAnalysis; using System.Text; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.ConvertBetweenRegularAndVerbatimString { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertBetweenRegularAndVerbatimString), Shared] [ExtensionOrder(Before = PredefinedCodeRefactoringProviderNames.ConvertToInterpolatedString)] internal class ConvertBetweenRegularAndVerbatimStringCodeRefactoringProvider : AbstractConvertBetweenRegularAndVerbatimStringCodeRefactoringProvider<LiteralExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public ConvertBetweenRegularAndVerbatimStringCodeRefactoringProvider() { } protected override bool IsInterpolation { get; } = false; protected override bool IsAppropriateLiteralKind(LiteralExpressionSyntax literalExpression) => literalExpression.Kind() == SyntaxKind.StringLiteralExpression; protected override void AddSubStringTokens(LiteralExpressionSyntax literalExpression, ArrayBuilder<SyntaxToken> subStringTokens) => subStringTokens.Add(literalExpression.Token); protected override bool IsVerbatim(LiteralExpressionSyntax literalExpression) => CSharpSyntaxFacts.Instance.IsVerbatimStringLiteral(literalExpression.Token); protected override LiteralExpressionSyntax CreateVerbatimStringExpression(IVirtualCharService charService, StringBuilder sb, LiteralExpressionSyntax stringExpression) { sb.Append('@'); sb.Append(DoubleQuote); AddVerbatimStringText(charService, sb, stringExpression.Token); sb.Append(DoubleQuote); return stringExpression.WithToken(CreateStringToken(sb)); } protected override LiteralExpressionSyntax CreateRegularStringExpression(IVirtualCharService charService, StringBuilder sb, LiteralExpressionSyntax stringExpression) { sb.Append(DoubleQuote); AddRegularStringText(charService, sb, stringExpression.Token); sb.Append(DoubleQuote); return stringExpression.WithToken(CreateStringToken(sb)); } private static SyntaxToken CreateStringToken(StringBuilder sb) => SyntaxFactory.Token( leading: default, SyntaxKind.StringLiteralToken, sb.ToString(), valueText: "", trailing: default); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Text; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.ConvertBetweenRegularAndVerbatimString { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertBetweenRegularAndVerbatimString), Shared] [ExtensionOrder(Before = PredefinedCodeRefactoringProviderNames.ConvertToInterpolatedString)] internal class ConvertBetweenRegularAndVerbatimStringCodeRefactoringProvider : AbstractConvertBetweenRegularAndVerbatimStringCodeRefactoringProvider<LiteralExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public ConvertBetweenRegularAndVerbatimStringCodeRefactoringProvider() { } protected override bool IsInterpolation { get; } = false; protected override bool IsAppropriateLiteralKind(LiteralExpressionSyntax literalExpression) => literalExpression.Kind() == SyntaxKind.StringLiteralExpression; protected override void AddSubStringTokens(LiteralExpressionSyntax literalExpression, ArrayBuilder<SyntaxToken> subStringTokens) => subStringTokens.Add(literalExpression.Token); protected override bool IsVerbatim(LiteralExpressionSyntax literalExpression) => CSharpSyntaxFacts.Instance.IsVerbatimStringLiteral(literalExpression.Token); protected override LiteralExpressionSyntax CreateVerbatimStringExpression(IVirtualCharService charService, StringBuilder sb, LiteralExpressionSyntax stringExpression) { sb.Append('@'); sb.Append(DoubleQuote); AddVerbatimStringText(charService, sb, stringExpression.Token); sb.Append(DoubleQuote); return stringExpression.WithToken(CreateStringToken(sb)); } protected override LiteralExpressionSyntax CreateRegularStringExpression(IVirtualCharService charService, StringBuilder sb, LiteralExpressionSyntax stringExpression) { sb.Append(DoubleQuote); AddRegularStringText(charService, sb, stringExpression.Token); sb.Append(DoubleQuote); return stringExpression.WithToken(CreateStringToken(sb)); } private static SyntaxToken CreateStringToken(StringBuilder sb) => SyntaxFactory.Token( leading: default, SyntaxKind.StringLiteralToken, sb.ToString(), valueText: "", trailing: default); } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/VisualBasic/Test/Emit/ErrorHandling.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class ErrorHandlingTests Inherits BasicTestBase <Fact()> Public Sub ErrorHandler_WithValidLabel_No_Resume() Dim compilationDef = <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() Dim sPath As String = "" sPath = "Test1" On Error GoTo goo Error 5 Console.WriteLine(sPath) Exit Sub goo: sPath &amp;= "goo" Console.WriteLine(sPath) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompileAndVerify(compilation) End Sub <Fact()> Public Sub ErrorHandler_WithGotoMinus1andMatchingLabel() Dim compilationDef = <compilation> <file name="a.vb"> Imports System Module Module1 Public Sub Main() On Error GoTo -1 Error 5 exit sub goo: Resume End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompileAndVerify(compilation) End Sub <Fact()> Public Sub Error_ErrorHandler_WithGoto0andNoMatchingLabel() Dim compilationDef = <compilation> <file name="a.vb"> Imports System Module Module1 Public Sub Main() On Error GoTo 0 Error 5 exit sub Goo: Resume End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompileAndVerify(compilation) 'compilation.VerifyDiagnostics() End Sub <Fact()> Public Sub Error_ErrorHandler_WithResumeNext() Dim compilationDef = <compilation> <file name="a.vb"> Imports System Module Module1 Public Sub Main() On Error Resume Next Error 5 exit sub End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompileAndVerify(compilation) 'compilation.VerifyDiagnostics() End Sub <Fact()> Public Sub ErrorHandler_WithValidLabelMatchingKeywordsEscaped() Dim compilationDef = <compilation> <file name="a.vb"> Imports System Module Module1 Public Sub Main() On Error GoTo [On] On Error GoTo [goto] 'Doesn't matter if case mismatch (Didn't pretty list correctly) On Error GoTo [Error] exit sub [Goto]: Resume [on] [On]: Resume [Error] [Error]: Resume [Goto] End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompileAndVerify(compilation) ' compilation.VerifyDiagnostics() End Sub <Fact()> Public Sub Error_ErrorHandler_WithValidLabelMatchingKeywordsNotEscaped() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Public Sub Main() On Error GoTo On On Error GoTo goto On Error GoTo Error [Goto]: Resume [on] [On]: Resume [Error] [Error]: Resume [Goto] End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedIdentifier, ""), Diagnostic(ERRID.ERR_ExpectedIdentifier, ""), Diagnostic(ERRID.ERR_ExpectedIdentifier, ""), Diagnostic(ERRID.ERR_LabelNotDefined1, "").WithArguments(""), Diagnostic(ERRID.ERR_LabelNotDefined1, "").WithArguments(""), Diagnostic(ERRID.ERR_LabelNotDefined1, "").WithArguments("")) End Sub <Fact()> Public Sub Error_ErrorHandler_WithInValidLabelMatchingKeywordsEscaped() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Public Sub Main() On Error GoTo [On] On Error GoTo [goto] 'Doesn't matter if case mismatch (Didn't pretty list correctly) On Error GoTo [Error] Goto: Resume on On: Resume Error Error: Resume Goto End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedIdentifier, ""), Diagnostic(ERRID.ERR_ExpectedIdentifier, ""), Diagnostic(ERRID.ERR_ObsoleteOnGotoGosub, ""), Diagnostic(ERRID.ERR_ExpectedIdentifier, ""), Diagnostic(ERRID.ERR_ExpectedExpression, ""), Diagnostic(ERRID.ERR_ExpectedIdentifier, ""), Diagnostic(ERRID.ERR_LabelNotDefined1, "[On]").WithArguments("On"), Diagnostic(ERRID.ERR_LabelNotDefined1, "[goto]").WithArguments("goto"), Diagnostic(ERRID.ERR_LabelNotDefined1, "[Error]").WithArguments("Error"), Diagnostic(ERRID.ERR_LabelNotDefined1, "").WithArguments(""), Diagnostic(ERRID.ERR_LabelNotDefined1, "").WithArguments(""), Diagnostic(ERRID.ERR_LabelNotDefined1, "").WithArguments(""), Diagnostic(ERRID.ERR_LabelNotDefined1, "").WithArguments(""), Diagnostic(ERRID.ERR_LabelNotDefined1, "").WithArguments("")) End Sub <Fact()> Public Sub Error_ErrorHandler_WithGoto0andMatchingLabel() Dim compilationDef = <compilation> <file name="a.vb"> Imports System Module Module1 Public Sub Main() On Error GoTo 0 Error 5 exit sub 0: Resume End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) Dim compilationVerifier = CompileAndVerify(compilation) compilationVerifier.VerifyIL("Module1.Main", <![CDATA[ { // Code size 155 (0x9b) .maxstack 3 .locals init (Integer V_0, Integer V_1, Integer V_2, Integer V_3) .try { IL_0000: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()" IL_0005: ldc.i4.0 IL_0006: stloc.0 IL_0007: ldc.i4.2 IL_0008: stloc.2 IL_0009: ldc.i4.5 IL_000a: call "Function Microsoft.VisualBasic.CompilerServices.ProjectData.CreateProjectError(Integer) As System.Exception" IL_000f: throw IL_0010: ldc.i4.0 IL_0011: stloc.3 IL_0012: ldc.i4.5 IL_0013: stloc.2 IL_0014: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()" IL_0019: ldloc.1 IL_001a: brtrue.s IL_0029 IL_001c: ldc.i4 0x800a0014 IL_0021: call "Function Microsoft.VisualBasic.CompilerServices.ProjectData.CreateProjectError(Integer) As System.Exception" IL_0026: throw IL_0027: leave.s IL_0092 IL_0029: ldloc.1 IL_002a: br.s IL_002f IL_002c: ldloc.1 IL_002d: ldc.i4.1 IL_002e: add IL_002f: ldc.i4.0 IL_0030: stloc.1 IL_0031: switch ( IL_0052, IL_0000, IL_0007, IL_0027, IL_0010, IL_0012, IL_0027) IL_0052: leave.s IL_0087 IL_0054: ldloc.2 IL_0055: stloc.1 IL_0056: ldloc.0 IL_0057: switch ( IL_0064, IL_002c) IL_0064: leave.s IL_0087 } filter { IL_0066: isinst "System.Exception" IL_006b: ldnull IL_006c: cgt.un IL_006e: ldloc.0 IL_006f: ldc.i4.0 IL_0070: cgt.un IL_0072: and IL_0073: ldloc.1 IL_0074: ldc.i4.0 IL_0075: ceq IL_0077: and IL_0078: endfilter } // end filter { // handler IL_007a: castclass "System.Exception" IL_007f: ldloc.3 IL_0080: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception, Integer)" IL_0085: leave.s IL_0054 } IL_0087: ldc.i4 0x800a0033 IL_008c: call "Function Microsoft.VisualBasic.CompilerServices.ProjectData.CreateProjectError(Integer) As System.Exception" IL_0091: throw IL_0092: ldloc.1 IL_0093: brfalse.s IL_009a IL_0095: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()" IL_009a: ret } ]]>) End Sub <ConditionalFact(GetType(DesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")> Public Sub Error_ErrorHandler_WithGoto1andMatchingLabel() Dim compilationDef = <compilation> <file name="a.vb"> Imports System Module Module1 Public Sub Main() On Error GoTo 1 Console.writeline("Start") Error 5 Console.writeline("2") exit sub 1: Console.writeline("1") Resume Next End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:=<![CDATA[Start 1 2]]>) End Sub <Fact()> Public Sub Error_ErrorHandler_WithMissingOrIncorrectLabels() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 sing Labels Public Sub Main() End Sub Sub Goto_MissingLabel() 'Error - label is not present On Error GoTo goo End Sub Sub GotoLabelInDifferentMethod() 'Error - no label in this method, in a different so it will fail On Error GoTo diffMethodLabel End Sub Sub GotoLabelInDifferentMethod() 'Error - no label in this method - trying to fully qualify will fail On Error GoTo DifferentMethod.diffMethodLabel End Sub Sub DifferentMethod() DiffMethodLabel: End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedSpecifier, "Labels"), Diagnostic(ERRID.ERR_ExpectedDeclaration, "sing"), Diagnostic(ERRID.ERR_ExpectedEOS, "."), Diagnostic(ERRID.ERR_DuplicateProcDef1, "GotoLabelInDifferentMethod").WithArguments("Public Sub GotoLabelInDifferentMethod()"), Diagnostic(ERRID.ERR_LabelNotDefined1, "goo").WithArguments("goo"), Diagnostic(ERRID.ERR_LabelNotDefined1, "diffMethodLabel").WithArguments("diffMethodLabel"), Diagnostic(ERRID.ERR_LabelNotDefined1, "DifferentMethod").WithArguments("DifferentMethod")) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29568")> Public Sub Error_ErrorHandler_BothTypesOfErrorHandling() Dim compilationDef = <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main TryAndOnErrorInSameMethod OnErrorAndTryInSameMethod End Sub Sub TryAndOnErrorInSameMethod() 'Nested Try On Error GoTo goo goo: Catch ex As Exception End Try End Sub Sub OnErrorAndTryInSameMethod() 'Sequential On Error GoTo goo goo: Try Catch ex As Exception End Try End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Dim ExpectedOutput = <![CDATA[Try On Error GoTo goo goo: Catch ex As Exception End Try]]> Dim ExpectedOutput2 = <![CDATA[Try Catch ex As Exception End Try]]> compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_TryAndOnErrorDoNotMix, ExpectedOutput), Diagnostic(ERRID.ERR_TryAndOnErrorDoNotMix, "On Error GoTo goo"), Diagnostic(ERRID.ERR_TryAndOnErrorDoNotMix, "On Error GoTo goo"), Diagnostic(ERRID.ERR_TryAndOnErrorDoNotMix, ExpectedOutput2) ) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29568")> Public Sub Error_ErrorHandler_InVBCore() 'Old Style handling not supported in VBCore Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Public Sub Main On Error GoTo goo goo: End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(compilationDef, references:={MscorlibRef, SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) Dim ExpectedOutput = <![CDATA[Public Sub Main On Error GoTo goo goo: End Sub]]> compilation.VerifyEmitDiagnostics(Diagnostic(ERRID.ERR_PlatformDoesntSupport, ExpectedOutput).WithArguments("Unstructured exception handling").WithLocation(2, 9)) End Sub <Fact()> Public Sub Error_ErrorHandler_InVBCore_LateBound1() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Dim a As Object Sub Main() a = New ABC a = a + 1 a = a &amp; "test" End Sub End Module Class ABC End Class </file> </compilation> Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(compilationDef, references:={MscorlibRef, SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) compilation.VerifyEmitDiagnostics(Diagnostic(ERRID.ERR_PlatformDoesntSupport, "a + 1").WithArguments("Late binding").WithLocation(6, 13), Diagnostic(ERRID.ERR_PlatformDoesntSupport, "a & ""test""").WithArguments("Late binding").WithLocation(8, 13) ) End Sub <Fact()> Public Sub Error_ErrorHandler_InVBCore_LikeOperator() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim testCheck As Boolean testCheck = "F" Like "F" End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(compilationDef, references:={MscorlibRef, SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) Dim ExpectedOutput = <![CDATA["F" Like "F"]]> compilation.VerifyEmitDiagnostics(Diagnostic(ERRID.ERR_PlatformDoesntSupport, ExpectedOutput).WithArguments("Like operator").WithLocation(5, 21)) End Sub <Fact()> Public Sub Error_ErrorHandler_InVBCore_ErrObject() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Error 1 End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(compilationDef, references:={MscorlibRef, SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) compilation.VerifyEmitDiagnostics(Diagnostic(ERRID.ERR_PlatformDoesntSupport, "Error 1").WithArguments("Unstructured exception handling").WithLocation(4, 18)) End Sub <Fact()> Public Sub Error_ErrorHandler_InVBCore_AnonymousType() Dim source = <compilation> <file name="a.vb"> Module Module1 Dim a As Object Sub Main() a = "1" Dim x = New With {.a = a, .b = a + 1} End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(source, references:={MscorlibRef, SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) compilation.VerifyEmitDiagnostics(Diagnostic(ERRID.ERR_PlatformDoesntSupport, "a + 1").WithArguments("Late binding").WithLocation(6, 40)) End Sub <Fact(), WorkItem(545772, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545772")> Public Sub VbCoreMyNamespace() Dim source = <compilation> <file name="a.vb"> Module Module1 Public Sub Main() My.Computer.FileSystem.WriteAllText("Test.txt","abc") End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(source, references:={MscorlibRef, SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_PlatformDoesntSupport, "My").WithArguments("My").WithLocation(3, 13)) End Sub <Fact()> Public Sub Error_ErrorHandler_OutsideOfMethodBody() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main End Sub 'Error Outside of Method Body On Error Goto goo Sub Goo End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "On Error Goto goo")) End Sub <Fact()> Public Sub ErrorHandler_In_Different_Types() 'Basic Validation that this is permissible in Class/Structure/(Module Tested elsewhere) 'Generic Dim compilationDef = <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main End Sub Class Goo Sub Method() On Error GoTo CLassMethodLabel CLassMethodLabel: End Sub Public Property ABC As String Set(value As String) On Error GoTo setLabel setLabel: End Set Get On Error GoTo getLabel getLabel: End Get End Property End Class Structure Goo_Struct Sub Method() On Error GoTo StructMethodLabel StructMethodLabel: End Sub Public Property ABC As String Set(value As String) On Error GoTo SetLabel setLabel: End Set Get On Error GoTo getLabel getLabel: End Get End Property End Structure Class GenericGoo(Of t) Sub Method() 'Normal Method In Generic Class On Error GoTo CLassMethodLabel CLassMethodLabel: End Sub Sub GenericMethod(Of u)(x As u) 'Generic Method In Generic Class On Error GoTo CLassMethodLabel CLassMethodLabel: End Sub Public Property ABC As String Set(value As String) On Error GoTo setLabel setLabel: End Set Get On Error GoTo getLabel getLabel: End Get End Property End Class End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) compilation.AssertNoDiagnostics() End Sub <Fact()> Public Sub ErrorHandler_Other_Constructor_Dispose() Dim compilationDef = <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main Dim X As New TestInConstructor Dim X2 As New TestInDisposeAndFinalize X2.Dispose() End Sub End Module Class TestInConstructor Sub New() On Error GoTo constructorError ConstructorError: End Sub End Class Class TestInDisposeAndFinalize Implements IDisposable Sub New() End Sub #Region "IDisposable Support" Private disposedValue As Boolean ' To detect redundant calls ' IDisposable Protected Overridable Sub Dispose(disposing As Boolean) On Error GoTo ConstructorError If Not Me.disposedValue Then If disposing Then ' TODO: dispose managed state (managed objects). End If ' TODO: free unmanaged resources (unmanaged objects) and override Finalize() below. ' TODO: set large fields to null. End If Me.disposedValue = True ConstructorError: End Sub ' TODO: override Finalize() only if Dispose(ByVal disposing As Boolean) above has code to free unmanaged resources. Protected Overrides Sub Finalize() On Error GoTo FInalizeError ' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above. Dispose(False) MyBase.Finalize() FInalizeError: End Sub ' This code added by Visual Basic to correctly implement the disposable pattern. Public Sub Dispose() Implements IDisposable.Dispose ' Do not change this code. Put cleanup code in Dispose(disposing As Boolean) above. Dispose(True) GC.SuppressFinalize(Me) End Sub #End Region End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) compilation.VerifyDiagnostics() End Sub <Fact()> Public Sub Error_InvalidTypes_ImplicitConversions() Dim compilationDef = <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main Error 1L Error 2S Error &quot;3&quot; Error 4! Error 5% End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) compilation.AssertNoDiagnostics() End Sub <Fact()> Public Sub Error_InvalidTypes_InvalidTypes_StrictOn() Dim compilationDef = <compilation> <file name="a.vb"> Option Strict On Module Module1 Sub Main Error 1L Error 2S Error &quot;3&quot; Error 4! Error 5% End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, """3""").WithArguments("String", "Integer"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "4!").WithArguments("Single", "Integer")) End Sub <Fact()> Public Sub ErrorHandler_Error_InSyncLockBlock() Dim compilationDef = <compilation> <file name="a.vb"> Class LockClass End Class Module Module1 Sub Main() Dim lock As New LockClass On Error GoTo handler SyncLock lock On Error GoTo goo goo: Resume Next End SyncLock Exit Sub End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_LabelNotDefined1, "handler").WithArguments("handler"), Diagnostic(ERRID.ERR_OnErrorInSyncLock, "On Error GoTo goo")) End Sub <ConditionalFact(GetType(DesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")> Public Sub ErrorHandler_Error_InMethodWithSyncLockBlock() 'Method has a Error Handler and Error Occurs within SyncLock 'resume next will occur outside of the SyncLock Block Dim compilationDef = <compilation> <file name="a.vb"> Imports System Class LockClass End Class Module Module1 Sub Main() Dim lock As New LockClass Console.WriteLine("Start") On Error GoTo handler SyncLock lock Console.WriteLine("In SyncLock") Error 1 Console.WriteLine("After Error In SyncLock") End SyncLock Console.WriteLine("End") Exit Sub handler: Console.WriteLine("Handler") Resume Next End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) compilation.VerifyDiagnostics() Dim CompilationVerifier = CompileAndVerify(compilation, expectedOutput:=<![CDATA[Start In SyncLock Handler End]]>) CompilationVerifier.VerifyIL("Module1.Main", <![CDATA[ { // Code size 248 (0xf8) .maxstack 3 .locals init (Integer V_0, Integer V_1, Integer V_2, LockClass V_3, //lock Object V_4, Boolean V_5) .try { IL_0000: ldc.i4.1 IL_0001: stloc.2 IL_0002: newobj "Sub LockClass..ctor()" IL_0007: stloc.3 IL_0008: ldc.i4.2 IL_0009: stloc.2 IL_000a: ldstr "Start" IL_000f: call "Sub System.Console.WriteLine(String)" IL_0014: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()" IL_0019: ldc.i4.2 IL_001a: stloc.0 IL_001b: ldc.i4.4 IL_001c: stloc.2 IL_001d: ldloc.3 IL_001e: stloc.s V_4 IL_0020: ldc.i4.0 IL_0021: stloc.s V_5 .try { IL_0023: ldloc.s V_4 IL_0025: ldloca.s V_5 IL_0027: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_002c: ldstr "In SyncLock" IL_0031: call "Sub System.Console.WriteLine(String)" IL_0036: ldc.i4.1 IL_0037: call "Function Microsoft.VisualBasic.CompilerServices.ProjectData.CreateProjectError(Integer) As System.Exception" IL_003c: throw } finally { IL_003d: ldloc.s V_5 IL_003f: brfalse.s IL_0048 IL_0041: ldloc.s V_4 IL_0043: call "Sub System.Threading.Monitor.Exit(Object)" IL_0048: endfinally } IL_0049: ldc.i4.5 IL_004a: stloc.2 IL_004b: ldstr "End" IL_0050: call "Sub System.Console.WriteLine(String)" IL_0055: br.s IL_0078 IL_0057: ldc.i4.7 IL_0058: stloc.2 IL_0059: ldstr "Handler" IL_005e: call "Sub System.Console.WriteLine(String)" IL_0063: ldc.i4.8 IL_0064: stloc.2 IL_0065: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()" IL_006a: ldloc.1 IL_006b: brtrue.s IL_007a IL_006d: ldc.i4 0x800a0014 IL_0072: call "Function Microsoft.VisualBasic.CompilerServices.ProjectData.CreateProjectError(Integer) As System.Exception" IL_0077: throw IL_0078: leave.s IL_00ef IL_007a: ldloc.1 IL_007b: ldc.i4.1 IL_007c: add IL_007d: ldc.i4.0 IL_007e: stloc.1 IL_007f: switch ( IL_00ac, IL_0000, IL_0008, IL_0014, IL_001b, IL_0049, IL_0078, IL_0057, IL_0063, IL_0078) IL_00ac: leave.s IL_00e4 IL_00ae: ldloc.2 IL_00af: stloc.1 IL_00b0: ldloc.0 IL_00b1: switch ( IL_00c2, IL_007a, IL_0057) IL_00c2: leave.s IL_00e4 } filter { IL_00c4: isinst "System.Exception" IL_00c9: ldnull IL_00ca: cgt.un IL_00cc: ldloc.0 IL_00cd: ldc.i4.0 IL_00ce: cgt.un IL_00d0: and IL_00d1: ldloc.1 IL_00d2: ldc.i4.0 IL_00d3: ceq IL_00d5: and IL_00d6: endfilter } // end filter { // handler IL_00d8: castclass "System.Exception" IL_00dd: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)" IL_00e2: leave.s IL_00ae } IL_00e4: ldc.i4 0x800a0033 IL_00e9: call "Function Microsoft.VisualBasic.CompilerServices.ProjectData.CreateProjectError(Integer) As System.Exception" IL_00ee: throw IL_00ef: ldloc.1 IL_00f0: brfalse.s IL_00f7 IL_00f2: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()" IL_00f7: ret } ]]>) End Sub <Fact> Public Sub SynthesizingDefaultConstructorsWithMsCorLibMissing_Nothing() Dim comp = CompilationUtils.CreateEmptyCompilation(" Class Test End Class ", options:=TestOptions.ReleaseDll.WithModuleName("testModule")) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30002: Type 'System.Void' is not defined. Class Test ~~~~~~~~~~~ BC31091: Import of type 'Object' from assembly or module 'testModule' failed. Class Test ~~~~ </expected>) End Sub <Fact> Public Sub SynthesizingDefaultConstructorsWithMsCorLibMissing_NoSystemVoid() Dim comp = CompilationUtils.CreateEmptyCompilation(" Namespace System Public Class [Object] End Class End Namespace Class Test End Class ", options:=TestOptions.ReleaseDll.WithModuleName("testModule")) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30002: Type 'System.Void' is not defined. Public Class [Object] ~~~~~~~~~~~~~~~~~~~~~~ BC30002: Type 'System.Void' is not defined. Class Test ~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub SynthesizingDefaultConstructorsWithMsCorLibMissing_NoSystemObject() Dim comp = CompilationUtils.CreateEmptyCompilation(" Namespace System Public Class Void End Class End Namespace Class Test End Class ", options:=TestOptions.ReleaseDll.WithModuleName("testModule")) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC31091: Import of type 'Object' from assembly or module 'testModule' failed. Public Class Void ~~~~ BC31091: Import of type 'Object' from assembly or module 'testModule' failed. Class Test ~~~~ </expected>) End Sub <Fact> Public Sub SynthesizingDefaultConstructorsWithMsCorLibMissing_NoSystemObjectDefaultConstructor() Dim comp = CompilationUtils.CreateEmptyCompilation(" Namespace System Public Class [Object] Public Sub New(other as Object) End Sub End Class Public Class Void Public Sub New() MyBase.New(Nothing) End Sub End Class End Namespace Class Test End Class ", options:=TestOptions.ReleaseDll.WithModuleName("testModule")) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30387: Class 'Test' must declare a 'Sub New' because its base class 'Object' does not have an accessible 'Sub New' that can be called with no arguments. Class Test ~~~~ </expected>) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class ErrorHandlingTests Inherits BasicTestBase <Fact()> Public Sub ErrorHandler_WithValidLabel_No_Resume() Dim compilationDef = <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() Dim sPath As String = "" sPath = "Test1" On Error GoTo goo Error 5 Console.WriteLine(sPath) Exit Sub goo: sPath &amp;= "goo" Console.WriteLine(sPath) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompileAndVerify(compilation) End Sub <Fact()> Public Sub ErrorHandler_WithGotoMinus1andMatchingLabel() Dim compilationDef = <compilation> <file name="a.vb"> Imports System Module Module1 Public Sub Main() On Error GoTo -1 Error 5 exit sub goo: Resume End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompileAndVerify(compilation) End Sub <Fact()> Public Sub Error_ErrorHandler_WithGoto0andNoMatchingLabel() Dim compilationDef = <compilation> <file name="a.vb"> Imports System Module Module1 Public Sub Main() On Error GoTo 0 Error 5 exit sub Goo: Resume End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompileAndVerify(compilation) 'compilation.VerifyDiagnostics() End Sub <Fact()> Public Sub Error_ErrorHandler_WithResumeNext() Dim compilationDef = <compilation> <file name="a.vb"> Imports System Module Module1 Public Sub Main() On Error Resume Next Error 5 exit sub End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompileAndVerify(compilation) 'compilation.VerifyDiagnostics() End Sub <Fact()> Public Sub ErrorHandler_WithValidLabelMatchingKeywordsEscaped() Dim compilationDef = <compilation> <file name="a.vb"> Imports System Module Module1 Public Sub Main() On Error GoTo [On] On Error GoTo [goto] 'Doesn't matter if case mismatch (Didn't pretty list correctly) On Error GoTo [Error] exit sub [Goto]: Resume [on] [On]: Resume [Error] [Error]: Resume [Goto] End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompileAndVerify(compilation) ' compilation.VerifyDiagnostics() End Sub <Fact()> Public Sub Error_ErrorHandler_WithValidLabelMatchingKeywordsNotEscaped() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Public Sub Main() On Error GoTo On On Error GoTo goto On Error GoTo Error [Goto]: Resume [on] [On]: Resume [Error] [Error]: Resume [Goto] End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedIdentifier, ""), Diagnostic(ERRID.ERR_ExpectedIdentifier, ""), Diagnostic(ERRID.ERR_ExpectedIdentifier, ""), Diagnostic(ERRID.ERR_LabelNotDefined1, "").WithArguments(""), Diagnostic(ERRID.ERR_LabelNotDefined1, "").WithArguments(""), Diagnostic(ERRID.ERR_LabelNotDefined1, "").WithArguments("")) End Sub <Fact()> Public Sub Error_ErrorHandler_WithInValidLabelMatchingKeywordsEscaped() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Public Sub Main() On Error GoTo [On] On Error GoTo [goto] 'Doesn't matter if case mismatch (Didn't pretty list correctly) On Error GoTo [Error] Goto: Resume on On: Resume Error Error: Resume Goto End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedIdentifier, ""), Diagnostic(ERRID.ERR_ExpectedIdentifier, ""), Diagnostic(ERRID.ERR_ObsoleteOnGotoGosub, ""), Diagnostic(ERRID.ERR_ExpectedIdentifier, ""), Diagnostic(ERRID.ERR_ExpectedExpression, ""), Diagnostic(ERRID.ERR_ExpectedIdentifier, ""), Diagnostic(ERRID.ERR_LabelNotDefined1, "[On]").WithArguments("On"), Diagnostic(ERRID.ERR_LabelNotDefined1, "[goto]").WithArguments("goto"), Diagnostic(ERRID.ERR_LabelNotDefined1, "[Error]").WithArguments("Error"), Diagnostic(ERRID.ERR_LabelNotDefined1, "").WithArguments(""), Diagnostic(ERRID.ERR_LabelNotDefined1, "").WithArguments(""), Diagnostic(ERRID.ERR_LabelNotDefined1, "").WithArguments(""), Diagnostic(ERRID.ERR_LabelNotDefined1, "").WithArguments(""), Diagnostic(ERRID.ERR_LabelNotDefined1, "").WithArguments("")) End Sub <Fact()> Public Sub Error_ErrorHandler_WithGoto0andMatchingLabel() Dim compilationDef = <compilation> <file name="a.vb"> Imports System Module Module1 Public Sub Main() On Error GoTo 0 Error 5 exit sub 0: Resume End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) Dim compilationVerifier = CompileAndVerify(compilation) compilationVerifier.VerifyIL("Module1.Main", <![CDATA[ { // Code size 155 (0x9b) .maxstack 3 .locals init (Integer V_0, Integer V_1, Integer V_2, Integer V_3) .try { IL_0000: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()" IL_0005: ldc.i4.0 IL_0006: stloc.0 IL_0007: ldc.i4.2 IL_0008: stloc.2 IL_0009: ldc.i4.5 IL_000a: call "Function Microsoft.VisualBasic.CompilerServices.ProjectData.CreateProjectError(Integer) As System.Exception" IL_000f: throw IL_0010: ldc.i4.0 IL_0011: stloc.3 IL_0012: ldc.i4.5 IL_0013: stloc.2 IL_0014: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()" IL_0019: ldloc.1 IL_001a: brtrue.s IL_0029 IL_001c: ldc.i4 0x800a0014 IL_0021: call "Function Microsoft.VisualBasic.CompilerServices.ProjectData.CreateProjectError(Integer) As System.Exception" IL_0026: throw IL_0027: leave.s IL_0092 IL_0029: ldloc.1 IL_002a: br.s IL_002f IL_002c: ldloc.1 IL_002d: ldc.i4.1 IL_002e: add IL_002f: ldc.i4.0 IL_0030: stloc.1 IL_0031: switch ( IL_0052, IL_0000, IL_0007, IL_0027, IL_0010, IL_0012, IL_0027) IL_0052: leave.s IL_0087 IL_0054: ldloc.2 IL_0055: stloc.1 IL_0056: ldloc.0 IL_0057: switch ( IL_0064, IL_002c) IL_0064: leave.s IL_0087 } filter { IL_0066: isinst "System.Exception" IL_006b: ldnull IL_006c: cgt.un IL_006e: ldloc.0 IL_006f: ldc.i4.0 IL_0070: cgt.un IL_0072: and IL_0073: ldloc.1 IL_0074: ldc.i4.0 IL_0075: ceq IL_0077: and IL_0078: endfilter } // end filter { // handler IL_007a: castclass "System.Exception" IL_007f: ldloc.3 IL_0080: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception, Integer)" IL_0085: leave.s IL_0054 } IL_0087: ldc.i4 0x800a0033 IL_008c: call "Function Microsoft.VisualBasic.CompilerServices.ProjectData.CreateProjectError(Integer) As System.Exception" IL_0091: throw IL_0092: ldloc.1 IL_0093: brfalse.s IL_009a IL_0095: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()" IL_009a: ret } ]]>) End Sub <ConditionalFact(GetType(DesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")> Public Sub Error_ErrorHandler_WithGoto1andMatchingLabel() Dim compilationDef = <compilation> <file name="a.vb"> Imports System Module Module1 Public Sub Main() On Error GoTo 1 Console.writeline("Start") Error 5 Console.writeline("2") exit sub 1: Console.writeline("1") Resume Next End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:=<![CDATA[Start 1 2]]>) End Sub <Fact()> Public Sub Error_ErrorHandler_WithMissingOrIncorrectLabels() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 sing Labels Public Sub Main() End Sub Sub Goto_MissingLabel() 'Error - label is not present On Error GoTo goo End Sub Sub GotoLabelInDifferentMethod() 'Error - no label in this method, in a different so it will fail On Error GoTo diffMethodLabel End Sub Sub GotoLabelInDifferentMethod() 'Error - no label in this method - trying to fully qualify will fail On Error GoTo DifferentMethod.diffMethodLabel End Sub Sub DifferentMethod() DiffMethodLabel: End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedSpecifier, "Labels"), Diagnostic(ERRID.ERR_ExpectedDeclaration, "sing"), Diagnostic(ERRID.ERR_ExpectedEOS, "."), Diagnostic(ERRID.ERR_DuplicateProcDef1, "GotoLabelInDifferentMethod").WithArguments("Public Sub GotoLabelInDifferentMethod()"), Diagnostic(ERRID.ERR_LabelNotDefined1, "goo").WithArguments("goo"), Diagnostic(ERRID.ERR_LabelNotDefined1, "diffMethodLabel").WithArguments("diffMethodLabel"), Diagnostic(ERRID.ERR_LabelNotDefined1, "DifferentMethod").WithArguments("DifferentMethod")) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29568")> Public Sub Error_ErrorHandler_BothTypesOfErrorHandling() Dim compilationDef = <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main TryAndOnErrorInSameMethod OnErrorAndTryInSameMethod End Sub Sub TryAndOnErrorInSameMethod() 'Nested Try On Error GoTo goo goo: Catch ex As Exception End Try End Sub Sub OnErrorAndTryInSameMethod() 'Sequential On Error GoTo goo goo: Try Catch ex As Exception End Try End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Dim ExpectedOutput = <![CDATA[Try On Error GoTo goo goo: Catch ex As Exception End Try]]> Dim ExpectedOutput2 = <![CDATA[Try Catch ex As Exception End Try]]> compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_TryAndOnErrorDoNotMix, ExpectedOutput), Diagnostic(ERRID.ERR_TryAndOnErrorDoNotMix, "On Error GoTo goo"), Diagnostic(ERRID.ERR_TryAndOnErrorDoNotMix, "On Error GoTo goo"), Diagnostic(ERRID.ERR_TryAndOnErrorDoNotMix, ExpectedOutput2) ) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29568")> Public Sub Error_ErrorHandler_InVBCore() 'Old Style handling not supported in VBCore Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Public Sub Main On Error GoTo goo goo: End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(compilationDef, references:={MscorlibRef, SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) Dim ExpectedOutput = <![CDATA[Public Sub Main On Error GoTo goo goo: End Sub]]> compilation.VerifyEmitDiagnostics(Diagnostic(ERRID.ERR_PlatformDoesntSupport, ExpectedOutput).WithArguments("Unstructured exception handling").WithLocation(2, 9)) End Sub <Fact()> Public Sub Error_ErrorHandler_InVBCore_LateBound1() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Dim a As Object Sub Main() a = New ABC a = a + 1 a = a &amp; "test" End Sub End Module Class ABC End Class </file> </compilation> Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(compilationDef, references:={MscorlibRef, SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) compilation.VerifyEmitDiagnostics(Diagnostic(ERRID.ERR_PlatformDoesntSupport, "a + 1").WithArguments("Late binding").WithLocation(6, 13), Diagnostic(ERRID.ERR_PlatformDoesntSupport, "a & ""test""").WithArguments("Late binding").WithLocation(8, 13) ) End Sub <Fact()> Public Sub Error_ErrorHandler_InVBCore_LikeOperator() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim testCheck As Boolean testCheck = "F" Like "F" End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(compilationDef, references:={MscorlibRef, SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) Dim ExpectedOutput = <![CDATA["F" Like "F"]]> compilation.VerifyEmitDiagnostics(Diagnostic(ERRID.ERR_PlatformDoesntSupport, ExpectedOutput).WithArguments("Like operator").WithLocation(5, 21)) End Sub <Fact()> Public Sub Error_ErrorHandler_InVBCore_ErrObject() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main() Error 1 End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(compilationDef, references:={MscorlibRef, SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) compilation.VerifyEmitDiagnostics(Diagnostic(ERRID.ERR_PlatformDoesntSupport, "Error 1").WithArguments("Unstructured exception handling").WithLocation(4, 18)) End Sub <Fact()> Public Sub Error_ErrorHandler_InVBCore_AnonymousType() Dim source = <compilation> <file name="a.vb"> Module Module1 Dim a As Object Sub Main() a = "1" Dim x = New With {.a = a, .b = a + 1} End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(source, references:={MscorlibRef, SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) compilation.VerifyEmitDiagnostics(Diagnostic(ERRID.ERR_PlatformDoesntSupport, "a + 1").WithArguments("Late binding").WithLocation(6, 40)) End Sub <Fact(), WorkItem(545772, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545772")> Public Sub VbCoreMyNamespace() Dim source = <compilation> <file name="a.vb"> Module Module1 Public Sub Main() My.Computer.FileSystem.WriteAllText("Test.txt","abc") End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(source, references:={MscorlibRef, SystemRef, SystemCoreRef}, options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_PlatformDoesntSupport, "My").WithArguments("My").WithLocation(3, 13)) End Sub <Fact()> Public Sub Error_ErrorHandler_OutsideOfMethodBody() Dim compilationDef = <compilation> <file name="a.vb"> Module Module1 Sub Main End Sub 'Error Outside of Method Body On Error Goto goo Sub Goo End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "On Error Goto goo")) End Sub <Fact()> Public Sub ErrorHandler_In_Different_Types() 'Basic Validation that this is permissible in Class/Structure/(Module Tested elsewhere) 'Generic Dim compilationDef = <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main End Sub Class Goo Sub Method() On Error GoTo CLassMethodLabel CLassMethodLabel: End Sub Public Property ABC As String Set(value As String) On Error GoTo setLabel setLabel: End Set Get On Error GoTo getLabel getLabel: End Get End Property End Class Structure Goo_Struct Sub Method() On Error GoTo StructMethodLabel StructMethodLabel: End Sub Public Property ABC As String Set(value As String) On Error GoTo SetLabel setLabel: End Set Get On Error GoTo getLabel getLabel: End Get End Property End Structure Class GenericGoo(Of t) Sub Method() 'Normal Method In Generic Class On Error GoTo CLassMethodLabel CLassMethodLabel: End Sub Sub GenericMethod(Of u)(x As u) 'Generic Method In Generic Class On Error GoTo CLassMethodLabel CLassMethodLabel: End Sub Public Property ABC As String Set(value As String) On Error GoTo setLabel setLabel: End Set Get On Error GoTo getLabel getLabel: End Get End Property End Class End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) compilation.AssertNoDiagnostics() End Sub <Fact()> Public Sub ErrorHandler_Other_Constructor_Dispose() Dim compilationDef = <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main Dim X As New TestInConstructor Dim X2 As New TestInDisposeAndFinalize X2.Dispose() End Sub End Module Class TestInConstructor Sub New() On Error GoTo constructorError ConstructorError: End Sub End Class Class TestInDisposeAndFinalize Implements IDisposable Sub New() End Sub #Region "IDisposable Support" Private disposedValue As Boolean ' To detect redundant calls ' IDisposable Protected Overridable Sub Dispose(disposing As Boolean) On Error GoTo ConstructorError If Not Me.disposedValue Then If disposing Then ' TODO: dispose managed state (managed objects). End If ' TODO: free unmanaged resources (unmanaged objects) and override Finalize() below. ' TODO: set large fields to null. End If Me.disposedValue = True ConstructorError: End Sub ' TODO: override Finalize() only if Dispose(ByVal disposing As Boolean) above has code to free unmanaged resources. Protected Overrides Sub Finalize() On Error GoTo FInalizeError ' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above. Dispose(False) MyBase.Finalize() FInalizeError: End Sub ' This code added by Visual Basic to correctly implement the disposable pattern. Public Sub Dispose() Implements IDisposable.Dispose ' Do not change this code. Put cleanup code in Dispose(disposing As Boolean) above. Dispose(True) GC.SuppressFinalize(Me) End Sub #End Region End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) compilation.VerifyDiagnostics() End Sub <Fact()> Public Sub Error_InvalidTypes_ImplicitConversions() Dim compilationDef = <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main Error 1L Error 2S Error &quot;3&quot; Error 4! Error 5% End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) compilation.AssertNoDiagnostics() End Sub <Fact()> Public Sub Error_InvalidTypes_InvalidTypes_StrictOn() Dim compilationDef = <compilation> <file name="a.vb"> Option Strict On Module Module1 Sub Main Error 1L Error 2S Error &quot;3&quot; Error 4! Error 5% End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, """3""").WithArguments("String", "Integer"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "4!").WithArguments("Single", "Integer")) End Sub <Fact()> Public Sub ErrorHandler_Error_InSyncLockBlock() Dim compilationDef = <compilation> <file name="a.vb"> Class LockClass End Class Module Module1 Sub Main() Dim lock As New LockClass On Error GoTo handler SyncLock lock On Error GoTo goo goo: Resume Next End SyncLock Exit Sub End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_LabelNotDefined1, "handler").WithArguments("handler"), Diagnostic(ERRID.ERR_OnErrorInSyncLock, "On Error GoTo goo")) End Sub <ConditionalFact(GetType(DesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")> Public Sub ErrorHandler_Error_InMethodWithSyncLockBlock() 'Method has a Error Handler and Error Occurs within SyncLock 'resume next will occur outside of the SyncLock Block Dim compilationDef = <compilation> <file name="a.vb"> Imports System Class LockClass End Class Module Module1 Sub Main() Dim lock As New LockClass Console.WriteLine("Start") On Error GoTo handler SyncLock lock Console.WriteLine("In SyncLock") Error 1 Console.WriteLine("After Error In SyncLock") End SyncLock Console.WriteLine("End") Exit Sub handler: Console.WriteLine("Handler") Resume Next End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) compilation.VerifyDiagnostics() Dim CompilationVerifier = CompileAndVerify(compilation, expectedOutput:=<![CDATA[Start In SyncLock Handler End]]>) CompilationVerifier.VerifyIL("Module1.Main", <![CDATA[ { // Code size 248 (0xf8) .maxstack 3 .locals init (Integer V_0, Integer V_1, Integer V_2, LockClass V_3, //lock Object V_4, Boolean V_5) .try { IL_0000: ldc.i4.1 IL_0001: stloc.2 IL_0002: newobj "Sub LockClass..ctor()" IL_0007: stloc.3 IL_0008: ldc.i4.2 IL_0009: stloc.2 IL_000a: ldstr "Start" IL_000f: call "Sub System.Console.WriteLine(String)" IL_0014: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()" IL_0019: ldc.i4.2 IL_001a: stloc.0 IL_001b: ldc.i4.4 IL_001c: stloc.2 IL_001d: ldloc.3 IL_001e: stloc.s V_4 IL_0020: ldc.i4.0 IL_0021: stloc.s V_5 .try { IL_0023: ldloc.s V_4 IL_0025: ldloca.s V_5 IL_0027: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_002c: ldstr "In SyncLock" IL_0031: call "Sub System.Console.WriteLine(String)" IL_0036: ldc.i4.1 IL_0037: call "Function Microsoft.VisualBasic.CompilerServices.ProjectData.CreateProjectError(Integer) As System.Exception" IL_003c: throw } finally { IL_003d: ldloc.s V_5 IL_003f: brfalse.s IL_0048 IL_0041: ldloc.s V_4 IL_0043: call "Sub System.Threading.Monitor.Exit(Object)" IL_0048: endfinally } IL_0049: ldc.i4.5 IL_004a: stloc.2 IL_004b: ldstr "End" IL_0050: call "Sub System.Console.WriteLine(String)" IL_0055: br.s IL_0078 IL_0057: ldc.i4.7 IL_0058: stloc.2 IL_0059: ldstr "Handler" IL_005e: call "Sub System.Console.WriteLine(String)" IL_0063: ldc.i4.8 IL_0064: stloc.2 IL_0065: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()" IL_006a: ldloc.1 IL_006b: brtrue.s IL_007a IL_006d: ldc.i4 0x800a0014 IL_0072: call "Function Microsoft.VisualBasic.CompilerServices.ProjectData.CreateProjectError(Integer) As System.Exception" IL_0077: throw IL_0078: leave.s IL_00ef IL_007a: ldloc.1 IL_007b: ldc.i4.1 IL_007c: add IL_007d: ldc.i4.0 IL_007e: stloc.1 IL_007f: switch ( IL_00ac, IL_0000, IL_0008, IL_0014, IL_001b, IL_0049, IL_0078, IL_0057, IL_0063, IL_0078) IL_00ac: leave.s IL_00e4 IL_00ae: ldloc.2 IL_00af: stloc.1 IL_00b0: ldloc.0 IL_00b1: switch ( IL_00c2, IL_007a, IL_0057) IL_00c2: leave.s IL_00e4 } filter { IL_00c4: isinst "System.Exception" IL_00c9: ldnull IL_00ca: cgt.un IL_00cc: ldloc.0 IL_00cd: ldc.i4.0 IL_00ce: cgt.un IL_00d0: and IL_00d1: ldloc.1 IL_00d2: ldc.i4.0 IL_00d3: ceq IL_00d5: and IL_00d6: endfilter } // end filter { // handler IL_00d8: castclass "System.Exception" IL_00dd: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)" IL_00e2: leave.s IL_00ae } IL_00e4: ldc.i4 0x800a0033 IL_00e9: call "Function Microsoft.VisualBasic.CompilerServices.ProjectData.CreateProjectError(Integer) As System.Exception" IL_00ee: throw IL_00ef: ldloc.1 IL_00f0: brfalse.s IL_00f7 IL_00f2: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()" IL_00f7: ret } ]]>) End Sub <Fact> Public Sub SynthesizingDefaultConstructorsWithMsCorLibMissing_Nothing() Dim comp = CompilationUtils.CreateEmptyCompilation(" Class Test End Class ", options:=TestOptions.ReleaseDll.WithModuleName("testModule")) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30002: Type 'System.Void' is not defined. Class Test ~~~~~~~~~~~ BC31091: Import of type 'Object' from assembly or module 'testModule' failed. Class Test ~~~~ </expected>) End Sub <Fact> Public Sub SynthesizingDefaultConstructorsWithMsCorLibMissing_NoSystemVoid() Dim comp = CompilationUtils.CreateEmptyCompilation(" Namespace System Public Class [Object] End Class End Namespace Class Test End Class ", options:=TestOptions.ReleaseDll.WithModuleName("testModule")) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30002: Type 'System.Void' is not defined. Public Class [Object] ~~~~~~~~~~~~~~~~~~~~~~ BC30002: Type 'System.Void' is not defined. Class Test ~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub SynthesizingDefaultConstructorsWithMsCorLibMissing_NoSystemObject() Dim comp = CompilationUtils.CreateEmptyCompilation(" Namespace System Public Class Void End Class End Namespace Class Test End Class ", options:=TestOptions.ReleaseDll.WithModuleName("testModule")) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC31091: Import of type 'Object' from assembly or module 'testModule' failed. Public Class Void ~~~~ BC31091: Import of type 'Object' from assembly or module 'testModule' failed. Class Test ~~~~ </expected>) End Sub <Fact> Public Sub SynthesizingDefaultConstructorsWithMsCorLibMissing_NoSystemObjectDefaultConstructor() Dim comp = CompilationUtils.CreateEmptyCompilation(" Namespace System Public Class [Object] Public Sub New(other as Object) End Sub End Class Public Class Void Public Sub New() MyBase.New(Nothing) End Sub End Class End Namespace Class Test End Class ", options:=TestOptions.ReleaseDll.WithModuleName("testModule")) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30387: Class 'Test' must declare a 'Sub New' because its base class 'Object' does not have an accessible 'Sub New' that can be called with no arguments. Class Test ~~~~ </expected>) End Sub End Class End Namespace
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/CSharp/Portable/Symbols/Source/SourceMethodSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Base class to represent all source method-like symbols. This includes /// things like ordinary methods and constructors, and functions /// like lambdas and local functions. /// </summary> internal abstract class SourceMethodSymbol : MethodSymbol { /// <summary> /// If there are no constraints, returns an empty immutable array. Otherwise, returns an immutable /// array of types, indexed by the constrained type parameter in <see cref="MethodSymbol.TypeParameters"/>. /// </summary> public abstract ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes(); /// <summary> /// If there are no constraints, returns an empty immutable array. Otherwise, returns an immutable /// array of kinds, indexed by the constrained type parameter in <see cref="MethodSymbol.TypeParameters"/>. /// </summary> public abstract ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds(); protected static void ReportBadRefToken(TypeSyntax returnTypeSyntax, BindingDiagnosticBag diagnostics) { if (!returnTypeSyntax.HasErrors) { var refKeyword = returnTypeSyntax.GetFirstToken(); diagnostics.Add(ErrorCode.ERR_UnexpectedToken, refKeyword.GetLocation(), refKeyword.ToString()); } } protected bool AreContainingSymbolLocalsZeroed { get { if (ContainingSymbol is SourceMethodSymbol method) { return method.AreLocalsZeroed; } else if (ContainingType is SourceMemberContainerTypeSymbol type) { return type.AreLocalsZeroed; } else { // Sometimes a source method symbol can be contained in a non-source symbol. // For example in EE. We aren't concerned with respecting SkipLocalsInit in such cases. return true; } } } internal void ReportAsyncParameterErrors(BindingDiagnosticBag diagnostics, Location location) { foreach (var parameter in Parameters) { if (parameter.RefKind != RefKind.None) { diagnostics.Add(ErrorCode.ERR_BadAsyncArgType, getLocation(parameter, location)); } else if (parameter.Type.IsUnsafe()) { diagnostics.Add(ErrorCode.ERR_UnsafeAsyncArgType, getLocation(parameter, location)); } else if (parameter.Type.IsRestrictedType()) { diagnostics.Add(ErrorCode.ERR_BadSpecialByRefLocal, getLocation(parameter, location), parameter.Type); } } static Location getLocation(ParameterSymbol parameter, Location location) => parameter.Locations.FirstOrDefault() ?? location; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Base class to represent all source method-like symbols. This includes /// things like ordinary methods and constructors, and functions /// like lambdas and local functions. /// </summary> internal abstract class SourceMethodSymbol : MethodSymbol { /// <summary> /// If there are no constraints, returns an empty immutable array. Otherwise, returns an immutable /// array of types, indexed by the constrained type parameter in <see cref="MethodSymbol.TypeParameters"/>. /// </summary> public abstract ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes(); /// <summary> /// If there are no constraints, returns an empty immutable array. Otherwise, returns an immutable /// array of kinds, indexed by the constrained type parameter in <see cref="MethodSymbol.TypeParameters"/>. /// </summary> public abstract ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds(); protected static void ReportBadRefToken(TypeSyntax returnTypeSyntax, BindingDiagnosticBag diagnostics) { if (!returnTypeSyntax.HasErrors) { var refKeyword = returnTypeSyntax.GetFirstToken(); diagnostics.Add(ErrorCode.ERR_UnexpectedToken, refKeyword.GetLocation(), refKeyword.ToString()); } } protected bool AreContainingSymbolLocalsZeroed { get { if (ContainingSymbol is SourceMethodSymbol method) { return method.AreLocalsZeroed; } else if (ContainingType is SourceMemberContainerTypeSymbol type) { return type.AreLocalsZeroed; } else { // Sometimes a source method symbol can be contained in a non-source symbol. // For example in EE. We aren't concerned with respecting SkipLocalsInit in such cases. return true; } } } internal void ReportAsyncParameterErrors(BindingDiagnosticBag diagnostics, Location location) { foreach (var parameter in Parameters) { if (parameter.RefKind != RefKind.None) { diagnostics.Add(ErrorCode.ERR_BadAsyncArgType, getLocation(parameter, location)); } else if (parameter.Type.IsUnsafe()) { diagnostics.Add(ErrorCode.ERR_UnsafeAsyncArgType, getLocation(parameter, location)); } else if (parameter.Type.IsRestrictedType()) { diagnostics.Add(ErrorCode.ERR_BadSpecialByRefLocal, getLocation(parameter, location), parameter.Type); } } static Location getLocation(ParameterSymbol parameter, Location location) => parameter.Locations.FirstOrDefault() ?? location; } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/Shared/GlobalAssemblyCacheHelpers/FusionAssemblyIdentity.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Reflection; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal sealed class FusionAssemblyIdentity { [Flags] internal enum ASM_DISPLAYF { VERSION = 0x01, CULTURE = 0x02, PUBLIC_KEY_TOKEN = 0x04, PUBLIC_KEY = 0x08, CUSTOM = 0x10, PROCESSORARCHITECTURE = 0x20, LANGUAGEID = 0x40, RETARGET = 0x80, CONFIG_MASK = 0x100, MVID = 0x200, CONTENT_TYPE = 0x400, FULL = VERSION | CULTURE | PUBLIC_KEY_TOKEN | RETARGET | PROCESSORARCHITECTURE | CONTENT_TYPE } internal enum PropertyId { PUBLIC_KEY = 0, // 0 PUBLIC_KEY_TOKEN, // 1 HASH_VALUE, // 2 NAME, // 3 MAJOR_VERSION, // 4 MINOR_VERSION, // 5 BUILD_NUMBER, // 6 REVISION_NUMBER, // 7 CULTURE, // 8 PROCESSOR_ID_ARRAY, // 9 OSINFO_ARRAY, // 10 HASH_ALGID, // 11 ALIAS, // 12 CODEBASE_URL, // 13 CODEBASE_LASTMOD, // 14 NULL_PUBLIC_KEY, // 15 NULL_PUBLIC_KEY_TOKEN, // 16 CUSTOM, // 17 NULL_CUSTOM, // 18 MVID, // 19 FILE_MAJOR_VERSION, // 20 FILE_MINOR_VERSION, // 21 FILE_BUILD_NUMBER, // 22 FILE_REVISION_NUMBER, // 23 RETARGET, // 24 SIGNATURE_BLOB, // 25 CONFIG_MASK, // 26 ARCHITECTURE, // 27 CONTENT_TYPE, // 28 MAX_PARAMS // 29 } private static class CANOF { public const uint PARSE_DISPLAY_NAME = 0x1; public const uint SET_DEFAULT_VALUES = 0x2; } [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("CD193BC0-B4BC-11d2-9833-00C04FC31D2E")] internal unsafe interface IAssemblyName { void SetProperty(PropertyId id, void* data, uint size); [PreserveSig] int GetProperty(PropertyId id, void* data, ref uint size); [PreserveSig] int Finalize(); [PreserveSig] int GetDisplayName(byte* buffer, ref uint characterCount, ASM_DISPLAYF dwDisplayFlags); [PreserveSig] int __BindToObject(/*...*/); [PreserveSig] int __GetName(/*...*/); [PreserveSig] int GetVersion(out uint versionHi, out uint versionLow); [PreserveSig] int IsEqual(IAssemblyName pName, uint dwCmpFlags); [PreserveSig] int Clone(out IAssemblyName pName); } [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("7c23ff90-33af-11d3-95da-00a024a85b51")] internal interface IApplicationContext { } // NOTE: The CLR caches assembly identities, but doesn't do so in a threadsafe manner. // Wrap all calls to this with a lock. private static readonly object s_assemblyIdentityGate = new object(); private static int CreateAssemblyNameObject(out IAssemblyName ppEnum, string szAssemblyName, uint dwFlags, IntPtr pvReserved) { lock (s_assemblyIdentityGate) { return RealCreateAssemblyNameObject(out ppEnum, szAssemblyName, dwFlags, pvReserved); } } [DllImport("clr", EntryPoint = "CreateAssemblyNameObject", CharSet = CharSet.Unicode, PreserveSig = true)] private static extern int RealCreateAssemblyNameObject(out IAssemblyName ppEnum, [MarshalAs(UnmanagedType.LPWStr)] string szAssemblyName, uint dwFlags, IntPtr pvReserved); private const int ERROR_INSUFFICIENT_BUFFER = unchecked((int)0x8007007A); private const int FUSION_E_INVALID_NAME = unchecked((int)0x80131047); internal static unsafe string GetDisplayName(IAssemblyName nameObject, ASM_DISPLAYF displayFlags) { int hr; uint characterCountIncludingTerminator = 0; hr = nameObject.GetDisplayName(null, ref characterCountIncludingTerminator, displayFlags); if (hr == 0) { return String.Empty; } if (hr != ERROR_INSUFFICIENT_BUFFER) { throw Marshal.GetExceptionForHR(hr); } byte[] data = new byte[(int)characterCountIncludingTerminator * 2]; fixed (byte* p = data) { hr = nameObject.GetDisplayName(p, ref characterCountIncludingTerminator, displayFlags); if (hr != 0) { throw Marshal.GetExceptionForHR(hr); } return Marshal.PtrToStringUni((IntPtr)p, (int)characterCountIncludingTerminator - 1); } } internal static unsafe byte[] GetPropertyBytes(IAssemblyName nameObject, PropertyId propertyId) { int hr; uint size = 0; hr = nameObject.GetProperty(propertyId, null, ref size); if (hr == 0) { return null; } if (hr != ERROR_INSUFFICIENT_BUFFER) { throw Marshal.GetExceptionForHR(hr); } byte[] data = new byte[(int)size]; fixed (byte* p = data) { hr = nameObject.GetProperty(propertyId, p, ref size); if (hr != 0) { throw Marshal.GetExceptionForHR(hr); } } return data; } internal static unsafe string GetPropertyString(IAssemblyName nameObject, PropertyId propertyId) { byte[] data = GetPropertyBytes(nameObject, propertyId); if (data == null) { return null; } fixed (byte* p = data) { return Marshal.PtrToStringUni((IntPtr)p, (data.Length / 2) - 1); } } internal static unsafe bool IsKeyOrTokenEmpty(IAssemblyName nameObject, PropertyId propertyId) { Debug.Assert(propertyId == PropertyId.NULL_PUBLIC_KEY_TOKEN || propertyId == PropertyId.NULL_PUBLIC_KEY); uint size = 0; int hr = nameObject.GetProperty(propertyId, null, ref size); return hr == 0; } internal static unsafe Version GetVersion(IAssemblyName nameObject) { uint hi, lo; int hr = nameObject.GetVersion(out hi, out lo); if (hr != 0) { Debug.Assert(hr == FUSION_E_INVALID_NAME); return null; } return new Version((int)(hi >> 16), (int)(hi & 0xffff), (int)(lo >> 16), (int)(lo & 0xffff)); } internal static Version GetVersion(IAssemblyName name, out AssemblyIdentityParts parts) { uint? major = GetPropertyWord(name, PropertyId.MAJOR_VERSION); uint? minor = GetPropertyWord(name, PropertyId.MINOR_VERSION); uint? build = GetPropertyWord(name, PropertyId.BUILD_NUMBER); uint? revision = GetPropertyWord(name, PropertyId.REVISION_NUMBER); parts = 0; if (major != null) { parts |= AssemblyIdentityParts.VersionMajor; } if (minor != null) { parts |= AssemblyIdentityParts.VersionMinor; } if (build != null) { parts |= AssemblyIdentityParts.VersionBuild; } if (revision != null) { parts |= AssemblyIdentityParts.VersionRevision; } return new Version((int)(major ?? 0), (int)(minor ?? 0), (int)(build ?? 0), (int)(revision ?? 0)); } internal static byte[] GetPublicKeyToken(IAssemblyName nameObject) { byte[] result = GetPropertyBytes(nameObject, PropertyId.PUBLIC_KEY_TOKEN); if (result != null) { return result; } if (IsKeyOrTokenEmpty(nameObject, PropertyId.NULL_PUBLIC_KEY_TOKEN)) { return Array.Empty<byte>(); } return null; } internal static byte[] GetPublicKey(IAssemblyName nameObject) { byte[] result = GetPropertyBytes(nameObject, PropertyId.PUBLIC_KEY); if (result != null) { return result; } if (IsKeyOrTokenEmpty(nameObject, PropertyId.NULL_PUBLIC_KEY)) { return Array.Empty<byte>(); } return null; } internal static unsafe uint? GetPropertyWord(IAssemblyName nameObject, PropertyId propertyId) { uint result; uint size = sizeof(uint); int hr = nameObject.GetProperty(propertyId, &result, ref size); if (hr != 0) { throw Marshal.GetExceptionForHR(hr); } if (size == 0) { return null; } return result; } internal static string GetName(IAssemblyName nameObject) { return GetPropertyString(nameObject, PropertyId.NAME); } internal static string GetCulture(IAssemblyName nameObject) { return GetPropertyString(nameObject, PropertyId.CULTURE); } internal static AssemblyContentType GetContentType(IAssemblyName nameObject) { return (AssemblyContentType)(GetPropertyWord(nameObject, PropertyId.CONTENT_TYPE) ?? 0); } internal static ProcessorArchitecture GetProcessorArchitecture(IAssemblyName nameObject) { return (ProcessorArchitecture)(GetPropertyWord(nameObject, PropertyId.ARCHITECTURE) ?? 0); } internal static unsafe AssemblyNameFlags GetFlags(IAssemblyName nameObject) { AssemblyNameFlags result = 0; uint retarget = GetPropertyWord(nameObject, PropertyId.RETARGET) ?? 0; if (retarget != 0) { result |= AssemblyNameFlags.Retargetable; } return result; } private static unsafe void SetProperty(IAssemblyName nameObject, PropertyId propertyId, string data) { if (data == null) { nameObject.SetProperty(propertyId, null, 0); } else { Debug.Assert(data.IndexOf('\0') == -1); fixed (char* p = data) { Debug.Assert(p[data.Length] == '\0'); // size is in bytes, include trailing \0 character: nameObject.SetProperty(propertyId, p, (uint)(data.Length + 1) * 2); } } } private static unsafe void SetProperty(IAssemblyName nameObject, PropertyId propertyId, byte[] data) { if (data == null) { nameObject.SetProperty(propertyId, null, 0); } else { fixed (byte* p = data) { nameObject.SetProperty(propertyId, p, (uint)data.Length); } } } private static unsafe void SetProperty(IAssemblyName nameObject, PropertyId propertyId, ushort data) { nameObject.SetProperty(propertyId, &data, sizeof(ushort)); } private static unsafe void SetProperty(IAssemblyName nameObject, PropertyId propertyId, uint data) { nameObject.SetProperty(propertyId, &data, sizeof(uint)); } private static unsafe void SetPublicKeyToken(IAssemblyName nameObject, byte[] value) { // An empty public key token is set via NULL_PUBLIC_KEY_TOKEN property. if (value != null && value.Length == 0) { nameObject.SetProperty(PropertyId.NULL_PUBLIC_KEY_TOKEN, null, 0); } else { SetProperty(nameObject, PropertyId.PUBLIC_KEY_TOKEN, value); } } /// <summary> /// Converts <see cref="IAssemblyName"/> to <see cref="AssemblyName"/> with all metadata fields filled. /// </summary> /// <returns> /// Assembly name with Version, Culture and PublicKeyToken components filled in: /// "SimpleName, Version=#.#.#.#, Culture=XXX, PublicKeyToken=XXXXXXXXXXXXXXXX". /// In addition Retargetable flag and ContentType are set. /// </returns> internal static AssemblyIdentity ToAssemblyIdentity(IAssemblyName nameObject) { if (nameObject == null) { return null; } AssemblyNameFlags flags = GetFlags(nameObject); byte[] publicKey = GetPublicKey(nameObject); bool hasPublicKey = publicKey != null && publicKey.Length != 0; AssemblyIdentityParts versionParts; return new AssemblyIdentity( GetName(nameObject), GetVersion(nameObject, out versionParts), GetCulture(nameObject) ?? "", (hasPublicKey ? publicKey : GetPublicKeyToken(nameObject)).AsImmutableOrNull(), hasPublicKey: hasPublicKey, isRetargetable: (flags & AssemblyNameFlags.Retargetable) != 0, contentType: GetContentType(nameObject)); } /// <summary> /// Converts <see cref="AssemblyName"/> to an equivalent <see cref="IAssemblyName"/>. /// </summary> internal static IAssemblyName ToAssemblyNameObject(AssemblyName name) { if (name == null) { return null; } IAssemblyName result; Marshal.ThrowExceptionForHR(CreateAssemblyNameObject(out result, null, 0, IntPtr.Zero)); string assemblyName = name.Name; if (assemblyName != null) { if (assemblyName.IndexOf('\0') >= 0) { #if SCRIPTING throw new ArgumentException(Scripting.ScriptingResources.InvalidCharactersInAssemblyName, nameof(name)); #elif EDITOR_FEATURES throw new ArgumentException(Microsoft.CodeAnalysis.Editor.EditorFeaturesResources.Invalid_characters_in_assembly_name, nameof(name)); #else throw new ArgumentException(Microsoft.CodeAnalysis.CodeAnalysisResources.InvalidCharactersInAssemblyName, nameof(name)); #endif } SetProperty(result, PropertyId.NAME, assemblyName); } if (name.Version != null) { SetProperty(result, PropertyId.MAJOR_VERSION, unchecked((ushort)name.Version.Major)); SetProperty(result, PropertyId.MINOR_VERSION, unchecked((ushort)name.Version.Minor)); SetProperty(result, PropertyId.BUILD_NUMBER, unchecked((ushort)name.Version.Build)); SetProperty(result, PropertyId.REVISION_NUMBER, unchecked((ushort)name.Version.Revision)); } string cultureName = name.CultureName; if (cultureName != null) { if (cultureName.IndexOf('\0') >= 0) { #if SCRIPTING throw new ArgumentException(Microsoft.CodeAnalysis.Scripting.ScriptingResources.InvalidCharactersInAssemblyName, nameof(name)); #elif EDITOR_FEATURES throw new ArgumentException(Microsoft.CodeAnalysis.Editor.EditorFeaturesResources.Invalid_characters_in_assembly_name, nameof(name)); #else throw new ArgumentException(Microsoft.CodeAnalysis.CodeAnalysisResources.InvalidCharactersInAssemblyName, nameof(name)); #endif } SetProperty(result, PropertyId.CULTURE, cultureName); } if (name.Flags == AssemblyNameFlags.Retargetable) { SetProperty(result, PropertyId.RETARGET, 1U); } if (name.ContentType != AssemblyContentType.Default) { SetProperty(result, PropertyId.CONTENT_TYPE, (uint)name.ContentType); } byte[] token = name.GetPublicKeyToken(); SetPublicKeyToken(result, token); return result; } /// <summary> /// Creates <see cref="IAssemblyName"/> object by parsing given display name. /// </summary> internal static IAssemblyName ToAssemblyNameObject(string displayName) { // CLR doesn't handle \0 in the display name well: if (displayName.IndexOf('\0') >= 0) { return null; } Debug.Assert(displayName != null); IAssemblyName result; int hr = CreateAssemblyNameObject(out result, displayName, CANOF.PARSE_DISPLAY_NAME, IntPtr.Zero); if (hr != 0) { return null; } Debug.Assert(result != null); return result; } /// <summary> /// Selects the candidate assembly with the largest version number. Uses culture as a tie-breaker if it is provided. /// All candidates are assumed to have the same name and must include versions and cultures. /// </summary> internal static IAssemblyName GetBestMatch(IEnumerable<IAssemblyName> candidates, string preferredCultureOpt) { IAssemblyName bestCandidate = null; Version bestVersion = null; string bestCulture = null; foreach (var candidate in candidates) { if (bestCandidate != null) { Version candidateVersion = GetVersion(candidate); Debug.Assert(candidateVersion != null); if (bestVersion == null) { bestVersion = GetVersion(bestCandidate); Debug.Assert(bestVersion != null); } int cmp = bestVersion.CompareTo(candidateVersion); if (cmp == 0) { if (preferredCultureOpt != null) { string candidateCulture = GetCulture(candidate); Debug.Assert(candidateCulture != null); if (bestCulture == null) { bestCulture = GetCulture(candidate); Debug.Assert(bestCulture != null); } // we have exactly the preferred culture or // we have neutral culture and the best candidate's culture isn't the preferred one: if (StringComparer.OrdinalIgnoreCase.Equals(candidateCulture, preferredCultureOpt) || candidateCulture.Length == 0 && !StringComparer.OrdinalIgnoreCase.Equals(bestCulture, preferredCultureOpt)) { bestCandidate = candidate; bestVersion = candidateVersion; bestCulture = candidateCulture; } } } else if (cmp < 0) { bestCandidate = candidate; bestVersion = candidateVersion; } } else { bestCandidate = candidate; } } return bestCandidate; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Reflection; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal sealed class FusionAssemblyIdentity { [Flags] internal enum ASM_DISPLAYF { VERSION = 0x01, CULTURE = 0x02, PUBLIC_KEY_TOKEN = 0x04, PUBLIC_KEY = 0x08, CUSTOM = 0x10, PROCESSORARCHITECTURE = 0x20, LANGUAGEID = 0x40, RETARGET = 0x80, CONFIG_MASK = 0x100, MVID = 0x200, CONTENT_TYPE = 0x400, FULL = VERSION | CULTURE | PUBLIC_KEY_TOKEN | RETARGET | PROCESSORARCHITECTURE | CONTENT_TYPE } internal enum PropertyId { PUBLIC_KEY = 0, // 0 PUBLIC_KEY_TOKEN, // 1 HASH_VALUE, // 2 NAME, // 3 MAJOR_VERSION, // 4 MINOR_VERSION, // 5 BUILD_NUMBER, // 6 REVISION_NUMBER, // 7 CULTURE, // 8 PROCESSOR_ID_ARRAY, // 9 OSINFO_ARRAY, // 10 HASH_ALGID, // 11 ALIAS, // 12 CODEBASE_URL, // 13 CODEBASE_LASTMOD, // 14 NULL_PUBLIC_KEY, // 15 NULL_PUBLIC_KEY_TOKEN, // 16 CUSTOM, // 17 NULL_CUSTOM, // 18 MVID, // 19 FILE_MAJOR_VERSION, // 20 FILE_MINOR_VERSION, // 21 FILE_BUILD_NUMBER, // 22 FILE_REVISION_NUMBER, // 23 RETARGET, // 24 SIGNATURE_BLOB, // 25 CONFIG_MASK, // 26 ARCHITECTURE, // 27 CONTENT_TYPE, // 28 MAX_PARAMS // 29 } private static class CANOF { public const uint PARSE_DISPLAY_NAME = 0x1; public const uint SET_DEFAULT_VALUES = 0x2; } [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("CD193BC0-B4BC-11d2-9833-00C04FC31D2E")] internal unsafe interface IAssemblyName { void SetProperty(PropertyId id, void* data, uint size); [PreserveSig] int GetProperty(PropertyId id, void* data, ref uint size); [PreserveSig] int Finalize(); [PreserveSig] int GetDisplayName(byte* buffer, ref uint characterCount, ASM_DISPLAYF dwDisplayFlags); [PreserveSig] int __BindToObject(/*...*/); [PreserveSig] int __GetName(/*...*/); [PreserveSig] int GetVersion(out uint versionHi, out uint versionLow); [PreserveSig] int IsEqual(IAssemblyName pName, uint dwCmpFlags); [PreserveSig] int Clone(out IAssemblyName pName); } [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("7c23ff90-33af-11d3-95da-00a024a85b51")] internal interface IApplicationContext { } // NOTE: The CLR caches assembly identities, but doesn't do so in a threadsafe manner. // Wrap all calls to this with a lock. private static readonly object s_assemblyIdentityGate = new object(); private static int CreateAssemblyNameObject(out IAssemblyName ppEnum, string szAssemblyName, uint dwFlags, IntPtr pvReserved) { lock (s_assemblyIdentityGate) { return RealCreateAssemblyNameObject(out ppEnum, szAssemblyName, dwFlags, pvReserved); } } [DllImport("clr", EntryPoint = "CreateAssemblyNameObject", CharSet = CharSet.Unicode, PreserveSig = true)] private static extern int RealCreateAssemblyNameObject(out IAssemblyName ppEnum, [MarshalAs(UnmanagedType.LPWStr)] string szAssemblyName, uint dwFlags, IntPtr pvReserved); private const int ERROR_INSUFFICIENT_BUFFER = unchecked((int)0x8007007A); private const int FUSION_E_INVALID_NAME = unchecked((int)0x80131047); internal static unsafe string GetDisplayName(IAssemblyName nameObject, ASM_DISPLAYF displayFlags) { int hr; uint characterCountIncludingTerminator = 0; hr = nameObject.GetDisplayName(null, ref characterCountIncludingTerminator, displayFlags); if (hr == 0) { return String.Empty; } if (hr != ERROR_INSUFFICIENT_BUFFER) { throw Marshal.GetExceptionForHR(hr); } byte[] data = new byte[(int)characterCountIncludingTerminator * 2]; fixed (byte* p = data) { hr = nameObject.GetDisplayName(p, ref characterCountIncludingTerminator, displayFlags); if (hr != 0) { throw Marshal.GetExceptionForHR(hr); } return Marshal.PtrToStringUni((IntPtr)p, (int)characterCountIncludingTerminator - 1); } } internal static unsafe byte[] GetPropertyBytes(IAssemblyName nameObject, PropertyId propertyId) { int hr; uint size = 0; hr = nameObject.GetProperty(propertyId, null, ref size); if (hr == 0) { return null; } if (hr != ERROR_INSUFFICIENT_BUFFER) { throw Marshal.GetExceptionForHR(hr); } byte[] data = new byte[(int)size]; fixed (byte* p = data) { hr = nameObject.GetProperty(propertyId, p, ref size); if (hr != 0) { throw Marshal.GetExceptionForHR(hr); } } return data; } internal static unsafe string GetPropertyString(IAssemblyName nameObject, PropertyId propertyId) { byte[] data = GetPropertyBytes(nameObject, propertyId); if (data == null) { return null; } fixed (byte* p = data) { return Marshal.PtrToStringUni((IntPtr)p, (data.Length / 2) - 1); } } internal static unsafe bool IsKeyOrTokenEmpty(IAssemblyName nameObject, PropertyId propertyId) { Debug.Assert(propertyId == PropertyId.NULL_PUBLIC_KEY_TOKEN || propertyId == PropertyId.NULL_PUBLIC_KEY); uint size = 0; int hr = nameObject.GetProperty(propertyId, null, ref size); return hr == 0; } internal static unsafe Version GetVersion(IAssemblyName nameObject) { uint hi, lo; int hr = nameObject.GetVersion(out hi, out lo); if (hr != 0) { Debug.Assert(hr == FUSION_E_INVALID_NAME); return null; } return new Version((int)(hi >> 16), (int)(hi & 0xffff), (int)(lo >> 16), (int)(lo & 0xffff)); } internal static Version GetVersion(IAssemblyName name, out AssemblyIdentityParts parts) { uint? major = GetPropertyWord(name, PropertyId.MAJOR_VERSION); uint? minor = GetPropertyWord(name, PropertyId.MINOR_VERSION); uint? build = GetPropertyWord(name, PropertyId.BUILD_NUMBER); uint? revision = GetPropertyWord(name, PropertyId.REVISION_NUMBER); parts = 0; if (major != null) { parts |= AssemblyIdentityParts.VersionMajor; } if (minor != null) { parts |= AssemblyIdentityParts.VersionMinor; } if (build != null) { parts |= AssemblyIdentityParts.VersionBuild; } if (revision != null) { parts |= AssemblyIdentityParts.VersionRevision; } return new Version((int)(major ?? 0), (int)(minor ?? 0), (int)(build ?? 0), (int)(revision ?? 0)); } internal static byte[] GetPublicKeyToken(IAssemblyName nameObject) { byte[] result = GetPropertyBytes(nameObject, PropertyId.PUBLIC_KEY_TOKEN); if (result != null) { return result; } if (IsKeyOrTokenEmpty(nameObject, PropertyId.NULL_PUBLIC_KEY_TOKEN)) { return Array.Empty<byte>(); } return null; } internal static byte[] GetPublicKey(IAssemblyName nameObject) { byte[] result = GetPropertyBytes(nameObject, PropertyId.PUBLIC_KEY); if (result != null) { return result; } if (IsKeyOrTokenEmpty(nameObject, PropertyId.NULL_PUBLIC_KEY)) { return Array.Empty<byte>(); } return null; } internal static unsafe uint? GetPropertyWord(IAssemblyName nameObject, PropertyId propertyId) { uint result; uint size = sizeof(uint); int hr = nameObject.GetProperty(propertyId, &result, ref size); if (hr != 0) { throw Marshal.GetExceptionForHR(hr); } if (size == 0) { return null; } return result; } internal static string GetName(IAssemblyName nameObject) { return GetPropertyString(nameObject, PropertyId.NAME); } internal static string GetCulture(IAssemblyName nameObject) { return GetPropertyString(nameObject, PropertyId.CULTURE); } internal static AssemblyContentType GetContentType(IAssemblyName nameObject) { return (AssemblyContentType)(GetPropertyWord(nameObject, PropertyId.CONTENT_TYPE) ?? 0); } internal static ProcessorArchitecture GetProcessorArchitecture(IAssemblyName nameObject) { return (ProcessorArchitecture)(GetPropertyWord(nameObject, PropertyId.ARCHITECTURE) ?? 0); } internal static unsafe AssemblyNameFlags GetFlags(IAssemblyName nameObject) { AssemblyNameFlags result = 0; uint retarget = GetPropertyWord(nameObject, PropertyId.RETARGET) ?? 0; if (retarget != 0) { result |= AssemblyNameFlags.Retargetable; } return result; } private static unsafe void SetProperty(IAssemblyName nameObject, PropertyId propertyId, string data) { if (data == null) { nameObject.SetProperty(propertyId, null, 0); } else { Debug.Assert(data.IndexOf('\0') == -1); fixed (char* p = data) { Debug.Assert(p[data.Length] == '\0'); // size is in bytes, include trailing \0 character: nameObject.SetProperty(propertyId, p, (uint)(data.Length + 1) * 2); } } } private static unsafe void SetProperty(IAssemblyName nameObject, PropertyId propertyId, byte[] data) { if (data == null) { nameObject.SetProperty(propertyId, null, 0); } else { fixed (byte* p = data) { nameObject.SetProperty(propertyId, p, (uint)data.Length); } } } private static unsafe void SetProperty(IAssemblyName nameObject, PropertyId propertyId, ushort data) { nameObject.SetProperty(propertyId, &data, sizeof(ushort)); } private static unsafe void SetProperty(IAssemblyName nameObject, PropertyId propertyId, uint data) { nameObject.SetProperty(propertyId, &data, sizeof(uint)); } private static unsafe void SetPublicKeyToken(IAssemblyName nameObject, byte[] value) { // An empty public key token is set via NULL_PUBLIC_KEY_TOKEN property. if (value != null && value.Length == 0) { nameObject.SetProperty(PropertyId.NULL_PUBLIC_KEY_TOKEN, null, 0); } else { SetProperty(nameObject, PropertyId.PUBLIC_KEY_TOKEN, value); } } /// <summary> /// Converts <see cref="IAssemblyName"/> to <see cref="AssemblyName"/> with all metadata fields filled. /// </summary> /// <returns> /// Assembly name with Version, Culture and PublicKeyToken components filled in: /// "SimpleName, Version=#.#.#.#, Culture=XXX, PublicKeyToken=XXXXXXXXXXXXXXXX". /// In addition Retargetable flag and ContentType are set. /// </returns> internal static AssemblyIdentity ToAssemblyIdentity(IAssemblyName nameObject) { if (nameObject == null) { return null; } AssemblyNameFlags flags = GetFlags(nameObject); byte[] publicKey = GetPublicKey(nameObject); bool hasPublicKey = publicKey != null && publicKey.Length != 0; AssemblyIdentityParts versionParts; return new AssemblyIdentity( GetName(nameObject), GetVersion(nameObject, out versionParts), GetCulture(nameObject) ?? "", (hasPublicKey ? publicKey : GetPublicKeyToken(nameObject)).AsImmutableOrNull(), hasPublicKey: hasPublicKey, isRetargetable: (flags & AssemblyNameFlags.Retargetable) != 0, contentType: GetContentType(nameObject)); } /// <summary> /// Converts <see cref="AssemblyName"/> to an equivalent <see cref="IAssemblyName"/>. /// </summary> internal static IAssemblyName ToAssemblyNameObject(AssemblyName name) { if (name == null) { return null; } IAssemblyName result; Marshal.ThrowExceptionForHR(CreateAssemblyNameObject(out result, null, 0, IntPtr.Zero)); string assemblyName = name.Name; if (assemblyName != null) { if (assemblyName.IndexOf('\0') >= 0) { #if SCRIPTING throw new ArgumentException(Scripting.ScriptingResources.InvalidCharactersInAssemblyName, nameof(name)); #elif EDITOR_FEATURES throw new ArgumentException(Microsoft.CodeAnalysis.Editor.EditorFeaturesResources.Invalid_characters_in_assembly_name, nameof(name)); #else throw new ArgumentException(Microsoft.CodeAnalysis.CodeAnalysisResources.InvalidCharactersInAssemblyName, nameof(name)); #endif } SetProperty(result, PropertyId.NAME, assemblyName); } if (name.Version != null) { SetProperty(result, PropertyId.MAJOR_VERSION, unchecked((ushort)name.Version.Major)); SetProperty(result, PropertyId.MINOR_VERSION, unchecked((ushort)name.Version.Minor)); SetProperty(result, PropertyId.BUILD_NUMBER, unchecked((ushort)name.Version.Build)); SetProperty(result, PropertyId.REVISION_NUMBER, unchecked((ushort)name.Version.Revision)); } string cultureName = name.CultureName; if (cultureName != null) { if (cultureName.IndexOf('\0') >= 0) { #if SCRIPTING throw new ArgumentException(Microsoft.CodeAnalysis.Scripting.ScriptingResources.InvalidCharactersInAssemblyName, nameof(name)); #elif EDITOR_FEATURES throw new ArgumentException(Microsoft.CodeAnalysis.Editor.EditorFeaturesResources.Invalid_characters_in_assembly_name, nameof(name)); #else throw new ArgumentException(Microsoft.CodeAnalysis.CodeAnalysisResources.InvalidCharactersInAssemblyName, nameof(name)); #endif } SetProperty(result, PropertyId.CULTURE, cultureName); } if (name.Flags == AssemblyNameFlags.Retargetable) { SetProperty(result, PropertyId.RETARGET, 1U); } if (name.ContentType != AssemblyContentType.Default) { SetProperty(result, PropertyId.CONTENT_TYPE, (uint)name.ContentType); } byte[] token = name.GetPublicKeyToken(); SetPublicKeyToken(result, token); return result; } /// <summary> /// Creates <see cref="IAssemblyName"/> object by parsing given display name. /// </summary> internal static IAssemblyName ToAssemblyNameObject(string displayName) { // CLR doesn't handle \0 in the display name well: if (displayName.IndexOf('\0') >= 0) { return null; } Debug.Assert(displayName != null); IAssemblyName result; int hr = CreateAssemblyNameObject(out result, displayName, CANOF.PARSE_DISPLAY_NAME, IntPtr.Zero); if (hr != 0) { return null; } Debug.Assert(result != null); return result; } /// <summary> /// Selects the candidate assembly with the largest version number. Uses culture as a tie-breaker if it is provided. /// All candidates are assumed to have the same name and must include versions and cultures. /// </summary> internal static IAssemblyName GetBestMatch(IEnumerable<IAssemblyName> candidates, string preferredCultureOpt) { IAssemblyName bestCandidate = null; Version bestVersion = null; string bestCulture = null; foreach (var candidate in candidates) { if (bestCandidate != null) { Version candidateVersion = GetVersion(candidate); Debug.Assert(candidateVersion != null); if (bestVersion == null) { bestVersion = GetVersion(bestCandidate); Debug.Assert(bestVersion != null); } int cmp = bestVersion.CompareTo(candidateVersion); if (cmp == 0) { if (preferredCultureOpt != null) { string candidateCulture = GetCulture(candidate); Debug.Assert(candidateCulture != null); if (bestCulture == null) { bestCulture = GetCulture(candidate); Debug.Assert(bestCulture != null); } // we have exactly the preferred culture or // we have neutral culture and the best candidate's culture isn't the preferred one: if (StringComparer.OrdinalIgnoreCase.Equals(candidateCulture, preferredCultureOpt) || candidateCulture.Length == 0 && !StringComparer.OrdinalIgnoreCase.Equals(bestCulture, preferredCultureOpt)) { bestCandidate = candidate; bestVersion = candidateVersion; bestCulture = candidateCulture; } } } else if (cmp < 0) { bestCandidate = candidate; bestVersion = candidateVersion; } } else { bestCandidate = candidate; } } return bestCandidate; } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/EditorFeatures/CSharpTest/Formatting/FormattingEngineTests_Venus.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting { public class FormattingEngineTests_Venus : CSharpFormattingEngineTestBase { public FormattingEngineTests_Venus(ITestOutputHelper output) : base(output) { } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting), Trait(Traits.Feature, Traits.Features.Venus)] public async Task SimpleOneLineNugget() { var code = @"public class Default { void PreRender() { #line ""Goo.aspx"", 1[| int x=1 ; |]#line hidden #line default } }"; var expected = @"public class Default { void PreRender() { #line ""Goo.aspx"", 1 int x = 1; #line hidden #line default } }"; await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 7); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting), Trait(Traits.Feature, Traits.Features.Venus)] public async Task SimpleMultiLineNugget() { var code = @"public class Default { void PreRender() { #line ""Goo.aspx"", 1[| if(true) { Console.WriteLine(5);} |]#line hidden #line default } }"; var expected = @"public class Default { void PreRender() { #line ""Goo.aspx"", 1 if (true) { Console.WriteLine(5); } #line hidden #line default } }"; await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 3); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting), Trait(Traits.Feature, Traits.Features.Venus)] public async Task SimpleQueryWithinNugget() { var code = @"public class Default { void PreRender() { #line ""Goo.aspx"", 1[| int[] numbers = { 5, 4, 1 }; var even = from n in numbers where n % 2 == 0 select n; |]#line hidden #line default } }"; var expected = @"public class Default { void PreRender() { #line ""Goo.aspx"", 1 int[] numbers = { 5, 4, 1 }; var even = from n in numbers where n % 2 == 0 select n; #line hidden #line default } }"; await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 7); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting), Trait(Traits.Feature, Traits.Features.Venus)] public async Task LambdaExpressionInNugget() { var code = @"public class Default { void PreRender() { #line ""Goo.aspx"", 1[| int[] source = new [] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8} ; foreach(int i in source.Where(x => x > 5)) Console.WriteLine(i); |]#line hidden #line default } }"; var expected = @"public class Default { void PreRender() { #line ""Goo.aspx"", 1 int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 }; foreach (int i in source.Where(x => x > 5)) Console.WriteLine(i); #line hidden #line default } }"; await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 3); } [WorkItem(576457, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576457")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting), Trait(Traits.Feature, Traits.Features.Venus)] public async Task StatementLambdaInNugget() { var code = @"public class Default { void PreRender() { #line ""Goo.aspx"", 1[| int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 }; foreach (int i in source.Where( x => { if (x <= 3) return true; else if (x >= 7) return true; return false; } )) Console.WriteLine(i); |]#line hidden #line default } }"; var expected = @"public class Default { void PreRender() { #line ""Goo.aspx"", 1 int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 }; foreach (int i in source.Where( x => { if (x <= 3) return true; else if (x >= 7) return true; return false; } )) Console.WriteLine(i); #line hidden #line default } }"; // It is somewhat odd that the 'x' and the ')' maintain their // position relative to 'foreach', but the block doesn't, but that isn't // Venus specific, just the way the formatting engine is. await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 3); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting { public class FormattingEngineTests_Venus : CSharpFormattingEngineTestBase { public FormattingEngineTests_Venus(ITestOutputHelper output) : base(output) { } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting), Trait(Traits.Feature, Traits.Features.Venus)] public async Task SimpleOneLineNugget() { var code = @"public class Default { void PreRender() { #line ""Goo.aspx"", 1[| int x=1 ; |]#line hidden #line default } }"; var expected = @"public class Default { void PreRender() { #line ""Goo.aspx"", 1 int x = 1; #line hidden #line default } }"; await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 7); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting), Trait(Traits.Feature, Traits.Features.Venus)] public async Task SimpleMultiLineNugget() { var code = @"public class Default { void PreRender() { #line ""Goo.aspx"", 1[| if(true) { Console.WriteLine(5);} |]#line hidden #line default } }"; var expected = @"public class Default { void PreRender() { #line ""Goo.aspx"", 1 if (true) { Console.WriteLine(5); } #line hidden #line default } }"; await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 3); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting), Trait(Traits.Feature, Traits.Features.Venus)] public async Task SimpleQueryWithinNugget() { var code = @"public class Default { void PreRender() { #line ""Goo.aspx"", 1[| int[] numbers = { 5, 4, 1 }; var even = from n in numbers where n % 2 == 0 select n; |]#line hidden #line default } }"; var expected = @"public class Default { void PreRender() { #line ""Goo.aspx"", 1 int[] numbers = { 5, 4, 1 }; var even = from n in numbers where n % 2 == 0 select n; #line hidden #line default } }"; await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 7); } [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting), Trait(Traits.Feature, Traits.Features.Venus)] public async Task LambdaExpressionInNugget() { var code = @"public class Default { void PreRender() { #line ""Goo.aspx"", 1[| int[] source = new [] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8} ; foreach(int i in source.Where(x => x > 5)) Console.WriteLine(i); |]#line hidden #line default } }"; var expected = @"public class Default { void PreRender() { #line ""Goo.aspx"", 1 int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 }; foreach (int i in source.Where(x => x > 5)) Console.WriteLine(i); #line hidden #line default } }"; await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 3); } [WorkItem(576457, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576457")] [WpfFact, Trait(Traits.Feature, Traits.Features.Formatting), Trait(Traits.Feature, Traits.Features.Venus)] public async Task StatementLambdaInNugget() { var code = @"public class Default { void PreRender() { #line ""Goo.aspx"", 1[| int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 }; foreach (int i in source.Where( x => { if (x <= 3) return true; else if (x >= 7) return true; return false; } )) Console.WriteLine(i); |]#line hidden #line default } }"; var expected = @"public class Default { void PreRender() { #line ""Goo.aspx"", 1 int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 }; foreach (int i in source.Where( x => { if (x <= 3) return true; else if (x >= 7) return true; return false; } )) Console.WriteLine(i); #line hidden #line default } }"; // It is somewhat odd that the 'x' and the ')' maintain their // position relative to 'foreach', but the block doesn't, but that isn't // Venus specific, just the way the formatting engine is. await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 3); } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Workspaces/Core/Portable/Shared/TestHooks/IAsynchronousOperationListener.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.Shared.TestHooks { internal interface IAsynchronousOperationListener : IExpeditableDelaySource { IAsyncToken BeginAsyncOperation(string name, object? tag = null, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.Shared.TestHooks { internal interface IAsynchronousOperationListener : IExpeditableDelaySource { IAsyncToken BeginAsyncOperation(string name, object? tag = null, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0); } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Tools/AnalyzerRunner/IncrementalAnalyzerRunner.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.FindSymbols.SymbolTree; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.IncrementalCaches; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Storage; namespace AnalyzerRunner { public sealed class IncrementalAnalyzerRunner { private readonly Workspace _workspace; private readonly Options _options; public IncrementalAnalyzerRunner(Workspace workspace, Options options) { _workspace = workspace; _options = options; } public bool HasAnalyzers => _options.IncrementalAnalyzerNames.Any(); public async Task RunAsync(CancellationToken cancellationToken) { if (!HasAnalyzers) { return; } var usePersistentStorage = _options.UsePersistentStorage; _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options .WithChangedOption(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.CSharp, _options.AnalysisScope) .WithChangedOption(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.VisualBasic, _options.AnalysisScope) .WithChangedOption(StorageOptions.Database, usePersistentStorage ? StorageDatabase.SQLite : StorageDatabase.None))); var exportProvider = (IMefHostExportProvider)_workspace.Services.HostServices; var solutionCrawlerRegistrationService = (SolutionCrawlerRegistrationService)_workspace.Services.GetRequiredService<ISolutionCrawlerRegistrationService>(); solutionCrawlerRegistrationService.Register(_workspace); if (usePersistentStorage) { var persistentStorageService = _workspace.Services.GetRequiredService<IPersistentStorageService>(); await using var persistentStorage = await persistentStorageService.GetStorageAsync(_workspace.CurrentSolution, cancellationToken).ConfigureAwait(false); if (persistentStorage is NoOpPersistentStorage) { throw new InvalidOperationException("Benchmark is not configured to use persistent storage."); } } var incrementalAnalyzerProviders = exportProvider.GetExports<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(); foreach (var incrementalAnalyzerName in _options.IncrementalAnalyzerNames) { var incrementalAnalyzerProvider = incrementalAnalyzerProviders.Where(x => x.Metadata.Name == incrementalAnalyzerName).SingleOrDefault(provider => provider.Metadata.WorkspaceKinds?.Contains(_workspace.Kind) ?? false)?.Value; incrementalAnalyzerProvider ??= incrementalAnalyzerProviders.Where(x => x.Metadata.Name == incrementalAnalyzerName).SingleOrDefault(provider => provider.Metadata.WorkspaceKinds?.Contains(WorkspaceKind.Host) ?? false)?.Value; incrementalAnalyzerProvider ??= incrementalAnalyzerProviders.Where(x => x.Metadata.Name == incrementalAnalyzerName).SingleOrDefault(provider => provider.Metadata.WorkspaceKinds?.Contains(WorkspaceKind.RemoteWorkspace) ?? false)?.Value; incrementalAnalyzerProvider ??= incrementalAnalyzerProviders.Where(x => x.Metadata.Name == incrementalAnalyzerName).Single(provider => provider.Metadata.WorkspaceKinds is null).Value; var incrementalAnalyzer = incrementalAnalyzerProvider.CreateIncrementalAnalyzer(_workspace); solutionCrawlerRegistrationService.GetTestAccessor().WaitUntilCompletion(_workspace, ImmutableArray.Create(incrementalAnalyzer)); switch (incrementalAnalyzerName) { case nameof(SymbolTreeInfoIncrementalAnalyzerProvider): var symbolTreeInfoCacheService = _workspace.Services.GetRequiredService<ISymbolTreeInfoCacheService>(); var symbolTreeInfo = await symbolTreeInfoCacheService.TryGetSourceSymbolTreeInfoAsync(_workspace.CurrentSolution.Projects.First(), cancellationToken).ConfigureAwait(false); if (symbolTreeInfo is null) { throw new InvalidOperationException("Benchmark failed to calculate symbol tree info."); } break; default: // No additional actions required break; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.FindSymbols.SymbolTree; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.IncrementalCaches; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Storage; namespace AnalyzerRunner { public sealed class IncrementalAnalyzerRunner { private readonly Workspace _workspace; private readonly Options _options; public IncrementalAnalyzerRunner(Workspace workspace, Options options) { _workspace = workspace; _options = options; } public bool HasAnalyzers => _options.IncrementalAnalyzerNames.Any(); public async Task RunAsync(CancellationToken cancellationToken) { if (!HasAnalyzers) { return; } var usePersistentStorage = _options.UsePersistentStorage; _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options .WithChangedOption(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.CSharp, _options.AnalysisScope) .WithChangedOption(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.VisualBasic, _options.AnalysisScope) .WithChangedOption(StorageOptions.Database, usePersistentStorage ? StorageDatabase.SQLite : StorageDatabase.None))); var exportProvider = (IMefHostExportProvider)_workspace.Services.HostServices; var solutionCrawlerRegistrationService = (SolutionCrawlerRegistrationService)_workspace.Services.GetRequiredService<ISolutionCrawlerRegistrationService>(); solutionCrawlerRegistrationService.Register(_workspace); if (usePersistentStorage) { var persistentStorageService = _workspace.Services.GetRequiredService<IPersistentStorageService>(); await using var persistentStorage = await persistentStorageService.GetStorageAsync(_workspace.CurrentSolution, cancellationToken).ConfigureAwait(false); if (persistentStorage is NoOpPersistentStorage) { throw new InvalidOperationException("Benchmark is not configured to use persistent storage."); } } var incrementalAnalyzerProviders = exportProvider.GetExports<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(); foreach (var incrementalAnalyzerName in _options.IncrementalAnalyzerNames) { var incrementalAnalyzerProvider = incrementalAnalyzerProviders.Where(x => x.Metadata.Name == incrementalAnalyzerName).SingleOrDefault(provider => provider.Metadata.WorkspaceKinds?.Contains(_workspace.Kind) ?? false)?.Value; incrementalAnalyzerProvider ??= incrementalAnalyzerProviders.Where(x => x.Metadata.Name == incrementalAnalyzerName).SingleOrDefault(provider => provider.Metadata.WorkspaceKinds?.Contains(WorkspaceKind.Host) ?? false)?.Value; incrementalAnalyzerProvider ??= incrementalAnalyzerProviders.Where(x => x.Metadata.Name == incrementalAnalyzerName).SingleOrDefault(provider => provider.Metadata.WorkspaceKinds?.Contains(WorkspaceKind.RemoteWorkspace) ?? false)?.Value; incrementalAnalyzerProvider ??= incrementalAnalyzerProviders.Where(x => x.Metadata.Name == incrementalAnalyzerName).Single(provider => provider.Metadata.WorkspaceKinds is null).Value; var incrementalAnalyzer = incrementalAnalyzerProvider.CreateIncrementalAnalyzer(_workspace); solutionCrawlerRegistrationService.GetTestAccessor().WaitUntilCompletion(_workspace, ImmutableArray.Create(incrementalAnalyzer)); switch (incrementalAnalyzerName) { case nameof(SymbolTreeInfoIncrementalAnalyzerProvider): var symbolTreeInfoCacheService = _workspace.Services.GetRequiredService<ISymbolTreeInfoCacheService>(); var symbolTreeInfo = await symbolTreeInfoCacheService.TryGetSourceSymbolTreeInfoAsync(_workspace.CurrentSolution.Projects.First(), cancellationToken).ConfigureAwait(false); if (symbolTreeInfo is null) { throw new InvalidOperationException("Benchmark failed to calculate symbol tree info."); } break; default: // No additional actions required break; } } } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Workspaces/Core/Portable/CaseCorrection/ICaseCorrectionService.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CaseCorrection { internal interface ICaseCorrectionService : ILanguageService { /// <summary> /// Case corrects all names found in the spans in the provided document. /// </summary> Task<Document> CaseCorrectAsync(Document document, ImmutableArray<TextSpan> spans, CancellationToken cancellationToken); /// <summary> /// Case corrects only things that don't require semantic information /// </summary> SyntaxNode CaseCorrect(SyntaxNode root, ImmutableArray<TextSpan> spans, Workspace workspace, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CaseCorrection { internal interface ICaseCorrectionService : ILanguageService { /// <summary> /// Case corrects all names found in the spans in the provided document. /// </summary> Task<Document> CaseCorrectAsync(Document document, ImmutableArray<TextSpan> spans, CancellationToken cancellationToken); /// <summary> /// Case corrects only things that don't require semantic information /// </summary> SyntaxNode CaseCorrect(SyntaxNode root, ImmutableArray<TextSpan> spans, Workspace workspace, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/VisualStudio/Core/Def/Implementation/DesignerAttribute/VisualStudioDesignerAttributeService.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.DesignerAttribute; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.VisualStudio.Designer.Interfaces; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell.Services; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.DesignerAttribute { [ExportEventListener(WellKnownEventListeners.Workspace, WorkspaceKind.Host), Shared] internal class VisualStudioDesignerAttributeService : ForegroundThreadAffinitizedObject, IDesignerAttributeListener, IEventListener<object>, IDisposable { private readonly VisualStudioWorkspaceImpl _workspace; /// <summary> /// Used to acquire the legacy project designer service. /// </summary> private readonly IServiceProvider _serviceProvider; /// <summary> /// Our connection to the remote OOP server. Created on demand when we startup and then /// kept around for the lifetime of this service. /// </summary> private RemoteServiceConnection<IRemoteDesignerAttributeDiscoveryService>? _lazyConnection; /// <summary> /// Cache from project to the CPS designer service for it. Computed on demand (which /// requires using the UI thread), but then cached for all subsequent notifications about /// that project. /// </summary> private readonly ConcurrentDictionary<ProjectId, IProjectItemDesignerTypeUpdateService?> _cpsProjects = new(); /// <summary> /// Cached designer service for notifying legacy projects about designer attributes. /// </summary> private IVSMDDesignerService? _legacyDesignerService; // We'll get notifications from the OOP server about new attribute arguments. Batch those // notifications up and deliver them to VS every second. private readonly AsyncBatchingWorkQueue<DesignerAttributeData>? _workQueue; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioDesignerAttributeService( VisualStudioWorkspaceImpl workspace, IThreadingContext threadingContext, IAsynchronousOperationListenerProvider asynchronousOperationListenerProvider, Shell.SVsServiceProvider serviceProvider) : base(threadingContext) { _workspace = workspace; _serviceProvider = serviceProvider; _workQueue = new AsyncBatchingWorkQueue<DesignerAttributeData>( TimeSpan.FromSeconds(1), this.NotifyProjectSystemAsync, asynchronousOperationListenerProvider.GetListener(FeatureAttribute.DesignerAttributes), ThreadingContext.DisposalToken); } public void Dispose() { _lazyConnection?.Dispose(); } void IEventListener<object>.StartListening(Workspace workspace, object _) { if (workspace is VisualStudioWorkspace) _ = StartAsync(); } private async Task StartAsync() { // Have to catch all exceptions coming through here as this is called from a // fire-and-forget method and we want to make sure nothing leaks out. try { await StartWorkerAsync().ConfigureAwait(false); } catch (OperationCanceledException) { // Cancellation is normal (during VS closing). Just ignore. } catch (Exception e) when (FatalError.ReportAndCatch(e)) { // Otherwise report a watson for any other exception. Don't bring down VS. This is // a BG service we don't want impacting the user experience. } } private async Task StartWorkerAsync() { var cancellationToken = ThreadingContext.DisposalToken; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { StartScanningForDesignerAttributesInCurrentProcess(cancellationToken); return; } // Pass ourselves in as the callback target for the OOP service. As it discovers // designer attributes it will call back into us to notify VS about it. _lazyConnection = client.CreateConnection<IRemoteDesignerAttributeDiscoveryService>(callbackTarget: this); // Now kick off scanning in the OOP process. // If the call fails an error has already been reported and there is nothing more to do. _ = await _lazyConnection.TryInvokeAsync( (service, callbackId, cancellationToken) => service.StartScanningForDesignerAttributesAsync(callbackId, cancellationToken), cancellationToken).ConfigureAwait(false); } public void StartScanningForDesignerAttributesInCurrentProcess(CancellationToken cancellation) { var registrationService = _workspace.Services.GetRequiredService<ISolutionCrawlerRegistrationService>(); var analyzerProvider = new InProcDesignerAttributeIncrementalAnalyzerProvider(this); registrationService.AddAnalyzerProvider( analyzerProvider, new IncrementalAnalyzerProviderMetadata( nameof(InProcDesignerAttributeIncrementalAnalyzerProvider), highPriorityForActiveFile: false, workspaceKinds: WorkspaceKind.Host)); } private async ValueTask NotifyProjectSystemAsync( ImmutableArray<DesignerAttributeData> data, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); using var _1 = ArrayBuilder<DesignerAttributeData>.GetInstance(out var filteredInfos); AddFilteredInfos(data, filteredInfos); // Now, group all the notifications by project and update all the projects in parallel. using var _2 = ArrayBuilder<Task>.GetInstance(out var tasks); foreach (var group in filteredInfos.GroupBy(a => a.DocumentId.ProjectId)) { cancellationToken.ThrowIfCancellationRequested(); tasks.Add(NotifyProjectSystemAsync(group.Key, group, cancellationToken)); } // Wait until all project updates have happened before processing the next batch. await Task.WhenAll(tasks).ConfigureAwait(false); } private void AddFilteredInfos(ImmutableArray<DesignerAttributeData> data, ArrayBuilder<DesignerAttributeData> filteredData) { using var _ = PooledHashSet<DocumentId>.GetInstance(out var seenDocumentIds); // Walk the list of designer items in reverse, and skip any items for a project once // we've already seen it once. That way, we're only reporting the most up to date // information for a project, and we're skipping the stale information. for (var i = data.Length - 1; i >= 0; i--) { var info = data[i]; if (seenDocumentIds.Add(info.DocumentId)) filteredData.Add(info); } } private async Task NotifyProjectSystemAsync( ProjectId projectId, IEnumerable<DesignerAttributeData> data, CancellationToken cancellationToken) { // Delegate to the CPS or legacy notification services as necessary. var cpsUpdateService = await GetUpdateServiceIfCpsProjectAsync(projectId, cancellationToken).ConfigureAwait(false); var task = cpsUpdateService == null ? NotifyLegacyProjectSystemAsync(projectId, data, cancellationToken) : NotifyCpsProjectSystemAsync(projectId, cpsUpdateService, data, cancellationToken); await task.ConfigureAwait(false); } private async Task NotifyLegacyProjectSystemAsync( ProjectId projectId, IEnumerable<DesignerAttributeData> data, CancellationToken cancellationToken) { // legacy project system can only be talked to on the UI thread. await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, cancellationToken); AssertIsForeground(); var designerService = _legacyDesignerService ??= (IVSMDDesignerService)_serviceProvider.GetService(typeof(SVSMDDesignerService)); if (designerService == null) return; var hierarchy = _workspace.GetHierarchy(projectId); if (hierarchy == null) return; foreach (var info in data) { cancellationToken.ThrowIfCancellationRequested(); NotifyLegacyProjectSystemOnUIThread(designerService, hierarchy, info); } } private void NotifyLegacyProjectSystemOnUIThread( IVSMDDesignerService designerService, IVsHierarchy hierarchy, DesignerAttributeData data) { this.AssertIsForeground(); var itemId = hierarchy.TryGetItemId(data.FilePath); if (itemId == VSConstants.VSITEMID_NIL) return; // PERF: Avoid sending the message if the project system already has the current value. if (ErrorHandler.Succeeded(hierarchy.GetProperty(itemId, (int)__VSHPROPID.VSHPROPID_ItemSubType, out var currentValue))) { var currentStringValue = string.IsNullOrEmpty(currentValue as string) ? null : (string)currentValue; if (string.Equals(currentStringValue, data.Category, StringComparison.OrdinalIgnoreCase)) return; } try { designerService.RegisterDesignViewAttribute( hierarchy, (int)itemId, dwClass: 0, pwszAttributeValue: data.Category); } catch { // DevDiv # 933717 // turns out RegisterDesignViewAttribute can throw in certain cases such as a file failed to be checked out by source control // or IVSHierarchy failed to set a property for this project // // just swallow it. don't crash VS. } } private async Task NotifyCpsProjectSystemAsync( ProjectId projectId, IProjectItemDesignerTypeUpdateService updateService, IEnumerable<DesignerAttributeData> data, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // We may have updates for many different configurations of the same logical project system project. // However, the project system only associates designer attributes with one of those projects. So just drop // the notifications for any sibling configurations. if (!_workspace.IsPrimaryProject(projectId)) return; // Broadcast all the information about all the documents in parallel to CPS. using var _ = ArrayBuilder<Task>.GetInstance(out var tasks); foreach (var info in data) { cancellationToken.ThrowIfCancellationRequested(); tasks.Add(NotifyCpsProjectSystemAsync(updateService, info, cancellationToken)); } await Task.WhenAll(tasks).ConfigureAwait(false); } private async Task NotifyCpsProjectSystemAsync( IProjectItemDesignerTypeUpdateService updateService, DesignerAttributeData data, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); try { await updateService.SetProjectItemDesignerTypeAsync(data.FilePath, data.Category).ConfigureAwait(false); } catch (ObjectDisposedException) { // we might call update service after project is already removed and get object disposed exception. // we will catch the exception and ignore. // see this PR for more detail - https://github.com/dotnet/roslyn/pull/35383 } } private async Task<IProjectItemDesignerTypeUpdateService?> GetUpdateServiceIfCpsProjectAsync( ProjectId projectId, CancellationToken cancellationToken) { if (!_cpsProjects.TryGetValue(projectId, out var updateService)) { await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, cancellationToken); this.AssertIsForeground(); updateService = ComputeUpdateService(); _cpsProjects.TryAdd(projectId, updateService); } return updateService; IProjectItemDesignerTypeUpdateService? ComputeUpdateService() { if (!_workspace.IsCPSProject(projectId)) return null; var vsProject = (IVsProject?)_workspace.GetHierarchy(projectId); if (vsProject == null) return null; if (ErrorHandler.Failed(vsProject.GetItemContext((uint)VSConstants.VSITEMID.Root, out var projectServiceProvider))) return null; var serviceProvider = new Shell.ServiceProvider(projectServiceProvider); return serviceProvider.GetService(typeof(IProjectItemDesignerTypeUpdateService)) as IProjectItemDesignerTypeUpdateService; } } /// <summary> /// Callback from the OOP service back into us. /// </summary> public ValueTask ReportDesignerAttributeDataAsync(ImmutableArray<DesignerAttributeData> data, CancellationToken cancellationToken) { Contract.ThrowIfNull(_workQueue); _workQueue.AddWork(data); return ValueTaskFactory.CompletedTask; } public ValueTask OnProjectRemovedAsync(ProjectId projectId, CancellationToken cancellationToken) { _cpsProjects.TryRemove(projectId, out _); return ValueTaskFactory.CompletedTask; } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.DesignerAttribute; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.VisualStudio.Designer.Interfaces; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell.Services; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.DesignerAttribute { [ExportEventListener(WellKnownEventListeners.Workspace, WorkspaceKind.Host), Shared] internal class VisualStudioDesignerAttributeService : ForegroundThreadAffinitizedObject, IDesignerAttributeListener, IEventListener<object>, IDisposable { private readonly VisualStudioWorkspaceImpl _workspace; /// <summary> /// Used to acquire the legacy project designer service. /// </summary> private readonly IServiceProvider _serviceProvider; /// <summary> /// Our connection to the remote OOP server. Created on demand when we startup and then /// kept around for the lifetime of this service. /// </summary> private RemoteServiceConnection<IRemoteDesignerAttributeDiscoveryService>? _lazyConnection; /// <summary> /// Cache from project to the CPS designer service for it. Computed on demand (which /// requires using the UI thread), but then cached for all subsequent notifications about /// that project. /// </summary> private readonly ConcurrentDictionary<ProjectId, IProjectItemDesignerTypeUpdateService?> _cpsProjects = new(); /// <summary> /// Cached designer service for notifying legacy projects about designer attributes. /// </summary> private IVSMDDesignerService? _legacyDesignerService; // We'll get notifications from the OOP server about new attribute arguments. Batch those // notifications up and deliver them to VS every second. private readonly AsyncBatchingWorkQueue<DesignerAttributeData>? _workQueue; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioDesignerAttributeService( VisualStudioWorkspaceImpl workspace, IThreadingContext threadingContext, IAsynchronousOperationListenerProvider asynchronousOperationListenerProvider, Shell.SVsServiceProvider serviceProvider) : base(threadingContext) { _workspace = workspace; _serviceProvider = serviceProvider; _workQueue = new AsyncBatchingWorkQueue<DesignerAttributeData>( TimeSpan.FromSeconds(1), this.NotifyProjectSystemAsync, asynchronousOperationListenerProvider.GetListener(FeatureAttribute.DesignerAttributes), ThreadingContext.DisposalToken); } public void Dispose() { _lazyConnection?.Dispose(); } void IEventListener<object>.StartListening(Workspace workspace, object _) { if (workspace is VisualStudioWorkspace) _ = StartAsync(); } private async Task StartAsync() { // Have to catch all exceptions coming through here as this is called from a // fire-and-forget method and we want to make sure nothing leaks out. try { await StartWorkerAsync().ConfigureAwait(false); } catch (OperationCanceledException) { // Cancellation is normal (during VS closing). Just ignore. } catch (Exception e) when (FatalError.ReportAndCatch(e)) { // Otherwise report a watson for any other exception. Don't bring down VS. This is // a BG service we don't want impacting the user experience. } } private async Task StartWorkerAsync() { var cancellationToken = ThreadingContext.DisposalToken; var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { StartScanningForDesignerAttributesInCurrentProcess(cancellationToken); return; } // Pass ourselves in as the callback target for the OOP service. As it discovers // designer attributes it will call back into us to notify VS about it. _lazyConnection = client.CreateConnection<IRemoteDesignerAttributeDiscoveryService>(callbackTarget: this); // Now kick off scanning in the OOP process. // If the call fails an error has already been reported and there is nothing more to do. _ = await _lazyConnection.TryInvokeAsync( (service, callbackId, cancellationToken) => service.StartScanningForDesignerAttributesAsync(callbackId, cancellationToken), cancellationToken).ConfigureAwait(false); } public void StartScanningForDesignerAttributesInCurrentProcess(CancellationToken cancellation) { var registrationService = _workspace.Services.GetRequiredService<ISolutionCrawlerRegistrationService>(); var analyzerProvider = new InProcDesignerAttributeIncrementalAnalyzerProvider(this); registrationService.AddAnalyzerProvider( analyzerProvider, new IncrementalAnalyzerProviderMetadata( nameof(InProcDesignerAttributeIncrementalAnalyzerProvider), highPriorityForActiveFile: false, workspaceKinds: WorkspaceKind.Host)); } private async ValueTask NotifyProjectSystemAsync( ImmutableArray<DesignerAttributeData> data, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); using var _1 = ArrayBuilder<DesignerAttributeData>.GetInstance(out var filteredInfos); AddFilteredInfos(data, filteredInfos); // Now, group all the notifications by project and update all the projects in parallel. using var _2 = ArrayBuilder<Task>.GetInstance(out var tasks); foreach (var group in filteredInfos.GroupBy(a => a.DocumentId.ProjectId)) { cancellationToken.ThrowIfCancellationRequested(); tasks.Add(NotifyProjectSystemAsync(group.Key, group, cancellationToken)); } // Wait until all project updates have happened before processing the next batch. await Task.WhenAll(tasks).ConfigureAwait(false); } private void AddFilteredInfos(ImmutableArray<DesignerAttributeData> data, ArrayBuilder<DesignerAttributeData> filteredData) { using var _ = PooledHashSet<DocumentId>.GetInstance(out var seenDocumentIds); // Walk the list of designer items in reverse, and skip any items for a project once // we've already seen it once. That way, we're only reporting the most up to date // information for a project, and we're skipping the stale information. for (var i = data.Length - 1; i >= 0; i--) { var info = data[i]; if (seenDocumentIds.Add(info.DocumentId)) filteredData.Add(info); } } private async Task NotifyProjectSystemAsync( ProjectId projectId, IEnumerable<DesignerAttributeData> data, CancellationToken cancellationToken) { // Delegate to the CPS or legacy notification services as necessary. var cpsUpdateService = await GetUpdateServiceIfCpsProjectAsync(projectId, cancellationToken).ConfigureAwait(false); var task = cpsUpdateService == null ? NotifyLegacyProjectSystemAsync(projectId, data, cancellationToken) : NotifyCpsProjectSystemAsync(projectId, cpsUpdateService, data, cancellationToken); await task.ConfigureAwait(false); } private async Task NotifyLegacyProjectSystemAsync( ProjectId projectId, IEnumerable<DesignerAttributeData> data, CancellationToken cancellationToken) { // legacy project system can only be talked to on the UI thread. await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, cancellationToken); AssertIsForeground(); var designerService = _legacyDesignerService ??= (IVSMDDesignerService)_serviceProvider.GetService(typeof(SVSMDDesignerService)); if (designerService == null) return; var hierarchy = _workspace.GetHierarchy(projectId); if (hierarchy == null) return; foreach (var info in data) { cancellationToken.ThrowIfCancellationRequested(); NotifyLegacyProjectSystemOnUIThread(designerService, hierarchy, info); } } private void NotifyLegacyProjectSystemOnUIThread( IVSMDDesignerService designerService, IVsHierarchy hierarchy, DesignerAttributeData data) { this.AssertIsForeground(); var itemId = hierarchy.TryGetItemId(data.FilePath); if (itemId == VSConstants.VSITEMID_NIL) return; // PERF: Avoid sending the message if the project system already has the current value. if (ErrorHandler.Succeeded(hierarchy.GetProperty(itemId, (int)__VSHPROPID.VSHPROPID_ItemSubType, out var currentValue))) { var currentStringValue = string.IsNullOrEmpty(currentValue as string) ? null : (string)currentValue; if (string.Equals(currentStringValue, data.Category, StringComparison.OrdinalIgnoreCase)) return; } try { designerService.RegisterDesignViewAttribute( hierarchy, (int)itemId, dwClass: 0, pwszAttributeValue: data.Category); } catch { // DevDiv # 933717 // turns out RegisterDesignViewAttribute can throw in certain cases such as a file failed to be checked out by source control // or IVSHierarchy failed to set a property for this project // // just swallow it. don't crash VS. } } private async Task NotifyCpsProjectSystemAsync( ProjectId projectId, IProjectItemDesignerTypeUpdateService updateService, IEnumerable<DesignerAttributeData> data, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // We may have updates for many different configurations of the same logical project system project. // However, the project system only associates designer attributes with one of those projects. So just drop // the notifications for any sibling configurations. if (!_workspace.IsPrimaryProject(projectId)) return; // Broadcast all the information about all the documents in parallel to CPS. using var _ = ArrayBuilder<Task>.GetInstance(out var tasks); foreach (var info in data) { cancellationToken.ThrowIfCancellationRequested(); tasks.Add(NotifyCpsProjectSystemAsync(updateService, info, cancellationToken)); } await Task.WhenAll(tasks).ConfigureAwait(false); } private async Task NotifyCpsProjectSystemAsync( IProjectItemDesignerTypeUpdateService updateService, DesignerAttributeData data, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); try { await updateService.SetProjectItemDesignerTypeAsync(data.FilePath, data.Category).ConfigureAwait(false); } catch (ObjectDisposedException) { // we might call update service after project is already removed and get object disposed exception. // we will catch the exception and ignore. // see this PR for more detail - https://github.com/dotnet/roslyn/pull/35383 } } private async Task<IProjectItemDesignerTypeUpdateService?> GetUpdateServiceIfCpsProjectAsync( ProjectId projectId, CancellationToken cancellationToken) { if (!_cpsProjects.TryGetValue(projectId, out var updateService)) { await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, cancellationToken); this.AssertIsForeground(); updateService = ComputeUpdateService(); _cpsProjects.TryAdd(projectId, updateService); } return updateService; IProjectItemDesignerTypeUpdateService? ComputeUpdateService() { if (!_workspace.IsCPSProject(projectId)) return null; var vsProject = (IVsProject?)_workspace.GetHierarchy(projectId); if (vsProject == null) return null; if (ErrorHandler.Failed(vsProject.GetItemContext((uint)VSConstants.VSITEMID.Root, out var projectServiceProvider))) return null; var serviceProvider = new Shell.ServiceProvider(projectServiceProvider); return serviceProvider.GetService(typeof(IProjectItemDesignerTypeUpdateService)) as IProjectItemDesignerTypeUpdateService; } } /// <summary> /// Callback from the OOP service back into us. /// </summary> public ValueTask ReportDesignerAttributeDataAsync(ImmutableArray<DesignerAttributeData> data, CancellationToken cancellationToken) { Contract.ThrowIfNull(_workQueue); _workQueue.AddWork(data); return ValueTaskFactory.CompletedTask; } public ValueTask OnProjectRemovedAsync(ProjectId projectId, CancellationToken cancellationToken) { _cpsProjects.TryRemove(projectId, out _); return ValueTaskFactory.CompletedTask; } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/EditorFeatures/VisualBasicTest/ConvertForToForEach/ConvertForToForEachTests.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.ConvertForToForEach Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ConvertForToForEach Public Class ConvertForToForEachTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New VisualBasicConvertForToForEachCodeRefactoringProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestArray1() As Task Await TestInRegularAndScript1Async( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length - 1 Console.WriteLine(array(i)) next end sub end class", "imports System class C sub Test(array as string()) For Each {|Rename:v|} In array Console.WriteLine(v) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestForSelected() As Task Await TestInRegularAndScript1Async( "imports System class C sub Test(array as string()) [|For|] i = 0 to array.Length - 1 Console.WriteLine(array(i)) next end sub end class", "imports System class C sub Test(array as string()) For Each {|Rename:v|} In array Console.WriteLine(v) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestAtEndOfFor() As Task Await TestInRegularAndScript1Async( "imports System class C sub Test(array as string()) For i = 0 to array.Length - 1[||] Console.WriteLine(array(i)) next end sub end class", "imports System class C sub Test(array as string()) For Each {|Rename:v|} In array Console.WriteLine(v) next end sub end class") End Function <WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestBeforeFor() As Task Await TestInRegularAndScript1Async( "imports System class C sub Test(array as string()) [||] For i = 0 to array.Length - 1 Console.WriteLine(array(i)) next end sub end class", "imports System class C sub Test(array as string()) For Each {|Rename:v|} In array Console.WriteLine(v) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingAfterFor() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) For [||]i = 0 to array.Length - 1 Console.WriteLine(array(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestArrayPlusStep1() As Task Await TestInRegularAndScript1Async( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length - 1 step 1 Console.WriteLine(array(i)) next end sub end class", "imports System class C sub Test(array as string()) For Each {|Rename:v|} In array Console.WriteLine(v) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingWithWrongStep() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length - 1 step 2 Console.WriteLine(array(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingIfReferencingNotDeclaringVariable() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) dim i as integer [||]For i = 0 to array.Length - 1 step 2 Console.WriteLine(array(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingWithIncorrectCondition1() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length { Console.WriteLine(array(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingWithIncorrectCondition2() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) [||]For i = 0 to GetLength(array) - 1 { Console.WriteLine(array(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingWithIncorrectCondition3() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length - 2 { Console.WriteLine(array(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestNotStartingAtZero() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) [||]For i = 1 to array.Length - 1 { Console.WriteLine(array(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestList1() As Task Await TestInRegularAndScript1Async( "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) [||]For i = 0 to list.Count - 1 Console.WriteLine(list(i)) next end sub end class", "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) For Each {|Rename:v|} In list Console.WriteLine(v) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestChooseNameFromDeclarationStatement() As Task Await TestInRegularAndScript1Async( "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) [||]For i = 0 to list.Count - 1 dim val = list(i) Console.WriteLine(list(i)) next end sub end class", "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) For Each val In list Console.WriteLine(val) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestChooseNameAndTypeFromDeclarationStatement() As Task Await TestInRegularAndScript1Async( "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) [||]For i = 0 to list.Count - 1 dim val As Object = list(i) Console.WriteLine(list(i)) next end sub end class", "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) For Each val As Object In list Console.WriteLine(val) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestChooseNameFromDeclarationStatement_PreserveComments() As Task Await TestInRegularAndScript1Async( "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) [||]For i = 0 to list.Count - 1 ' loop comment dim val = list(i) Console.WriteLine(list(i)) next end sub end class", "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) For Each val In list ' loop comment Console.WriteLine(val) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestChooseNameFromDeclarationStatement_PreserveDirectives() As Task Await TestInRegularAndScript1Async( "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) [||]For i = 0 to list.Count - 1 #if true dim val = list(i) Console.WriteLine(list(i)) #end if next end sub end class", "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) For Each val In list #if true Console.WriteLine(val) #end if next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingIfVariableUsedNotForIndexing() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length - 1 Console.WriteLine(i) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingIfVariableUsedForIndexingNonCollection() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length - 1 Console.WriteLine(other(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestWarningIfCollectionWrittenTo() As Task Await TestInRegularAndScript1Async( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length - 1 array(i) = 1 next end sub end class", "imports System class C sub Test(array as string()) For Each {|Rename:v|} In array {|Warning:v|} = 1 next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestDifferentIndexerAndEnumeratorType() As Task Await TestInRegularAndScriptAsync( "imports System class MyList default public readonly property Item(i as integer) as string public function GetEnumerator() as Enumerator end function public structure Enumerator public readonly property Current as object end structure end class class C sub Test(list as MyList) ' need to use 'string' here to preserve original index semantics. [||]For i = 0 to list.Length - 1 Console.WriteLine(list(i)) next end sub end class", "imports System class MyList default public readonly property Item(i as integer) as string public function GetEnumerator() as Enumerator end function public structure Enumerator public readonly property Current as object end structure end class class C sub Test(list as MyList) ' need to use 'string' here to preserve original index semantics. For Each {|Rename:v|} As String In list Console.WriteLine(v) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestSameIndexerAndEnumeratorType() As Task Await TestInRegularAndScriptAsync( "imports System class MyList default public readonly property Item(i as integer) as object public function GetEnumerator() as Enumerator end function public structure Enumerator public readonly property Current as object end structure end class class C sub Test(list as MyList) ' can omit type here since the type stayed the same. [||]For i = 0 to list.Count - 1 Console.WriteLine(list(i)) next end sub end class", "imports System class MyList default public readonly property Item(i as integer) as object public function GetEnumerator() as Enumerator end function public structure Enumerator public readonly property Current as object end structure end class class C sub Test(list as MyList) ' can omit type here since the type stayed the same. For Each {|Rename:v|} In list Console.WriteLine(v) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestTrivia() As Task Await TestInRegularAndScript1Async( "imports System class C sub Test(array as string()) ' trivia 1 [||]For i = 0 to array.Length - 1 ' trivia 2 Console.WriteLine(array(i)) next ' trivia 3 end sub end class", "imports System class C sub Test(array as string()) ' trivia 1 For Each {|Rename:v|} In array ' trivia 2 Console.WriteLine(v) next ' trivia 3 end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> <WorkItem(32822, "https://github.com/dotnet/roslyn/issues/32822")> Public Async Function DoNotCrashOnInvalidCode() As Task Await TestMissingInRegularAndScriptAsync( " Class C Sub Test() Dim list = New List(Of Integer) [||]For newIndex = 0 To list.Count - 1 \' type the character '\' at the end of this line to invoke exception Next 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.CodeRefactorings Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.ConvertForToForEach Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ConvertForToForEach Public Class ConvertForToForEachTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New VisualBasicConvertForToForEachCodeRefactoringProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestArray1() As Task Await TestInRegularAndScript1Async( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length - 1 Console.WriteLine(array(i)) next end sub end class", "imports System class C sub Test(array as string()) For Each {|Rename:v|} In array Console.WriteLine(v) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestForSelected() As Task Await TestInRegularAndScript1Async( "imports System class C sub Test(array as string()) [|For|] i = 0 to array.Length - 1 Console.WriteLine(array(i)) next end sub end class", "imports System class C sub Test(array as string()) For Each {|Rename:v|} In array Console.WriteLine(v) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestAtEndOfFor() As Task Await TestInRegularAndScript1Async( "imports System class C sub Test(array as string()) For i = 0 to array.Length - 1[||] Console.WriteLine(array(i)) next end sub end class", "imports System class C sub Test(array as string()) For Each {|Rename:v|} In array Console.WriteLine(v) next end sub end class") End Function <WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestBeforeFor() As Task Await TestInRegularAndScript1Async( "imports System class C sub Test(array as string()) [||] For i = 0 to array.Length - 1 Console.WriteLine(array(i)) next end sub end class", "imports System class C sub Test(array as string()) For Each {|Rename:v|} In array Console.WriteLine(v) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingAfterFor() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) For [||]i = 0 to array.Length - 1 Console.WriteLine(array(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestArrayPlusStep1() As Task Await TestInRegularAndScript1Async( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length - 1 step 1 Console.WriteLine(array(i)) next end sub end class", "imports System class C sub Test(array as string()) For Each {|Rename:v|} In array Console.WriteLine(v) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingWithWrongStep() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length - 1 step 2 Console.WriteLine(array(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingIfReferencingNotDeclaringVariable() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) dim i as integer [||]For i = 0 to array.Length - 1 step 2 Console.WriteLine(array(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingWithIncorrectCondition1() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length { Console.WriteLine(array(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingWithIncorrectCondition2() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) [||]For i = 0 to GetLength(array) - 1 { Console.WriteLine(array(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingWithIncorrectCondition3() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length - 2 { Console.WriteLine(array(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestNotStartingAtZero() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) [||]For i = 1 to array.Length - 1 { Console.WriteLine(array(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestList1() As Task Await TestInRegularAndScript1Async( "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) [||]For i = 0 to list.Count - 1 Console.WriteLine(list(i)) next end sub end class", "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) For Each {|Rename:v|} In list Console.WriteLine(v) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestChooseNameFromDeclarationStatement() As Task Await TestInRegularAndScript1Async( "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) [||]For i = 0 to list.Count - 1 dim val = list(i) Console.WriteLine(list(i)) next end sub end class", "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) For Each val In list Console.WriteLine(val) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestChooseNameAndTypeFromDeclarationStatement() As Task Await TestInRegularAndScript1Async( "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) [||]For i = 0 to list.Count - 1 dim val As Object = list(i) Console.WriteLine(list(i)) next end sub end class", "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) For Each val As Object In list Console.WriteLine(val) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestChooseNameFromDeclarationStatement_PreserveComments() As Task Await TestInRegularAndScript1Async( "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) [||]For i = 0 to list.Count - 1 ' loop comment dim val = list(i) Console.WriteLine(list(i)) next end sub end class", "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) For Each val In list ' loop comment Console.WriteLine(val) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestChooseNameFromDeclarationStatement_PreserveDirectives() As Task Await TestInRegularAndScript1Async( "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) [||]For i = 0 to list.Count - 1 #if true dim val = list(i) Console.WriteLine(list(i)) #end if next end sub end class", "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) For Each val In list #if true Console.WriteLine(val) #end if next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingIfVariableUsedNotForIndexing() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length - 1 Console.WriteLine(i) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingIfVariableUsedForIndexingNonCollection() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length - 1 Console.WriteLine(other(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestWarningIfCollectionWrittenTo() As Task Await TestInRegularAndScript1Async( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length - 1 array(i) = 1 next end sub end class", "imports System class C sub Test(array as string()) For Each {|Rename:v|} In array {|Warning:v|} = 1 next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestDifferentIndexerAndEnumeratorType() As Task Await TestInRegularAndScriptAsync( "imports System class MyList default public readonly property Item(i as integer) as string public function GetEnumerator() as Enumerator end function public structure Enumerator public readonly property Current as object end structure end class class C sub Test(list as MyList) ' need to use 'string' here to preserve original index semantics. [||]For i = 0 to list.Length - 1 Console.WriteLine(list(i)) next end sub end class", "imports System class MyList default public readonly property Item(i as integer) as string public function GetEnumerator() as Enumerator end function public structure Enumerator public readonly property Current as object end structure end class class C sub Test(list as MyList) ' need to use 'string' here to preserve original index semantics. For Each {|Rename:v|} As String In list Console.WriteLine(v) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestSameIndexerAndEnumeratorType() As Task Await TestInRegularAndScriptAsync( "imports System class MyList default public readonly property Item(i as integer) as object public function GetEnumerator() as Enumerator end function public structure Enumerator public readonly property Current as object end structure end class class C sub Test(list as MyList) ' can omit type here since the type stayed the same. [||]For i = 0 to list.Count - 1 Console.WriteLine(list(i)) next end sub end class", "imports System class MyList default public readonly property Item(i as integer) as object public function GetEnumerator() as Enumerator end function public structure Enumerator public readonly property Current as object end structure end class class C sub Test(list as MyList) ' can omit type here since the type stayed the same. For Each {|Rename:v|} In list Console.WriteLine(v) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestTrivia() As Task Await TestInRegularAndScript1Async( "imports System class C sub Test(array as string()) ' trivia 1 [||]For i = 0 to array.Length - 1 ' trivia 2 Console.WriteLine(array(i)) next ' trivia 3 end sub end class", "imports System class C sub Test(array as string()) ' trivia 1 For Each {|Rename:v|} In array ' trivia 2 Console.WriteLine(v) next ' trivia 3 end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> <WorkItem(32822, "https://github.com/dotnet/roslyn/issues/32822")> Public Async Function DoNotCrashOnInvalidCode() As Task Await TestMissingInRegularAndScriptAsync( " Class C Sub Test() Dim list = New List(Of Integer) [||]For newIndex = 0 To list.Count - 1 \' type the character '\' at the end of this line to invoke exception Next End Sub End Class") End Function End Class End Namespace
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/CSharp/Portable/Declarations/SingleTypeDeclaration.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class SingleTypeDeclaration : SingleNamespaceOrTypeDeclaration { private readonly DeclarationKind _kind; private readonly TypeDeclarationFlags _flags; private readonly ushort _arity; private readonly DeclarationModifiers _modifiers; private readonly ImmutableArray<SingleTypeDeclaration> _children; [Flags] internal enum TypeDeclarationFlags : ushort { None = 0, AnyMemberHasExtensionMethodSyntax = 1 << 1, HasAnyAttributes = 1 << 2, HasBaseDeclarations = 1 << 3, AnyMemberHasAttributes = 1 << 4, HasAnyNontypeMembers = 1 << 5, /// <summary> /// Simple program uses await expressions. Set only in conjunction with <see cref="TypeDeclarationFlags.IsSimpleProgram"/> /// </summary> HasAwaitExpressions = 1 << 6, /// <summary> /// Set only in conjunction with <see cref="TypeDeclarationFlags.IsSimpleProgram"/> /// </summary> IsIterator = 1 << 7, /// <summary> /// Set only in conjunction with <see cref="TypeDeclarationFlags.IsSimpleProgram"/> /// </summary> HasReturnWithExpression = 1 << 8, IsSimpleProgram = 1 << 9, } internal SingleTypeDeclaration( DeclarationKind kind, string name, int arity, DeclarationModifiers modifiers, TypeDeclarationFlags declFlags, SyntaxReference syntaxReference, SourceLocation nameLocation, ImmutableSegmentedDictionary<string, VoidResult> memberNames, ImmutableArray<SingleTypeDeclaration> children, ImmutableArray<Diagnostic> diagnostics) : base(name, syntaxReference, nameLocation, diagnostics) { Debug.Assert(kind != DeclarationKind.Namespace); _kind = kind; _arity = (ushort)arity; _modifiers = modifiers; MemberNames = memberNames; _children = children; _flags = declFlags; } public override DeclarationKind Kind { get { return _kind; } } public new ImmutableArray<SingleTypeDeclaration> Children { get { return _children; } } public int Arity { get { return _arity; } } public DeclarationModifiers Modifiers { get { return _modifiers; } } public ImmutableSegmentedDictionary<string, VoidResult> MemberNames { get; } public bool AnyMemberHasExtensionMethodSyntax { get { return (_flags & TypeDeclarationFlags.AnyMemberHasExtensionMethodSyntax) != 0; } } public bool HasAnyAttributes { get { return (_flags & TypeDeclarationFlags.HasAnyAttributes) != 0; } } public bool HasBaseDeclarations { get { return (_flags & TypeDeclarationFlags.HasBaseDeclarations) != 0; } } public bool AnyMemberHasAttributes { get { return (_flags & TypeDeclarationFlags.AnyMemberHasAttributes) != 0; } } public bool HasAnyNontypeMembers { get { return (_flags & TypeDeclarationFlags.HasAnyNontypeMembers) != 0; } } public bool HasAwaitExpressions { get { return (_flags & TypeDeclarationFlags.HasAwaitExpressions) != 0; } } public bool HasReturnWithExpression { get { return (_flags & TypeDeclarationFlags.HasReturnWithExpression) != 0; } } public bool IsIterator { get { return (_flags & TypeDeclarationFlags.IsIterator) != 0; } } public bool IsSimpleProgram { get { return (_flags & TypeDeclarationFlags.IsSimpleProgram) != 0; } } protected override ImmutableArray<SingleNamespaceOrTypeDeclaration> GetNamespaceOrTypeDeclarationChildren() { return StaticCast<SingleNamespaceOrTypeDeclaration>.From(_children); } internal TypeDeclarationIdentity Identity { get { return new TypeDeclarationIdentity(this); } } // identity that is used when collecting all declarations // of same type across multiple containers internal struct TypeDeclarationIdentity : IEquatable<TypeDeclarationIdentity> { private readonly SingleTypeDeclaration _decl; internal TypeDeclarationIdentity(SingleTypeDeclaration decl) { _decl = decl; } public override bool Equals(object obj) { return obj is TypeDeclarationIdentity && Equals((TypeDeclarationIdentity)obj); } public bool Equals(TypeDeclarationIdentity other) { var thisDecl = _decl; var otherDecl = other._decl; // same as itself if ((object)thisDecl == otherDecl) { return true; } // arity, kind, name must match if ((thisDecl._arity != otherDecl._arity) || (thisDecl._kind != otherDecl._kind) || (thisDecl.name != otherDecl.name)) { return false; } if (thisDecl._kind == DeclarationKind.Enum || thisDecl._kind == DeclarationKind.Delegate) { // oh, so close, but enums and delegates cannot be partial return false; } return true; } public override int GetHashCode() { var thisDecl = _decl; return Hash.Combine(thisDecl.Name.GetHashCode(), Hash.Combine(thisDecl.Arity.GetHashCode(), (int)thisDecl.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. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class SingleTypeDeclaration : SingleNamespaceOrTypeDeclaration { private readonly DeclarationKind _kind; private readonly TypeDeclarationFlags _flags; private readonly ushort _arity; private readonly DeclarationModifiers _modifiers; private readonly ImmutableArray<SingleTypeDeclaration> _children; [Flags] internal enum TypeDeclarationFlags : ushort { None = 0, AnyMemberHasExtensionMethodSyntax = 1 << 1, HasAnyAttributes = 1 << 2, HasBaseDeclarations = 1 << 3, AnyMemberHasAttributes = 1 << 4, HasAnyNontypeMembers = 1 << 5, /// <summary> /// Simple program uses await expressions. Set only in conjunction with <see cref="TypeDeclarationFlags.IsSimpleProgram"/> /// </summary> HasAwaitExpressions = 1 << 6, /// <summary> /// Set only in conjunction with <see cref="TypeDeclarationFlags.IsSimpleProgram"/> /// </summary> IsIterator = 1 << 7, /// <summary> /// Set only in conjunction with <see cref="TypeDeclarationFlags.IsSimpleProgram"/> /// </summary> HasReturnWithExpression = 1 << 8, IsSimpleProgram = 1 << 9, } internal SingleTypeDeclaration( DeclarationKind kind, string name, int arity, DeclarationModifiers modifiers, TypeDeclarationFlags declFlags, SyntaxReference syntaxReference, SourceLocation nameLocation, ImmutableSegmentedDictionary<string, VoidResult> memberNames, ImmutableArray<SingleTypeDeclaration> children, ImmutableArray<Diagnostic> diagnostics) : base(name, syntaxReference, nameLocation, diagnostics) { Debug.Assert(kind != DeclarationKind.Namespace); _kind = kind; _arity = (ushort)arity; _modifiers = modifiers; MemberNames = memberNames; _children = children; _flags = declFlags; } public override DeclarationKind Kind { get { return _kind; } } public new ImmutableArray<SingleTypeDeclaration> Children { get { return _children; } } public int Arity { get { return _arity; } } public DeclarationModifiers Modifiers { get { return _modifiers; } } public ImmutableSegmentedDictionary<string, VoidResult> MemberNames { get; } public bool AnyMemberHasExtensionMethodSyntax { get { return (_flags & TypeDeclarationFlags.AnyMemberHasExtensionMethodSyntax) != 0; } } public bool HasAnyAttributes { get { return (_flags & TypeDeclarationFlags.HasAnyAttributes) != 0; } } public bool HasBaseDeclarations { get { return (_flags & TypeDeclarationFlags.HasBaseDeclarations) != 0; } } public bool AnyMemberHasAttributes { get { return (_flags & TypeDeclarationFlags.AnyMemberHasAttributes) != 0; } } public bool HasAnyNontypeMembers { get { return (_flags & TypeDeclarationFlags.HasAnyNontypeMembers) != 0; } } public bool HasAwaitExpressions { get { return (_flags & TypeDeclarationFlags.HasAwaitExpressions) != 0; } } public bool HasReturnWithExpression { get { return (_flags & TypeDeclarationFlags.HasReturnWithExpression) != 0; } } public bool IsIterator { get { return (_flags & TypeDeclarationFlags.IsIterator) != 0; } } public bool IsSimpleProgram { get { return (_flags & TypeDeclarationFlags.IsSimpleProgram) != 0; } } protected override ImmutableArray<SingleNamespaceOrTypeDeclaration> GetNamespaceOrTypeDeclarationChildren() { return StaticCast<SingleNamespaceOrTypeDeclaration>.From(_children); } internal TypeDeclarationIdentity Identity { get { return new TypeDeclarationIdentity(this); } } // identity that is used when collecting all declarations // of same type across multiple containers internal struct TypeDeclarationIdentity : IEquatable<TypeDeclarationIdentity> { private readonly SingleTypeDeclaration _decl; internal TypeDeclarationIdentity(SingleTypeDeclaration decl) { _decl = decl; } public override bool Equals(object obj) { return obj is TypeDeclarationIdentity && Equals((TypeDeclarationIdentity)obj); } public bool Equals(TypeDeclarationIdentity other) { var thisDecl = _decl; var otherDecl = other._decl; // same as itself if ((object)thisDecl == otherDecl) { return true; } // arity, kind, name must match if ((thisDecl._arity != otherDecl._arity) || (thisDecl._kind != otherDecl._kind) || (thisDecl.name != otherDecl.name)) { return false; } if (thisDecl._kind == DeclarationKind.Enum || thisDecl._kind == DeclarationKind.Delegate) { // oh, so close, but enums and delegates cannot be partial return false; } return true; } public override int GetHashCode() { var thisDecl = _decl; return Hash.Combine(thisDecl.Name.GetHashCode(), Hash.Combine(thisDecl.Arity.GetHashCode(), (int)thisDecl.Kind)); } } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/VisualBasic/Test/Emit/PDB/PDBExternalSourceDirectiveTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB Public Class PDBExternalSourceDirectiveTests Inherits BasicTestBase <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> <WorkItem(50611, "https://github.com/dotnet/roslyn/issues/50611")> Public Sub TwoMethodsOnlyOneWithMapping() Dim source = <compilation> <file name="a.vb"> Option Strict On Option Infer Off Option Explicit Off Imports System Imports System.Collections.Generic Class C1 Public Shared Sub FooInvisible() dim str as string = "World!" Console.WriteLine("Hello " &amp; str) End Sub Public Shared Sub Main() Console.WriteLine("Hello World") #ExternalSource("C:\abc\def.vb", 23) Console.WriteLine("Hello World") #End ExternalSource Console.WriteLine("Hello World") End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) ' Care about the fact that there is no file reference to a.vb ' Care about the fact that C1.FooInvisible doesn't include any sequence points compilation.VerifyPdb( <symbols> <files> <file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="70-82-DD-9A-57-B3-BE-57-7E-E8-B4-AE-B8-1E-1B-75-38-9D-13-C9"/> <file id="2" name="C:\abc\def.vb" language="VB"/> </files> <entryPoint declaringType="C1" methodName="Main"/> <methods> <method containingType="C1" name="FooInvisible"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> </method> <method containingType="C1" name="Main"> <sequencePoints> <entry offset="0x0" hidden="true" document="2"/> <entry offset="0x1" hidden="true" document="2"/> <entry offset="0xc" startLine="23" startColumn="9" endLine="23" endColumn="41" document="2"/> <entry offset="0x17" hidden="true" document="2"/> <entry offset="0x22" hidden="true" document="2"/> </sequencePoints> </method> </methods> </symbols>, format:=DebugInformationFormat.PortablePdb) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> <WorkItem(50611, "https://github.com/dotnet/roslyn/issues/50611")> Public Sub TwoMethodsOnlyOneWithMultipleMappingsAndRewriting() Dim source = <compilation> <file name="a.vb"> Option Strict On Option Infer Off Option Explicit Off Imports System Imports System.Collections.Generic Class C1 Public Shared Sub FooInvisible() dim str as string = "World!" Console.WriteLine("Hello " &amp; str) End Sub Public Shared Sub Main() Console.WriteLine("Hello World") #ExternalSource("C:\abc\def.vb", 23) Console.WriteLine("Hello World") Console.WriteLine("Hello World") #End ExternalSource #ExternalSource("C:\abc\def2.vb", 42) ' check that there are normal and hidden sequence points with mapping present ' because a for each will be rewritten for each i in new Integer() {1, 2, 3} Console.WriteLine(i) next i #End ExternalSource Console.WriteLine("Hello World") ' hidden sequence points of rewritten statements will survive *iiks*. for each i in new Integer() {1, 2, 3} Console.WriteLine(i) next i End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) ' Care about the fact that C1.FooInvisible doesn't include any sequence points ' Care about the fact that there is no file reference to a.vb compilation.VerifyPdb( <symbols> <files> <file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="DB-A9-94-EF-BC-DF-10-C9-60-0F-C0-C4-9F-E4-77-F9-37-CF-E1-CE"/> <file id="2" name="C:\abc\def.vb" language="VB"/> <file id="3" name="C:\abc\def2.vb" language="VB"/> </files> <entryPoint declaringType="C1" methodName="Main"/> <methods> <method containingType="C1" name="FooInvisible"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> </method> <method containingType="C1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="372"/> <slot kind="6" offset="363"/> <slot kind="8" offset="363"/> <slot kind="1" offset="363"/> <slot kind="6" offset="606"/> <slot kind="8" offset="606"/> <slot kind="1" offset="606"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" hidden="true" document="2"/> <entry offset="0x1" hidden="true" document="2"/> <entry offset="0xc" startLine="23" startColumn="9" endLine="23" endColumn="41" document="2"/> <entry offset="0x17" startLine="24" startColumn="9" endLine="24" endColumn="41" document="2"/> <entry offset="0x22" startLine="44" startColumn="9" endLine="44" endColumn="46" document="3"/> <entry offset="0x36" hidden="true" document="3"/> <entry offset="0x41" startLine="45" startColumn="13" endLine="45" endColumn="33" document="3"/> <entry offset="0x4d" startLine="46" startColumn="9" endLine="46" endColumn="15" document="3"/> <entry offset="0x4e" hidden="true" document="3"/> <entry offset="0x52" hidden="true" document="3"/> <entry offset="0x59" hidden="true" document="3"/> <entry offset="0x5c" hidden="true" document="3"/> <entry offset="0x67" hidden="true" document="3"/> <entry offset="0x7d" hidden="true" document="3"/> <entry offset="0x8a" hidden="true" document="3"/> <entry offset="0x96" hidden="true" document="3"/> <entry offset="0x97" hidden="true" document="3"/> <entry offset="0x9d" hidden="true" document="3"/> <entry offset="0xa7" hidden="true" document="3"/> <entry offset="0xab" hidden="true" document="3"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xac"> <local name="i" il_index="0" il_start="0x0" il_end="0xac" attributes="0"/> </scope> </method> </methods> </symbols>, format:=DebugInformationFormat.PortablePdb) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub EmptyExternalSourceWillBeIgnored() Dim source = <compilation> <file name="a.vb"> Option Strict On Option Infer Off Option Explicit Off Imports System Imports System.Collections.Generic Class C1 Public Shared Sub FooInvisible() dim str as string = "World!" Console.WriteLine("Hello " &amp; str) End Sub Public Shared Sub Main() Console.WriteLine("Hello World") #ExternalSource("C:\abc\def.vb", 23) #End ExternalSource Console.WriteLine("Hello World") End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb( <symbols> <files> <file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="EE-47-B3-F6-59-FA-0D-E8-DF-B2-26-6A-7D-82-D3-52-3E-0C-36-E1"/> </files> <entryPoint declaringType="C1" methodName="Main"/> <methods> <method containingType="C1" name="FooInvisible"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="9" startColumn="5" endLine="9" endColumn="37" document="1"/> <entry offset="0x1" startLine="10" startColumn="13" endLine="10" endColumn="37" document="1"/> <entry offset="0x7" startLine="11" startColumn="9" endLine="11" endColumn="42" document="1"/> <entry offset="0x18" startLine="12" startColumn="5" endLine="12" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x19"> <namespace name="System" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <currentnamespace name=""/> <local name="str" il_index="0" il_start="0x0" il_end="0x19" attributes="0"/> </scope> </method> <method containingType="C1" name="Main"> <sequencePoints> <entry offset="0x0" startLine="14" startColumn="5" endLine="14" endColumn="29" document="1"/> <entry offset="0x1" startLine="15" startColumn="9" endLine="15" endColumn="41" document="1"/> <entry offset="0xc" startLine="20" startColumn="9" endLine="20" endColumn="41" document="1"/> <entry offset="0x17" startLine="21" startColumn="5" endLine="21" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x18"> <importsforward declaringType="C1" methodName="FooInvisible"/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub MultipleEmptyExternalSourceWillBeIgnored() Dim source = <compilation> <file name="a.vb"> Option Strict On Option Infer Off Option Explicit Off Imports System Imports System.Collections.Generic Class C1 Public Shared Sub FooInvisible() dim str as string = "World!" Console.WriteLine("Hello " &amp; str) End Sub Public Shared Sub Main() #ExternalSource("C:\abc\def.vb", 21) #End ExternalSource Console.WriteLine("Hello World") #ExternalSource("C:\abc\def.vb", 22) #End ExternalSource Console.WriteLine("Hello World") #ExternalSource("C:\abc\def.vb", 23) #End ExternalSource End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb( <symbols> <files> <file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="B9-85-76-74-1E-E7-27-25-F7-8A-CB-A2-B1-9C-A4-CD-FD-49-8C-B7"/> </files> <entryPoint declaringType="C1" methodName="Main"/> <methods> <method containingType="C1" name="FooInvisible"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="9" startColumn="5" endLine="9" endColumn="37" document="1"/> <entry offset="0x1" startLine="10" startColumn="13" endLine="10" endColumn="37" document="1"/> <entry offset="0x7" startLine="11" startColumn="9" endLine="11" endColumn="42" document="1"/> <entry offset="0x18" startLine="12" startColumn="5" endLine="12" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x19"> <namespace name="System" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <currentnamespace name=""/> <local name="str" il_index="0" il_start="0x0" il_end="0x19" attributes="0"/> </scope> </method> <method containingType="C1" name="Main"> <sequencePoints> <entry offset="0x0" startLine="14" startColumn="5" endLine="14" endColumn="29" document="1"/> <entry offset="0x1" startLine="18" startColumn="9" endLine="18" endColumn="41" document="1"/> <entry offset="0xc" startLine="23" startColumn="9" endLine="23" endColumn="41" document="1"/> <entry offset="0x17" startLine="27" startColumn="5" endLine="27" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x18"> <importsforward declaringType="C1" methodName="FooInvisible"/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub MultipleEmptyExternalSourceWithNonEmptyExternalSource() Dim source = <compilation> <file name="a.vb"> Option Strict On Option Infer Off Option Explicit Off Imports System Imports System.Collections.Generic Class C1 Public Shared Sub FooInvisible() dim str as string = "World!" Console.WriteLine("Hello " &amp; str) End Sub Public Shared Sub Main() #ExternalSource("C:\abc\def.vb", 21) #End ExternalSource Console.WriteLine("Hello World") #ExternalSource("C:\abc\def.vb", 22) #End ExternalSource Console.WriteLine("Hello World") #ExternalSource("C:\abc\def.vb", 23) ' boo! #End ExternalSource End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) ' Care about the fact that there are no sequence points or referenced files compilation.VerifyPdb( <symbols> <files> <file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="B6-80-9E-65-43-38-00-C1-35-7F-AE-D0-60-F2-24-44-A8-11-C2-63"/> </files> <entryPoint declaringType="C1" methodName="Main"/> <methods> <method containingType="C1" name="FooInvisible"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> </method> <method containingType="C1" name="Main" format="windows"> <scope startOffset="0x0" endOffset="0x18"> <namespace name="System" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <currentnamespace name=""/> </scope> </method> </methods> </symbols>, ' Since the CDI is not emitted to Portable PDB it won't be present in the converted Windows PDB. options:=PdbValidationOptions.SkipConversionValidation) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub MultipleEmptyExternalSourceWithNonEmptyExternalSourceFollowedByEmptyExternalSource() Dim source = <compilation> <file name="a.vb"> Option Strict On Option Infer Off Option Explicit Off Imports System Imports System.Collections.Generic Class C1 Public Shared Sub FooInvisible() dim str as string = "World!" Console.WriteLine("Hello " &amp; str) End Sub Public Shared Sub Main() #ExternalSource("C:\abc\def.vb", 21) #End ExternalSource Console.WriteLine("Hello World") #ExternalSource("C:\abc\def.vb", 22) #End ExternalSource Console.WriteLine("Hello World") #ExternalSource("C:\abc\def.vb", 23) #End ExternalSource Console.WriteLine("Hello World") End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) ' Care about the fact that C1.FooInvisible and C1.Main include no sequence points ' Care about the fact that no files are referenced compilation.VerifyPdb( <symbols> <files> <file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="73-05-84-40-AC-E0-15-63-CC-FE-BD-9A-99-23-AA-BD-24-40-24-44"/> </files> <entryPoint declaringType="C1" methodName="Main"/> <methods> <method containingType="C1" name="FooInvisible"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> </method> <method containingType="C1" name="Main" format="windows"> <scope startOffset="0x0" endOffset="0x23"> <namespace name="System" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <currentnamespace name=""/> </scope> </method> </methods> </symbols>, options:=PdbValidationOptions.SkipConversionValidation) ' When converting from Portable to Windows the PDB writer doesn't create an entry for the Main method ' and thus there Is no entry point record either. End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> <WorkItem(50611, "https://github.com/dotnet/roslyn/issues/50611")> Public Sub TestPartialClassFieldInitializersWithExternalSource() Dim source = <compilation> <file name="C:\Abc\ACTUAL.vb"> #ExternalSource("C:\abc\def1.vb", 41) Option strict on imports system partial Class C1 public f1 as integer = 23 #End ExternalSource #ExternalSource("C:\abc\def1.vb", 10) Public sub DumpFields() Console.WriteLine(f1) Console.WriteLine(f2) End Sub #End ExternalSource #ExternalSource("C:\abc\def1.vb", 1) Public shared Sub Main(args() as string) Dim c as new C1 c.DumpFields() End sub #End ExternalSource End Class Class InActual public f1 as integer = 23 end Class #ExternalChecksum("C:\abc\def2.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "1234") #ExternalChecksum("BOGUS.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "1234") #ExternalChecksum("C:\Abc\ACTUAL.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "6789") </file> <file name="b.vb"> Option strict on imports system partial Class C1 #ExternalSource("C:\abc\def2.vb", 23) ' more lines to see a different span in the sequence points ... public f2 as integer = 42 #End ExternalSource #ExternalChecksum("BOGUS.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "1234") #ExternalChecksum("C:\Abc\ACTUAL.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "6789") End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) ' Care about the fact that InActual.ctor includes no sequence points ' Care about the fact that there is no file reference to ACTUAL.vb compilation.VerifyPdb( <symbols> <files> <file id="1" name="C:\Abc\ACTUAL.vb" language="VB" checksumAlgorithm="SHA1" checksum="27-52-E9-85-5A-AC-31-05-A5-6F-70-40-55-3A-9C-43-D2-07-0D-4B"/> <file id="2" name="b.vb" language="VB" checksumAlgorithm="SHA1" checksum="7F-D8-35-3F-B4-08-17-37-3E-37-30-26-2A-3F-0C-20-6F-48-2A-7A"/> <file id="3" name="C:\abc\def1.vb" language="VB"/> <file id="4" name="C:\abc\def2.vb" language="VB" checksumAlgorithm="406ea660-64cf-4c82-b6f0-42d48172a799" checksum="12-34"/> <file id="5" name="BOGUS.vb" language="VB" checksumAlgorithm="406ea660-64cf-4c82-b6f0-42d48172a799" checksum="12-34"/> </files> <entryPoint declaringType="C1" methodName="Main" parameterNames="args"/> <methods> <method containingType="C1" name=".ctor"> <sequencePoints> <entry offset="0x0" hidden="true" document="3"/> <entry offset="0x7" startLine="46" startColumn="12" endLine="46" endColumn="30" document="3"/> <entry offset="0xf" startLine="27" startColumn="36" endLine="27" endColumn="54" document="4"/> </sequencePoints> </method> <method containingType="C1" name="DumpFields"> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="28" document="3"/> <entry offset="0x1" startLine="11" startColumn="9" endLine="11" endColumn="30" document="3"/> <entry offset="0xd" startLine="12" startColumn="9" endLine="12" endColumn="30" document="3"/> <entry offset="0x19" startLine="13" startColumn="5" endLine="13" endColumn="12" document="3"/> </sequencePoints> </method> <method containingType="C1" name="Main" parameterNames="args"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="1" startColumn="5" endLine="1" endColumn="45" document="3"/> <entry offset="0x1" startLine="2" startColumn="13" endLine="2" endColumn="24" document="3"/> <entry offset="0x7" startLine="3" startColumn="9" endLine="3" endColumn="23" document="3"/> <entry offset="0xe" startLine="4" startColumn="5" endLine="4" endColumn="12" document="3"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xf"> <local name="c" il_index="0" il_start="0x0" il_end="0xf" attributes="0"/> </scope> </method> </methods> </symbols>, format:=DebugInformationFormat.PortablePdb) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub IllegalExternalSourceUsageShouldNotAssert_1() Dim source = <compilation> <file name="a.vb"> Option strict on public Class C1 #ExternalSource("bar1.vb", 41) #ExternalSource("bar1.vb", 41) public shared sub main() End sub #End ExternalSource #End ExternalSource boo End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.ReleaseExe).VerifyDiagnostics(Diagnostic(ERRID.ERR_NestedExternalSource, "#ExternalSource(""bar1.vb"", 41)"), Diagnostic(ERRID.ERR_EndExternalSource, "#End ExternalSource")) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub IllegalExternalSourceUsageShouldNotAssert_2() Dim source = <compilation> <file name="a.vb"> Option strict on public Class C1 #End ExternalSource #End ExternalSource public shared sub main() End sub boo End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.ReleaseExe).VerifyDiagnostics(Diagnostic(ERRID.ERR_EndExternalSource, "#End ExternalSource"), Diagnostic(ERRID.ERR_EndExternalSource, "#End ExternalSource"), Diagnostic(ERRID.ERR_ExpectedDeclaration, "boo")) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub IllegalExternalSourceUsageShouldNotAssert_3() Dim source = <compilation> <file name="a.vb"> Option strict on public Class C1 #End ExternalSource #ExternalSource("bar1.vb", 23) public shared sub main() End sub boo End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.ReleaseExe).VerifyDiagnostics(Diagnostic(ERRID.ERR_EndExternalSource, "#End ExternalSource"), Diagnostic(ERRID.ERR_ExpectedEndExternalSource, "#ExternalSource(""bar1.vb"", 23)"), Diagnostic(ERRID.ERR_ExpectedDeclaration, "boo")) End Sub <WorkItem(545302, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545302")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub IllegalExternalSourceUsageShouldNotAssert_4() Dim source = <compilation> <file name="a.vb"> Module Program Sub Main() #ExternalSource ("bar1.vb", 23) #ExternalSource ("bar1.vb", 23) System.Console.WriteLine("boo") #End ExternalSource End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.ReleaseExe).VerifyDiagnostics(Diagnostic(ERRID.ERR_NestedExternalSource, "#ExternalSource (""bar1.vb"", 23)")) End Sub <WorkItem(545307, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545307")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub OverflowLineNumbers() Dim source = <compilation> <file name="a.vb"> Option Strict On Imports System Imports System.Collections.Generic Module Program Public Sub Main() Console.WriteLine("Hello World") #ExternalSource("C:\abc\def.vb", 0) Console.WriteLine("Hello World") #End ExternalSource #ExternalSource("C:\abc\def.vb", 1) Console.WriteLine("Hello World") #End ExternalSource #ExternalSource("C:\abc\def.vb", 2147483647) Console.WriteLine("Hello World") #End ExternalSource #ExternalSource("C:\abc\def.vb", 2147483648) Console.WriteLine("Hello World") #End ExternalSource #ExternalSource("C:\abc\def.vb", 2147483649) Console.WriteLine("Hello World") #End ExternalSource #ExternalSource("C:\abc\def.vb", &amp;hfeefed) Console.WriteLine("Hello World") #End ExternalSource Console.WriteLine("Hello World") End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) ' Care about the fact that there is no document reference to a.vb compilation.VerifyPdb( <symbols> <files> <file id="1" name="C:\abc\def.vb" language="VB"/> <file id="2" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="D2-FF-05-F8-B7-A2-25-B0-96-D9-97-2F-05-F8-F0-B5-81-8D-98-1D"/> </files> <entryPoint declaringType="Program" methodName="Main"/> <methods> <method containingType="Program" name="Main"> <sequencePoints> <entry offset="0x0" hidden="true" document="1"/> <entry offset="0x1" hidden="true" document="1"/> <entry offset="0xc" startLine="0" startColumn="9" endLine="0" endColumn="41" document="1"/> <entry offset="0x17" startLine="1" startColumn="9" endLine="1" endColumn="41" document="1"/> <entry offset="0x22" startLine="16777215" startColumn="9" endLine="16777215" endColumn="41" document="1"/> <entry offset="0x2d" startLine="16777215" startColumn="9" endLine="16777215" endColumn="41" document="1"/> <entry offset="0x38" startLine="16777215" startColumn="9" endLine="16777215" endColumn="41" document="1"/> <entry offset="0x43" startLine="16707565" startColumn="9" endLine="16707565" endColumn="41" document="1"/> <entry offset="0x4e" hidden="true" document="1"/> <entry offset="0x59" hidden="true" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x5a"> <namespace name="System" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <currentnamespace name=""/> </scope> </method> </methods> </symbols>, format:=DebugInformationFormat.Pdb) End Sub <WorkItem(846584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/846584")> <WorkItem(50611, "https://github.com/dotnet/roslyn/issues/50611")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub RelativePathForExternalSource() Dim source = <compilation> <file name="C:\Folder1\Folder2\Test1.vb"> #ExternalChecksum("..\Test2.vb","{406ea660-64cf-4c82-b6f0-42d48172a799}","DB788882721B2B27C90579D5FE2A0418") Class Test1 Sub Main() #ExternalSource("..\Test2.vb",4) Main() #End ExternalSource End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.DebugDll.WithSourceReferenceResolver(SourceFileResolver.Default)) ' Care about the fact that there is no document reference to C:\Folder1\Folder2\Test1.vb compilation.VerifyPdb( <symbols> <files> <file id="1" name="C:\Folder1\Folder2\Test1.vb" language="VB" checksumAlgorithm="SHA1" checksum="B9-49-3D-62-89-9B-B2-2F-B6-72-90-A1-2D-01-11-89-B4-C2-83-B4"/> <file id="2" name="C:\Folder1\Test2.vb" language="VB" checksumAlgorithm="406ea660-64cf-4c82-b6f0-42d48172a799" checksum="DB-78-88-82-72-1B-2B-27-C9-05-79-D5-FE-2A-04-18"/> </files> <methods> <method containingType="Test1" name="Main"> <sequencePoints> <entry offset="0x0" hidden="true" document="2"/> <entry offset="0x1" startLine="4" startColumn="2" endLine="4" endColumn="8" document="2"/> <entry offset="0x8" hidden="true" document="2"/> </sequencePoints> </method> </methods> </symbols>, format:=DebugInformationFormat.PortablePdb) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB Public Class PDBExternalSourceDirectiveTests Inherits BasicTestBase <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> <WorkItem(50611, "https://github.com/dotnet/roslyn/issues/50611")> Public Sub TwoMethodsOnlyOneWithMapping() Dim source = <compilation> <file name="a.vb"> Option Strict On Option Infer Off Option Explicit Off Imports System Imports System.Collections.Generic Class C1 Public Shared Sub FooInvisible() dim str as string = "World!" Console.WriteLine("Hello " &amp; str) End Sub Public Shared Sub Main() Console.WriteLine("Hello World") #ExternalSource("C:\abc\def.vb", 23) Console.WriteLine("Hello World") #End ExternalSource Console.WriteLine("Hello World") End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) ' Care about the fact that there is no file reference to a.vb ' Care about the fact that C1.FooInvisible doesn't include any sequence points compilation.VerifyPdb( <symbols> <files> <file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="70-82-DD-9A-57-B3-BE-57-7E-E8-B4-AE-B8-1E-1B-75-38-9D-13-C9"/> <file id="2" name="C:\abc\def.vb" language="VB"/> </files> <entryPoint declaringType="C1" methodName="Main"/> <methods> <method containingType="C1" name="FooInvisible"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> </method> <method containingType="C1" name="Main"> <sequencePoints> <entry offset="0x0" hidden="true" document="2"/> <entry offset="0x1" hidden="true" document="2"/> <entry offset="0xc" startLine="23" startColumn="9" endLine="23" endColumn="41" document="2"/> <entry offset="0x17" hidden="true" document="2"/> <entry offset="0x22" hidden="true" document="2"/> </sequencePoints> </method> </methods> </symbols>, format:=DebugInformationFormat.PortablePdb) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> <WorkItem(50611, "https://github.com/dotnet/roslyn/issues/50611")> Public Sub TwoMethodsOnlyOneWithMultipleMappingsAndRewriting() Dim source = <compilation> <file name="a.vb"> Option Strict On Option Infer Off Option Explicit Off Imports System Imports System.Collections.Generic Class C1 Public Shared Sub FooInvisible() dim str as string = "World!" Console.WriteLine("Hello " &amp; str) End Sub Public Shared Sub Main() Console.WriteLine("Hello World") #ExternalSource("C:\abc\def.vb", 23) Console.WriteLine("Hello World") Console.WriteLine("Hello World") #End ExternalSource #ExternalSource("C:\abc\def2.vb", 42) ' check that there are normal and hidden sequence points with mapping present ' because a for each will be rewritten for each i in new Integer() {1, 2, 3} Console.WriteLine(i) next i #End ExternalSource Console.WriteLine("Hello World") ' hidden sequence points of rewritten statements will survive *iiks*. for each i in new Integer() {1, 2, 3} Console.WriteLine(i) next i End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) ' Care about the fact that C1.FooInvisible doesn't include any sequence points ' Care about the fact that there is no file reference to a.vb compilation.VerifyPdb( <symbols> <files> <file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="DB-A9-94-EF-BC-DF-10-C9-60-0F-C0-C4-9F-E4-77-F9-37-CF-E1-CE"/> <file id="2" name="C:\abc\def.vb" language="VB"/> <file id="3" name="C:\abc\def2.vb" language="VB"/> </files> <entryPoint declaringType="C1" methodName="Main"/> <methods> <method containingType="C1" name="FooInvisible"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> </method> <method containingType="C1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="372"/> <slot kind="6" offset="363"/> <slot kind="8" offset="363"/> <slot kind="1" offset="363"/> <slot kind="6" offset="606"/> <slot kind="8" offset="606"/> <slot kind="1" offset="606"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" hidden="true" document="2"/> <entry offset="0x1" hidden="true" document="2"/> <entry offset="0xc" startLine="23" startColumn="9" endLine="23" endColumn="41" document="2"/> <entry offset="0x17" startLine="24" startColumn="9" endLine="24" endColumn="41" document="2"/> <entry offset="0x22" startLine="44" startColumn="9" endLine="44" endColumn="46" document="3"/> <entry offset="0x36" hidden="true" document="3"/> <entry offset="0x41" startLine="45" startColumn="13" endLine="45" endColumn="33" document="3"/> <entry offset="0x4d" startLine="46" startColumn="9" endLine="46" endColumn="15" document="3"/> <entry offset="0x4e" hidden="true" document="3"/> <entry offset="0x52" hidden="true" document="3"/> <entry offset="0x59" hidden="true" document="3"/> <entry offset="0x5c" hidden="true" document="3"/> <entry offset="0x67" hidden="true" document="3"/> <entry offset="0x7d" hidden="true" document="3"/> <entry offset="0x8a" hidden="true" document="3"/> <entry offset="0x96" hidden="true" document="3"/> <entry offset="0x97" hidden="true" document="3"/> <entry offset="0x9d" hidden="true" document="3"/> <entry offset="0xa7" hidden="true" document="3"/> <entry offset="0xab" hidden="true" document="3"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xac"> <local name="i" il_index="0" il_start="0x0" il_end="0xac" attributes="0"/> </scope> </method> </methods> </symbols>, format:=DebugInformationFormat.PortablePdb) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub EmptyExternalSourceWillBeIgnored() Dim source = <compilation> <file name="a.vb"> Option Strict On Option Infer Off Option Explicit Off Imports System Imports System.Collections.Generic Class C1 Public Shared Sub FooInvisible() dim str as string = "World!" Console.WriteLine("Hello " &amp; str) End Sub Public Shared Sub Main() Console.WriteLine("Hello World") #ExternalSource("C:\abc\def.vb", 23) #End ExternalSource Console.WriteLine("Hello World") End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb( <symbols> <files> <file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="EE-47-B3-F6-59-FA-0D-E8-DF-B2-26-6A-7D-82-D3-52-3E-0C-36-E1"/> </files> <entryPoint declaringType="C1" methodName="Main"/> <methods> <method containingType="C1" name="FooInvisible"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="9" startColumn="5" endLine="9" endColumn="37" document="1"/> <entry offset="0x1" startLine="10" startColumn="13" endLine="10" endColumn="37" document="1"/> <entry offset="0x7" startLine="11" startColumn="9" endLine="11" endColumn="42" document="1"/> <entry offset="0x18" startLine="12" startColumn="5" endLine="12" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x19"> <namespace name="System" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <currentnamespace name=""/> <local name="str" il_index="0" il_start="0x0" il_end="0x19" attributes="0"/> </scope> </method> <method containingType="C1" name="Main"> <sequencePoints> <entry offset="0x0" startLine="14" startColumn="5" endLine="14" endColumn="29" document="1"/> <entry offset="0x1" startLine="15" startColumn="9" endLine="15" endColumn="41" document="1"/> <entry offset="0xc" startLine="20" startColumn="9" endLine="20" endColumn="41" document="1"/> <entry offset="0x17" startLine="21" startColumn="5" endLine="21" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x18"> <importsforward declaringType="C1" methodName="FooInvisible"/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub MultipleEmptyExternalSourceWillBeIgnored() Dim source = <compilation> <file name="a.vb"> Option Strict On Option Infer Off Option Explicit Off Imports System Imports System.Collections.Generic Class C1 Public Shared Sub FooInvisible() dim str as string = "World!" Console.WriteLine("Hello " &amp; str) End Sub Public Shared Sub Main() #ExternalSource("C:\abc\def.vb", 21) #End ExternalSource Console.WriteLine("Hello World") #ExternalSource("C:\abc\def.vb", 22) #End ExternalSource Console.WriteLine("Hello World") #ExternalSource("C:\abc\def.vb", 23) #End ExternalSource End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb( <symbols> <files> <file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="B9-85-76-74-1E-E7-27-25-F7-8A-CB-A2-B1-9C-A4-CD-FD-49-8C-B7"/> </files> <entryPoint declaringType="C1" methodName="Main"/> <methods> <method containingType="C1" name="FooInvisible"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="9" startColumn="5" endLine="9" endColumn="37" document="1"/> <entry offset="0x1" startLine="10" startColumn="13" endLine="10" endColumn="37" document="1"/> <entry offset="0x7" startLine="11" startColumn="9" endLine="11" endColumn="42" document="1"/> <entry offset="0x18" startLine="12" startColumn="5" endLine="12" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x19"> <namespace name="System" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <currentnamespace name=""/> <local name="str" il_index="0" il_start="0x0" il_end="0x19" attributes="0"/> </scope> </method> <method containingType="C1" name="Main"> <sequencePoints> <entry offset="0x0" startLine="14" startColumn="5" endLine="14" endColumn="29" document="1"/> <entry offset="0x1" startLine="18" startColumn="9" endLine="18" endColumn="41" document="1"/> <entry offset="0xc" startLine="23" startColumn="9" endLine="23" endColumn="41" document="1"/> <entry offset="0x17" startLine="27" startColumn="5" endLine="27" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x18"> <importsforward declaringType="C1" methodName="FooInvisible"/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub MultipleEmptyExternalSourceWithNonEmptyExternalSource() Dim source = <compilation> <file name="a.vb"> Option Strict On Option Infer Off Option Explicit Off Imports System Imports System.Collections.Generic Class C1 Public Shared Sub FooInvisible() dim str as string = "World!" Console.WriteLine("Hello " &amp; str) End Sub Public Shared Sub Main() #ExternalSource("C:\abc\def.vb", 21) #End ExternalSource Console.WriteLine("Hello World") #ExternalSource("C:\abc\def.vb", 22) #End ExternalSource Console.WriteLine("Hello World") #ExternalSource("C:\abc\def.vb", 23) ' boo! #End ExternalSource End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) ' Care about the fact that there are no sequence points or referenced files compilation.VerifyPdb( <symbols> <files> <file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="B6-80-9E-65-43-38-00-C1-35-7F-AE-D0-60-F2-24-44-A8-11-C2-63"/> </files> <entryPoint declaringType="C1" methodName="Main"/> <methods> <method containingType="C1" name="FooInvisible"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> </method> <method containingType="C1" name="Main" format="windows"> <scope startOffset="0x0" endOffset="0x18"> <namespace name="System" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <currentnamespace name=""/> </scope> </method> </methods> </symbols>, ' Since the CDI is not emitted to Portable PDB it won't be present in the converted Windows PDB. options:=PdbValidationOptions.SkipConversionValidation) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub MultipleEmptyExternalSourceWithNonEmptyExternalSourceFollowedByEmptyExternalSource() Dim source = <compilation> <file name="a.vb"> Option Strict On Option Infer Off Option Explicit Off Imports System Imports System.Collections.Generic Class C1 Public Shared Sub FooInvisible() dim str as string = "World!" Console.WriteLine("Hello " &amp; str) End Sub Public Shared Sub Main() #ExternalSource("C:\abc\def.vb", 21) #End ExternalSource Console.WriteLine("Hello World") #ExternalSource("C:\abc\def.vb", 22) #End ExternalSource Console.WriteLine("Hello World") #ExternalSource("C:\abc\def.vb", 23) #End ExternalSource Console.WriteLine("Hello World") End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) ' Care about the fact that C1.FooInvisible and C1.Main include no sequence points ' Care about the fact that no files are referenced compilation.VerifyPdb( <symbols> <files> <file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="73-05-84-40-AC-E0-15-63-CC-FE-BD-9A-99-23-AA-BD-24-40-24-44"/> </files> <entryPoint declaringType="C1" methodName="Main"/> <methods> <method containingType="C1" name="FooInvisible"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> </method> <method containingType="C1" name="Main" format="windows"> <scope startOffset="0x0" endOffset="0x23"> <namespace name="System" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <currentnamespace name=""/> </scope> </method> </methods> </symbols>, options:=PdbValidationOptions.SkipConversionValidation) ' When converting from Portable to Windows the PDB writer doesn't create an entry for the Main method ' and thus there Is no entry point record either. End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> <WorkItem(50611, "https://github.com/dotnet/roslyn/issues/50611")> Public Sub TestPartialClassFieldInitializersWithExternalSource() Dim source = <compilation> <file name="C:\Abc\ACTUAL.vb"> #ExternalSource("C:\abc\def1.vb", 41) Option strict on imports system partial Class C1 public f1 as integer = 23 #End ExternalSource #ExternalSource("C:\abc\def1.vb", 10) Public sub DumpFields() Console.WriteLine(f1) Console.WriteLine(f2) End Sub #End ExternalSource #ExternalSource("C:\abc\def1.vb", 1) Public shared Sub Main(args() as string) Dim c as new C1 c.DumpFields() End sub #End ExternalSource End Class Class InActual public f1 as integer = 23 end Class #ExternalChecksum("C:\abc\def2.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "1234") #ExternalChecksum("BOGUS.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "1234") #ExternalChecksum("C:\Abc\ACTUAL.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "6789") </file> <file name="b.vb"> Option strict on imports system partial Class C1 #ExternalSource("C:\abc\def2.vb", 23) ' more lines to see a different span in the sequence points ... public f2 as integer = 42 #End ExternalSource #ExternalChecksum("BOGUS.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "1234") #ExternalChecksum("C:\Abc\ACTUAL.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "6789") End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) ' Care about the fact that InActual.ctor includes no sequence points ' Care about the fact that there is no file reference to ACTUAL.vb compilation.VerifyPdb( <symbols> <files> <file id="1" name="C:\Abc\ACTUAL.vb" language="VB" checksumAlgorithm="SHA1" checksum="27-52-E9-85-5A-AC-31-05-A5-6F-70-40-55-3A-9C-43-D2-07-0D-4B"/> <file id="2" name="b.vb" language="VB" checksumAlgorithm="SHA1" checksum="7F-D8-35-3F-B4-08-17-37-3E-37-30-26-2A-3F-0C-20-6F-48-2A-7A"/> <file id="3" name="C:\abc\def1.vb" language="VB"/> <file id="4" name="C:\abc\def2.vb" language="VB" checksumAlgorithm="406ea660-64cf-4c82-b6f0-42d48172a799" checksum="12-34"/> <file id="5" name="BOGUS.vb" language="VB" checksumAlgorithm="406ea660-64cf-4c82-b6f0-42d48172a799" checksum="12-34"/> </files> <entryPoint declaringType="C1" methodName="Main" parameterNames="args"/> <methods> <method containingType="C1" name=".ctor"> <sequencePoints> <entry offset="0x0" hidden="true" document="3"/> <entry offset="0x7" startLine="46" startColumn="12" endLine="46" endColumn="30" document="3"/> <entry offset="0xf" startLine="27" startColumn="36" endLine="27" endColumn="54" document="4"/> </sequencePoints> </method> <method containingType="C1" name="DumpFields"> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="28" document="3"/> <entry offset="0x1" startLine="11" startColumn="9" endLine="11" endColumn="30" document="3"/> <entry offset="0xd" startLine="12" startColumn="9" endLine="12" endColumn="30" document="3"/> <entry offset="0x19" startLine="13" startColumn="5" endLine="13" endColumn="12" document="3"/> </sequencePoints> </method> <method containingType="C1" name="Main" parameterNames="args"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="4"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="1" startColumn="5" endLine="1" endColumn="45" document="3"/> <entry offset="0x1" startLine="2" startColumn="13" endLine="2" endColumn="24" document="3"/> <entry offset="0x7" startLine="3" startColumn="9" endLine="3" endColumn="23" document="3"/> <entry offset="0xe" startLine="4" startColumn="5" endLine="4" endColumn="12" document="3"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xf"> <local name="c" il_index="0" il_start="0x0" il_end="0xf" attributes="0"/> </scope> </method> </methods> </symbols>, format:=DebugInformationFormat.PortablePdb) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub IllegalExternalSourceUsageShouldNotAssert_1() Dim source = <compilation> <file name="a.vb"> Option strict on public Class C1 #ExternalSource("bar1.vb", 41) #ExternalSource("bar1.vb", 41) public shared sub main() End sub #End ExternalSource #End ExternalSource boo End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.ReleaseExe).VerifyDiagnostics(Diagnostic(ERRID.ERR_NestedExternalSource, "#ExternalSource(""bar1.vb"", 41)"), Diagnostic(ERRID.ERR_EndExternalSource, "#End ExternalSource")) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub IllegalExternalSourceUsageShouldNotAssert_2() Dim source = <compilation> <file name="a.vb"> Option strict on public Class C1 #End ExternalSource #End ExternalSource public shared sub main() End sub boo End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.ReleaseExe).VerifyDiagnostics(Diagnostic(ERRID.ERR_EndExternalSource, "#End ExternalSource"), Diagnostic(ERRID.ERR_EndExternalSource, "#End ExternalSource"), Diagnostic(ERRID.ERR_ExpectedDeclaration, "boo")) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub IllegalExternalSourceUsageShouldNotAssert_3() Dim source = <compilation> <file name="a.vb"> Option strict on public Class C1 #End ExternalSource #ExternalSource("bar1.vb", 23) public shared sub main() End sub boo End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.ReleaseExe).VerifyDiagnostics(Diagnostic(ERRID.ERR_EndExternalSource, "#End ExternalSource"), Diagnostic(ERRID.ERR_ExpectedEndExternalSource, "#ExternalSource(""bar1.vb"", 23)"), Diagnostic(ERRID.ERR_ExpectedDeclaration, "boo")) End Sub <WorkItem(545302, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545302")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub IllegalExternalSourceUsageShouldNotAssert_4() Dim source = <compilation> <file name="a.vb"> Module Program Sub Main() #ExternalSource ("bar1.vb", 23) #ExternalSource ("bar1.vb", 23) System.Console.WriteLine("boo") #End ExternalSource End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.ReleaseExe).VerifyDiagnostics(Diagnostic(ERRID.ERR_NestedExternalSource, "#ExternalSource (""bar1.vb"", 23)")) End Sub <WorkItem(545307, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545307")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub OverflowLineNumbers() Dim source = <compilation> <file name="a.vb"> Option Strict On Imports System Imports System.Collections.Generic Module Program Public Sub Main() Console.WriteLine("Hello World") #ExternalSource("C:\abc\def.vb", 0) Console.WriteLine("Hello World") #End ExternalSource #ExternalSource("C:\abc\def.vb", 1) Console.WriteLine("Hello World") #End ExternalSource #ExternalSource("C:\abc\def.vb", 2147483647) Console.WriteLine("Hello World") #End ExternalSource #ExternalSource("C:\abc\def.vb", 2147483648) Console.WriteLine("Hello World") #End ExternalSource #ExternalSource("C:\abc\def.vb", 2147483649) Console.WriteLine("Hello World") #End ExternalSource #ExternalSource("C:\abc\def.vb", &amp;hfeefed) Console.WriteLine("Hello World") #End ExternalSource Console.WriteLine("Hello World") End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) ' Care about the fact that there is no document reference to a.vb compilation.VerifyPdb( <symbols> <files> <file id="1" name="C:\abc\def.vb" language="VB"/> <file id="2" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="D2-FF-05-F8-B7-A2-25-B0-96-D9-97-2F-05-F8-F0-B5-81-8D-98-1D"/> </files> <entryPoint declaringType="Program" methodName="Main"/> <methods> <method containingType="Program" name="Main"> <sequencePoints> <entry offset="0x0" hidden="true" document="1"/> <entry offset="0x1" hidden="true" document="1"/> <entry offset="0xc" startLine="0" startColumn="9" endLine="0" endColumn="41" document="1"/> <entry offset="0x17" startLine="1" startColumn="9" endLine="1" endColumn="41" document="1"/> <entry offset="0x22" startLine="16777215" startColumn="9" endLine="16777215" endColumn="41" document="1"/> <entry offset="0x2d" startLine="16777215" startColumn="9" endLine="16777215" endColumn="41" document="1"/> <entry offset="0x38" startLine="16777215" startColumn="9" endLine="16777215" endColumn="41" document="1"/> <entry offset="0x43" startLine="16707565" startColumn="9" endLine="16707565" endColumn="41" document="1"/> <entry offset="0x4e" hidden="true" document="1"/> <entry offset="0x59" hidden="true" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x5a"> <namespace name="System" importlevel="file"/> <namespace name="System.Collections.Generic" importlevel="file"/> <currentnamespace name=""/> </scope> </method> </methods> </symbols>, format:=DebugInformationFormat.Pdb) End Sub <WorkItem(846584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/846584")> <WorkItem(50611, "https://github.com/dotnet/roslyn/issues/50611")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub RelativePathForExternalSource() Dim source = <compilation> <file name="C:\Folder1\Folder2\Test1.vb"> #ExternalChecksum("..\Test2.vb","{406ea660-64cf-4c82-b6f0-42d48172a799}","DB788882721B2B27C90579D5FE2A0418") Class Test1 Sub Main() #ExternalSource("..\Test2.vb",4) Main() #End ExternalSource End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( source, TestOptions.DebugDll.WithSourceReferenceResolver(SourceFileResolver.Default)) ' Care about the fact that there is no document reference to C:\Folder1\Folder2\Test1.vb compilation.VerifyPdb( <symbols> <files> <file id="1" name="C:\Folder1\Folder2\Test1.vb" language="VB" checksumAlgorithm="SHA1" checksum="B9-49-3D-62-89-9B-B2-2F-B6-72-90-A1-2D-01-11-89-B4-C2-83-B4"/> <file id="2" name="C:\Folder1\Test2.vb" language="VB" checksumAlgorithm="406ea660-64cf-4c82-b6f0-42d48172a799" checksum="DB-78-88-82-72-1B-2B-27-C9-05-79-D5-FE-2A-04-18"/> </files> <methods> <method containingType="Test1" name="Main"> <sequencePoints> <entry offset="0x0" hidden="true" document="2"/> <entry offset="0x1" startLine="4" startColumn="2" endLine="4" endColumn="8" document="2"/> <entry offset="0x8" hidden="true" document="2"/> </sequencePoints> </method> </methods> </symbols>, format:=DebugInformationFormat.PortablePdb) End Sub End Class End Namespace
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForLocalFunctionHelper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody { internal class UseExpressionBodyForLocalFunctionHelper : UseExpressionBodyHelper<LocalFunctionStatementSyntax> { public static readonly UseExpressionBodyForLocalFunctionHelper Instance = new(); private UseExpressionBodyForLocalFunctionHelper() : base(IDEDiagnosticIds.UseExpressionBodyForLocalFunctionsDiagnosticId, EnforceOnBuildValues.UseExpressionBodyForLocalFunctions, new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_expression_body_for_local_functions), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)), new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_block_body_for_local_functions), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)), CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, ImmutableArray.Create(SyntaxKind.LocalFunctionStatement)) { } protected override BlockSyntax GetBody(LocalFunctionStatementSyntax statement) => statement.Body; protected override ArrowExpressionClauseSyntax GetExpressionBody(LocalFunctionStatementSyntax statement) => statement.ExpressionBody; protected override SyntaxToken GetSemicolonToken(LocalFunctionStatementSyntax statement) => statement.SemicolonToken; protected override LocalFunctionStatementSyntax WithSemicolonToken(LocalFunctionStatementSyntax statement, SyntaxToken token) => statement.WithSemicolonToken(token); protected override LocalFunctionStatementSyntax WithExpressionBody(LocalFunctionStatementSyntax statement, ArrowExpressionClauseSyntax expressionBody) => statement.WithExpressionBody(expressionBody); protected override LocalFunctionStatementSyntax WithBody(LocalFunctionStatementSyntax statement, BlockSyntax body) => statement.WithBody(body); protected override bool CreateReturnStatementForExpression( SemanticModel semanticModel, LocalFunctionStatementSyntax statement) { if (statement.Modifiers.Any(SyntaxKind.AsyncKeyword)) { // if it's 'async TaskLike' (where TaskLike is non-generic) we do *not* want to // create a return statement. This is just the 'async' version of a 'void' local function. var symbol = semanticModel.GetDeclaredSymbol(statement); return symbol is IMethodSymbol methodSymbol && methodSymbol.ReturnType is INamedTypeSymbol namedType && namedType.Arity != 0; } return !statement.ReturnType.IsVoid(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody { internal class UseExpressionBodyForLocalFunctionHelper : UseExpressionBodyHelper<LocalFunctionStatementSyntax> { public static readonly UseExpressionBodyForLocalFunctionHelper Instance = new(); private UseExpressionBodyForLocalFunctionHelper() : base(IDEDiagnosticIds.UseExpressionBodyForLocalFunctionsDiagnosticId, EnforceOnBuildValues.UseExpressionBodyForLocalFunctions, new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_expression_body_for_local_functions), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)), new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_block_body_for_local_functions), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)), CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, ImmutableArray.Create(SyntaxKind.LocalFunctionStatement)) { } protected override BlockSyntax GetBody(LocalFunctionStatementSyntax statement) => statement.Body; protected override ArrowExpressionClauseSyntax GetExpressionBody(LocalFunctionStatementSyntax statement) => statement.ExpressionBody; protected override SyntaxToken GetSemicolonToken(LocalFunctionStatementSyntax statement) => statement.SemicolonToken; protected override LocalFunctionStatementSyntax WithSemicolonToken(LocalFunctionStatementSyntax statement, SyntaxToken token) => statement.WithSemicolonToken(token); protected override LocalFunctionStatementSyntax WithExpressionBody(LocalFunctionStatementSyntax statement, ArrowExpressionClauseSyntax expressionBody) => statement.WithExpressionBody(expressionBody); protected override LocalFunctionStatementSyntax WithBody(LocalFunctionStatementSyntax statement, BlockSyntax body) => statement.WithBody(body); protected override bool CreateReturnStatementForExpression( SemanticModel semanticModel, LocalFunctionStatementSyntax statement) { if (statement.Modifiers.Any(SyntaxKind.AsyncKeyword)) { // if it's 'async TaskLike' (where TaskLike is non-generic) we do *not* want to // create a return statement. This is just the 'async' version of a 'void' local function. var symbol = semanticModel.GetDeclaredSymbol(statement); return symbol is IMethodSymbol methodSymbol && methodSymbol.ReturnType is INamedTypeSymbol namedType && namedType.Arity != 0; } return !statement.ReturnType.IsVoid(); } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./docs/wiki/images/fig7.png
PNG  IHDR hSsRGBgAMA a pHYsodIDATx^ `T'>oyۿ>Oyo_bA< XnHhmKŅbRj+l$$,dOf& "nIs~gnnn&2Ifs=w9wܹsG7mr[q>|&fӺu:fGևnѓ>UV0vPنfc{gD=̣Sk!GP/~ٶg/n}cTV0sqӿ7jJiM>vqh)3S1VJم5]SKEc$XAhQ735|zeHUfiN״)Xx {(X(fVשu)=22=q.IlP|E 0Z]aj^wDNh'"ŤomphdPg@Bc&48nQK65~D{b Y۬mZ뤞Fi:34dR#j+gLHmzpfYmzp*r,UY/sދtQ%'PUp2Cm6  n^F9pBӚ!Uh&$| >c}tFalV[nZ"pf$Uf D8AH*zj s#nImnZ"pj6eę>#%YB-AO&MYeEpcCE n3S&mPKڌ۬%N!+AZUmPK٨͢'0CS fL@-50;Yv 4 ҘیnW*F`[v~tԄ{]I >2td 4颿̹ﭭ1ڬ63I|Vy7ӃIb(5bMU0B#,55U%f6RZ*Ն\ MHciIJJR)WVV];e 1\a=ILm>ە*ׯW(((P#mqu6GvC5EHg}{,3-FڵKMcY<~ ^=jrZ/)-ՍLच/ZPISz܈vŽ=C;Xx*W"w˝t,Sϊ []R*u6[5U,j:t{I5O%%Y1O'ojMCD%5h^;U^$Q sUZ{{vY]]KM`*$ 0h5{`ޔԌ\Q#Zrct: j n6͊_ݽgݧS 55Z4.=v;Z.119HSf|q c4hS)I2"YQ__GfTCmj܄*]ȟL dfVJjT `nٲ9>~K|||BBBbb b(3N4eUk7nlܴ&E`YY9&2֬m+5hQQkٰy-7ǯݴf t닋@[:]Tu6SX h3$ ߂i9Uș(Alr|kcҖ6Q oʭ]F~a>צfj34,HE;hE-Ml,<;fVhfM~b@?T9CAؼ`֓ۂ3G4mоF<J .Q}90k\Ĉt:}֬v k āT%q9\NWJu{-rr9RN81ֿk-yScEr/ --M1|Yvy,P)`_]vnRRu$TWW:EbjhhEZغuJu\ظq7lؠRvVU*S8M`j7;#2u TRRFZc Vzܧ[4g<P^'QETUEeKJ.R}D͝;/6&n<+VF`EUTʸ?N1ֻۛzm3,S>>X{彯<w/SU9f<=7^kBBMm5eqצ*~)'םl1/UoENvdgoWE#/_pt7d|̸Lcg11ːnltcZru$T!cv_MFUjX};bڪr;W -|{ήc,|fi:_.^n?;ftkDAl3r׾8;p@=hS@%TFL~P3O?4,r %LVL'?wÏi3쫅(L6f*Q1>d_ڬ}3CD>5]Vl"}9mbhKӥ)_):' YJ/^qIm5jjjՈ/P=YBej/E[?qIn8<q/͝@4-۶mSpC6Gr:w;xu݅ VnvZSe$D!&S]xȮm&n>=n=!hj-AGmR4r%>Qv ־r` b"r"!^L˕W +BYZˍs; efFENTxjsrݗҥ&,'@iH#G|ˍ H@&mjnVԹj`E.%>6s"r9km<N K|tzWȖ(BNdÒ>h3qQsa+ qa#gjK둁CYwٲeJ̦MT*wmV^^~uWkT-/Yr!HkdqU_b)Mr!Hlnjǭ!Gk3CBVmƄfY =BnЃ,6 =BnЃ,6 =BnЃ,6 =BnЃ,<CnЃ,6 =DBK=fl+'DD=.}I[NbxxC&Lu2.'!mFoIӳ<o>_Ъz*"ˀhT:iOqsc72m_4$u8laqi2|aMj+E oIٲeofM4 jTMCiq6XVƀ4-3V5iV)z卍:tFO`k(sqI,Rmfs9#rYΓo6vn5z |"v@EoI'0nbE+qòFjjXF'^JH3a6Nd/Fe@!-CTb(gh3,6 =BnЃ,6UV%tGT Yry颡QsLu@p*6'~nooo@y$n^ڠP%f~B*6UO%dqYpcЩ~\۬fNJzjNT Y3lpůR6cGP"j.Cp*jw5f >}+n8YW vu P>jNnS9 jN>}DqÙp*hX-7bcJzj}<rsȘ{]W1ޢ|&P3tmۨ}Ҩ/L]_t^j|֙帬"Ζ=21IW-Ol=U{= ~t=5O&Haubg_wV3 ]5MeffTmmRRJܹSc AԾ !4j6ۺuJyi Y[U* O 96op~s;e|63Ɠ~Rg~ۦ ?hwU;N{Si3I,b@rz-9P`BӠ5F)fsَ\ϊ:G#.9^+s~Wm66ca6цyibEZDgی ~ˡߗy&l Z˖fYzvR+IO׵n]qZj]rkkw*D5kҍ3TN# 53'%cgjFNjF@ߙf"mօT66MZEWM]e(rr=x ]5LlI;`mmU[[W%fh .UU*`<(UXWWG0ϋܲ-> j0 Y c[&vqffֶmbwdefz˥k-[lO9ܲ MOObvǖ7j͚o M"enRkYkv㌻k$'ٸy6oYqMs5?ed`8Sc'XVd۫k6l֭ٸiM.'o;;</}-"9rXD}BQ)o\U.K0^bːʕW 5 ZVR<a5DɧZG%JKJssQm_ִ6[@'T_Qk䀹UugJ{\5^Ե6s:Ye!m2Cy"+#b mֲs\wѮ2 S11}E.BHվwDխkZ(pu-q?"UYYEq@=6 NLi+UB6V.!v4%j1%kfj)m1@lInvDW+W-T&v+))DFB(q9XkQ9Ou`7oܹO{11TF'/(TE1-5}Uu*W[x%)$dѣr.5^tI$.nN\Yѳ絬<IlNLm|eJIiUe*gm.z,j3,ïz'//;]uz+N/0UTUO{5zNmm:m[6[v=?[^q6&&u1g/;eKZ(6 U_~M5kyrq~܅g#11 olTgS[ܼl%ƼUW\Tڋ/~k/Ͻu"iߞ;oʼc+3\x'H7,u7dN_4fb'1;Դl+*jrթ ?~BeCáêhGK2%Xm#㥿kpߵ٦MTyyy*563yX[rTѰ_QLgG6^j}5I=Rh=<ۧ40lذĮoGZ>4Mjj1}f# 6tDpm&2!-luYktmfp\} L5e. -5uvWQfsZQ+nk6kYaCjZ)D ]&:؀{4 oCTxm&>|li,, ̀LF!>]{J|Q%4b+6+])[4W M LG ֶ|nRLex1/>>kE2ݠBܟp"jV¿k/;x񝭿+@9Xw޷6IM7m-l6G}q =d)5::hȅч3V$䇌"%GWTA1,\Bo Ζ.6UUU]-[Tn<뗷^ʅ pa/+@Xp|I4uq_]]>qj*62fL?,hfLmzpfYmzpfYmzpfYmzpfYmzpfYmzpZfԘa7-r#׏y(j"O;E !1micF~m2ͅD5C4K/KBkCv 0SM;2<_;??f@$U"%ΟҞAQo{Ӡu)[E-v5MC77mn.~ݢkNqVY:j)ߏ ߠQf-1D3 =̔O1͟8;G{ ];a'^):=jO=Yq8bܴSac1& L)ȏbD5_XRk ]˰,VU-&!d>Sgfwf>~nX]}tߝ(Le0mq6ƕ`["̬S,+Hjf[wAyV \ V{ J*P<WhK(:tF̜, ьgD9$乸/YN9SJ.<`^~e,ju"\R¬ڹ ,I _;o4xx衇Qr+HTGQ|ټyaԴ+Q̙;v45QhEmKl{!0cuYmŒbT;0AÌa3 :f t8&p1aC3&l#}áQ<dvLB0c x0cu '4(WkÌ [!%quz(pxD}zWL/:fMVc FO,qTa tx0cuf35(_3&l#J\tƠ9]:\CbvzP:8̘Aaf5aƄ-tSA "p]GJJ- /fLBG裳.Ӊ050a}Z/fLآ`7m 5aƄ-tz*\؂w}`IC*LۍK90x_LOp OkT.#>t1j&\#OPA50ìRu1uʧPA5L=ImtKU#_#}¥=]^S S&ԅ3r1Kx DKvO?y0 Tf&Q> f%%%j˶mTΝ;UKEEJ%33ԨqO#> Lg_ʧPAafSSSՈ/TmLg*UPfq&h= 4=EoifnȧPAap ݵkJuU/YYY*unZ7Z*wEZ:Tr@?.,mC ace=;0^QQ6$W%UbdCfӷV ޷JWܻwowD7|npHe>t! fN~5MRZCǍ+3I7t ɻc=@Ҟ㵭rHWϽwC\I+7U弔zkQmޒBSyW*'ʊ8qTc럪0i af:MRZJb_]gZQ+7QTTV P[TA&?Z˃rI%<d*[.q8Nyi)@=z"Hп34jБE9EG"]10ja.]Fu~1v5{yKF?<? R͏R.8"xjk?.gpe85C =`&&&Sn#U9T^"!xݬE}7 v\0*k $20TTBNH gS%% V@0Į'C)a:4oo߾jLԃFi=AM`b~~>Κ@FnEq5b{חY?–x?ӈ[b8 Yj\K(]TBD B1C b(Ձ 0"-fAJRe<{;S$*~%$'FhCe9tu,%5{ys͛;gbc>=o옘ٱ'zVttt ƢgώT$bf!'nNl,R(3gnM`}m?ٚ%ƢhHhHhYz~*,> x{ @{HfTݣFXn,Z,-bE"üACc#pA1`kEKa czҢ?9i2XbPY &|8bU?׿:D\[4;_q(p_\(9ke8r䨪}Ygڬ#g;'ķֻ^c݇H.ue 0a*iTUdwXnW[%L,>DŹJ:XW:B?}J2< Nqr9&;yæ7dj=uTf{ôTN"Nf5)Stcq<C{1qqCh@pcff 6ӂbAZ$j'0oC/@f&ek5Ol 9<F=. p! QI!#ML!936oN\ȍԼXL1L4cDѹ͙;m9U%5pTy05HORj~[  B(ed |od*Ip8:jWqF%xX[gfd\,d; Vy_5UO W`wD0++kݸ O*!D+ORQ xttqwKUB:g..cj:Kg5EjDՁl*;jу*((#ى , -'N> -Dh@aa!uhUUUj-Cvqd0WBĎ:ff" нuXS,S1kܠ$--M"*B(hVC|ڬX{ǫpruHߟ_WhU@K? 6dff^ٴETN4͆\;jΖn}|]XC\SAdff΀٣?,^\\LAUhbjH- F~y E;R Y^M6#;W_h(mjyqv)_u2;QxUN926ZBQmG쪘9p,Fb8iWg&ļ'c UpٲŇ#!Ӟ↡sG<HPǀQ[avGc ì?k~5Fy_n8yǶ?(I_66ʙ|Yvvx/7'=6>1l>>xTQ /_9z<ͫ2@ظ̙b|v"uЀ %|Ƥ.Ќr9VV۽WXZ,HO~KԶn,ehZ RӉl=gyvӄeVNդ719?孃v S 11Ξ5Ϟ=]HϞF]wͨj ϾYR *8̺IrrJ1LTPqG^^^AA }vЙ fo#_vM6yyE4ϖ@zNi˅:&QA5ÌniJ@u?Pw;HOnuSDŀ.њ.jU?Fg,5UL(#^a BƩ^}|(³zx/ꨠ⾙Zvv T!ė) ODzXӉ2~2k. !3v`r233$i =4#V  TPw(EPPBx4f1&O;jEyPO"FĜ5YYY޸2*abk֬'u0q.,8JL/*,⩈!OoyJ6hH`T{TjUU(펜,Y?2Ԣ~uMޮ4b`"_9"[<o$0Bס܄Vܹs׮]2} 3mUE=ӿ\:=99ABJhoZ 61e{u<Fi|=8oq ^/SB% uc Hh:rGGb,#֭:ӺqC5AX#˂Kƙ?9+уj*۝bqO~|AӾ>?ꪸn6d`DN" \J,-3Aꯎ"ɦM" $USTP-Ӓqėbpx_B.qAE~C ={!yeẖ֝.Q^j޶0! ~s"4NgPgTP16lEQVVRLBY{DE W^'-j"SwPu1 *Pa6<Yx#FX!cA{rE>_xȩ\cip|!f$^P4(2b.O;?:wt W|X2?8/ _̟lʜwbcR(G"*8n?S~FAkV^_wY^Tf <TP 3^ 8j6i3 :f t8&0mc&p1L0ca0AÌa3 :f t8&p1L0ca0AÌa3 :f tDc&p1L0c쯫vX IY*Ɂ/}c 99ǔ<ErmS|í?-}9RHO;mX1i׌yqu(._|K];66IcGMSf ŒQc&mygߺx#'G:|7y&\]֡ =j}ht!XH =3k{ѣ[#>*<Bq`(E)̂jcoyWo}7;jc{IO>?QsF1޽XMTbe,!|0kc>1 hx*]{=S0Ca񌣲pc4 CaD[ZY-}٨ t|^43_oyC;SGchw~Dڢ1ۦ^">{g ?96[6G#GtO|뇓+œշ2X&x#D 鍛E)N+4yH !}A-Kӆ9"s 4|7M,VHIkOdZcҲ1MeBD}cHʰ,VHXq3S;ך>^ܔr;21gjߝzˬ1 @(Y^$#W͟q;di=X0~_Xe7kn]F3?Ӱ"Ƥ(Ɛx(6$b̔.5ƵaX-׊N>ҴPփ Wi]:b!W}W؈CgNF{. DEXUoWRY5}$\qBb*?e)߿2s dGm{*~aQF~1 m1'cWcVnX2d|I* !c<Q[q0r5G!$CCbsH(|+(Y"_@qFD;Bw  Ra,LmM5`-ZblJk^mdIcDcuYb  &#bL-ҋA6qX1BUO^@TOnV{`o9jg9$SjDQ[n}lYC榦M DIQ&hcڨ%O2B1Œcucsr0xe `B ._+"Z)u/X,VGR1 4c \8&p1Lpc10ca 1 .c \8&p1Lpc“U 9}%^8Ƙ|ߡ VCGRk]74jtn7TgQkc O1D҈411+{/F ^8Ƙw>62f SVYcz^8ƘD}Z/cLx@1&<Q{Ѵf6@Z/cLxB1l8Ƙ Z3ں>I1\CwAPlh}n騅4Wp1D }2)~}CE 1fB1@t!xcP ITkc O(^8ƘDAF)~H36cb? rc [>8Ƙ ŀ s=nIz,1&?={މJLp1`1 \( $d51Ƅ'}Z/cLx c21j p1 @Q 1 (>!Q4=2UV5"V)c*ja^8Ƙ@ϙ04ꞡQN%<[@L۝>JȸrOϹB.mA<&aȾБ14 c@P Ng9FycF- 3xcuITkc O(Mlk8Ƙ5A}0>IiQTk0(?oDŖ1fA1N%̧B{~Bk]lqk$=}P<S\,_>]|n*p1@1@?MdFp#>N@:rb Xi3(-/k&,hMVcLxVc sdе"nj @QceM/Ov)T2 ~JB6<S<*v5*?#ȏ{"䁘9}qS1jBGO?OSc'"B,nIXzzP 1KC!?%[~V|%=L>#1D t_"$TlykIZS&kIMH}nkz H$AϪ(ҋ5m (SFPcc=!~@APLZc[{?gϞjU5Ϡhhv5")))QٶmJ`֭eeejSdLcYYYUUUj@g-RSZZ8ӋP cP#\S.hONN޿gXauӍDq~ɴWhmcV clDO\l66*333//Fe0VF%*ԝwq}*+Řݲ.ZH輛V Lb fR#CWkSSSHP:0;;;''N+GiUC+*@1>bпVĉ_. 6j ^&`t.D]ꨳ;l.^6r8j0c Lr +/̴$qT,STYYŀnB,8VÃS҇M25Fhga٨|?ek2joFblStJ}Ȁ)LR xNK`qrFawKx$#5mPAUU0 c21G á| q@oh9W Y1&pn$*=-#OUd@-qyhT!TUSZa*qB%9UֲnК/U1y A⪶0bS~cs?$)9:1ohyq$!yr':kO~b]ų[G̘x~q+t?"c"1 1cYKeO <+>ucUS^)853N@W,\j~GvWpK!ለv_ oqS#Y3y^uuIoCUd\T!:?^e 5UCV[ueEEfFFee%͂x#sӡ! o-8j)|=6tO'ѣghAPYWlY=H7{6&n6Rdd槧wQ8Pl\Q|ZmV׺u}zWdeښ;~֣Un'bJ+++P)QXA1U!p]M9X;}u T*Dرm?[+,os"<m60t50}EĬV+Nyyy:$gbB+(Zλ.8bi@>˅8/hcB( $P2Qg?9O/52r>{BoB1D jD=䢢fuvÇSRR 279233hijl#yRbǧ=Eg*?WIERZZZUU\~ t4MD2B E h:1# n=X__YYKy rPiG3m! @1n i*4XvNNG\;P*sz$ F%.8cuɽ2DdRQxKopjZt0ՅDyGUŵT{pwH+q;+3 BÌ eJTZ'%mھ3۷+bGnߒe <'$o޴)=} 2l۶UW"j5-XqiCBu7I\:k6\m{nU@Ee嚵&ZmʁE%B]Vc=cf7oMYnúk7m^qmNToc̈ 7T7o߾QC*s1ڮxنDVBBjӚMWqV֙ϩAˢJc _~xQLkjn$/cϛ=(Erϋ=oϙ3̜93fvЬٳgP(z91;3g̈ ";6.EhW\Y1㫖%Fӄ,lmA~>ɲuYjU9O6eZQ\٬t+,5얈ٚ6 %VӢ53{s{4|@M'0DǁѯF  "ڎqZVk':{ c2R1ࠠK@Ud`Ѣccc7}Xt곒#Q?}0f<=)b| o!ςTxw[|ℂGj^q>\eĀ!ӧ4 ]Oe4_ZQTiZkZeHL-mZM,Uե4Týw@tH+`5o}qs3byehV O Qs WUdb .e_9 jVZҥOhzW?7 NG#gC5P'cOAhP7AS:cq-Vj<M1q1Dy bL{-8]Ę.uuFkу K~G2KDث:Z6L{jHGk] 3ueĘJEUd@2ǘIrPGblũcQ?1<1Z]ZGͦ=,/ WκB"f *-/t[ j^FLR{$6V 7nYZ}23+**(`j/(ƚ<M0)zDO ][hjjlj4ƛfxSӥKbzΎQ͉CJ΅Ɗ:oΜyzgظ9m^uл߈86bEGQ4U U##Y|*uWS};MԞ jR6-Ũm~EaWóuR/4oʵl:q;OԻ J5m=Cr%-f\!O .lu:9򻹈1rJǘfEXz͐0Ik.-s!+I莭JL&da5vM<\p[W]sޡczUwzjj8\Es`h}"' SR%Hc+VYsՋFQ{#i`Z8ƺ;UBqXyQ#xxID2НU3D8j:S>I9r$99 l&O8C,NHJ+ebBkvޝ qC4Hii $;1֣g@ɴfEap#Scwl1!4$.VD<Zs*M`%`\i&}cAD6ZVpP"M ZYlqL`OETVT` j}%}^D:r1:ǙDTWlܸZnqj U|SUg;,;HJLLXLѨG | aUU7hWQ1@Z:e:WX)c4j2['uy0!cZ8>,;p٬z \x#UKt߄Yp3Ӂ@ˉV$LžC {jmڴPa~6|] 硒RD^!ETVVKB ȕuVT`jI$!*oq87ՠ;P5s,1{snysCbVAUgS/rSؖc޴J3VK<Ӫh˗/_j-RV.]ψtii9s9g`(w=a\\S+Dzb>5ߢˍ)))NuQ=TE<ꆍ[ԾVϏAc!&bH(ˀ)Kc aU*|a׮]ƐьZ N'b11$c1.qٶnuUg}VmOPhfĬq@$98s &}yr?bs~oG}˗Ŝbc{P)!|c)dz/V^V~54~z"?&&\5j@"&0POڍ'?ʦʿLJp)Jj^: ~@4_\[q=3-!q+-qYəב4/9Dط'rBﹿ(9s^r 9G$UZx_55L&b,ߎEb9o;&gzϜQuI>4=4oχRn-7`e"F%s|TUv w'v76/~턻vHprT-c]kDѥp꣏>Q( 􂈱?yU](xOyz-=+ 14`uJ$f<rucB-8{l$d"R)A1jLQbX:/XO=(Oz1rEHJ1L0"b҈7{j BkaLg'r]˫?1y t 1vłěe[؝g-o݉2(އ'5c#jblo!`]l].`CD 1Qkދ%$*T-!cAe'y ڼɧT9jU5_w((4 C-K$ u =5 ?m>BF/cݢS2fǘ0c'WO1(,,ܵk @~, puMTdeeugv&<_{W]?} Xd/%^SJOo1}Xj+UԴ=2] e8T]ړ0]eRBW<a@jntavO{Nn|U$VxsoF&k&Rc8=k/?$^U-E{l+!4"m1EkӨB˃bTc,lܵ@Ę!Gb@1/Kb̔DpcY;` 5oJvAژXp~2aX 6mӦM8x'E#GҐkmk5ٳ{`0pbLZ]WPl/檪ÇShU^t $"r!J݋] WPC}}=/d:$cL$2D B!c4 * kK"|H ?'^ gh^[~JRjD8ʄ!0P$Q=zʕ+ۧ2DqQYxѓө 1a Q%\֯B26;N!Z1f?`+=`wmr(CCú`ol%F8w68`Gvg$ ӌUJסÇoݚp$,СC2E=)2j+(tJ@%7 2}BXS' !5I-1gݷ\W Ta\E(F3ٟԾ);SvlϢW7"iiiY4 $_'(QDqZx$vJ$@m9f ǚi_ӴZ/=*z'ZdnYI/O_rXx/`ek֬X,WZ6$"kr ~JMbߐhW 1uE6HW& G˕ϐ` Hz(ME0I6t=L1r?Y"<.ro5(;=U?Q P?! k׉= .\~?mG?|ȡQ|Q{u0mb#O8*I Q/.b̸bS9c\_O<}H8K.6ǥ*g@Sc2*!B_B!>| G[CQ&~D1@c"'&SjyL?Wmٝ?y*~'1ĵb…q]b2Jm,OjڬAH[b5/"*S3O*A ѓj!X,zP*R$F._Ř<h!Q46II] NίpӪ׻l.(w7d2xqj:GY[笮:}*#ޟ? n\R")?p]8=Ee\urF mdz1.] )nӋQz7 ?3U29zի>tHfPU݂c1r"AD~҇c2b_] {cv j2ˀL :k9ry \&pu?tu_fZv~{^c'S}ZWwʕ>~2 *c@{h&ڿ/x%7h""R%: aBοcGH\21pu*}br6";'#e",M GDlV򓲗1#MzAfT@LҡHe50%&%.5H>xntzYSC@1aRc29zýOPk`AM8zx<Stw./x˻#UӋp1Lpc10w18&p1Lpc10ca 1 .c \8&p1Lpc10ca 1 .c \8&p1Lpc10ca 1 .c \8&p1Lpc10ca 1 .c \8&p1Lpc10ca 1 .c \8&p1Lpc10ca1<iQ㦲XcL(_\qw(}aQޚM@Fb8vM6j6G#Qvnr-Ӈ0rܔȱBN&S3uiM7m2!fytVϊ/߿~ !}PՎ#F]m˷r2Նz4|`,i-=o2;2>6ŔiR+& iҖSz3⶟P難zlmkK_~d-?nݱ?M=baL9ѓ7o&׍vݸ~w#cH?zV\qW2QNgF Cc?w<L@/fQ ݊jbtUPSck@z<zc9"*!7Z{\@NIbHcV׉!CJޭe >t[\YKn_47=E57_^o?|RsQwE,4bφѢY, jds[R fun%SI3f ;i+26@Vb+'z!1yQ-*-cM8ٰۦFOK};aOaM72麻}i'#n|47ylpG@D©ac^777}n2?tcً&a),u[M!06nOaa=|ݸ"ljpᑓ>8%OuDd>5qȟ2ơ:=rToCn-SsRX,Tuda?cLSn?mO;u8ܴN1~,rNQXfDqZQA4|t51ƥX,+N& dX:QƨiX,+(N|aqɨ˘ @>3Y,8YuWc􍚩}הcM?̺b))Sh^S&4ͤ̍ ~qY,2Fi̛А iL]7Q7 C`\P^R&T9͵fTtT e).Fyg}^`T$S>LHƍgX,Vi q͔og՞̫˸,  X,NRNUSS=+S,<|;Yu;6=U[wf9vO' S}+olӽ/ס3+3ie\xɼy8T(z¸i=zPz,ldp<:)t\,/޳rcLPUYANE'j綗ZLCX"gE rG ꙝ6Ll޸%tЧ5혹ItN6Ci.~ u2]p28{s5dm WᲿf NV]VWClhԄoE>'[yo!'N濪uIO/ljK1֏Xb\"'٘'io!M3вQ%Fi311SkjXF PgђS"@'MTc)^?Ym/ TbX?'#+(i9UVO>vzPp/|J^|wI Pz,lu'czJs2jdꊝaaBv2a&a'caBv2a&a'caBv2a&a'caBv2a&a'caBv2a&a'caBv2a&a'caBv2aPDm|;1 Ä>Pd 0:{q.Zau#q`-)}*om'0\@t* FMoooXkCov2aPBڽu¥)L{dH` d'Qd 0:0Ʒ;0L(N N0 JS{sDREa uj}`TGd 0:{9S<>SO5ޚ9Tk}1̅'>}tJw&1 ԩ5Q'䈇1$';0hLuLV⟑1'AGL3 AafN(\Jd 0uj}a(>Pd 0:>ru(Ua&PFa&<Qv!ѯ8S\>8c$'^afNLTOÊ >>]'ʧ|$)#f?]LzzD= ;0EڽoUG`BdZ4!aR贽 4p,a{^'3~ SĬvafN;0Ejہa&Pv`'c %ԩ=9pBmR;EaDCv2a:{џ-tO09@H<O?*T.}dh=o-8 dȘ9EJd W.z䜄7b0j0_!a(Ew2zFGGs*adxu_K'_H0D1*AK&Cd~zNuj>y'v2a:w;>Ԉ v2a:>01 Ä>Pd 0:>rd 0:>d 0uj7p*aJ/O|a;0E ߨ[~E<./~EO3Kh4=Tb^XxpT=9UKu"GU5z^_mv2a:wΙ afNCq2 0 uj`Kya'c %ԩ=1u|Je'c 'ԩ=Qi~a'cǚ3ej}^^p<sZa5{#]UYW4NOMF֏aΣN^*`*K!;uK!py Q {`9 rZ&Z>g?B?B?r-E?ׂF!Z*fr2~ND+'xξAۛ<ՋIMf}ͳXk%=U |,N0Aڻiއ '{OS!!ϻB_{0z@ ͋+˜$rW3 '(}[$P?SΫN0ACv2& UB;SCml+pUv& L9&XݔcU;L9hjUkf߿۶m[n˫P:>ru(Ul@QVVKرcAeOeeejj鈝;w_vQ8B999*awlZ,́[ഞRYKLLd:YYYj@뙜YPP0a:{q. M3==y G<yH}ϡx ;Y著Ss~~>[B UUUjKtɌ:jݻ޽ZM`l@Zoc5RXzz7}呠gQX<X/_r!|ަO*q2΋5W/a'7-5mEEEjtt"[n ~ҁ"*?Qˁa-dlHPPl@<.XڴVX݅KAޅ2>gO`+r<a\v爯G_#QXm)--E`ǎ=(..^~=:=:8l߾}ڶπ hvhh'`WsƤqacPD@8}Fav2Sf>ʂuQξCn۴q{bΔ={;e?>ՔC٩E(.IO'KLܵiӎk={ HMMݶm{Ķ(ַ41-gkΔmeNۖ+%5/9%/5 SRwef//9lְ4ds; v23+6̴tM5lڴ [k^_',5=y56SVl^jixK*!qZvMAAAff& `:ggam44q-~IE4j˚&eib^;NLvݘN|wC59NS#֬5zz[~s6m`Zi}JJKM+lmޒRЅm/Y|K\5(tc-v<Ç|{>tGx ;m?{lG&/6{f; u\q$SgE8הy_fq'wRӘm 4}"^LFg/Z1TznКξ;&ʿqf.:Jn-s;ԫOy!/R;Z>X NYHg!ϰDH# B$DxNl 3EWL5,"lL'==߸KlJ9yLl{'HLg!Y".GXjNQꔉ$"}QLA62_o}`> N1^)>y9Oq,l0;ri,ڥ<(+g`amޝ#g{ee01t'r8#m3$ː 踽/\:á/:zK(&.(G--\4ȔOGO%pU9nYFhv)-Oj%d-TTT$%%/2k%mTuuN};aC4˚ PW;<WL͘YmZ/bOx6ʄa`2x /!_<Yr9\´ZNSx]!''^fmҪT1D>IPBe1:F'sL'0-YD9Y=2kduO9 a%ůѝLHɬ61NfS_?i[T(M|[{NnGC|^qj0 [N$5 W]S#Ät. CXpl߾===؁bTĶM#YV]kW5$ F}-]YmeKy g'u`' hho>N!0&r^|X^@Cߣs[L%(rVuuΝ;);v(//ԥ2yie: @`2-:>|xQm$ܜ ݷ.d=Kee%wj$`S#!BdaH 92[MhQ%3)!H, b#݊D>rJ𶌌{W) Z[5dtɂ'ñ㏎` Plr]aRCCr/!\iԀ+M\ff&NgD B@TR_sr8`EC]v_1rf=Z8&0ra\1NzRRRГF 9r'ֳ֓V:#)!;|²j%=dn?% yp|, -[0+;29U`I:TJ.S 6b )۫0MBU8"!g S<'(Nzݺu6mU%nJoSnc}js|Co 6PqsՊo??!Qvk87Jtc!4*zy!d<TJT^n}*ijYbW%-ũ2:0KzɨQ)~TKP#&a 0unڴ lX"a-KBsIp*LӃ ",\bz>T D[_a^Zrָfb5*Ϊ 7LeBr  QYݦGlLG_C5oJa$U[H6]ᤏ/|]} WB83+%a8ꗈm -..޾}{ZZځt^2ER26 ;!chNp2{ӎP{P֪*5ԩ=SҶ=dY۳0iqA=<(IȁD1147z.7z._܈?|$J#e-QqWT aqf=g͚/9sFtYg͞5k v11ѱqOLllLl(iq(i1c␏,bvY918~B&@Ypݹڣe E{RאB9OĠ'#LOC:{M\́AZ݃ڴ9oZ66 .yĥeuT}ߵZ"C!H<&8`Z -^3 $B^zLpctϞ=))) /r8Š熃\3^3$fYEɝ]'Č됏 __qin/@#whN<̄셶'SӚ/7?ϛE x2ao6~ÄI/`N {LFwQVhF|w^p1ua8dupd/7'nv,>01s͋33:zΜsfy".n.4Ec>09F(M›Psbg|y11ѿ|f9ODϞ'll9@Yqs3N%$媭ݛE$h‰@3xJ%yߙ\o4aQ 7{DAΑEө@ 3o8"6(:B,V#LQ Fq@'{m޸yݚ7OIN֞}AFifg~A)_^GB3d3b!~Å"E +33:d`m m;N&MFK_Ycm}:.ݽ5y8hͿPرA+#"FaƯ YT- wß̘;;;7;/5<7zԃQ#G:[-ZfZƜSų><șPr>YG˦O񋋯H`ꢸ/\n}LtjX!NG۾Tֻ\Ǹ?<F2jm,24 z{^8?R>9H|~Rd9rꚓ~ID?l:vsfH;y |ϛE, FQ /ߤgq 3ezN&>ӲˑBNFV8SmXr"DO e%b K;\/1;M@1x'ulJ`W,=-&]9sq8aeut,u!lL~N!GrRPPCm^8MjBK['0*1/KKGɮUXKvW,G߂2(D8qv]p27°g0`Wd%r,\t( 벯c#'ala`(3PuQk㗶Nf9ߖ62TD'~j}S!N檝l1N5MaQw{=. {cސ&'k<#ƪz2Ore'LY㨩s&Hx έ0:Gh#V 1eLhENV_b WHU>P'ًr2`XLuؙ1d"`)ߤum =Vkm+OeGGhim{f=WSxI8g~eytY$]B'zlƦ/=͗'fM6 x<PEe4Ț($2m9:648z뭹s̞'?c!bgΊ5#vsΎ-> C-ngbfŊDGϝ1;nVظ1s0ѳ1qyscf̎*0wL8qϊQ rKWt mHFNI+qm3#Ѥֺ?Vonx۴ʬ\h?=ɓųbjӚ[j38m/)# ,hOj)?щ!{!N跉~";Qt"npҥr{_3kuXڦN]?k+Ǟ'oSU`}% kMe[cTUUѻv?$k#M"@}kEj%=dhVRZ %e d,\. 2eR z'䗋gOSYYyyER2H>TXy* J~YjЭи0v9UUuuⲲr9,;PVzvAEIQqQ~! z(:2%%III)) Fa S&Pu CוX˪+eJ[Rť ,/æ^qQ*ʷ&o1:=+AȥBzUU^e(.AW+-W@Iy ȗ]Uc OB'%%@{ Np 8p +++55lN&.TRg:)GrE/ ˈcLyi HVĚۋko,]"Oa , e@܍kŗY1"bh qAN8Ů]HWUAqHp_8$Q<= ;tjĬ58蕌CfPX8Ԁ0AZb ]h913v b:Df;NV̍+\'@><v慥aOgyQu"Q1KNNw}\#z?tboeP GzzZ*6V<[mQ r2?V#^̤tm*!MyDBt!,EEEg |0O%a-G,k*3T;I!f(9VAA]Sdi8pE x( 1TH@ anG$}dtڠyTPwZ*t%ѐF~Τ44Ny9DN 0/l6$.`_vTE.~4a_aOsd! b#o 9VkZZR8Yqqu EmIݻwcU+**ЩO=^:;wBq|1IH|E~޻woii)v&OM F?ӑؓjqlavQ:vM@[`u󾮮~ㆍk֬?4;:NDm}Q9JBtusv$<Z31rխ]nÆK.o!S=fyl8AbDءCmسgoffVjjb1|zBV."BnLc=dZIL6X7 ňvee+WZۓG  v%ے MLL& DdEF x)_1P6߸a&h˖7o9MjӦ}iaڼ2 =zM:2sشf妵҆jع+o^ 6oIW`BiY!=}[ZZJo- ct[zfzz^ؿRSSSRq^RRa?4]Q^rxun߸aӦ[6n,rCdTPXX=뱒X3SӥZmI-JaAٹkwZz&)5-CT%3`z8qٳq񔟜j:{AIɴtdE^)pR/R/fXA}LlޒV/oex_ꔾT-~Y~#}ANnrrvSrss23; f͚3g.HF9sm8DhތݒRgmݚZ3l(ߢ'ګ455={kKUj?Xw>sF_~P J`'= U;HN}%fϻ`n~Wg"s)uP.jĖ-?&pՋ3LuSOfzG$XOILWcbRcҹWeccʼnH1rr4c윞O9&=';;j*.zo@ + |";$*c Jؿ~|BVa0F.:k=&&6=Ecjq$b0AitBEcbK|@Qıwc<j2w[,{߯ƼUFeƼ JX}(fA[ wŋ-tf,sϝ2/KM'n>cwJڠA6ְWT>>Zp]X.vzr/6edr4z!ȧ zyçOŬqGksE&ͱ&O˦ĸ1 z3R (i͈LԶOkQʬŊ.8U~VxZ 5"2Q2>Iʳ;#&R K['Qu[xk g|P7X ꚓT=Wm^:03,xU9򊳰(I=8%c)Yi1DkbF:Hz{_ZcMD&CO-8[AQ$8>QCћV꾈QjX-N(q֣%]p,+9ᙳv\$d11`jH/#'[V'; 8  PL4悱ds0ljrÁXVO( j[H9VOA M;D9bwR=H@rc(`4.8;W,{' |Wh|ߞ{l=>0 n83QFӐ&_ČD :j*D?*)蚓QNJ_nM8 23{Mirvh?Pȱg3ԃDs\ zu ra˖~f=~?˹F2-dLOI_!hRל邓ud*myTdL邓u rjmbtGv^eͪ)W_]V#6o C7t|6} L>ٻZn߫һZVDGU#vz'jz^ZؾWO?-tȾ_~i^?ߟ_/9;~iH\\χ>ɘ>`׮];vP# 0݃{vޝ 0>a'cOOOW# 0Nw轫μka;]KH)..NNNֿd 0v2THHC>x1<W+ʪV@7gr )dteKjn\}5k0OW{SwsAjWwF 3"Z$ht~1ZS=ʻ<HP=gSg~O%Fڿ]ɾꍢ=Nz\.EۧxliҮ<.ߡu%?Ek:G^K/ZSCS(i7zP?jw-ҚjSoa'N7L'Z:?,&|'C#Daj%<ۧ/,:+FCMbFdH(pr4|o$'&  iɐ5`d `'c\$z['j%r@i>WJ^r )dLdffvK}BEE֭[EE1a> o}}]8&:+, VRRRyyE>12.f! )$5R8#<ŋWi]UUQݽP;_!E%*+>>C!ȧ QmL'* Dևa>,9ZU61y 5O T/ax^:@݄ f'CR]BiT;kjj*:0 ;Y8Pc%ցR8L Á3XVFSRR 鞺rFB2,%t“jV; 9X3 .݆S?9u˥c(**T scBeddڵ+'' RX+ZyY &dCxΨ*`!B޾SDV uir:#I3Q 8qST&;JeJEq1]8o]2cK4 3m{f28N=-= ˅YGUudlWD0LN8ش?qϏ-qo1 F^0z,/`FMݨ;ŠKʅ :0a::jЙ::6n[?/O;P-cpHCX t˭Ғ7l޴iG9NN ?OG?G;B]wM㮻 E提$GTP ݉9o Qnaq2;<bF ܍yׄ; 0ꞻk w^z]$ ꅿx ?wfK?<0a;Y8+YfFLEk,L!F)'ZD[㚽`v1=8tiC4,fGIr)b5mfvZ56.GA faM a,iCPY2#bTJkn]M=mPQyE׭ ,3-]ֆ U- 3a' Vl6#=e]'MAlNN0J3SsA]Nɭ7Q]MX?D,&d/~'m|)5vIMe;dMԞDO+L#~=DDsڌkMƦj'SIr2ˏ~ oqR x6*8Le.|7闢 7Bmb2r0rDyNfy5% %)-jb2&O:OlB̅i떈#!ZYw>br/`' \2b ImpWMVq-DOMw#;Hsgt$E-uk˴:ɽb'c,:Mz Z9îaEF>w}{>}kC<YZQrԺj.0U!!?&O!*NJGn~u=w5ϿVaĈFL\/q v:V9rddaQÆERaC(22rH|Q4e({f~u()*uUGE0vmc#D1PX%UR&ZHޢnoP%%-y|oFtJ_pʍT 3a' {K8fC54&;1Dy6xV9.{M悽8"_~K^c[5V['yFOcx>TcI5Ho`Iy| Dk&"`J0:}UY] =}_ @uH(*mVK<NliV5 g*VZP]--x߿_ivN⴪7nL~2< _Vj ` @I#*Oa'c@`' M[BTr/qV&@HVTT7w v2 vn֚3KHH@;; 6ω^aӦMׯR ô;&TR ô;-|)Daa@?$=wؾf-jm&|a'cETpuvHuVfҧ\_;cv2[lJT[YD\PoJ8"KNEXxDq|cZDdhDy$}I0fDydT4KTR *pX"}X. TR+iX%2P#KG3TL=]uL]hcs}V)"pсPL Nc<|ds/}hG?X^e/_vtHS ݕPrؘg6̏b9IF>rA& ;3`'cEdp 2^ }ޯUnN ɘnʟ@\m_~生 jm&|a'caBv2a&a'caB9_|90 'Mʥs2a1 0 ;0 ڰ1 0 ;0 ڰ1 0r&1 0;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ('v2a&a'caBv2a&a'caBv2a&a'caBv2a&a'caB'cX,+tN&y`/߿~K?6&dj_\q^ثknnvG~e6nJ丩7z 7mXd|ĸi׎r1)rCrbR㑖 M.45J1vmFrim#=g_\Ma/6 445 D4ec&Ɔ{dmo ?äagS"NfԘ)cdQE>l&0nr؇FzNϊ/߿~ Gt&'*7/`oecںÔ6yЋ9vx) S)ǧnӿ5a,:.YW^?'gnp'_;#E"LqOq۔aGny rܤ'=?|eHYq_aS8 Nf0lcq|JcI]x SfgusʔVe66|c&wWTvsw{57bo{dm6瑣'0vꍣG|ؘQ~ݸ;emomƶӳ/߿¦6FC33 5 ?NA~o3i$4Ȩ>&դ-o]a.Qrh8iKMՇaNc-i0 R~ie?gQxnoLO]76?ûYuƵNo^t<-Lw7_=Io0rHYq_à^$&MK1د.%ILE$) r&r)[W3E}e`9duTVFJ4;R]uicQ2p օ!Ik" ȪO=frSc mr1wo<w] /ް8 Ky͟Z\pPo>!]Y[oϱ?1@,ҕzs)%I<QӃ9 lIrl%„|y-NxGb*ocSFrͥpGΝ5;ou'K\pWzwM5n.g]D-;׎zUǾۃW>4/F>P9bzGl?~JUEץNƦ<M̎u 2$fTCI1/h&{c&u5ۦG:{lϣn6'1=qS'VnmSț^~C7/>;\s[n4l#f,bzAl:ImH^N[[c;2߭2<s#o}q\sǔ1uc|o7cΘI#?4|׏y˔S|6KaX,VԁAϜMa"M1~ʍ ^?nxCLz0rp/F 9qBs(J|'Z|L< L7/bXAS6.<eQLۦG¥+9Ta ظi2+qgRؘ3`8赣sb.bM},1^ES㧍@ N6v:lO;^ GM>%zl-`X,VP5{cFDѵB|A["A٘)·s& #99cX,Voh@ۘpsH갌*ZX,+6|aqI*^>b 1d2Ʃ$,  e\bݎᲔ4jT,aw g0F \gY8[4n<bB]-66Sɴ{4Mx1& f2}t QtXu:c.j)"ݰXԀ2&S5< ͸XYnGǿ+v 8 ƳX,+J_}0  lCx%"3G%(ilzydcrTiW QÎǿᲛK>o[eLhY,2zbcT%fe`4Tr;k!$ i8z](@9*olLS) 1 C %Lrb|?A&=uʊLμbXP!ۆ]в=@LJƍgX,VwobX/ecV)bBNlcS {VY,+x_6:tƔkz卍`SKDa X'%<X,Voʧ)9fٚkOArZ躪kѫ-RSlcؓL]%f/Ab_s޼y4`cX,ac8fb8ԕY_l6<aXldPy i^=֭C\޶Of۫(\lc,7rFO펍Q6Ithƚ!=D'oUG $IFS{mI ^bO|<x 1Q4mJu cmb|IK<Γk!h=z2Y$r/w)-|qP,bpo- r0J6#ېm(7U!$٘sSbYHj V p;䴷D^m\"߂ҷbH+qSukX6.$!1sGSSӎe;DehhihX'%t ~0ІaҨ%fhj*Xޔe;n<J+r±DCGEz۲EZI6)NLƪ׿S0 s{G ȇl S[zc=mqT;"[oX L('acUL6ƚF-ke-$^dlLMX43L1[l'*Q^Mbg$mbػ>-Y//kҺae[3`c4ۿxQ͓|uODc3. dc>EaAi1d4oaOZ٘ Z@'œDgc`0 \JtQL?6fX'%t!.lQo G-QDKt3NE6bzSɼ~MɂwW j10O>^lG0I ݁Sz]6bzSluBSfJtMd1tQ; Hy>[X,Vo]c+rzJ!uSlc,76bX1uaaB 1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a`UBv`c pB??`c |60 ma&4hkcK]QFMvH@V{DX#T,uEz簍1 Ä ~lGQ"ja.%> *@6* pcrba˯ Hb)`c :YEQ =3!'0ؙC'3y`c :76f草6?9d:lc 0a)ӻbCES>#U290Llc 0aۘOaB11 Älc>ac 6PTma&L3Ӵf?bc 7|60 ma&4hkcw~÷r|S>W4ש)HmafƢ:wP<s|sG|gJZ2>aTdcKAjH ac)4z"oaJ[IuϹ^^@! h,ByQ>1* "'H1 8bחDЯht}r4l sc^+)!D *lc 01S60 3hat0`cp鍅lc 00E%a„pac |60 dc ƴ1 Älc>ac |60 S K/抖Mamm^lmc~0 tژ[|{W赊K&n]bƼo V]$;S|mK&{Kz= lc 06FuIҦ7όo3!A{cd~##ӻwz=4㰍1 8>rh?b$ s_GP,ZvC2E>l:1agi7ޠ a~l,`cpu(*60 &0L61aЀm'lc 0A8٘c0lc 0aB٘ڪv`c 7|60 ma&4hkc,5ޚ¥TkMjK1 8XGFM9-HQ}a9⭉o~ Suaj'71Rɡ_H/·6F?*A 9ZQ0̀=%]6F1 Ē34g Swad=FP%:lkaۘz=ZH@SaCGmz]3ǐ2㟉^P9*$$r^BD~ >acp._/dQC1a#6FwԁQw`cp`oacpu(*60 &0L61a ltЧ$0Lf61apm'lc 0ۘOaB7W)^S;jԷ5ЂzMK&R0̀go8~7"G{5|Ugacp1ttkANǼ1_qKی70#^ntw-b^b1T+^,Bv/˂60 3kc6dc7֫QL]aXoOa^¥uՊ:S.3QZ|ަ0̀CuO6&/`W\QE yKC~[C&pDyϰ1 0icCggfPacBO @X?maff6֡dm ɵ 0L"l,pj%mⰍ1 Älcma&Talc 0J8٘c0lc 0aB٘1apm ,v{Iii?Z'a `@ٚtU321 yؒ˖o>S#ZGJ'y۪Pzq[˨L/o46tj5HO&֫cz<^Bo;+j~x)zt  z7-^2uFhc-?]>]$^L Dir,,G G̎u@&rL1PRZjg1 y|:Fd$^;Mv|z/M eId6Vt&% Ƽ9aF*FKքfxR`cdIt6F>:U 1It3vc >Ba(^f/ %<C^"RƘdczkMH=b*4Oboҁ<$J>{ҷ=dUfot65ސS6t\z!rk=dcLo}1|\XMGd׮`uɉG&;%<f2tۘM[6t@[ͼWbc"CN{6&k'bc_u {2'}ؘmazƘG<&3PTmlR^^n#Oc󄓍;1Hkى;v(**Q0Lź׬ͅy^D{ۙ3QWxrss333 a|N6fSTml bwܙZ\\e***H;tXIeeezz6X[n۶-??f 3 33߮i-ݻѭ?uYYY`]vjҦ,݋Q5alcm,ؿ?:.8Ɂ娑T^TTFhdtmp*5a16यFS6FVWWާn7gffwR Eژxozɽ݉{_*ʹ**>؇wm,L())7|::m]ľ};vذJϘLJB1sDm,@~tm,)++KOOlj;TFDl^0=K{1z/@Lrͩk¥ax!LWCyV#bc}lc!Feee U˷mۦFAwl(,, ƆkzfOOm3`=ە ]LƼ' a?zI ɮǨ19'C=*)lc!Buu5\xԍ/p^V#fuf8YHtpAF QSjjUkǤT1!N{1 LHĪm?uW)vIp81sdԯ_B} *)>肛m{@' 55*'@IIIj' }Dwl2=XB_Z{MKKWOWKMTRLzo7{;{ lذ"11ǻ8öl٢{ cUVZ>/#V'c' Qdc}B 6vtm?w;ծN4p25Leo}vv} 333ܵkCM5.ewٝuBv2Eꪷ;X 󱍅.afc܇I)--)wܗB r[z~0es&%JKgTRҹOۛVi;rtfgf姧+%'ٲ%g̔zfOEEEi\YVV}c73)mgRZnrڮyivJNKIݝ;5-/=}OZΣG Bp@8>G1,_e enKAi+JO}6mܮY<}-WDG๛Z o*o߁!C6֭<̌uд}7ӣiإM IbEW6+-٪h5Sh6{ca2N)7w}؎;"Lқ Ӳ49uJoW TTT{'`DCնLUK&ҨY.kBe!KePs7v)[d' U'#?'crN)99EK7 &kMW &gT-~y {SppuՂCݻwضmۆN0ސ?aQ6JE| iKؔ]HEkh 3!K8٘c0B_N1٘ܡRf1NƳO/m,ٺu+llÆ 999&3](<ݞjg٘xQ%a>Xgc%\zڤ.Rw/xK^y޸ ?uƎ|v mSW&/m̳Hkz6u\bQs 1٘kG{Mͳǃ!:vHAfZo93]EacdEO\C7`]"N o{YJk/6{}HgmRwl=gNjyN$ƐԾ!JRW\jmLcsVO㙤5h}r_N,M~]=cb҅G. Zzzok<Gy'QX12Bĭ21,9偐6IQ ac`i", 6&sdEؾWvpPYL6VHU_^rAy?Go %LK;I\plG׷#m<qCݱ1H!m1H1aKu =´6F%uuƄ{p/t˾85!my eVjcH$Ð^6~R{i<kM'1H1|K1 17}2CtAZ/q:RNog&PL; r|)ޅ(^(r*aJ(Ww ^ h8pzclct)ƄyЧT-~ƺOO5 xC}&hQ@?HHHoZGyaVf&->)MfYE} >ޚx:)HAZȌZ+O&0:RqX>*Ӟq 00ꊑ3^mh86(q]^{٧wIɦT-~y"ӊUԂÈI6aK1EtlrlYy՝VgYǃj-߱}{fffAA}=5ꬑ GVcz6F"cE 0ژ[ژd 6 &N˂7)Dw wڬ!0qSXܹ+_15FUdO+?aZ _~״jꥪdg-Z*|q%~OͼGci_Z΂t:ctA W;pӐ i! ʧF( 6m,ZK$Mœȧ̻Fl,~=6dȤI z+-6v^|U⳱g }GT<C***/rݳKRM9@a:RSrԞ='#'˴*84!)!a֭MlƍM9$mȰ\̔])9);S3wZ-;5#JȅRJٶ?)#jk~A6RX]]]}}=j*&|̨{6}MZUlhh_ ~זF0@? ߆vi 946n܌QG zOBGf7jjkȽUG K$$\EIHP 4J9LY+QQ^uAtg:L6рݯa *iiipW uVHg%sNWFF&p[Nt0C#“01?ltS۷ohDt cF*FX_ar,:Gb_&ƂDAAA?[棣c520? S2`۶ei(S,iWE >2 -gr),,޾};\tQB3zZtgc?裁2tL88Sk251xxˑ?sEȍ0Dm2J@/泥B8X 7*X_&z4OBg7u c0V!^ҴZY4vQYhH`*z&@[߿^rii)P>Y-!l_&z.u6G{"oEZdGҩEF9H`X]]k.ݻѦ(&ge:1z7&wF)0J\."_ƷT\i\EJ#ES"Ct䊫51N+@SC|g"莋䔅=Fyt+D2j\B%uCO$\g ~SSSj=tX= SZ *`LC@g 4#B7F 6=%>&anw +$L`&f4rA,EZIda` ???^ӱH6$;:EG/pdeeaQ9/y(j[CYQbC!!Jci^4,b@hי*lcgl=:X$,Ll@Z[email protected]^~, 6 kj8XZ=C9Xvjk͛6lP^^5cx* 6_w8"zfHtowq"dj8q%fDlv:Z$uQ!.3$H(@%HP)-' âu {eY^7a=`c'"?`|[0g=lnrޛ\H{/\$B/ $$iڦm @.7ErfV"b1 cky{fvvVJڕsΜ9sfym+5iiKKK1'brDJ5Lh M& R`!H,[ lǎ])̾uv%/NO]z8(ǻ.%5e7Poddd`2_X LA֭[WVa^=u u'<$5c1ݛ;f|/ƿziA<op?dqx4荄["ٞ*fXRp }BxCu`k4F[ká`Eze=a-Zr%1CK]\} <!Wp}nf;N;j]^ z_-B7?>\o/΁F Yŋm7iz^M6L\= c}]`LѸs"CQ}8.\0Dgi fA"z7XCŹZ~ %ZՠB+ ,c0DYʫW3jZjW1Ы0˟2\bظa#Q %%HQ5Rs3֧aFLߠ[߸ itC %("nvvիSRR WXK{V\NU @ _UZfZ l U YaM;z#x ޚW.YjJ˔/ZrޒТ+}sbVEwnsm_] ټy3n+6l,|saVrUHA0k7BZne.d+ǽӝSlEVd9I +ѹ.~s2$h@he&gcCmmG *:ƒZIU@Kj\`v@lCC* %F`.q![V78._o1FNeJX V/)Tx=>]Tu c03uuz"a #om=ڊGZւ%ӊ 8e+ET> ŭUBEl)bSp߬5{VRrRRRԩSCDB|\B<O( dP!>.DJTxފ6@kIC-%&}Q>wpLu !Bzҭ<]B7>^fK 3=\lyL{tqt]k|:f1u+B-|C֦lꈉ4Hnq15%1u_z"5mG(ڸ~c2+*XHr QuЪUtV?6[qcxQ1c To1ҤIɎةGM>?ӶEsd/'a1^6pz"a,==:D?E,D'ĶL: {"W 5pk˷hdK~5~4{ZZZzm!Lx I3mڴ3fSRL+> n*T |ԩqSi8ijĤ8ȩdXAup)t tո\)b刏IVRB -tYʤ?9 \B-Q>:҆䏻fV'g(AA.&z8=2rWo 7 ʕ 3sV\\LIO/ܶmkRS lϛ~^,<qXB,*Oo#f/{wzpL:~$^k:NR^xՂH50j$M칔3eE+P2= WAMINmdeexݲ1utIdࠔ}P6mZDD4*O45)>)UIPC؂!˅qHH8%qz\fLON"FގOJ\bZo[c$qp.U.ջ27fÁwbgl'Kֽ<;,Dy|=:3RCE a$8@<i'㮫BA&vͺ%.^8sKwS5էqN#pT}0x{Nq0eۉ2jw 08|0 c)F(A):ri: +\*s()K /x;[C鏄{s8ս{6d=eޯym>PS-|nNYXbP`Vӹ|‰?Xx;-{6z&fӈ|4{0'.~ME<s=;tlBT !Po8M-M*=NLqSɥF\z#OQ@8i*{-DwgO238'7auR%^Sh#[+ohɛtE{d}3߰.I?bs:s.A!"އ#EXR84b:>cCh 5/3_> ט~cx†>;Qs AbPR<yqnD[:t#ȇ%C#(ծ{>G4}'dׇ8X[v cw߻1Sʭo~cuyXճ0;>Kc/z--(׿N4Gk>@o^BPﷆJ0Da̫Øi1N(KSQH7{bbq_{YcjM^ K4'Uq?Lԑ(؛lڭ1SÙ|*ұX>3>KRь?N)+ c0:%UV b!!.iE!&a8D!!zR I-̿ȍyk1lH-lж{ ˜ #Ӄ01O6|BD#ĭIApVjbζ< *h-%haa q{!D#ɦ܃T5-oW=vc@C wP~Yz}, qa cMɶߍվ/hCƉ`|j`\4f|UrV_'RyK$CΤ3(E1X`[_8QQ1}&Q-_ppA筣@Rcv 09 c)& E0,1D#,;n(DedHڰ{`7FƎ[`Ucǎ !_ crC4 $P>,B. X!CC8<a cW5FE:/[u,0f/ Ve~rcĉØrcʢn &_1s>{1=\:c+SEV͹TOĜg+k*=ʓ ?+ 4f;3cTUo7u3 SUQTa ^Jm -gUa@UK].n,L u vca!\Ƭo-C&5ME=cUXsV w7][]2Rsz%a(raюay mןusԼsn?̼3q;] $uщOQqJqe2D s<곹[s˭7o+,t_i 8aAUĪtb+g9i;ʟBTx3j!U큖Tz䛃-EEeuuFII-ܢ>0@R $L051F- Eq^IqӒQiS⒧zb|B2 ԧ gO0&`O¶ɉI+Vj]r;񎊝8j#/ h>%(kP";c=aTqqH߿u[ 7\}L]D)æ Ũt9n,&n CY5&vQ/{SCO§0F_}P c8VOp&9Ov ;tv#L~Il<*ʛs<^G};Ńrmؐoj" #a *" =i:FA:]oL֖Z64UGKZ FLK/DKN!TRr2bN2Y}'LKN"Iu3%ᴤiӓMCJzCI?``zw5jxxcG}*;'A76b=ܢ랺A7>^^m/!*μk &O dO缲5[Cԟ\7яx뼍ކG%f[c(7 l7"/GEyY7nCs QjWͳCjw4^~~ttwc_Jpr^Nr }mo-,*<Uo<`ƍ[l>t?z&)}ކ1rUoN2l%-+!٠j*h[xsI5+Cq~U HJY Ue.$N Wj.=/G=|n]^VQah{v"er#apt:mR2ݜT\Rb+iW@Ǹjj[ 3Y:7=جP(-(C%eК)xC\NUo஭q9ssrrs.'1A E2ok<ʲJ:]+(/.ؘAgWS'C)@j́ iD,~{zoxXjYL}. tWR͹! Nt=E-t ᱅ &\QkOʨ@V$r(JHЃ-E!3"i裣\rZ36gPu3 x3::Տl@ F0o}]}WKhdPV7ةk5{FtӦ5Hcޢn;QjpBjTgR@\V[·7%46[XPG?GA'RTTe K38@jTNIIAl'^15Ì gt}-Mx큑 yZG5 ?4oSӑ@N'Z?]V65ͥ_꼩(%555w1zq:u֡9Q=]]+* qwÆ D㗆 tF#u|yb>ݺu+2<eM$zG7:VH!baFA5[P-u}u0Tjκ1ieggsRQV***233׬Y .tI_ǻ淮t)N۠CRU >e  R^M,M[XX3]1 a `VҩT4#OqhЫiZjSe0رc^-[+ ˿ UQpA9#QpO T }Ԫ2= u4Tӈ˂͛7WUUYۙ쾼|ӦM֭ӥB{*E jd-Po]==Bb R cWw)"s`R-4SS-̙28bbcOgVY9Ϋ*++q& w9YHIII"?"H` B.HEC] cu{BJH$7FB8` # DLD5^o t>bT#!z!P0m `;|[email protected]rS\\wuPEXd#y -).ƛ?ZYg@1+(]1 a* /U  &\$0c4WSSq/k Q:a}>  s0kvs),'PgB zk֬F}b9ba,ZGxԿ xw-E8"X; k$6otׄ0d+yiBAcKsbiV6 ]TO#РL#*++_ǻ,//Qm|_Xǖ-[oߎ1^Ulܸ7AװN@իWD*V ֭i 9ll /H#Hfvp|&/ xD5 0™póGjj*?L<0և Bًr媥KbY]]D<I,//D/Y7|' *uﱌzLުE-YX~;!_OϮDcӴr5Ͻ 3p'[1Çٮ`C,X07\>K@=ß~=ڑ0WY~/Q>ܥMaBDEWVV566|k^Wj7{P*UˏWS[񌩇 } Wqx32jGgٚK>`Bb4bLm^ aT eզ:^{ i+TCat;Ђ)QBU#Zl92CkѴC;k5kbuY OD¾]!aѪ@r<[͡H=E Yr/_ƸBT|P} @];0Ž̒3́.| $ݱc粥|xTǬߥ9-Q0f}MBDjUʒ%[6441u.㍠! i\!Hs]io H{:cC*PG˦+D`6+">X¼N;gӦM ~(++۸qczzziiu+WvB z֭+VXxiHZ-!-^d2L ˖ĴT,]2tNYo7co4wކ@v^FN.}-DZ4oiś +WNQ?hnּii$Y(_F6@ε.mݺקܹӴbvSRR/[QJcU%x"K PSGtA$7jIIqɆtcRS8iiӶdn8%7eOZ~)]X(..FHCLECLSD!j._6Z˖/hK/c IIIӦAIJӦO6cXVyuܥ).n{T|Az{ Wc橧'zd}wp P mR˖~,Rw}FFF/ච;wq$%Ĥĸ8ɣds@<MB4̝;NrxC :I ,ɺe+7kv*7|IMpҢ~|x@!̤_  c}]t:|I0DDY.)*UHM=@SMޘ<Fn)Dӧc x衇u?:ok.*ú[ `lūшNiDiXhK8ZE JqOv1egg(ԿRؿ'%[Prbix$p$!x񲩩[XhwB^϶p -}t E[dB c؅>AaLݻw[aLPԃ<I^cg@Yp{ Ϝ}H c3Jv=ys֮Kӯ@ al _EX ˢصo*NMNbϗql='to:M. sYVduF7 :]U5ZL:;v}MZZ>F:!a)ԮFأxk~x ׏{8Z%r/Gºsot>0Eªu^|X8@gED[=Tvgjs==/r地;)Yٹ&DQ63ḘF*POD6AvEcr.QPc32Cup?`z'G?+RSOnVrrru:ƚ[A1hޱ2!%4r`}ݒ<X]ر<\Ɗ|DX?a c OOLzWԔwKpQ[BW߶~gBۯ>H`-Sg<k>8(یOk3?wBI4!ѽ[Q_BԾz,N3h\Cs.UsG_hʍvՔni m=csݚ7<?jmiVGa},հw~~d`~'Jټ~SAS `(yv*DtD /U5F }B7<\ytW#P%bZr?E1l6<>vدvrPSڸιꀿ;ihYez8WCKHli~3G2PX^{VhFElJkP,w4GYu?DDl1RwSlaMW"Veo-_\9gE26d/(&ƚ E1cp&HvGs9hbdw0&LzwGz cVݗϻ1l̻8f8Djo܋BD&d)8& ϋM/OCh 5o?eMzWoY!V+{ D51 QAˋ9- al_(A96AKuf{Y};B k#n a A'!  kEw|lưD h Be<T8yMto:D}[GSr9*Bx !!]O,06yS7x9Nvx?/@a"Gg&EuEg( %d cH 1B<0fn Hma c.`j>ꆛV"aBB4B0CUȢYlÁ41lH#?Z&*\YUC\zU;$5qƐh~/ ;U1{X$ ې0ѝ蔎_al2g0*Yx8EH6hQ !b!!yūKxMLD!.E/%*ƌ UWs0 ܿ{1DCPG7a wWDP[߬a A%ǖPa V0gc5p[’h cZ`u ؆sn b-! أOnE>nDMBb^Tc0+k9KC1c7v4!҈^-_쏝<菊Χt7UL50򖏝06ܘ` ch^ [!Ae;r3 ]`؍oZwxdQx9;r&,3Ɣ91DAApxO=/0@RpcXARՐEjii1s"*6P?*|a 3 cz_į;ʈjҐ1$ Aa G^"36.=c6EZZ1tOcƌ@!*#;v?>˹ vcU0vV!wYjQa "Q ݑc\fkv&BX` cn,\t͍u:zokW=cVa4[){nݛN6@Nt-3= c!n,\u|c2w|: 3fн锅rm'\0l[ں~K}y݉N}7p=}d֬;SwS6na %]]2?=lk[Y6r?\cH'***R IIIkBnEt]p[p Qn+fLn-8|X y@8p@aQMlڔ1m4}Hrr򺐟>:tEqqfV ^c~ '|Z  cB05YYYo  cB=1555W]!\HzEwØInnMtFHzErRSSKJJt^HzE/ØI~~~zz7~D0&p1Y8OL HzExØIaa!Z @˜+(mO cBXf͖-]f/)--Ŏn Hzŋ`tٸqc^^Ԃ HzA;X۷oOIIq:ػX4AHzN;.a!aLK]ߊs{JVު{oplTsfG(!r06)=?qcHB|ۆn=a06ԙ7mOC`m9 N70&B/06Ա1ro-:Uc-u`5|ԡ V1Kδ[--.~{=Şgm{~/tAh$ ula"SipGH=:Zp 6D}1|Ec>WT]z>p)}_f Ԓit'5޴_8B١=v϶"!1:>!!=>ZFC 0&N[7  ٺ9~D mbG|e0%V#\32˩uϐe$w0`(U0! A5FxC3m~dUWQuƖ6-HDP7 cuȄn Tk9ݛ5~amnY$}C=c`́0Fk?%v%1*n~KSn,M*'s:ƍp1Ɣ!KEP(D5=n]ču,8fu*VYȊ ǟ 0H\>Y.蔛o6Xy{g 4Ƅ'zчm3u_먣ZhRVVyιoZ(df 0HrmܸQg"\銕+WTWG! `E˜:1TUUv1YD D.; WQQ^SS55xA]__ B:4ɺ֭[αSqfPΘiA c<Ac@%_=Z1A&EQQQFFQЀCM,?Dz͛7s<^" c f$*v90YcFZ%s0{:ߦ 0x/j%uA7],l˖-#B!a, E1zM*0H aFYSw.ΚVaaaVVVii)E b$tx1#UUUfA$E9A9[tJE2fI<AcvH9}Xj?Ak0_ٰ_Hp wp˜mM8mӹP~FXtG!ĜH=Q}`,0# \n7aLx)BUT=?D"Pk @RRRQëLxU-a+VAޖCh#u։9~FXt0 |d9̨B$ Q_MEfVa3F7Wi[mAʇPNT-jbHCB>r,ںu+*#*p .ؐ7ESUkRW+͢ X%L cэ EO( P!,effcݾ};t[í081Jdϣ>WVpkT aYTT]VVFEuuNmp1 fYVKZl5kPvUځtX`p:/B a,dL.f^3%6z <q+W?>["uaq21,!ʚMT!qZKuf-:+)-&X3~aW(r i@ASLpn` -Q5܁*,,LKK !Hn|&மs"VxNԫ*ܾJB)h᪥[6ecVWQ1\V@DNࣿau_EfZڪQ>oߚn͛7[~ . ! YUB5*a\PT]"-_U0ڧDngP=&9Ȑ\ B0xk˷zދ>o33vg!:3g>nig?pyZƩcVÜ>O]vQ宸{;~EƌyXYci9:s3Ϻų.zv6ܲ| x}gIL J3g<.8‹.",.| ߅^!} Pv!_SQ1c󹐄.9ywCۢUj 5TsІfV+n .8KKIۂ]@HCv%<|/sOee7(覴w1qԭ-&)dc4Ygv͎:;Nszzeat r6_}yEE˓T=ʱp6goڒQRNSPVݩkǰaða2@&(b!u ހkbZTLuQCn#Fq0`)1=nQ<Ƣoc} 0qǔx%$咩1:{cg?o}pCj8sz<x4՟<\72bd\㓋Դjjjk8~qG!VKP?Ge}x| [pt+00aTprNCԔɱQב/X1:@o^B0fd[[չj==Զ:t!@s#61, Q7b)6/ z'b9"5aÿs`:XGubrwh/Ço8P#vw}K>oj)Qh b'/haGƪ  ף];G˜  cM}SQlDil%VznSvmC\^hj޲NӿW߶bA:ՆVag;?nΟVݥFgoۿЩG)KV+W_p-tY[!nFZaKKˁO=?N{VϓP~М(Okl%V wvoz@?iiݽ3 _5ϵU܅[X kZ}u8-dQiU-5d֎25Ј:`w`6GuAH'ܲ>N<9&_}d-tY[!(;f=s0ijx?XSoٿOVyjDYXXr[U c " ^+c-G&DIJ?Ci9x%?UB>}q8{el :6vpVmY̐Ua=dޜDUt~Ջ-tY[!X7|qkڿ]O{ᘵiH_4\06kzGE ?a,fDABCܘ$N cX? ]ih!tyƬ:l#RSbGvP9!0*,m*݊ y$E7ޣnUNh3Ri "0vy^hQXxABL [L:0z#a ]VVa#a,q6V_4%Tg|B}4?1ԧeuz/=MQh۱k'8np$)o)vZDGl#f{SmΊ%FO=wC]<쳿[O)W8þp 7*ՍGObXE۩?HZ+c#v~_AuNFF5,uKsnE<ƢZ|{\5f8GF@#=4 G<;˓gtm_ZB<|>lK~ux=<n9aĽ'{CO%9i&_z5NSm߾k=z􈑣GEihGĒ4rHCH#Q45BU5r448)tMUoQI#G>qP4z4 PeD>456+ں5_[Wb!Oꖮyrbq" Ƣj_vz<Foc#eݍ$ u&Rȹ3aMFOz|zP_`訄v !U{5KC]hiE=ǃ:v=O'꽴D mՁUƦ;֯__S]vXPXjZD^L̵hJ`ͶmtJN0)_m1㢟Y!# qRDju^=>ixjQHkcu<.wcG" {Q UZu(bQl?ZZw@HZT[PP[$v˂~y(G: ǶMV0z-^k4BUއH0 d` O&z ]zVaL)fd#Ev GP(ڎ*S 8A,YGQJoZ6C ݐĶ cmCC#lSYYyYY L{ ָ%Tn°"aLBD s*gV!ӹv̮vxa>SdMf@ (!D$ CT\ W t°b:-0333WF$ BHۜ@.1F l׮]wE˜ 1!a+zrrrڇ1!D$ U]]]SScF˜ 1!qaxY&55u:/BHD,IҥUUU4ʁ\yA:F˜`߾};f|8lzuԂ#*..A:F˜ZBg >Q8Ƅ ;c W^y >X;LO۠" cB)..?L2wʕ$AHzȲe>5j>NYp&1H coHz-;X>TgT:6&vs8FٵZGZ:ՆT/8ffN):Ӄ0RՆ%W$&RNΚL]!aL Hz-QL?9G;%cLfE/+F&$ƨ(;Q+#жZ[}B^P GT8p`_p*j ;=e6:^:*L#!rKyX?zk#VKk5kv537I3ʂ>nݎOLl9~'oyȢڎV&%Ʋ$c*_{VH1a( aL!;@1/ىsB f@Mäݘư-1 0kC6QY{f\>Gp!-aO)0n(i~#!?n?mׁ {'aL HzH_CLҩPP1{cdF:k$ C cBYbڇA4$ =ROCzX]NG;нA1礥ϘqۭL"z7B UVK/007o~YY j$ Q1A!0& D1A(F˜ HAnoA!5 ڗ}  c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!06+uNA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ P:' Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B D"H$:0&D"QJ˜H$XDZ#Ͼ2d<duUp:*Dll"\C .[![ByV!e<duUp:*Dll"_Ǟ|iqacs~sUՉc1&5'FzkFZO9Q;Ff #N8~' 1^=rܵ3j5h T$蚑Ff4jhiulkFxYO9;zęW8Nr2Up:*Dll"\C .[![ByV!e<duUp:*Dll"\C /[E@c~E߂(d9yտ0cgN:qμ~O9zQg^q˜:J8\DK75ahXrkJGrb'iWF1c~u'jWs nr2Up:*Dll"\C .[![ByV!e<duUp:*Dll"\C /[Eݑl5{'^Zxek!(*kUK1h-ȉ1ʢHEw~u'“.3~qaUs5z0WWx3SN=oo8n#sҙ̫N͈1W闟8]q9[N>Qcq'qZ}hX>n{% ؈Zל4c5\܉tc &ӯίzY>N.'#[ByV!e<duUp:*Dll"\C .[![ByV!e<d_LVʺtbVO4\~ïXW_39:c`6F޴w߻&x~ȱ,|/z,bdWuBGdNtŊ֎Rogג/:>~1q5dv9N9y3 9Ѕ?q_FFN}U2u/?|_~}DxL1k)g&17̫N:μ3=~so8kO>>W?>x∱W8ˉg]ukNwͩc97rl,{bBByV!e<duUp:*Dll"\C .[![ByV!e<duU|/ ]12۪!dfN(.w$ke. E#Ǿ2,=:IDATa+mZMN'`ta7 ?Q&ؗ 5ݑy}2VtOj8ض>e6fV*w X̽3]'6O{_sx1ן|an۷7__g%>E<wf.xጋ&y</w9w\vM?SOdf֑x:λ_{Ÿi'߼fug༿GUyGw$kis=Xl"\C .[![ByV!e<duUp:*Dll"\C .[![B!.V7ꨵvOO0Եn<gއ_1kBzuUboi] f؞vW5uݕi`^XK Ա췓cU&*[f/F5⤱N?Mh呲L8y̕9׾mn'={3>+O=cם0_zq]8/yzW O7wj¹W>z`:{=3g|ziy:RK//μ1W;m<sNU*J?+jCcHel5Y]1o.+ku_&v:yˊir6VUUzGR6 3T%AeF( j|aQΛNUωe׺Y*Ǯ߱FH3ړrC9_믧>|eSŋuMϹq#μvm9G{9:r ]pU7,y+ܫոko<-Ly3.}5ϘvٓN?Gbę7ܫN: r۾}D"H$DC\]l߇ߐu͕}rGzBs`ДؘfUpPD6 D>|üp>]1càruhlhG\hY]V1axȳ9Qg失W2~ c&Ow ;a#Ϲn{OU?>sՈ&fm;cჿ:S~w֯-v5꟏iNċ?z̯Ϻᔛ|hi8;1&<i` 9a~A]xCy1GvFβ[wE"H$DC\.ʀfdu6ud3g]M~xg_F?ixԱ7uʸ^?z'qbiO8gԩȎ<Ϲǝ&;gMy{cI\߿rٗr'r~Gvoߍ<~_'1akO:lI㯸+O8/>?7g'?›Ko8ˎ? ϾӮ;+1c"H$DA1ՕT'N!~ ¡\w4w?Qg_7 '</|oǍ>{Gϑ/9g0juN=n&pU߹9G~׌>ʓ^s9'^yOwco^~ܸ+{3'SιnY׍ȱWs%-M<iܵOu6rhc뿞z֟Ν0c.\$D"H$$ENgElm]qTFyͨ׎>g]s+G~7 Sն^4aX+.fx%$E1]ԕ> BkGv8z\>W{v::tWx'PMޑH$D"H4x$~l$.c`cEOr'}`D\X׌׌ JY5a#¿M1n"TRv_lμjکmTaxM<鬉'u-ވ3qU'Ү5H$D"hHIc&`4I9t\UeFj? $2N^Uc#NF[^ʏY-lưV}NN+GȒ[gYq]" D"H$ *bD鱆bҕZX2ieTSFK2tqվ]mh$dԆj[]SUTD"H$;śA)vl5;m[N'n}H$D"(J$~l|'5u.VmeorGVeH$D"(z$~l|2Mр+Ď٪D"H$DѯXss2>_`[wj)y=\*̸qOVo5^]gNƥL>h]BdQUB|ȗ"H$D"Q?FvwtKMA}Ǵ/RH[BmV*ve|E"H$D"Qc?oϔʽ[I*f*T~vyvEnw{YW{P|;%h70*m GM v*SIm4`Lw.vb^U+-D"H$SOm Y[R}g *4nF)k.3E5q-loU`/ҝYۦPe0z^]ۥVm+=v?2_iH$D"H k׉"y qs k4Q[w=g ʲ#G҂i'&vRNʹJY@vhTo\ٶ(H$D"H$4uqR?<^Ow|8~$ŏD"H$DEWZ$D"H$EďD"H$D"Q+ȏ0?UW$D"H$D}-/c"Q8K#PN+taH$DA=n߻n;n}4]Ռ ut[}Sp((ZxAIU]cZeSAW!a[BG"v D"H$uÏw㖢ԴmN؄B<m6@3κ{[ZC"kvBbK®?pӆuTۮcz! ďďD"H$Z"](3 6nmmyL߆e;Q5;:.cΛĶ!Kv/7> ~ᤤm%Xr˭(autscG l7|{T%c'f /+WgM? E*s܏x>t)Allg]?哓#sBKH$DA1]W7py[oӑӉ%pZ]l=J6`^VWf=tRi{ǬmY] ĬB_<gZSpsynW#(Ѽ'S\̏2Z 2hm͘B^UtIvBc-Dh^KZedYVM7e\tlYm+c"H$:} ތ֢"clB6lSWA-1mj|K7 QڒMKR:t-V%Z󸚥tS|o ۪Pt׆?>Q&Y4T9=^i-\hȮfLaUdXG~ j׌AhY E+&;ڌYB[*=$t]ue)nyJ~̨N5KSAl;IH$DA1w?qkhqֽݑہzpY^PD~nmK}66o膘at:o֎:do뗔Uf:Ť$ȽK{0cEmU'^ 9AՂC{Lg}^?h&l13aBGymn ފ2QQ:D%['!ՏQIY2yi|rV57JH$DAmn^Nĉ㡫]^[%rte5gb1˼KFQ,v+٦i$m3crܷXaF5cd2 ,wG^aeդ!kB`)lUHcݕ-?^D"H4(ճcm2s誗,ȎAm~G==DU>PS #,6[ d>{ezs?9KNB3c?~KH$DA(%P8;FmPĀ.: @XďD"H$?&H0<.[E"H$ďD"H$D"??$   %AAAc   1AAAA    ~LAAa`?&  00AAAď   AAAc   1AAAA    ~LAAa`?&  00AAAď   AAAc   1AAAA    ~LAAa`?&  00AAAď   AA!_SahZ=B   cCc  Y:AABA   D]}%O^0լ~aKܸ(in޳2Qfw=v[Ur%]:s.lޓZVF=j?ws_yc+E!V|0AA!Sf,௬tPM.0E%1ls'ƈAAȢ/mrM'tUz0s?'㞛+k1AAA,zչL.[@/7:vOO0Z?&  E~L4AABA   DdžAA!?6t?&  i{an@   D"vSǑK   D"c  0$?AA!A(~l{u. g]n>,zQhYoLwN۟jď  K?36,{V&Qj^37LX%~LAAP5+ys5n^5In57+V+kcT򄹨Tp1ՌB=Zw`D~lWBAAL{eNz0Ț.˚:"bY .4q[؞Ɓn*G`l̊1AAAt5LdgծC6Lo'e3m1"ec_l٥`~ұKzYoTԀa.ď  [L,Eۉ|ď  g~LSď  @XnAABA   DdžAA!?6t?&  5K7g ~LAA" c)G%~LAAc1AAA@ď  K?aKxfsJ>g %ByKg\I󞔩F+AAaHХ#3 ]:ۼF=Y<yyœԗ.urVHq .Yv{a`m:vQcc@5^զ?A   c&)2]۞0UF Xbfjɬ`x9=luMXZ&iצ?\9*?&  C.Uhd3F&G^|f^թ n*ZשFdTH/k5@   B?fż[BX?&  C1e~P ď  gDŽ>E   ďE z/ݜ1AAA,ď ď  Bd!~l ~LAA" cc=n@   D"vSAA! ?AA!D   cJ<al@zCtsNU:yOTޅ3l쫹y'w6L?&  Cc:#`.q<· \`37:c  0$zu(~Ye7hk6ԨxhQ5u3Jۍ)vw)kǰ-ZnU칹[0mB;L􇁦Gʹ6%!"~LAAc~p1=afcQ1Avd^hOJ"X#1VsE.Q5k-T5>؎3@f>mނO]AA!AH~2TtoJ.{P"=r50xZVwՌ:v?40<S̸|T2njoFY@F{5$AA#c9?3Æ2Q &"ݏ?AADď  @XnAABA   DdžAA!?6t?&  5K7g ~LAA" c^ ~LAAc1AAA@ď   D?w=ҙhnWMtG47Y|17tˋ\ͼKz^n좏?&  C1..EN u.Ԅ2 $-XSff f Ǟx`ʦڭLVPmwh7{bcYǂv7+k_ YWuYgAA!A\f!]1j6Ɖ}m[ئ}2֏mnS6gl~>T!~LAAcM=ca_؋ <;0H;c{W͚? ԹkY ҏۦ̸m^e14y?c   tE~П4Q'^3?&6ZÁnKÀ1rV3~!}R3z?&6@% & c9x7   tT拏3k_67uߞ:AAA:@~$~LAAcCc  Y@l;tsAA!?rc  @ď  @X"~LQYYhqK/guwwnYSse% N~y_ɓ;,W47Y ?,z3יC i|>ItHj6Ў:@VEp!cې/O^ď /}puaZ_x1t& HH~)3n!)wҟMZ_w,6Lٳuɍ\̀edq\&Zo?&~L\6!jWFVO  #18a_w=1eWo+ɡ[L.*U4w5u?~;'  nM )賉PP<N.ښ:.;4! rf<DJ 0PǴ oc9Xu:Tܬfw0yusz[#/~ѲyNal~̸?fMw1A@g~,ƿlk?PoO'Z%v(Eh}_, ,7R~5^ď E~{R +Ə)륾DžrInywC?FL;5<ڱ1VZl=a+hsi?\e@rNpx_[ v*~LA~ ?Vύl(U-]x H&u[[7^ R ?pI;TӆتcSuhGjj[lnud̸:ɿؤ&~LA(c y'et~H"~L0Х{B"Dz NRj }5 ;KA~K>,ˆ:3=~]̛iܸ_՚>.W$~LA("͏ @ a ?B\Hly4MYqm^oXwǨWTrȿUTcM<c B$#~,a7{ ď Bď 1AZx<ȰQ8.3sKYYҧOAcCc0p=KfpĆo:ֲJ}pe۷o߲eKZZի׬YiӦ]OAz1Ax<XuZ;-!Y :M`2334>v؊Bۍ7*WUUYYA:BXbX3?&۷_e˖-al z,Gzz:ڬ czǬU^fdd8N]˃뒒 m6^n[A*"vStGa0K|'|\ه[OhCqq. c&4p;W.((EQEmm-N8N ^̴4x6XMq\0rMa#~,?&]B+==WpbzuME}CjWTTA^ <n`sssaqສ m@ď %%%[l6 n%>8ק~ \ eZ$cIUcé[m F~y_ɓ'u577+~Qfcn&w<׼ҙ[&/F]uO({ 0BknO>n#4+~L۷!tB /٨`ͫ~c&. $55T mpBp* iii(A=+ 'es%]l+(UrYv>,zOFKy7.BTG.vO^v}j+6 Pzuv!~ >FKOO~k/sq+7ߏYy+Op֏Gfdd`TLa K~ i @{W2Yw`}6f ;xG6ȏ{'Tux.ԻtHda>?ŧ~٧͟} ?&a fퟯxu2Gyy.֏ǫ.BF{QQHPͬ):ܱ鬺 7z-I#A1}[J3 6qF +x2[`eU?vL߬T@MjZy#OSc[nwqq+^09|ohJ@ouQdfff¸br8i^p=_O\+Wt==Puی֏yL?zWI~K?{ma0?c&tfP~?1A X,-W"ײ+V*шW%/LϥK.6(,,+"Rp -[,ryJ0].G ӎxR坬hTBXkǨdʛ3%B~,\ ]'_4ܧrLRQQ_JIIxIdS]] 'Ɩ&55N ײz]ăkn9 .T `Ƹiii?618xE-**˜7?w.?̃ezjndA>W-\ %[(76oa[YY5ڛ1Aȏ >O?yPpYիWWpUWG֭c{`WG8 T0l0`)?9=?wqbYj}zw]Kתk}nwtעk*+kjk;w6x몼}Z~k??>䓏_͟QZZ6قiO聋/}aGzꍧ׬Ymҙ`+^)))Vt\Gs/9uޅ潹Dp\׮G;Tw3^}eza"'hk[&Mv{[C/]60?f-X?j>y}Zs\{mՄ.: {>};ߟ/.>}磂ҹ&U>_J>8o{~ |qKla 3^MH~E cfcBYzɱӏϚr}秪 L|. QW 05짟/[Y^S\\Bc5⮑֮Н5g|{|` ".?񿰰NO/--'kQϿc{w8ZԲ*\\ b-éڑ篼^[p]^zJ #147+67DŽ˅g?gsJwqFa&*ҝ>o.᏾y!{&׬:f16?lD(߾[<Js`'}!\TUUoݺ 0eeggu%Ŷm0}-[ Nե{[.H1G1Qxr ;vd#1(9#1!xb[bb$ G ?Cu>Ta.Q}X п@l;>}g~N?&ct? jjjJKKu'w|\.f 6_L7 :c>,V"8#d8Zeqeaj99 B#dwm嫭Êm>YA">?Ͼfŏ =s?fVE~³'j=mJo.uyi[m{o_۾[|r6N}b=aZ>_G^??6oZު<ɚm=> T A?@#V2v=֗cEqqesrr.vqƤJ;hSӪ??2ZeZ2lXX;ce55ʏѓ<X&#U"B?lUvtʟ4_?&.؈,-mo0~򥛛) >i|w?򖯚ۼi_ܬc;ˢe~Cc _"m[,* `Ÿw[:N QvM?rel_K Ul 5\e]ׯ~,bL}qY;+gUi6f' w4K3=UfQ?zm~`]}fuzٞpo=T/oV/A?5ʹ /66at Y,}*~/ˏjӬ~L*iFj c4~ֿW *;; ?@~,&X,؃NgӏU㲫- cSYnSN-|০;x-ώoQ&͟~)YB؋a.vUkrY(y=ZxLϕ-?fz$mYb`x`u؀}2z{*m13Ktr?thm~z)ٷS³c12+\V)^w fUm Y}D1ub&Z|Y'?(,m& ^W~9+ ?f3}9+cQA~~?f?t bi 1͚+?6JbcZ ?Ì sŠZv͘RO&ݢK?ּ肞SfnF.;QZ߸L-47Y|q۟xS!?!mT`vx3 Ī'557ia ?<C119_Xo}K{ͱ)qiiܦb_vlcf% 1ldU~w~csv_1uNobS1w%t}9Q>ز?u@SYla[1Κpڭ~,plF1UISz c\Y|'hW\XT+ǐ3-5mǚZ84<eX,5 ?6q7f<5:q\7BOH¬Q ;aGJ`:A7rS?۰dffSMM O؊̗lj𔣚uC1cBOo>g&X)f1ZcP~^$QǢxCv3Zw|ql =Sqwa1>`èu0F٬' * ˪J+k*ʶfggA ''#n,M? pK9A,.1:f}ccâ.dMLZ;Anm{*5 i[7n{Rx ǘ~,xAw"ijY=US}a⍫L3f}^(>5xcB/A$.,,|c$vYB\ii7xy2t| }zͶ¢kz~~/.՝5qQ?)'HTW<VkCX6]t[1d9bհluh{β1,x9a}Zuy0OC<Ǎƒ•¡)F(VZYYc Xejkȱ)VƊ@p1E |{010Wftljӈ ?FI,.P/pc-`${ }(m1kM?z;vIU/K+6uyEc?&t B# غuqsY[s?/'sʨ{FΜ5&V/  eN<=F8uxYs232|iNqՒ)ǝ> +v\Us[ᦰ>g;l-zQ=ikA?~%D,u-Ͻofe{5t/ONSY'qɟ:/,:)'4}f{{v4ռUO㯐_!=C{-޺\.d;f0fׯ_|yJJ bǶmPF ##Yyj.AD-;?5˸٥2ifa3X`Kge'X2Ԅ_Џ4hgK!UgFl~*Ǽe۽!f'ڏ ґ 6mљ!γ襪 `FFGuQw_RRf͚|j]>u o]ې!<>7YTB nO]_n4Vzk\;vԹ;6l7x})pBJKԮbC ،1YYY6lذu۷N'ZFi%\^!QH~, d= lUS[5`kM4맟Ŀ>5`6ďY?RPP`|wlm  zSSx+]0'>QzkYP.JP]qֺ<XWO C[[Xk04>d1Ϧ4H(V Ӫ:1e˖ eD%sE ֎뛘mҎ8a+t&5[~&*Pfzf>3?6AOfCc5YYYk֬-E*b`'D(ʃF0;Z>x 6\ZǬU oF~JhKZ"%JU oQJc 3v:%%% /QHὠi0-^Ĭ̘upVcVXc͟ K&~lH(5̆1+" xqX\\Lp l`E<p:OO'ԓPtUr2SJ^JH*kKChSez*΢ 5}ZZZ GqF"Qެ3̅XZ(Ag}٧cr, %HD!~̊4}WUUatݺH<uRDZa kHc 3=Gp>e t dQz7 iFXbEjj*N$Nqe_uC}ee|bsnj?;21}A""ր?fEX배"sCpavHpNuAoQ]"t>v#fiUZaXKiK.ۺukyy9V>6{Kդ޵ 70cǢXF!~̊[xaX*McHj 6]ib=@2 mO 1DR77ӍNf͚͛7íVݣp0?6ig+#="zN,RP<,2AWk"$ -Znm7p7lܸ TUU1zp;ՙ>;X]. ܮKYYYٗA_ ϗuu|Xг7H]ó@,L/9%YE_/A3fkh7,/8H#QPPrJ8a8R8Xkmչ4^#P(t foN~X 3]vt.z:C+k&7s,RXXaÆl$pd~#kM mp6Ph-mmu a*j*`wjQQŋ'-[۶f}AnUN݇W :;j!]>@ D榤^|媕[/󎄰WLx*//Ex/GOvXt)L^7`"ڲe ::%]ԔBp%\g m۶Z /yxŔ[]]s53'RmyodF=sV*NpDFyee4H~H^^?_.m QbWE i0``⤁#*@aG oc׺Z7?6t?S@. R{C d1r!fqܛ6mM=?!?ȎuNF- 5BF׳@!44Qջ`tB7a#*qP[fLzEw[+]TФ\ 5S-,D!$Wi)VpoO.˨΁ g8UD 9^;{+՘ +yRRR=t z^YAM k:x}Wxl 5>hѢ%K,[ qQ</&'u1*TTΏ!K41]~6LA60K%Z WVVV Wqq19 644 j\yC $8*1!YDXUCG&@t*VO6T 5]g Cwcх~,!~L74CW`mѭ oG.K332Vez%%%^_0U566"`c'NJ^:ܾ9SG/C-!X- P9]0i{ m^mK=Pز x ;a^KaMky:su!LA8)E..)F9~FaKཀ-]#[ 8 !\TBӁg 9kj}d0 @D`U>"^)-[ M-b@ރ^„CW4?sڿ9p8k^\Sŀxg%F\,_n-??!T꼅{B#:i%<$}skVb4 0u0I5Oy/rǧZV.oY""׏]M ڡ[@h Or(zPazث_>jd2&說*ӱ`BBԫ 8и;p; ȾYf,ྰE?z iTK+{ sN q"Xsz\ ۋqJqUUJ$]5:oÎթӊJKvxU6^└m#/^lP7n܈K^wfGp9H]RG\!R{\;]. @ݞ:TT`2jNW[ K+*Qªr:Tr54j+=M LeznQD ꕖT (Q,afDDB9H?b \NExCACVoK/ؿюU}:`%91Z>SX]]qa061cV]:[EfaJp!ɬVT1")syKSJ9?]%VL^01 Wt޿o?7С|{|"M~{kX|:(B1":ZAh5m7oZۙP}:T+>~{C_aWTC%Fj޽.q5'!0w*4I|WclфIO?=k;w߽BݣEkfbIo=3gђ(3gB6PSB{Il0s֬\ +yWEKNμY @uʀVsU ;>}w}_0?7/M s<^PWޮ;jkoI{tsϾ_i;?]1Hɝ?TK]?=?9c`{~[3Nt'\E!NE07?:g?Hwg&#s<c91n]$OfenxbgqwwWrqee;Z=nxW]e˯yn/9fU81DSd~{~{1Gm??M/c~r69w~w}l/~۞_;뼮:>UB7kA*%:wY ._á7ׯ__#D>*< ZV>PuB.宁7ĊzoF-ϫjO_߳;~ EWHKU?GJ_jI⑌H~y19߿w 3~yL;}CѺJwEc>tU (s68^!z\?VYYw^ّ#-֖hA[[[(?omEi*J*U MKkkK zGVf#6 Kq60bęӳ.v*TleKĤ3%%'%$'%$ģ0!1$&&&%'c5T< %$OOLmh $aK1ZEۉq ]Mf29>$, TPaZ7-Jj JKA&I^>O]HP2Su{=Z]zu'>q0ǤXT(13r8t,Ee3D *e\.|Gۺ Y0V8E9 w}fK$%wQɏqYE齯tp\p$$dBSDS&0rdG MAjm\@̊w8b7|]UWΥa-.oשl6ap:UUUl6ꢢk!`ƊV^xť%Ӟ?[j8@W$Iة1S1nɑ*]d6w8s |SP뫅% 88Z7RŏE8x T֛Gu> Ë9t .:HSE07䀈aB)B$o}PFo1:c( F;:|TB=7Pvؑ3w \1jnb--+}@H$vvtz%O<ddP4}dxرIq:QkpJJIq $re d5R{ӕQ.(!.))aZ2 wozXs&'?5)ajR"M1kD 6DnQY>e-_\<'V;_ .O9*v0](WB:t$!6>m:ר{FenН<o>{f^z9v"_V^^>ށ7^uw~[_qtܤ̕4ԕM\_a3YaP\ .+D0Fן)VWct/^Dp 6`ҸK ,';'---5%u \kZ*+gKqi1u)ç|7fB 9xb8M6<4PcIʦ8^zeOSuM_5ďE8uBYЛG5k'9_}?푯ߑͭG_~CvЁo:@Zh呏t @#呕C &-Pu y-K+}klD7P~ß}`7G>;DLA[}SgQOUo>#e![hT>#s7l'dee' /Ubοn4yrRr2Yq S&N[oMI.iw:%i n6{=0)9뮞LNm7zԄS>yZr\|RBrۦޕtf$N:=iSfLK>#a ࣦ݊OM4 /!qZ|iIw$'NJmjRoIN@mq>eRҭS<:ۦO8-qj3_t9n,)nzҔnN쏉HH4=!I{e p._O]дo**}U. 3. \QM…cdpI)$_sKGlWbDG̤PHďE\ u{ݦu={LJ<nNr59qKX\"n5gUշmoQqPYSNzEW` ÄC_L+sUw5e˖}c%֦۰qÖ̒r(9LCRQ ~Fш8MG è3Gu׬O%${y&8ӹvOЏ &ďExɴS W@)عŕ rտ{%c_9 OGzv/AniZ -+>YZٽa***~衇.V+w JKZkWͻrzg?ˬ'tUi/}Sϼ6fi'{s3cŊu VCѠʱl﮿{0 coۛu%nlHUy~7~n)r؉5% CciQ|&sk?;}/UjUؔXDQ*I;5ZJūr\r#HeecJ,9xٲWP\1fKtL wv97#= :sWFfMP7Wyԩf [nSO55?ۇ5A Džan&\YC|v5r۩m?FiŨ6x c^2m!~lUJJ#p@oͻ$qre6J4-S ۡޥ󼗲[Iv"զ.+\NۨYXKYo le3^¤}T;ßս:{>7Mضa[ _}YT{9ߌ60iq'{ ֿ_rr ~lK~M=Q͢f}cf5g?vY;oW6f=_|^,Żէ[צ=3w`c0cP1$>1d}_?&Os [_JޡzCU ~,`VUomcmܽo9=z)Jle?36ɸ`H1Q8l5'_w#j-{0$lǏ/ݎFs<3۪Uu<ά 2ToJc;zkӦy& uHjU9O*Bj.oq9)qg K6u8yㅪ2|GvgcJo)]:DT 3d3{ƍ>h[A>iӷAwִRI=~׾rJNl]~cʽ߿C~O?j#-Ok׏YjXwhq=vg3>6gҼ4kK{~ջ{v2t$Pwɞ}\Н>zcov`#H`àp]i/ YlYmϴj u>˴a䲼mcJ V\wvk3l=k6?.ɃMSȭcNkةڏ=1XeMe-݄bN6>H [չ6nXȏNLɼ5 Cc,bG%_ Ҵ}3;SϽRuM_'#3?N~LQň:DKM]dZe钾 `"~c}i"[_p5ٮ͏E"ďƌA܏)E#]`zZ6mKf_B2o2vb&8&:s0N }q敮юu[L2惈|ٲ5:U7؏׼ꪗ/)1:JO_?cC ӁOuLE?xٜ6a@3E~1НRRgn\RZZY]wu>VNZhUpCR#~l~,==p jQW(4?8{+J {**"ߏ=C>{f^~%v"_cϼ 3C'\cz啕6nCQ1PDUNJpz>5AGƌ Q ϾbUu]StN] SOXZBԣ^fܵngYJH?SiP)Kd:+!a's;f؏F.hB^ca }鮡_Cj+*p1~}ذ!=77nvm566Х1(tN ~l~o%TRO!T?(!OJ/|=4-exK DkkKkC~akl*IJ-8]ڝIe\Zܢ*[Q-}]yW\\V_ E7g cϙ>mڴĄxуy U^COWOa,ȒU$oL$K>-aFRz$=HNC(4Ӱ={JNH^'&HLNާ_F qjvt(9@MQE*KHj>jMm-A{=>o}}KS:<<ԞrZ@j4%v.6[<? E?n{f?Խ6ႇkY~'Nr?osۯE4d F_uUZrwFG>!AS0Vfn9b}0= 12.V87;boB oϯzKT~1~4%JbY+:%D5+w~]Ɲߣg$5eÆoÉi@Ꮙ]5Pgcwc ssBeT~wں.g "OOu[>8 n,'''==}ʕk֬Aْ*Xl`:4@F2lސď "׏QT\\ZV" M PY [*h9ZC/xbWmDqj>Xxw֍S /nt}%nkJJ22lnڱs]55NL4jnÁݱcً/3g3g- ӎai\~VI3ƿ&UzNI3Ocst;1S5WzRT%QFM@Ug{_3g ׭_tt} ކzO}.`>8s&͙j)Ι|SL|kqW>qX[1i򫓧Ι2Em{s:ҹ27D6^r#|{ݙ[8' Lqr]|K`u]ߘ9#H;|TVV-XOu[m%i+dtpaK5,M}|}ڿINVDO2HsCM S^25OBL2< Ug汫ng{zs[swhlUWVmڲnݺ|$u!L 31!やTkhB6=uŅ|N럹o@:U Ec44eN\IX{+\ ^haG q :y>q͌|^ZIU;UU*..˜ܺ5t]4$a5 #A}z>kHcí/_|Æ [nݾ};g,A  .=\&i_.f5kj\մ4Ɏ~Wm>>`}Js5܈~t" =| 0٥$`sS퀦jtd\nt,놬ZVt*lS]VԺ=8 zhfZtG BpPـ uiXTUWWT9k0Yz_BSVVx`gӦM8]:#𕯇 BnzpA}SmC& ,tr䂜NL#C*}} ו QME ZgYxSlNvKr O[SZVZUUi36% P0rNBQKQDTW_8=7nWWfNFgFۃUU28aLtQD^Cx=A}S)((.)),q (tbX˜?-W+gd{kW6oe @1E.`Y1 SЖ/((zv6ZdH]tJl>j(TaOEF!N)tWV3cp@mU`1 QR3QC'?EBB;ק1zk. 6ioʪk ȨN!T|OR~ Gf"Xjvz25YBrd1`B1|/'\#_!5ݣ.t:O==ռWKuЦnXmOk(br۶mŝ4$X]be̽ 8.7B@Wx(`41rTchDTCǍÃixM7AC.;Lإv׈F+i@ tÆ k֬ǀ4"aubu MVTTe 4NMMŻ Qr[A 0bFŵLmVfoU0YBsPe<*FO1v fG}Ӡ2PoCq mR@Iگ"9n444lݺp:@"\qfdd_^p0[dvxR"?A4@|/SuesR__%6\'j˜5xS@ K${s~R'5_aII?k0zqab g;vE3^=۠ tpG?J=ԐF<1H8.8%c fu4 ƴ[GKOۍh4Y Rnna;wzo mBD!艮$=ev OkC糽v g q]( É)"USW?7mJj{Z_B[1 ?^[d@ *ғ'Wq}I4 X )xkjG TTkV\⢶V Tpii).7oތW|L]vʨm! @P9=x+ِ!Cӹ~L#(lW=IcTDsNII $)++j< MP;۸qcJJNg% J؏ a{ХB. Bzە~2T|d@SXXzj\P|0[d!I#لeu ݣsk3t.t8|R`n \v܉,>,Y%(;؊f`=n"_0K2fLdiDzNg 9Xzm;aK.ci(ڲeŋD lᐥ- 7QO[KOOs ٟ"c 5_itwA$ }U@"UVT Lyfa avvvjjjyy.c[d!cL:11%x6c c4}5,zqɋ.d}mݺu͚56lpIIy VH2ՠsnW62MX$+^< I"3mTCax08R $Q~~>͛sssj`AO fAfddxDN?F`C޽ Nvq<@d@*((΢pl эBrZZƍOCЏE}#%o#ko=HЍZW`fcpz۶m=~HS}nѫHc:;xHKB{Ӧt^&0eܼAhVcv,A9&0&a~081~Y1=t"az!bFcVIq׮]|͑]TTiT@$PL?JJJRRRrrr0M?fEW<$"pΝ 6== .myb5,SS?컐4QQPP܈'7͑`x[.rNp050_ N/W~xű ڢB HE(1u E~((ā o+oB?&Ⴇ}/իW\r˖-[jUn.=3B:TUU"///Aaa K.]x˗,Y^7پ}&Ś5k0qz B]:F,T^\~m+؆ W)HbccTO&=A\*JKK11j 8F!AtƵ~?_kK_]D:OoӦx`û/V5w뼵 Z@mۆظq#^ц﫯\o.&dĬ6 9G󚾐z윥K.YdѢYYƟ+z Bqa2IOOץCӹb }áqf*({$\ c|vkk6oXM-8yy[U5wBI;Sr%i= ,FpܹV1UWWÃUlXf-Y8;vNE t'\Bg>LJvઝ-g[+RMS CZff&E-[:[6} B9abiy`A,(( j?&D%*T嘈)7!ruNG 'hGWjꚥKeg \qӥf26zܗ_xʕ+"< :?@DZ/]Tz72.q5Shf0ŭ%cu\MoiZZ%K7m\SlG hH38 fҏZVP:%e[p))o1D]3*gT=3O,Km!SS9%b+|:/A bgz-MQnMO5Dq,k׮[@]japT7H_?4}W'%&TMt䤤Clܸ1\G8\jC 8B5DlS'&}&VN׀Xuǎ]\dTrw[|[ ^:==IkD 7ocǙ6oF=@dWN#}"++t:3JlS<X\aH766 NS\-XYN Whtnڹ{ݕ9ٹ+V_dҥ^ܚtaPg]cwא1!NnMT1'sGӎF>—>C^/@x𢘃A$J<H\ʳsk|׳dF,ǎGlv|vNAA+ϕ R5k`WݨrJLPc AY07m۶-\GMLL#ªx`QaB<%'"BK#$tk䄋ッ?8BV+KSVLx%|16u؈FۊԵ=Œ3X$%%͚5{eammۊo{tzݻ7???++ _ ͟=~nj*ةJH Ĕ)qS iV3mVZWB}|7nܤ>{ٓVy2x[R j>gWq|Z08cJrr67w3裏d唔3x U6f.Zry˰_yuP ~Ln8ϟ0@RRr*Q'%'+%M X;0g,Z_|fs>,,S'&wl*~k 5^x|pϞFkMZ--\ o߾K ә%KIJL4JD̙Iw\H(ߝlνFF\:^qΚ9+5uMyyyBY 4* FwLr<x_WdcxYN8"uPtHƑVUU)x;i[a8rV\5~|^G}g!.VgSď ^<<]}"`OR HTtXͮ~`U ^϶{;px9Ѩ{Fen87.#cCgfø{OFfuCݻwgggiիW'Ӎ#L_xFE23(&p*=!&Q!L9e(SRRps9$a1dB^ґeўeG X>!=csƖpC}~KX.;#0cBb",9tcc#&?PSq/Վ68]/?{;ďE;z ]  \4 O|9+Xӣ1yͮ\ cEi{ҪV?f%Z`[999]^ 2xُ$a4 ‚1aRTTk/>=Yp2B>"Nڷ౅X?5EW5HH~f:w,ߗ΄+Vk:cG7_h ]?\߻o+ďY܏󩮯g^ڿ5w6ϢMT1".^-fl ܢC~Õt%Zeo|fלΧ氪i坴nZobn}Vom+WN/UVx{xT}H@l'q쵝n46n}M>>my6q}_c 㤵_i':N67#W$>3IȀ`L93 0+_F |>9hV?{HVJwweeJUzNJ'fQqI f?7S'ev̱ο+yZ]t j* l='jܿf$,})644N&'7|Z9nz,#64w_>?y敵,ím,ylOcoLؕYc+&J?.c'\i/;[OcGaha1,417\c^%KW _n'f[Ap *ҫ&oێ=n4M+7$D19bkȲdfQ[6䓁3NDUxvjQNFLm' Guϴ<fݻ& _H|%U!0yěGƖjautN >c;CջL<ƒ8}TĪ_鴥b4yKo q b1Uënj<:OS$a66hhS" IŐ^֤Oos<fb6N?:Tyˇ?]*~2+527e!-TW:CfXY;~c$VPiK.ipޢĦcF}5jP%8׹yN=nr4HĪ鴥b4yKo q b1Uënj<:OS$a66hhS ):\8sPOǡt:OS>w<c͕}N,t$o}7ުVnVQ3 򺯸FcZ;wS3aLOjw-c+gy ~\ҖĪ_c4yKo iq b1g>^5LRu7<gp w]OG"5K^9`VKۑcst\'Ti&7 ܠVGϔRy}"g7[_xwqwc&M<d'lRz\%<K+7L |L.;˔<6k45VֶRKZ~޹\Swn0]|LFdc:[cN2KSTFӋfX4DG=L1^Z dP7p%D-oNTyu7cL2_>mse1DcfSRqvz^YzL8/ܨcO K*yÒ+3<1'kTdV5ljGuffg&Sd,c:[cN2KSTFӋ<f~\Mmtgn&SN/7y2N?_VKĭ6%ɛ1Ik&hgc<f1߯KksOTKS|̍:6J$eI1|̮|̓ǜeKP>NewX4vLՎ\HL"a=] npy o3b*T;[߱O^XV,]Np/7ylaYtM[Uy Mww~C`ۼ%kylڦssg\rSOg+E"+cfkj9ujρ-FDzu\V^y}"SR<hС7(}=;&)5Km|~/2s #a*.)_OO~o;E=3x.ۿw[yM!#,]ʿ;MG"vV[[X4Fhs|rͫs"&t{M}8媮]g?{z9Yt5:6n?Cӧzf+ tX0o(<ēs|H488XQYysɦ͋ l).Ӏ ֮kz-[֒2z֕d$ٲgiVY_q=#ERٖҌ/YJ*z{gOwwO}C6-ojhlU,.)+,*<.s3mi7y_ںFe|^]/Ş݋N-۞=kg׮]%/[J6<gUUUv)vU]]]YY!)se>A 2l߾BY4!YȈijZgܑ̗<AYooo]]]YYY[[[~`v1>T}}} Z[[l+@Vc˛eٶy .<appP3 i3pc|K臇[ZZ./ y ?6[0IFY[[ij^: fΝ6ma[H$^YYY[[w^UXc(aL^B'+J0ATTUUXc ee\sg{ G"V}CCaQQFޝsa 0(EM'xs{yX,f/A6˖8Ʊ[y @|SaUW"z1eHf¼u/go[mzs-͋Um퟼pf{y eyE y lylSgd!bp|һiZ69vha (9|^PcM7YS教c]vd^5/?)W8n/dO!8QW_}( y ,4lrdWB]'R+:erx)O8ylrE)od̓sr^2`fs&;poMfg:̐^r&L*JIX:[ӓ5EO JV=>lFnf<M:) .G?=yR69H(}RɮML=RLR^y !S>J-i<fܼ{򘮳1:Tu$ج<lcO՜HcLdG|-BvlGfrǞհ̡H*J1SһUgCpX*Mɇs\=;r9+lV8 M/kF3ƧuumyB]΋񟺻{zUX,~C|?()O?808h pI*+-P<Z5u[vo<"Hն Z3x֒7fϧXIffm,dl:[u< ;[^^i1X,UUUU[[{!JJJR544gmxxضsD0/CCCv3MpX<`N$?Hd2) vԴs'9{ =IEJ@ww$՚IbH$eI$gyeigsssOOYvXc"  ý3ve]uAnii$/7gbbe[m(g=qi*dA`0888::*;Jw G253 3\9ؘz%ʗMQQʲLlbbB.Xv{,7W[UfF *}U$IlxxJ6Z}7ijeF s6\aͲeY޽n۶m4$ʵa.fL`3±r̰rF!dr5 $W|-u/nE<mTIsJ– cBY▼ʪ:n[JH3}f6;zkV ɟeN<!DupsiOOgAɂ_c[邑CL$9;6yȔ F ry``\*?{Xlckk*ؒFYʓd0Y*wƒ:${DigfW>Y*̹{Kg6ʬ ,54LWw0>3Tr,ܞp9'5e̳XVͲxbrDݰ۴UxXTcb1&;jUrO=*&IniLiP)nRFvҢPݹsg}}8p@";xu?PsHhI?HԢڢ;)\zƶdF"tQF}pFZ.*s4}Z[[Qڄcnq[\1gP sHg9ICCC^p M_cvb y Ylļ !rQ*'KXa1˫,tKH]vͮߕޔ,;m$SM-Mt;-uM/%'iݬLL^r(Jjfs@#ǐe-rޟ3tPl̲jC{YOc"Uy5oذaݺuɜ9!@<,01g*/V fNhl,≑[?*}2{ɂP!Fr1cǶmUre˖[Jܵ˂7& =#j~f5駷32ۑҍNݒ4eWԣF %MJP1$wIr#~~ *en1 S3]qVEF{Y+s.<n#={JKK7n޼}.s`f>;un>m7g&ǀ\ZcϒH276&͒:~H$U U#2[ᨳza]5qo(2;Ըy-ŕk[f͚&I&rKofFrnT2Uf9EEtUʨH$S?%dP}PۻY}䪨$l3@^*,̼?:=Gڊ "&*2:<t42[IbT\GGGaQ|rMP[;Ȃ08e9.Au/Id֮p1!>KFG}P$wO_WGwGsw[ݮm ]mm m;ڛv7WYnloƆֆ憶FݭqG,4JշJiټaƊ[6E41_RdSOē Uevyli'# 㣒Hrbb|xdu{WuEC}up:T5e*g&Vj)}wIuu5h9kp`h|l_2ݽdg6H6{1d1n\ooowwwMMMyyEʊʭBWTy.KS=Y)+/.UqұLvUTa#zm*J 6%ܪf_=RMDJi(DuuTȦ5TssK__ʍgś*Iv?޾N~{H<cckC~ pg pW^T,rp*YW*ɭU% LYki`U򗬼{ oJ?GI3 b 5OFQ.9"alt_R%nO<˾]/X3%eιM|UiyEo[~;:jJʊ7mX_^[⒒=i_c~z$=ǯ⊀ )/ٍTiWtɺU͆:\8 9m1";Zl'Z6a 5,OPRQJw'4W]uO?s?0688yf\%o]կF-t V𝁐`kyf@p-Yv0Bw_ ^ҊH<WOI$;[715^Wew sѩ,kRӓw2MvgJBK̗T%PPe8l867Y[K{:zyZ̷I0z% S$C=rZFޱ+5Ť2:Z68C8cϳsr=sw.Ɇ 6o+\꺌l<.1>̺Cw=*WC+B*{|-;yLrGH_K6 ޓw #K$\kJ:{K((+GcilLQ?#K]'Gb>jd9p@"Ӗʹ UMet6e&/H:8|K,P(Q\D2P*$1%Xl|||ƍ_B'K*ErP0\ tȇt\@^~@dP@ͰF($?^&{Tg7,Rj|PNRJԫCpn_9XXM;$3LuқsPLv`0Ofe6 p^85[i / /P8,ȓ m޶l)HJ9"; cF\$A4$wɫy tkCYnp+KsSk7gɆM 4o%_EQAkEx%%=]9yp~X~շŪ>X,~՚ϭ R2=yX#~У+B?[.g|d{"/ƾ*y5gQ:hW.>Y|>6<}<ľIS̕fE7}o╡/[#eG(=);pjZr?>f)uoxf+y,HOZAӟ/K*e=y+j `< f&cﻯU|FISQ=|U0Ѵ( hN5''9j<W)ofNߨtÝ:uZ3~tP?9}j/T=tjujsCR*cre/VP'ފ#X;ؙYk.Ex%ş/|^:7|r*{g3Ihnlr/~_^'L3CM"-}#pLʏcN(rH*2<fd\8E fn.NtE_1eFpZj$2 Q*\ y<K}("c_4X1y x|5wm U]yUiS{q,SE]8sh<k(] R.fMJqQ=8~rZs,<l ڻa?0f_1\^w)\Ἧ,yMr(#lkH?x7B+/ K5;=p=)ߺ52'}fg63鑌F##cبoɻCRe09)3=~~pO^w}^&r=LT{T |-bҕ)M#X4GbIaNV_F֮]{׆60N( ~A]P3}p~^=E0/ f|dn ~CI5ʚ #yy]ˡ^Wqj%"2T>j:yE! ]C^!u~GйXsa}ւwqqɕ~$#). Y; @|6t8[ }-``m%÷Ic xzzYPnn o 6%Vmy[7n oܱ4|{xm% 6ǞDX<%wwWqF'ɱK_xxC^%w.Z~yr\ԩu ʉHo /yiޭCyrBaNSޙ@_=;wGbDlDzgL$s{zzJT KvW̼㼔,H Kkl_"]۽6U ' $ՅJ,&/ɗ*1IHPRٔӲ $_,]Y4?򥁥A~8_jjG&ӑ,V^$/5KJ{HVwE W, ,.CK+< X* lաɫk/% <搯:f:Ղflٲ󙚿H$~ˆ|=C+?ls[ y Yr$>7_bپ:Z뚚kjZZ[ۤNVdAZvW#=KmSKMSv]P"%:Zw3$abed{l$UGL21Lcc}Muumu- jkMԪFUMu͵RҭAtyRWCIM3Hݶ]uc}0i~c~:.n*blhhؾ}۶V-u9)Mmj[U%SmQSuTVTTlwӣT#!͂JW63oQn۶JFeKjOM1Y689.Zv5<1O{ϩ*+VTTf4{ј=03 hl(Ehb"OFbG"%.r`褖e4ϷԲ4d2:*5*K_jS<&;9D6H8'ۤWt$E<d\桾w񘌚2GJLUv%c#17g-#8#ѸDp,վ#J&q')5܋ }\Y h}K>nJ:~K؞{zaޮ.m; nYm體6ZQA<%3vpKҥ<My(H␈B\rN䝘eZe#InC+'bⒶd<nT7UE&&LtTL1՝ G>[Q̝nfqHtUVoiN1h(r[zaZjgJ`Ӕ3M3ԜK.| 2,?Ǫ'TO,툆^-kʴ/E 6AMMuI#<ޛ\[Vzbnݞқ<*QVD <S9{fZTMft L쾗 g}O_ؘ_,IdՅFdy ;iRԊm75eV*K''ʍRs8եO2- ]H$رaϞ=c:y>|9 c@N%̚!62%J0)8u#YڼX~V,Vċ/811Q[[k.Մ19Fdy ȉ t O=L 3y̴G_XwwwMMMkklZ}  [email protected]$1Y%ݫB  c@.$a$IFv񁁁uɫ,9{3"9_ 'Onv_򋋋+**zzz|wy\w*cGss"$eEѡ!IbF+((v`4440V]]m[/HH}aE1dJv!Č-%7d\%Vʧ~<UZZ&јSop#ܦo,tu `Ak$e1uu|gV-zO>{Q2Tm=;O}5k'~~$nd[~ y 6oO^ooر'z۶ď6,zk׮#@+_;aaz{q:W˿d(;/o?z1xc{ޙ(g|yx_~6f<3ra<σvP-Gy7}+dohZZ_8z;Vy[qª<p){} Kt9Ӂ՚cgE<GQ>^+cc/JL+jLLW˿eZd *U~oѐJ۩w'^x ;R!ʉW&^8:u[1vMOĥƹсC}%ϼdFuN::d>'чNYf{;}-ԝ up苧Nx3IRWe>d<fQC!Js;+<mPtyssZcCCOܻj}vO `+<ěw_EщH{T=a’Ĥ㿒ɟ␓ X:y'MOIPr엲t^jz:L>oV|Л'N79T6ܺCO KSN 2y GSroVu2Q]RI_}OF I5H^8Xy 9 W .=<.Đ!-i'Z }[y]2jXA+m(QRݼ֧_O5tV咭%J9z>f.ILRM1=%YI뀥IzD3̰Al5%s0QMx&󘙒;H7ԙ< y f~E?Ǎ Bz32StA>qV;g\_)˓܇BG1C}NM}& {eL hb]_jV~G=qjQm<nw?g|; oNSywyA{R=UU' ~Ly'1ϻ;\v3wƹcӳ]rXO(y 6\C,ߞ7_02]np , 1>hjl?_ g?GMM?o[68mTx~6 cQVV/dٱ@}K7'~ʳaxxp<`Cɢo~`coo(Ky bX__޽+^Ч72Hjpp^@1y A$Ktsy ;s)< ?c< ?c< ?cTWR1 < ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?Ry| @n1y A1y A1y A1Gf(((r\1(((<FQEQEQG-ve/m[IENDB`
PNG  IHDR hSsRGBgAMA a pHYsodIDATx^ `T'>oyۿ>Oyo_bA< XnHhmKŅbRj+l$$,dOf& "nIs~gnnn&2Ifs=w9wܹsG7mr[q>|&fӺu:fGևnѓ>UV0vPنfc{gD=̣Sk!GP/~ٶg/n}cTV0sqӿ7jJiM>vqh)3S1VJم5]SKEc$XAhQ735|zeHUfiN״)Xx {(X(fVשu)=22=q.IlP|E 0Z]aj^wDNh'"ŤomphdPg@Bc&48nQK65~D{b Y۬mZ뤞Fi:34dR#j+gLHmzpfYmzp*r,UY/sދtQ%'PUp2Cm6  n^F9pBӚ!Uh&$| >c}tFalV[nZ"pf$Uf D8AH*zj s#nImnZ"pj6eę>#%YB-AO&MYeEpcCE n3S&mPKڌ۬%N!+AZUmPK٨͢'0CS fL@-50;Yv 4 ҘیnW*F`[v~tԄ{]I >2td 4颿̹ﭭ1ڬ63I|Vy7ӃIb(5bMU0B#,55U%f6RZ*Ն\ MHciIJJR)WVV];e 1\a=ILm>ە*ׯW(((P#mqu6GvC5EHg}{,3-FڵKMcY<~ ^=jrZ/)-ՍLच/ZPISz܈vŽ=C;Xx*W"w˝t,Sϊ []R*u6[5U,j:t{I5O%%Y1O'ojMCD%5h^;U^$Q sUZ{{vY]]KM`*$ 0h5{`ޔԌ\Q#Zrct: j n6͊_ݽgݧS 55Z4.=v;Z.119HSf|q c4hS)I2"YQ__GfTCmj܄*]ȟL dfVJjT `nٲ9>~K|||BBBbb b(3N4eUk7nlܴ&E`YY9&2֬m+5hQQkٰy-7ǯݴf t닋@[:]Tu6SX h3$ ߂i9Uș(Alr|kcҖ6Q oʭ]F~a>צfj34,HE;hE-Ml,<;fVhfM~b@?T9CAؼ`֓ۂ3G4mоF<J .Q}90k\Ĉt:}֬v k āT%q9\NWJu{-rr9RN81ֿk-yScEr/ --M1|Yvy,P)`_]vnRRu$TWW:EbjhhEZغuJu\ظq7lؠRvVU*S8M`j7;#2u TRRFZc Vzܧ[4g<P^'QETUEeKJ.R}D͝;/6&n<+VF`EUTʸ?N1ֻۛzm3,S>>X{彯<w/SU9f<=7^kBBMm5eqצ*~)'םl1/UoENvdgoWE#/_pt7d|̸Lcg11ːnltcZru$T!cv_MFUjX};bڪr;W -|{ήc,|fi:_.^n?;ftkDAl3r׾8;p@=hS@%TFL~P3O?4,r %LVL'?wÏi3쫅(L6f*Q1>d_ڬ}3CD>5]Vl"}9mbhKӥ)_):' YJ/^qIm5jjjՈ/P=YBej/E[?qIn8<q/͝@4-۶mSpC6Gr:w;xu݅ VnvZSe$D!&S]xȮm&n>=n=!hj-AGmR4r%>Qv ־r` b"r"!^L˕W +BYZˍs; efFENTxjsrݗҥ&,'@iH#G|ˍ H@&mjnVԹj`E.%>6s"r9km<N K|tzWȖ(BNdÒ>h3qQsa+ qa#gjK둁CYwٲeJ̦MT*wmV^^~uWkT-/Yr!HkdqU_b)Mr!Hlnjǭ!Gk3CBVmƄfY =BnЃ,6 =BnЃ,6 =BnЃ,6 =BnЃ,<CnЃ,6 =DBK=fl+'DD=.}I[NbxxC&Lu2.'!mFoIӳ<o>_Ъz*"ˀhT:iOqsc72m_4$u8laqi2|aMj+E oIٲeofM4 jTMCiq6XVƀ4-3V5iV)z卍:tFO`k(sqI,Rmfs9#rYΓo6vn5z |"v@EoI'0nbE+qòFjjXF'^JH3a6Nd/Fe@!-CTb(gh3,6 =BnЃ,6UV%tGT Yry颡QsLu@p*6'~nooo@y$n^ڠP%f~B*6UO%dqYpcЩ~\۬fNJzjNT Y3lpůR6cGP"j.Cp*jw5f >}+n8YW vu P>jNnS9 jN>}DqÙp*hX-7bcJzj}<rsȘ{]W1ޢ|&P3tmۨ}Ҩ/L]_t^j|֙帬"Ζ=21IW-Ol=U{= ~t=5O&Haubg_wV3 ]5MeffTmmRRJܹSc AԾ !4j6ۺuJyi Y[U* O 96op~s;e|63Ɠ~Rg~ۦ ?hwU;N{Si3I,b@rz-9P`BӠ5F)fsَ\ϊ:G#.9^+s~Wm66ca6цyibEZDgی ~ˡߗy&l Z˖fYzvR+IO׵n]qZj]rkkw*D5kҍ3TN# 53'%cgjFNjF@ߙf"mօT66MZEWM]e(rr=x ]5LlI;`mmU[[W%fh .UU*`<(UXWWG0ϋܲ-> j0 Y c[&vqffֶmbwdefz˥k-[lO9ܲ MOObvǖ7j͚o M"enRkYkv㌻k$'ٸy6oYqMs5?ed`8Sc'XVd۫k6l֭ٸiM.'o;;</}-"9rXD}BQ)o\U.K0^bːʕW 5 ZVR<a5DɧZG%JKJssQm_ִ6[@'T_Qk䀹UugJ{\5^Ե6s:Ye!m2Cy"+#b mֲs\wѮ2 S11}E.BHվwDխkZ(pu-q?"UYYEq@=6 NLi+UB6V.!v4%j1%kfj)m1@lInvDW+W-T&v+))DFB(q9XkQ9Ou`7oܹO{11TF'/(TE1-5}Uu*W[x%)$dѣr.5^tI$.nN\Yѳ絬<IlNLm|eJIiUe*gm.z,j3,ïz'//;]uz+N/0UTUO{5zNmm:m[6[v=?[^q6&&u1g/;eKZ(6 U_~M5kyrq~܅g#11 olTgS[ܼl%ƼUW\Tڋ/~k/Ͻu"iߞ;oʼc+3\x'H7,u7dN_4fb'1;Դl+*jrթ ?~BeCáêhGK2%Xm#㥿kpߵ٦MTyyy*563yX[rTѰ_QLgG6^j}5I=Rh=<ۧ40lذĮoGZ>4Mjj1}f# 6tDpm&2!-luYktmfp\} L5e. -5uvWQfsZQ+nk6kYaCjZ)D ]&:؀{4 oCTxm&>|li,, ̀LF!>]{J|Q%4b+6+])[4W M LG ֶ|nRLex1/>>kE2ݠBܟp"jV¿k/;x񝭿+@9Xw޷6IM7m-l6G}q =d)5::hȅч3V$䇌"%GWTA1,\Bo Ζ.6UUU]-[Tn<뗷^ʅ pa/+@Xp|I4uq_]]>qj*62fL?,hfLmzpfYmzpfYmzpfYmzpfYmzpfYmzpZfԘa7-r#׏y(j"O;E !1micF~m2ͅD5C4K/KBkCv 0SM;2<_;??f@$U"%ΟҞAQo{Ӡu)[E-v5MC77mn.~ݢkNqVY:j)ߏ ߠQf-1D3 =̔O1͟8;G{ ];a'^):=jO=Yq8bܴSac1& L)ȏbD5_XRk ]˰,VU-&!d>Sgfwf>~nX]}tߝ(Le0mq6ƕ`["̬S,+Hjf[wAyV \ V{ J*P<WhK(:tF̜, ьgD9$乸/YN9SJ.<`^~e,ju"\R¬ڹ ,I _;o4xx衇Qr+HTGQ|ټyaԴ+Q̙;v45QhEmKl{!0cuYmŒbT;0AÌa3 :f t8&p1aC3&l#}áQ<dvLB0c x0cu '4(WkÌ [!%quz(pxD}zWL/:fMVc FO,qTa tx0cuf35(_3&l#J\tƠ9]:\CbvzP:8̘Aaf5aƄ-tSA "p]GJJ- /fLBG裳.Ӊ050a}Z/fLآ`7m 5aƄ-tz*\؂w}`IC*LۍK90x_LOp OkT.#>t1j&\#OPA50ìRu1uʧPA5L=ImtKU#_#}¥=]^S S&ԅ3r1Kx DKvO?y0 Tf&Q> f%%%j˶mTΝ;UKEEJ%33ԨqO#> Lg_ʧPAafSSSՈ/TmLg*UPfq&h= 4=EoifnȧPAap ݵkJuU/YYY*unZ7Z*wEZ:Tr@?.,mC ace=;0^QQ6$W%UbdCfӷV ޷JWܻwowD7|npHe>t! fN~5MRZCǍ+3I7t ɻc=@Ҟ㵭rHWϽwC\I+7U弔zkQmޒBSyW*'ʊ8qTc럪0i af:MRZJb_]gZQ+7QTTV P[TA&?Z˃rI%<d*[.q8Nyi)@=z"Hп34jБE9EG"]10ja.]Fu~1v5{yKF?<? R͏R.8"xjk?.gpe85C =`&&&Sn#U9T^"!xݬE}7 v\0*k $20TTBNH gS%% V@0Į'C)a:4oo߾jLԃFi=AM`b~~>Κ@FnEq5b{חY?–x?ӈ[b8 Yj\K(]TBD B1C b(Ձ 0"-fAJRe<{;S$*~%$'FhCe9tu,%5{ys͛;gbc>=o옘ٱ'zVttt ƢgώT$bf!'nNl,R(3gnM`}m?ٚ%ƢhHhHhYz~*,> x{ @{HfTݣFXn,Z,-bE"üACc#pA1`kEKa czҢ?9i2XbPY &|8bU?׿:D\[4;_q(p_\(9ke8r䨪}Ygڬ#g;'ķֻ^c݇H.ue 0a*iTUdwXnW[%L,>DŹJ:XW:B?}J2< Nqr9&;yæ7dj=uTf{ôTN"Nf5)Stcq<C{1qqCh@pcff 6ӂbAZ$j'0oC/@f&ek5Ol 9<F=. p! QI!#ML!936oN\ȍԼXL1L4cDѹ͙;m9U%5pTy05HORj~[  B(ed |od*Ip8:jWqF%xX[gfd\,d; Vy_5UO W`wD0++kݸ O*!D+ORQ xttqwKUB:g..cj:Kg5EjDՁl*;jу*((#ى , -'N> -Dh@aa!uhUUUj-Cvqd0WBĎ:ff" нuXS,S1kܠ$--M"*B(hVC|ڬX{ǫpruHߟ_WhU@K? 6dff^ٴETN4͆\;jΖn}|]XC\SAdff΀٣?,^\\LAUhbjH- F~y E;R Y^M6#;W_h(mjyqv)_u2;QxUN926ZBQmG쪘9p,Fb8iWg&ļ'c UpٲŇ#!Ӟ↡sG<HPǀQ[avGc ì?k~5Fy_n8yǶ?(I_66ʙ|Yvvx/7'=6>1l>>xTQ /_9z<ͫ2@ظ̙b|v"uЀ %|Ƥ.Ќr9VV۽WXZ,HO~KԶn,ehZ RӉl=gyvӄeVNդ719?孃v S 11Ξ5Ϟ=]HϞF]wͨj ϾYR *8̺IrrJ1LTPqG^^^AA }vЙ fo#_vM6yyE4ϖ@zNi˅:&QA5ÌniJ@u?Pw;HOnuSDŀ.њ.jU?Fg,5UL(#^a BƩ^}|(³zx/ꨠ⾙Zvv T!ė) ODzXӉ2~2k. !3v`r233$i =4#V  TPw(EPPBx4f1&O;jEyPO"FĜ5YYY޸2*abk֬'u0q.,8JL/*,⩈!OoyJ6hH`T{TjUU(펜,Y?2Ԣ~uMޮ4b`"_9"[<o$0Bס܄Vܹs׮]2} 3mUE=ӿ\:=99ABJhoZ 61e{u<Fi|=8oq ^/SB% uc Hh:rGGb,#֭:ӺqC5AX#˂Kƙ?9+уj*۝bqO~|AӾ>?ꪸn6d`DN" \J,-3Aꯎ"ɦM" $USTP-Ӓqėbpx_B.qAE~C ={!yeẖ֝.Q^j޶0! ~s"4NgPgTP16lEQVVRLBY{DE W^'-j"SwPu1 *Pa6<Yx#FX!cA{rE>_xȩ\cip|!f$^P4(2b.O;?:wt W|X2?8/ _̟lʜwbcR(G"*8n?S~FAkV^_wY^Tf <TP 3^ 8j6i3 :f t8&0mc&p1L0ca0AÌa3 :f t8&p1L0ca0AÌa3 :f tDc&p1L0c쯫vX IY*Ɂ/}c 99ǔ<ErmS|í?-}9RHO;mX1i׌yqu(._|K];66IcGMSf ŒQc&mygߺx#'G:|7y&\]֡ =j}ht!XH =3k{ѣ[#>*<Bq`(E)̂jcoyWo}7;jc{IO>?QsF1޽XMTbe,!|0kc>1 hx*]{=S0Ca񌣲pc4 CaD[ZY-}٨ t|^43_oyC;SGchw~Dڢ1ۦ^">{g ?96[6G#GtO|뇓+œշ2X&x#D 鍛E)N+4yH !}A-Kӆ9"s 4|7M,VHIkOdZcҲ1MeBD}cHʰ,VHXq3S;ך>^ܔr;21gjߝzˬ1 @(Y^$#W͟q;di=X0~_Xe7kn]F3?Ӱ"Ƥ(Ɛx(6$b̔.5ƵaX-׊N>ҴPփ Wi]:b!W}W؈CgNF{. DEXUoWRY5}$\qBb*?e)߿2s dGm{*~aQF~1 m1'cWcVnX2d|I* !c<Q[q0r5G!$CCbsH(|+(Y"_@qFD;Bw  Ra,LmM5`-ZblJk^mdIcDcuYb  &#bL-ҋA6qX1BUO^@TOnV{`o9jg9$SjDQ[n}lYC榦M DIQ&hcڨ%O2B1Œcucsr0xe `B ._+"Z)u/X,VGR1 4c \8&p1Lpc10ca 1 .c \8&p1Lpc“U 9}%^8Ƙ|ߡ VCGRk]74jtn7TgQkc O1D҈411+{/F ^8Ƙw>62f SVYcz^8ƘD}Z/cLx@1&<Q{Ѵf6@Z/cLxB1l8Ƙ Z3ں>I1\CwAPlh}n騅4Wp1D }2)~}CE 1fB1@t!xcP ITkc O(^8ƘDAF)~H36cb? rc [>8Ƙ ŀ s=nIz,1&?={މJLp1`1 \( $d51Ƅ'}Z/cLx c21j p1 @Q 1 (>!Q4=2UV5"V)c*ja^8Ƙ@ϙ04ꞡQN%<[@L۝>JȸrOϹB.mA<&aȾБ14 c@P Ng9FycF- 3xcuITkc O(Mlk8Ƙ5A}0>IiQTk0(?oDŖ1fA1N%̧B{~Bk]lqk$=}P<S\,_>]|n*p1@1@?MdFp#>N@:rb Xi3(-/k&,hMVcLxVc sdе"nj @QceM/Ov)T2 ~JB6<S<*v5*?#ȏ{"䁘9}qS1jBGO?OSc'"B,nIXzzP 1KC!?%[~V|%=L>#1D t_"$TlykIZS&kIMH}nkz H$AϪ(ҋ5m (SFPcc=!~@APLZc[{?gϞjU5Ϡhhv5")))QٶmJ`֭eeejSdLcYYYUUUj@g-RSZZ8ӋP cP#\S.hONN޿gXauӍDq~ɴWhmcV clDO\l66*333//Fe0VF%*ԝwq}*+Řݲ.ZH輛V Lb fR#CWkSSSHP:0;;;''N+GiUC+*@1>bпVĉ_. 6j ^&`t.D]ꨳ;l.^6r8j0c Lr +/̴$qT,STYYŀnB,8VÃS҇M25Fhga٨|?ek2joFblStJ}Ȁ)LR xNK`qrFawKx$#5mPAUU0 c21G á| q@oh9W Y1&pn$*=-#OUd@-qyhT!TUSZa*qB%9UֲnК/U1y A⪶0bS~cs?$)9:1ohyq$!yr':kO~b]ų[G̘x~q+t?"c"1 1cYKeO <+>ucUS^)853N@W,\j~GvWpK!ለv_ oqS#Y3y^uuIoCUd\T!:?^e 5UCV[ueEEfFFee%͂x#sӡ! o-8j)|=6tO'ѣghAPYWlY=H7{6&n6Rdd槧wQ8Pl\Q|ZmV׺u}zWdeښ;~֣Un'bJ+++P)QXA1U!p]M9X;}u T*Dرm?[+,os"<m60t50}EĬV+Nyyy:$gbB+(Zλ.8bi@>˅8/hcB( $P2Qg?9O/52r>{BoB1D jD=䢢fuvÇSRR 279233hijl#yRbǧ=Eg*?WIERZZZUU\~ t4MD2B E h:1# n=X__YYKy rPiG3m! @1n i*4XvNNG\;P*sz$ F%.8cuɽ2DdRQxKopjZt0ՅDyGUŵT{pwH+q;+3 BÌ eJTZ'%mھ3۷+bGnߒe <'$o޴)=} 2l۶UW"j5-XqiCBu7I\:k6\m{nU@Ee嚵&ZmʁE%B]Vc=cf7oMYnúk7m^qmNToc̈ 7T7o߾QC*s1ڮxنDVBBjӚMWqV֙ϩAˢJc _~xQLkjn$/cϛ=(Erϋ=oϙ3̜93fvЬٳgP(z91;3g̈ ";6.EhW\Y1㫖%Fӄ,lmA~>ɲuYjU9O6eZQ\٬t+,5얈ٚ6 %VӢ53{s{4|@M'0DǁѯF  "ڎqZVk':{ c2R1ࠠK@Ud`Ѣccc7}Xt곒#Q?}0f<=)b| o!ςTxw[|ℂGj^q>\eĀ!ӧ4 ]Oe4_ZQTiZkZeHL-mZM,Uե4Týw@tH+`5o}qs3byehV O Qs WUdb .e_9 jVZҥOhzW?7 NG#gC5P'cOAhP7AS:cq-Vj<M1q1Dy bL{-8]Ę.uuFkу K~G2KDث:Z6L{jHGk] 3ueĘJEUd@2ǘIrPGblũcQ?1<1Z]ZGͦ=,/ WκB"f *-/t[ j^FLR{$6V 7nYZ}23+**(`j/(ƚ<M0)zDO ][hjjlj4ƛfxSӥKbzΎQ͉CJ΅Ɗ:oΜyzgظ9m^uл߈86bEGQ4U U##Y|*uWS};MԞ jR6-Ũm~EaWóuR/4oʵl:q;OԻ J5m=Cr%-f\!O .lu:9򻹈1rJǘfEXz͐0Ik.-s!+I莭JL&da5vM<\p[W]sޡczUwzjj8\Es`h}"' SR%Hc+VYsՋFQ{#i`Z8ƺ;UBqXyQ#xxID2НU3D8j:S>I9r$99 l&O8C,NHJ+ebBkvޝ qC4Hii $;1֣g@ɴfEap#Scwl1!4$.VD<Zs*M`%`\i&}cAD6ZVpP"M ZYlqL`OETVT` j}%}^D:r1:ǙDTWlܸZnqj U|SUg;,;HJLLXLѨG | aUU7hWQ1@Z:e:WX)c4j2['uy0!cZ8>,;p٬z \x#UKt߄Yp3Ӂ@ˉV$LžC {jmڴPa~6|] 硒RD^!ETVVKB ȕuVT`jI$!*oq87ՠ;P5s,1{snysCbVAUgS/rSؖc޴J3VK<Ӫh˗/_j-RV.]ψtii9s9g`(w=a\\S+Dzb>5ߢˍ)))NuQ=TE<ꆍ[ԾVϏAc!&bH(ˀ)Kc aU*|a׮]ƐьZ N'b11$c1.qٶnuUg}VmOPhfĬq@$98s &}yr?bs~oG}˗Ŝbc{P)!|c)dz/V^V~54~z"?&&\5j@"&0POڍ'?ʦʿLJp)Jj^: ~@4_\[q=3-!q+-qYəב4/9Dط'rBﹿ(9s^r 9G$UZx_55L&b,ߎEb9o;&gzϜQuI>4=4oχRn-7`e"F%s|TUv w'v76/~턻vHprT-c]kDѥp꣏>Q( 􂈱?yU](xOyz-=+ 14`uJ$f<rucB-8{l$d"R)A1jLQbX:/XO=(Oz1rEHJ1L0"b҈7{j BkaLg'r]˫?1y t 1vłěe[؝g-o݉2(އ'5c#jblo!`]l].`CD 1Qkދ%$*T-!cAe'y ڼɧT9jU5_w((4 C-K$ u =5 ?m>BF/cݢS2fǘ0c'WO1(,,ܵk @~, puMTdeeugv&<_{W]?} Xd/%^SJOo1}Xj+UԴ=2] e8T]ړ0]eRBW<a@jntavO{Nn|U$VxsoF&k&Rc8=k/?$^U-E{l+!4"m1EkӨB˃bTc,lܵ@Ę!Gb@1/Kb̔DpcY;` 5oJvAژXp~2aX 6mӦM8x'E#GҐkmk5ٳ{`0pbLZ]WPl/檪ÇShU^t $"r!J݋] WPC}}=/d:$cL$2D B!c4 * kK"|H ?'^ gh^[~JRjD8ʄ!0P$Q=zʕ+ۧ2DqQYxѓө 1a Q%\֯B26;N!Z1f?`+=`wmr(CCú`ol%F8w68`Gvg$ ӌUJסÇoݚp$,СC2E=)2j+(tJ@%7 2}BXS' !5I-1gݷ\W Ta\E(F3ٟԾ);SvlϢW7"iiiY4 $_'(QDqZx$vJ$@m9f ǚi_ӴZ/=*z'ZdnYI/O_rXx/`ek֬X,WZ6$"kr ~JMbߐhW 1uE6HW& G˕ϐ` Hz(ME0I6t=L1r?Y"<.ro5(;=U?Q P?! k׉= .\~?mG?|ȡQ|Q{u0mb#O8*I Q/.b̸bS9c\_O<}H8K.6ǥ*g@Sc2*!B_B!>| G[CQ&~D1@c"'&SjyL?Wmٝ?y*~'1ĵb…q]b2Jm,OjڬAH[b5/"*S3O*A ѓj!X,zP*R$F._Ř<h!Q46II] NίpӪ׻l.(w7d2xqj:GY[笮:}*#ޟ? n\R")?p]8=Ee\urF mdz1.] )nӋQz7 ?3U29zի>tHfPU݂c1r"AD~҇c2b_] {cv j2ˀL :k9ry \&pu?tu_fZv~{^c'S}ZWwʕ>~2 *c@{h&ڿ/x%7h""R%: aBοcGH\21pu*}br6";'#e",M GDlV򓲗1#MzAfT@LҡHe50%&%.5H>xntzYSC@1aRc29zýOPk`AM8zx<Stw./x˻#UӋp1Lpc10w18&p1Lpc10ca 1 .c \8&p1Lpc10ca 1 .c \8&p1Lpc10ca 1 .c \8&p1Lpc10ca 1 .c \8&p1Lpc10ca 1 .c \8&p1Lpc10ca1<iQ㦲XcL(_\qw(}aQޚM@Fb8vM6j6G#Qvnr-Ӈ0rܔȱBN&S3uiM7m2!fytVϊ/߿~ !}PՎ#F]m˷r2Նz4|`,i-=o2;2>6ŔiR+& iҖSz3⶟P難zlmkK_~d-?nݱ?M=baL9ѓ7o&׍vݸ~w#cH?zV\qW2QNgF Cc?w<L@/fQ ݊jbtUPSck@z<zc9"*!7Z{\@NIbHcV׉!CJޭe >t[\YKn_47=E57_^o?|RsQwE,4bφѢY, jds[R fun%SI3f ;i+26@Vb+'z!1yQ-*-cM8ٰۦFOK};aOaM72麻}i'#n|47ylpG@D©ac^777}n2?tcً&a),u[M!06nOaa=|ݸ"ljpᑓ>8%OuDd>5qȟ2ơ:=rToCn-SsRX,Tuda?cLSn?mO;u8ܴN1~,rNQXfDqZQA4|t51ƥX,+N& dX:QƨiX,+(N|aqɨ˘ @>3Y,8YuWc􍚩}הcM?̺b))Sh^S&4ͤ̍ ~qY,2Fi̛А iL]7Q7 C`\P^R&T9͵fTtT e).Fyg}^`T$S>LHƍgX,Vi q͔og՞̫˸,  X,NRNUSS=+S,<|;Yu;6=U[wf9vO' S}+olӽ/ס3+3ie\xɼy8T(z¸i=zPz,ldp<:)t\,/޳rcLPUYANE'j綗ZLCX"gE rG ꙝ6Ll޸%tЧ5혹ItN6Ci.~ u2]p28{s5dm WᲿf NV]VWClhԄoE>'[yo!'N濪uIO/ljK1֏Xb\"'٘'io!M3вQ%Fi311SkjXF PgђS"@'MTc)^?Ym/ TbX?'#+(i9UVO>vzPp/|J^|wI Pz,lu'czJs2jdꊝaaBv2a&a'caBv2a&a'caBv2a&a'caBv2a&a'caBv2a&a'caBv2a&a'caBv2aPDm|;1 Ä>Pd 0:{q.Zau#q`-)}*om'0\@t* FMoooXkCov2aPBڽu¥)L{dH` d'Qd 0:0Ʒ;0L(N N0 JS{sDREa uj}`TGd 0:{9S<>SO5ޚ9Tk}1̅'>}tJw&1 ԩ5Q'䈇1$';0hLuLV⟑1'AGL3 AafN(\Jd 0uj}a(>Pd 0:>ru(Ua&PFa&<Qv!ѯ8S\>8c$'^afNLTOÊ >>]'ʧ|$)#f?]LzzD= ;0EڽoUG`BdZ4!aR贽 4p,a{^'3~ SĬvafN;0Ejہa&Pv`'c %ԩ=9pBmR;EaDCv2a:{џ-tO09@H<O?*T.}dh=o-8 dȘ9EJd W.z䜄7b0j0_!a(Ew2zFGGs*adxu_K'_H0D1*AK&Cd~zNuj>y'v2a:w;>Ԉ v2a:>01 Ä>Pd 0:>rd 0:>d 0uj7p*aJ/O|a;0E ߨ[~E<./~EO3Kh4=Tb^XxpT=9UKu"GU5z^_mv2a:wΙ afNCq2 0 uj`Kya'c %ԩ=1u|Je'c 'ԩ=Qi~a'cǚ3ej}^^p<sZa5{#]UYW4NOMF֏aΣN^*`*K!;uK!py Q {`9 rZ&Z>g?B?B?r-E?ׂF!Z*fr2~ND+'xξAۛ<ՋIMf}ͳXk%=U |,N0Aڻiއ '{OS!!ϻB_{0z@ ͋+˜$rW3 '(}[$P?SΫN0ACv2& UB;SCml+pUv& L9&XݔcU;L9hjUkf߿۶m[n˫P:>ru(Ul@QVVKرcAeOeeejj鈝;w_vQ8B999*awlZ,́[ഞRYKLLd:YYYj@뙜YPP0a:{q. M3==y G<yH}ϡx ;Y著Ss~~>[B UUUjKtɌ:jݻ޽ZM`l@Zoc5RXzz7}呠gQX<X/_r!|ަO*q2΋5W/a'7-5mEEEjtt"[n ~ҁ"*?Qˁa-dlHPPl@<.XڴVX݅KAޅ2>gO`+r<a\v爯G_#QXm)--E`ǎ=(..^~=:=:8l߾}ڶπ hvhh'`WsƤqacPD@8}Fav2Sf>ʂuQξCn۴q{bΔ={;e?>ՔC٩E(.IO'KLܵiӎk={ HMMݶm{Ķ(ַ41-gkΔmeNۖ+%5/9%/5 SRwef//9lְ4ds; v23+6̴tM5lڴ [k^_',5=y56SVl^jixK*!qZvMAAAff& `:ggam44q-~IE4j˚&eib^;NLvݘN|wC59NS#֬5zz[~s6m`Zi}JJKM+lmޒRЅm/Y|K\5(tc-v<Ç|{>tGx ;m?{lG&/6{f; u\q$SgE8הy_fq'wRӘm 4}"^LFg/Z1TznКξ;&ʿqf.:Jn-s;ԫOy!/R;Z>X NYHg!ϰDH# B$DxNl 3EWL5,"lL'==߸KlJ9yLl{'HLg!Y".GXjNQꔉ$"}QLA62_o}`> N1^)>y9Oq,l0;ri,ڥ<(+g`amޝ#g{ee01t'r8#m3$ː 踽/\:á/:zK(&.(G--\4ȔOGO%pU9nYFhv)-Oj%d-TTT$%%/2k%mTuuN};aC4˚ PW;<WL͘YmZ/bOx6ʄa`2x /!_<Yr9\´ZNSx]!''^fmҪT1D>IPBe1:F'sL'0-YD9Y=2kduO9 a%ůѝLHɬ61NfS_?i[T(M|[{NnGC|^qj0 [N$5 W]S#Ät. CXpl߾===؁bTĶM#YV]kW5$ F}-]YmeKy g'u`' hho>N!0&r^|X^@Cߣs[L%(rVuuΝ;);v(//ԥ2yie: @`2-:>|xQm$ܜ ݷ.d=Kee%wj$`S#!BdaH 92[MhQ%3)!H, b#݊D>rJ𶌌{W) Z[5dtɂ'ñ㏎` Plr]aRCCr/!\iԀ+M\ff&NgD B@TR_sr8`EC]v_1rf=Z8&0ra\1NzRRRГF 9r'ֳ֓V:#)!;|²j%=dn?% yp|, -[0+;29U`I:TJ.S 6b )۫0MBU8"!g S<'(Nzݺu6mU%nJoSnc}js|Co 6PqsՊo??!Qvk87Jtc!4*zy!d<TJT^n}*ijYbW%-ũ2:0KzɨQ)~TKP#&a 0unڴ lX"a-KBsIp*LӃ ",\bz>T D[_a^Zrָfb5*Ϊ 7LeBr  QYݦGlLG_C5oJa$U[H6]ᤏ/|]} WB83+%a8ꗈm -..޾}{ZZځt^2ER26 ;!chNp2{ӎP{P֪*5ԩ=SҶ=dY۳0iqA=<(IȁD1147z.7z._܈?|$J#e-QqWT aqf=g͚/9sFtYg͞5k v11ѱqOLllLl(iq(i1c␏,bvY918~B&@Ypݹڣe E{RאB9OĠ'#LOC:{M\́AZ݃ڴ9oZ66 .yĥeuT}ߵZ"C!H<&8`Z -^3 $B^zLpctϞ=))) /r8Š熃\3^3$fYEɝ]'Č됏 __qin/@#whN<̄셶'SӚ/7?ϛE x2ao6~ÄI/`N {LFwQVhF|w^p1ua8dupd/7'nv,>01s͋33:zΜsfy".n.4Ec>09F(M›Psbg|y11ѿ|f9ODϞ'll9@Yqs3N%$媭ݛE$h‰@3xJ%yߙ\o4aQ 7{DAΑEө@ 3o8"6(:B,V#LQ Fq@'{m޸yݚ7OIN֞}AFifg~A)_^GB3d3b!~Å"E +33:d`m m;N&MFK_Ycm}:.ݽ5y8hͿPرA+#"FaƯ YT- wß̘;;;7;/5<7zԃQ#G:[-ZfZƜSų><șPr>YG˦O񋋯H`ꢸ/\n}LtjX!NG۾Tֻ\Ǹ?<F2jm,24 z{^8?R>9H|~Rd9rꚓ~ID?l:vsfH;y |ϛE, FQ /ߤgq 3ezN&>ӲˑBNFV8SmXr"DO e%b K;\/1;M@1x'ulJ`W,=-&]9sq8aeut,u!lL~N!GrRPPCm^8MjBK['0*1/KKGɮUXKvW,G߂2(D8qv]p27°g0`Wd%r,\t( 벯c#'ala`(3PuQk㗶Nf9ߖ62TD'~j}S!N檝l1N5MaQw{=. {cސ&'k<#ƪz2Ore'LY㨩s&Hx έ0:Gh#V 1eLhENV_b WHU>P'ًr2`XLuؙ1d"`)ߤum =Vkm+OeGGhim{f=WSxI8g~eytY$]B'zlƦ/=͗'fM6 x<PEe4Ț($2m9:648z뭹s̞'?c!bgΊ5#vsΎ-> C-ngbfŊDGϝ1;nVظ1s0ѳ1qyscf̎*0wL8qϊQ rKWt mHFNI+qm3#Ѥֺ?Vonx۴ʬ\h?=ɓųbjӚ[j38m/)# ,hOj)?щ!{!N跉~";Qt"npҥr{_3kuXڦN]?k+Ǟ'oSU`}% kMe[cTUUѻv?$k#M"@}kEj%=dhVRZ %e d,\. 2eR z'䗋gOSYYyyER2H>TXy* J~YjЭи0v9UUuuⲲr9,;PVzvAEIQqQ~! z(:2%%III)) Fa S&Pu CוX˪+eJ[Rť ,/æ^qQ*ʷ&o1:=+AȥBzUU^e(.AW+-W@Iy ȗ]Uc OB'%%@{ Np 8p +++55lN&.TRg:)GrE/ ˈcLyi HVĚۋko,]"Oa , e@܍kŗY1"bh qAN8Ů]HWUAqHp_8$Q<= ;tjĬ58蕌CfPX8Ԁ0AZb ]h913v b:Df;NV̍+\'@><v慥aOgyQu"Q1KNNw}\#z?tboeP GzzZ*6V<[mQ r2?V#^̤tm*!MyDBt!,EEEg |0O%a-G,k*3T;I!f(9VAA]Sdi8pE x( 1TH@ anG$}dtڠyTPwZ*t%ѐF~Τ44Ny9DN 0/l6$.`_vTE.~4a_aOsd! b#o 9VkZZR8Yqqu EmIݻwcU+**ЩO=^:;wBq|1IH|E~޻woii)v&OM F?ӑؓjqlavQ:vM@[`u󾮮~ㆍk֬?4;:NDm}Q9JBtusv$<Z31rխ]nÆK.o!S=fyl8AbDءCmسgoffVjjb1|zBV."BnLc=dZIL6X7 ňvee+WZۓG  v%ے MLL& DdEF x)_1P6߸a&h˖7o9MjӦ}iaڼ2 =zM:2sشf妵҆jع+o^ 6oIW`BiY!=}[ZZJo- ct[zfzz^ؿRSSSRq^RRa?4]Q^rxun߸aӦ[6n,rCdTPXX=뱒X3SӥZmI-JaAٹkwZz&)5-CT%3`z8qٳq񔟜j:{AIɴtdE^)pR/R/fXA}LlޒV/oex_ꔾT-~Y~#}ANnrrvSrss23; f͚3g.HF9sm8DhތݒRgmݚZ3l(ߢ'ګ455={kKUj?Xw>sF_~P J`'= U;HN}%fϻ`n~Wg"s)uP.jĖ-?&pՋ3LuSOfzG$XOILWcbRcҹWeccʼnH1rr4c윞O9&=';;j*.zo@ + |";$*c Jؿ~|BVa0F.:k=&&6=Ecjq$b0AitBEcbK|@Qıwc<j2w[,{߯ƼUFeƼ JX}(fA[ wŋ-tf,sϝ2/KM'n>cwJڠA6ְWT>>Zp]X.vzr/6edr4z!ȧ zyçOŬqGksE&ͱ&O˦ĸ1 z3R (i͈LԶOkQʬŊ.8U~VxZ 5"2Q2>Iʳ;#&R K['Qu[xk g|P7X ꚓT=Wm^:03,xU9򊳰(I=8%c)Yi1DkbF:Hz{_ZcMD&CO-8[AQ$8>QCћV꾈QjX-N(q֣%]p,+9ᙳv\$d11`jH/#'[V'; 8  PL4悱ds0ljrÁXVO( j[H9VOA M;D9bwR=H@rc(`4.8;W,{' |Wh|ߞ{l=>0 n83QFӐ&_ČD :j*D?*)蚓QNJ_nM8 23{Mirvh?Pȱg3ԃDs\ zu ra˖~f=~?˹F2-dLOI_!hRל邓ud*myTdL邓u rjmbtGv^eͪ)W_]V#6o C7t|6} L>ٻZn߫һZVDGU#vz'jz^ZؾWO?-tȾ_~i^?ߟ_/9;~iH\\χ>ɘ>`׮];vP# 0݃{vޝ 0>a'cOOOW# 0Nw轫μka;]KH)..NNNֿd 0v2THHC>x1<W+ʪV@7gr )dteKjn\}5k0OW{SwsAjWwF 3"Z$ht~1ZS=ʻ<HP=gSg~O%Fڿ]ɾꍢ=Nz\.EۧxliҮ<.ߡu%?Ek:G^K/ZSCS(i7zP?jw-ҚjSoa'N7L'Z:?,&|'C#Daj%<ۧ/,:+FCMbFdH(pr4|o$'&  iɐ5`d `'c\$z['j%r@i>WJ^r )dLdffvK}BEE֭[EE1a> o}}]8&:+, VRRRyyE>12.f! )$5R8#<ŋWi]UUQݽP;_!E%*+>>C!ȧ QmL'* Dևa>,9ZU61y 5O T/ax^:@݄ f'CR]BiT;kjj*:0 ;Y8Pc%ցR8L Á3XVFSRR 鞺rFB2,%t“jV; 9X3 .݆S?9u˥c(**T scBeddڵ+'' RX+ZyY &dCxΨ*`!B޾SDV uir:#I3Q 8qST&;JeJEq1]8o]2cK4 3m{f28N=-= ˅YGUudlWD0LN8ش?qϏ-qo1 F^0z,/`FMݨ;ŠKʅ :0a::jЙ::6n[?/O;P-cpHCX t˭Ғ7l޴iG9NN ?OG?G;B]wM㮻 E提$GTP ݉9o Qnaq2;<bF ܍yׄ; 0ꞻk w^z]$ ꅿx ?wfK?<0a;Y8+YfFLEk,L!F)'ZD[㚽`v1=8tiC4,fGIr)b5mfvZ56.GA faM a,iCPY2#bTJkn]M=mPQyE׭ ,3-]ֆ U- 3a' Vl6#=e]'MAlNN0J3SsA]Nɭ7Q]MX?D,&d/~'m|)5vIMe;dMԞDO+L#~=DDsڌkMƦj'SIr2ˏ~ oqR x6*8Le.|7闢 7Bmb2r0rDyNfy5% %)-jb2&O:OlB̅i떈#!ZYw>br/`' \2b ImpWMVq-DOMw#;Hsgt$E-uk˴:ɽb'c,:Mz Z9îaEF>w}{>}kC<YZQrԺj.0U!!?&O!*NJGn~u=w5ϿVaĈFL\/q v:V9rddaQÆERaC(22rH|Q4e({f~u()*uUGE0vmc#D1PX%UR&ZHޢnoP%%-y|oFtJ_pʍT 3a' {K8fC54&;1Dy6xV9.{M悽8"_~K^c[5V['yFOcx>TcI5Ho`Iy| Dk&"`J0:}UY] =}_ @uH(*mVK<NliV5 g*VZP]--x߿_ivN⴪7nL~2< _Vj ` @I#*Oa'c@`' M[BTr/qV&@HVTT7w v2 vn֚3KHH@;; 6ω^aӦMׯR ô;&TR ô;-|)Daa@?$=wؾf-jm&|a'cETpuvHuVfҧ\_;cv2[lJT[YD\PoJ8"KNEXxDq|cZDdhDy$}I0fDydT4KTR *pX"}X. TR+iX%2P#KG3TL=]uL]hcs}V)"pсPL Nc<|ds/}hG?X^e/_vtHS ݕPrؘg6̏b9IF>rA& ;3`'cEdp 2^ }ޯUnN ɘnʟ@\m_~生 jm&|a'caBv2a&a'caB9_|90 'Mʥs2a1 0 ;0 ڰ1 0 ;0 ڰ1 0r&1 0;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ڰ1 0 ;0 ('v2a&a'caBv2a&a'caBv2a&a'caBv2a&a'caB'cX,+tN&y`/߿~K?6&dj_\q^ثknnvG~e6nJ丩7z 7mXd|ĸi׎r1)rCrbR㑖 M.45J1vmFrim#=g_\Ma/6 445 D4ec&Ɔ{dmo ?äagS"NfԘ)cdQE>l&0nr؇FzNϊ/߿~ Gt&'*7/`oecںÔ6yЋ9vx) S)ǧnӿ5a,:.YW^?'gnp'_;#E"LqOq۔aGny rܤ'=?|eHYq_aS8 Nf0lcq|JcI]x SfgusʔVe66|c&wWTvsw{57bo{dm6瑣'0vꍣG|ؘQ~ݸ;emomƶӳ/߿¦6FC33 5 ?NA~o3i$4Ȩ>&դ-o]a.Qrh8iKMՇaNc-i0 R~ie?gQxnoLO]76?ûYuƵNo^t<-Lw7_=Io0rHYq_à^$&MK1د.%ILE$) r&r)[W3E}e`9duTVFJ4;R]uicQ2p օ!Ik" ȪO=frSc mr1wo<w] /ް8 Ky͟Z\pPo>!]Y[oϱ?1@,ҕzs)%I<QӃ9 lIrl%„|y-NxGb*ocSFrͥpGΝ5;ou'K\pWzwM5n.g]D-;׎zUǾۃW>4/F>P9bzGl?~JUEץNƦ<M̎u 2$fTCI1/h&{c&u5ۦG:{lϣn6'1=qS'VnmSț^~C7/>;\s[n4l#f,bzAl:ImH^N[[c;2߭2<s#o}q\sǔ1uc|o7cΘI#?4|׏y˔S|6KaX,VԁAϜMa"M1~ʍ ^?nxCLz0rp/F 9qBs(J|'Z|L< L7/bXAS6.<eQLۦG¥+9Ta ظi2+qgRؘ3`8赣sb.bM},1^ES㧍@ N6v:lO;^ GM>%zl-`X,VP5{cFDѵB|A["A٘)·s& #99cX,Voh@ۘpsH갌*ZX,+6|aqI*^>b 1d2Ʃ$,  e\bݎᲔ4jT,aw g0F \gY8[4n<bB]-66Sɴ{4Mx1& f2}t QtXu:c.j)"ݰXԀ2&S5< ͸XYnGǿ+v 8 ƳX,+J_}0  lCx%"3G%(ilzydcrTiW QÎǿᲛK>o[eLhY,2zbcT%fe`4Tr;k!$ i8z](@9*olLS) 1 C %Lrb|?A&=uʊLμbXP!ۆ]в=@LJƍgX,VwobX/ecV)bBNlcS {VY,+x_6:tƔkz卍`SKDa X'%<X,Voʧ)9fٚkOArZ躪kѫ-RSlcؓL]%f/Ab_s޼y4`cX,ac8fb8ԕY_l6<aXldPy i^=֭C\޶Of۫(\lc,7rFO펍Q6Ithƚ!=D'oUG $IFS{mI ^bO|<x 1Q4mJu cmb|IK<Γk!h=z2Y$r/w)-|qP,bpo- r0J6#ېm(7U!$٘sSbYHj V p;䴷D^m\"߂ҷbH+qSukX6.$!1sGSSӎe;DehhihX'%t ~0ІaҨ%fhj*Xޔe;n<J+r±DCGEz۲EZI6)NLƪ׿S0 s{G ȇl S[zc=mqT;"[oX L('acUL6ƚF-ke-$^dlLMX43L1[l'*Q^Mbg$mbػ>-Y//kҺae[3`c4ۿxQ͓|uODc3. dc>EaAi1d4oaOZ٘ Z@'œDgc`0 \JtQL?6fX'%t!.lQo G-QDKt3NE6bzSɼ~MɂwW j10O>^lG0I ݁Sz]6bzSluBSfJtMd1tQ; Hy>[X,Vo]c+rzJ!uSlc,76bX1uaaB 1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a&acaB1a`UBv`c pB??`c |60 ma&4hkcK]QFMvH@V{DX#T,uEz簍1 Ä ~lGQ"ja.%> *@6* pcrba˯ Hb)`c :YEQ =3!'0ؙC'3y`c :76f草6?9d:lc 0a)ӻbCES>#U290Llc 0aۘOaB11 Älc>ac 6PTma&L3Ӵf?bc 7|60 ma&4hkcw~÷r|S>W4ש)HmafƢ:wP<s|sG|gJZ2>aTdcKAjH ac)4z"oaJ[IuϹ^^@! h,ByQ>1* "'H1 8bחDЯht}r4l sc^+)!D *lc 01S60 3hat0`cp鍅lc 00E%a„pac |60 dc ƴ1 Älc>ac |60 S K/抖Mamm^lmc~0 tژ[|{W赊K&n]bƼo V]$;S|mK&{Kz= lc 06FuIҦ7όo3!A{cd~##ӻwz=4㰍1 8>rh?b$ s_GP,ZvC2E>l:1agi7ޠ a~l,`cpu(*60 &0L61aЀm'lc 0A8٘c0lc 0aB٘ڪv`c 7|60 ma&4hkc,5ޚ¥TkMjK1 8XGFM9-HQ}a9⭉o~ Suaj'71Rɡ_H/·6F?*A 9ZQ0̀=%]6F1 Ē34g Swad=FP%:lkaۘz=ZH@SaCGmz]3ǐ2㟉^P9*$$r^BD~ >acp._/dQC1a#6FwԁQw`cp`oacpu(*60 &0L61a ltЧ$0Lf61apm'lc 0ۘOaB7W)^S;jԷ5ЂzMK&R0̀go8~7"G{5|Ugacp1ttkANǼ1_qKی70#^ntw-b^b1T+^,Bv/˂60 3kc6dc7֫QL]aXoOa^¥uՊ:S.3QZ|ަ0̀CuO6&/`W\QE yKC~[C&pDyϰ1 0icCggfPacBO @X?maff6֡dm ɵ 0L"l,pj%mⰍ1 Älcma&Talc 0J8٘c0lc 0aB٘1apm ,v{Iii?Z'a `@ٚtU321 yؒ˖o>S#ZGJ'y۪Pzq[˨L/o46tj5HO&֫cz<^Bo;+j~x)zt  z7-^2uFhc-?]>]$^L Dir,,G G̎u@&rL1PRZjg1 y|:Fd$^;Mv|z/M eId6Vt&% Ƽ9aF*FKքfxR`cdIt6F>:U 1It3vc >Ba(^f/ %<C^"RƘdczkMH=b*4Oboҁ<$J>{ҷ=dUfot65ސS6t\z!rk=dcLo}1|\XMGd׮`uɉG&;%<f2tۘM[6t@[ͼWbc"CN{6&k'bc_u {2'}ؘmazƘG<&3PTmlR^^n#Oc󄓍;1Hkى;v(**Q0Lź׬ͅy^D{ۙ3QWxrss333 a|N6fSTml bwܙZ\\e***H;tXIeeezz6X[n۶-??f 3 33߮i-ݻѭ?uYYY`]vjҦ,݋Q5alcm,ؿ?:.8Ɂ娑T^TTFhdtmp*5a16यFS6FVWWާn7gffwR Eژxozɽ݉{_*ʹ**>؇wm,L())7|::m]ľ};vذJϘLJB1sDm,@~tm,)++KOOlj;TFDl^0=K{1z/@Lrͩk¥ax!LWCyV#bc}lc!Feee U˷mۦFAwl(,, ƆkzfOOm3`=ە ]LƼ' a?zI ɮǨ19'C=*)lc!Buu5\xԍ/p^V#fuf8YHtpAF QSjjUkǤT1!N{1 LHĪm?uW)vIp81sdԯ_B} *)>肛m{@' 55*'@IIIj' }Dwl2=XB_Z{MKKWOWKMTRLzo7{;{ lذ"11ǻ8öl٢{ cUVZ>/#V'c' Qdc}B 6vtm?w;ծN4p25Leo}vv} 333ܵkCM5.ewٝuBv2Eꪷ;X 󱍅.afc܇I)--)wܗB r[z~0es&%JKgTRҹOۛVi;rtfgf姧+%'ٲ%g̔zfOEEEi\YVV}c73)mgRZnrڮyivJNKIݝ;5-/=}OZΣG Bp@8>G1,_e enKAi+JO}6mܮY<}-WDG๛Z o*o߁!C6֭<̌uд}7ӣiإM IbEW6+-٪h5Sh6{ca2N)7w}؎;"Lқ Ӳ49uJoW TTT{'`DCնLUK&ҨY.kBe!KePs7v)[d' U'#?'crN)99EK7 &kMW &gT-~y {SppuՂCݻwضmۆN0ސ?aQ6JE| iKؔ]HEkh 3!K8٘c0B_N1٘ܡRf1NƳO/m,ٺu+llÆ 999&3](<ݞjg٘xQ%a>Xgc%\zڤ.Rw/xK^y޸ ?uƎ|v mSW&/m̳Hkz6u\bQs 1٘kG{Mͳǃ!:vHAfZo93]EacdEO\C7`]"N o{YJk/6{}HgmRwl=gNjyN$ƐԾ!JRW\jmLcsVO㙤5h}r_N,M~]=cb҅G. Zzzok<Gy'QX12Bĭ21,9偐6IQ ac`i", 6&sdEؾWvpPYL6VHU_^rAy?Go %LK;I\plG׷#m<qCݱ1H!m1H1aKu =´6F%uuƄ{p/t˾85!my eVjcH$Ð^6~R{i<kM'1H1|K1 17}2CtAZ/q:RNog&PL; r|)ޅ(^(r*aJ(Ww ^ h8pzclct)ƄyЧT-~ƺOO5 xC}&hQ@?HHHoZGyaVf&->)MfYE} >ޚx:)HAZȌZ+O&0:RqX>*Ӟq 00ꊑ3^mh86(q]^{٧wIɦT-~y"ӊUԂÈI6aK1EtlrlYy՝VgYǃj-߱}{fffAA}=5ꬑ GVcz6F"cE 0ژ[ژd 6 &N˂7)Dw wڬ!0qSXܹ+_15FUdO+?aZ _~״jꥪdg-Z*|q%~OͼGci_Z΂t:ctA W;pӐ i! ʧF( 6m,ZK$Mœȧ̻Fl,~=6dȤI z+-6v^|U⳱g }GT<C***/rݳKRM9@a:RSrԞ='#'˴*84!)!a֭MlƍM9$mȰ\̔])9);S3wZ-;5#JȅRJٶ?)#jk~A6RX]]]}}=j*&|̨{6}MZUlhh_ ~זF0@? ߆vi 946n܌QG zOBGf7jjkȽUG K$$\EIHP 4J9LY+QQ^uAtg:L6рݯa *iiipW uVHg%sNWFF&p[Nt0C#“01?ltS۷ohDt cF*FX_ar,:Gb_&ƂDAAA?[棣c520? S2`۶ei(S,iWE >2 -gr),,޾};\tQB3zZtgc?裁2tL88Sk251xxˑ?sEȍ0Dm2J@/泥B8X 7*X_&z4OBg7u c0V!^ҴZY4vQYhH`*z&@[߿^rii)P>Y-!l_&z.u6G{"oEZdGҩEF9H`X]]k.ݻѦ(&ge:1z7&wF)0J\."_ƷT\i\EJ#ES"Ct䊫51N+@SC|g"莋䔅=Fyt+D2j\B%uCO$\g ~SSSj=tX= SZ *`LC@g 4#B7F 6=%>&anw +$L`&f4rA,EZIda` ???^ӱH6$;:EG/pdeeaQ9/y(j[CYQbC!!Jci^4,b@hי*lcgl=:X$,Ll@Z[email protected]^~, 6 kj8XZ=C9Xvjk͛6lP^^5cx* 6_w8"zfHtowq"dj8q%fDlv:Z$uQ!.3$H(@%HP)-' âu {eY^7a=`c'"?`|[0g=lnrޛ\H{/\$B/ $$iڦm @.7ErfV"b1 cky{fvvVJڕsΜ9sfym+5iiKKK1'brDJ5Lh M& R`!H,[ lǎ])̾uv%/NO]z8(ǻ.%5e7Poddd`2_X LA֭[WVa^=u u'<$5c1ݛ;f|/ƿziA<op?dqx4荄["ٞ*fXRp }BxCu`k4F[ká`Eze=a-Zr%1CK]\} <!Wp}nf;N;j]^ z_-B7?>\o/΁F Yŋm7iz^M6L\= c}]`LѸs"CQ}8.\0Dgi fA"z7XCŹZ~ %ZՠB+ ,c0DYʫW3jZjW1Ы0˟2\bظa#Q %%HQ5Rs3֧aFLߠ[߸ itC %("nvvիSRR WXK{V\NU @ _UZfZ l U YaM;z#x ޚW.YjJ˔/ZrޒТ+}sbVEwnsm_] ټy3n+6l,|saVrUHA0k7BZne.d+ǽӝSlEVd9I +ѹ.~s2$h@he&gcCmmG *:ƒZIU@Kj\`v@lCC* %F`.q![V78._o1FNeJX V/)Tx=>]Tu c03uuz"a #om=ڊGZւ%ӊ 8e+ET> ŭUBEl)bSp߬5{VRrRRRԩSCDB|\B<O( dP!>.DJTxފ6@kIC-%&}Q>wpLu !Bzҭ<]B7>^fK 3=\lyL{tqt]k|:f1u+B-|C֦lꈉ4Hnq15%1u_z"5mG(ڸ~c2+*XHr QuЪUtV?6[qcxQ1c To1ҤIɎةGM>?ӶEsd/'a1^6pz"a,==:D?E,D'ĶL: {"W 5pk˷hdK~5~4{ZZZzm!Lx I3mڴ3fSRL+> n*T |ԩqSi8ijĤ8ȩdXAup)t tո\)b刏IVRB -tYʤ?9 \B-Q>:҆䏻fV'g(AA.&z8=2rWo 7 ʕ 3sV\\LIO/ܶmkRS lϛ~^,<qXB,*Oo#f/{wzpL:~$^k:NR^xՂH50j$M칔3eE+P2= WAMINmdeexݲ1utIdࠔ}P6mZDD4*O45)>)UIPC؂!˅qHH8%qz\fLON"FގOJ\bZo[c$qp.U.ջ27fÁwbgl'Kֽ<;,Dy|=:3RCE a$8@<i'㮫BA&vͺ%.^8sKwS5էqN#pT}0x{Nq0eۉ2jw 08|0 c)F(A):ri: +\*s()K /x;[C鏄{s8ս{6d=eޯym>PS-|nNYXbP`Vӹ|‰?Xx;-{6z&fӈ|4{0'.~ME<s=;tlBT !Po8M-M*=NLqSɥF\z#OQ@8i*{-DwgO238'7auR%^Sh#[+ohɛtE{d}3߰.I?bs:s.A!"އ#EXR84b:>cCh 5/3_> ט~cx†>;Qs AbPR<yqnD[:t#ȇ%C#(ծ{>G4}'dׇ8X[v cw߻1Sʭo~cuyXճ0;>Kc/z--(׿N4Gk>@o^BPﷆJ0Da̫Øi1N(KSQH7{bbq_{YcjM^ K4'Uq?Lԑ(؛lڭ1SÙ|*ұX>3>KRь?N)+ c0:%UV b!!.iE!&a8D!!zR I-̿ȍyk1lH-lж{ ˜ #Ӄ01O6|BD#ĭIApVjbζ< *h-%haa q{!D#ɦ܃T5-oW=vc@C wP~Yz}, qa cMɶߍվ/hCƉ`|j`\4f|UrV_'RyK$CΤ3(E1X`[_8QQ1}&Q-_ppA筣@Rcv 09 c)& E0,1D#,;n(DedHڰ{`7FƎ[`Ucǎ !_ crC4 $P>,B. X!CC8<a cW5FE:/[u,0f/ Ve~rcĉØrcʢn &_1s>{1=\:c+SEV͹TOĜg+k*=ʓ ?+ 4f;3cTUo7u3 SUQTa ^Jm -gUa@UK].n,L u vca!\Ƭo-C&5ME=cUXsV w7][]2Rsz%a(raюay mןusԼsn?̼3q;] $uщOQqJqe2D s<곹[s˭7o+,t_i 8aAUĪtb+g9i;ʟBTx3j!U큖Tz䛃-EEeuuFII-ܢ>0@R $L051F- Eq^IqӒQiS⒧zb|B2 ԧ gO0&`O¶ɉI+Vj]r;񎊝8j#/ h>%(kP";c=aTqqH߿u[ 7\}L]D)æ Ũt9n,&n CY5&vQ/{SCO§0F_}P c8VOp&9Ov ;tv#L~Il<*ʛs<^G};Ńrmؐoj" #a *" =i:FA:]oL֖Z64UGKZ FLK/DKN!TRr2bN2Y}'LKN"Iu3%ᴤiӓMCJzCI?``zw5jxxcG}*;'A76b=ܢ랺A7>^^m/!*μk &O dO缲5[Cԟ\7яx뼍ކG%f[c(7 l7"/GEyY7nCs QjWͳCjw4^~~ttwc_Jpr^Nr }mo-,*<Uo<`ƍ[l>t?z&)}ކ1rUoN2l%-+!٠j*h[xsI5+Cq~U HJY Ue.$N Wj.=/G=|n]^VQah{v"er#apt:mR2ݜT\Rb+iW@Ǹjj[ 3Y:7=جP(-(C%eК)xC\NUo஭q9ssrrs.'1A E2ok<ʲJ:]+(/.ؘAgWS'C)@j́ iD,~{zoxXjYL}. tWR͹! Nt=E-t ᱅ &\QkOʨ@V$r(JHЃ-E!3"i裣\rZ36gPu3 x3::Տl@ F0o}]}WKhdPV7ةk5{FtӦ5Hcޢn;QjpBjTgR@\V[·7%46[XPG?GA'RTTe K38@jTNIIAl'^15Ì gt}-Mx큑 yZG5 ?4oSӑ@N'Z?]V65ͥ_꼩(%555w1zq:u֡9Q=]]+* qwÆ D㗆 tF#u|yb>ݺu+2<eM$zG7:VH!baFA5[P-u}u0Tjκ1ieggsRQV***233׬Y .tI_ǻ淮t)N۠CRU >e  R^M,M[XX3]1 a `VҩT4#OqhЫiZjSe0رc^-[+ ˿ UQpA9#QpO T }Ԫ2= u4Tӈ˂͛7WUUYۙ쾼|ӦM֭ӥB{*E jd-Po]==Bb R cWw)"s`R-4SS-̙28bbcOgVY9Ϋ*++q& w9YHIII"?"H` B.HEC] cu{BJH$7FB8` # DLD5^o t>bT#!z!P0m `;|[email protected]rS\\wuPEXd#y -).ƛ?ZYg@1+(]1 a* /U  &\$0c4WSSq/k Q:a}>  s0kvs),'PgB zk֬F}b9ba,ZGxԿ xw-E8"X; k$6otׄ0d+yiBAcKsbiV6 ]TO#РL#*++_ǻ,//Qm|_Xǖ-[oߎ1^Ulܸ7AװN@իWD*V ֭i 9ll /H#Hfvp|&/ xD5 0™póGjj*?L<0և Bًr媥KbY]]D<I,//D/Y7|' *uﱌzLުE-YX~;!_OϮDcӴr5Ͻ 3p'[1Çٮ`C,X07\>K@=ß~=ڑ0WY~/Q>ܥMaBDEWVV566|k^Wj7{P*UˏWS[񌩇 } Wqx32jGgٚK>`Bb4bLm^ aT eզ:^{ i+TCat;Ђ)QBU#Zl92CkѴC;k5kbuY OD¾]!aѪ@r<[͡H=E Yr/_ƸBT|P} @];0Ž̒3́.| $ݱc粥|xTǬߥ9-Q0f}MBDjUʒ%[6441u.㍠! i\!Hs]io H{:cC*PG˦+D`6+">X¼N;gӦM ~(++۸qczzziiu+WvB z֭+VXxiHZ-!-^d2L ˖ĴT,]2tNYo7co4wކ@v^FN.}-DZ4oiś +WNQ?hnּii$Y(_F6@ε.mݺקܹӴbvSRR/[QJcU%x"K PSGtA$7jIIqɆtcRS8iiӶdn8%7eOZ~)]X(..FHCLECLSD!j._6Z˖/hK/c IIIӦAIJӦO6cXVyuܥ).n{T|Az{ Wc橧'zd}wp P mR˖~,Rw}FFF/ච;wq$%Ĥĸ8ɣds@<MB4̝;NrxC :I ,ɺe+7kv*7|IMpҢ~|x@!̤_  c}]t:|I0DDY.)*UHM=@SMޘ<Fn)Dӧc x衇u?:ok.*ú[ `lūшNiDiXhK8ZE JqOv1egg(ԿRؿ'%[Prbix$p$!x񲩩[XhwB^϶p -}t E[dB c؅>AaLݻw[aLPԃ<I^cg@Yp{ Ϝ}H c3Jv=ys֮Kӯ@ al _EX ˢصo*NMNbϗql='to:M. sYVduF7 :]U5ZL:;v}MZZ>F:!a)ԮFأxk~x ׏{8Z%r/Gºsot>0Eªu^|X8@gED[=Tvgjs==/r地;)Yٹ&DQ63ḘF*POD6AvEcr.QPc32Cup?`z'G?+RSOnVrrru:ƚ[A1hޱ2!%4r`}ݒ<X]ر<\Ɗ|DX?a c OOLzWԔwKpQ[BW߶~gBۯ>H`-Sg<k>8(یOk3?wBI4!ѽ[Q_BԾz,N3h\Cs.UsG_hʍvՔni m=csݚ7<?jmiVGa},հw~~d`~'Jټ~SAS `(yv*DtD /U5F }B7<\ytW#P%bZr?E1l6<>vدvrPSڸιꀿ;ihYez8WCKHli~3G2PX^{VhFElJkP,w4GYu?DDl1RwSlaMW"Veo-_\9gE26d/(&ƚ E1cp&HvGs9hbdw0&LzwGz cVݗϻ1l̻8f8Djo܋BD&d)8& ϋM/OCh 5o?eMzWoY!V+{ D51 QAˋ9- al_(A96AKuf{Y};B k#n a A'!  kEw|lưD h Be<T8yMto:D}[GSr9*Bx !!]O,06yS7x9Nvx?/@a"Gg&EuEg( %d cH 1B<0fn Hma c.`j>ꆛV"aBB4B0CUȢYlÁ41lH#?Z&*\YUC\zU;$5qƐh~/ ;U1{X$ ې0ѝ蔎_al2g0*Yx8EH6hQ !b!!yūKxMLD!.E/%*ƌ UWs0 ܿ{1DCPG7a wWDP[߬a A%ǖPa V0gc5p[’h cZ`u ؆sn b-! أOnE>nDMBb^Tc0+k9KC1c7v4!҈^-_쏝<菊Χt7UL50򖏝06ܘ` ch^ [!Ae;r3 ]`؍oZwxdQx9;r&,3Ɣ91DAApxO=/0@RpcXARՐEjii1s"*6P?*|a 3 cz_į;ʈjҐ1$ Aa G^"36.=c6EZZ1tOcƌ@!*#;v?>˹ vcU0vV!wYjQa "Q ݑc\fkv&BX` cn,\t͍u:zokW=cVa4[){nݛN6@Nt-3= c!n,\u|c2w|: 3fн锅rm'\0l[ں~K}y݉N}7p=}d֬;SwS6na %]]2?=lk[Y6r?\cH'***R IIIkBnEt]p[p Qn+fLn-8|X y@8p@aQMlڔ1m4}Hrr򺐟>:tEqqfV ^c~ '|Z  cB05YYYo  cB=1555W]!\HzEwØInnMtFHzErRSSKJJt^HzE/ØI~~~zz7~D0&p1Y8OL HzExØIaa!Z @˜+(mO cBXf͖-]f/)--Ŏn Hzŋ`tٸqc^^Ԃ HzA;X۷oOIIq:ػX4AHzN;.a!aLK]ߊs{JVު{oplTsfG(!r06)=?qcHB|ۆn=a06ԙ7mOC`m9 N70&B/06Ա1ro-:Uc-u`5|ԡ V1Kδ[--.~{=Şgm{~/tAh$ ula"SipGH=:Zp 6D}1|Ec>WT]z>p)}_f Ԓit'5޴_8B١=v϶"!1:>!!=>ZFC 0&N[7  ٺ9~D mbG|e0%V#\32˩uϐe$w0`(U0! A5FxC3m~dUWQuƖ6-HDP7 cuȄn Tk9ݛ5~amnY$}C=c`́0Fk?%v%1*n~KSn,M*'s:ƍp1Ɣ!KEP(D5=n]ču,8fu*VYȊ ǟ 0H\>Y.蔛o6Xy{g 4Ƅ'zчm3u_먣ZhRVVyιoZ(df 0HrmܸQg"\銕+WTWG! `E˜:1TUUv1YD D.; WQQ^SS55xA]__ B:4ɺ֭[αSqfPΘiA c<Ac@%_=Z1A&EQQQFFQЀCM,?Dz͛7s<^" c f$*v90YcFZ%s0{:ߦ 0x/j%uA7],l˖-#B!a, E1zM*0H aFYSw.ΚVaaaVVVii)E b$tx1#UUUfA$E9A9[tJE2fI<AcvH9}Xj?Ak0_ٰ_Hp wp˜mM8mӹP~FXtG!ĜH=Q}`,0# \n7aLx)BUT=?D"Pk @RRRQëLxU-a+VAޖCh#u։9~FXt0 |d9̨B$ Q_MEfVa3F7Wi[mAʇPNT-jbHCB>r,ںu+*#*p .ؐ7ESUkRW+͢ X%L cэ EO( P!,effcݾ};t[í081Jdϣ>WVpkT aYTT]VVFEuuNmp1 fYVKZl5kPvUځtX`p:/B a,dL.f^3%6z <q+W?>["uaq21,!ʚMT!qZKuf-:+)-&X3~aW(r i@ASLpn` -Q5܁*,,LKK !Hn|&மs"VxNԫ*ܾJB)h᪥[6ecVWQ1\V@DNࣿau_EfZڪQ>oߚn͛7[~ . ! YUB5*a\PT]"-_U0ڧDngP=&9Ȑ\ B0xk˷zދ>o33vg!:3g>nig?pyZƩcVÜ>O]vQ宸{;~EƌyXYci9:s3Ϻų.zv6ܲ| x}gIL J3g<.8‹.",.| ߅^!} Pv!_SQ1c󹐄.9ywCۢUj 5TsІfV+n .8KKIۂ]@HCv%<|/sOee7(覴w1qԭ-&)dc4Ygv͎:;Nszzeat r6_}yEE˓T=ʱp6goڒQRNSPVݩkǰaða2@&(b!u ހkbZTLuQCn#Fq0`)1=nQ<Ƣoc} 0qǔx%$咩1:{cg?o}pCj8sz<x4՟<\72bd\㓋Դjjjk8~qG!VKP?Ge}x| [pt+00aTprNCԔɱQב/X1:@o^B0fd[[չj==Զ:t!@s#61, Q7b)6/ z'b9"5aÿs`:XGubrwh/Ço8P#vw}K>oj)Qh b'/haGƪ  ף];G˜  cM}SQlDil%VznSvmC\^hj޲NӿW߶bA:ՆVag;?nΟVݥFgoۿЩG)KV+W_p-tY[!nFZaKKˁO=?N{VϓP~М(Okl%V wvoz@?iiݽ3 _5ϵU܅[X kZ}u8-dQiU-5d֎25Ј:`w`6GuAH'ܲ>N<9&_}d-tY[!(;f=s0ijx?XSoٿOVyjDYXXr[U c " ^+c-G&DIJ?Ci9x%?UB>}q8{el :6vpVmY̐Ua=dޜDUt~Ջ-tY[!X7|qkڿ]O{ᘵiH_4\06kzGE ?a,fDABCܘ$N cX? ]ih!tyƬ:l#RSbGvP9!0*,m*݊ y$E7ޣnUNh3Ri "0vy^hQXxABL [L:0z#a ]VVa#a,q6V_4%Tg|B}4?1ԧeuz/=MQh۱k'8np$)o)vZDGl#f{SmΊ%FO=wC]<쳿[O)W8þp 7*ՍGObXE۩?HZ+c#v~_AuNFF5,uKsnE<ƢZ|{\5f8GF@#=4 G<;˓gtm_ZB<|>lK~ux=<n9aĽ'{CO%9i&_z5NSm߾k=z􈑣GEihGĒ4rHCH#Q45BU5r448)tMUoQI#G>qP4z4 PeD>456+ں5_[Wb!Oꖮyrbq" Ƣj_vz<Foc#eݍ$ u&Rȹ3aMFOz|zP_`訄v !U{5KC]hiE=ǃ:v=O'꽴D mՁUƦ;֯__S]vXPXjZD^L̵hJ`ͶmtJN0)_m1㢟Y!# qRDju^=>ixjQHkcu<.wcG" {Q UZu(bQl?ZZw@HZT[PP[$v˂~y(G: ǶMV0z-^k4BUއH0 d` O&z ]zVaL)fd#Ev GP(ڎ*S 8A,YGQJoZ6C ݐĶ cmCC#lSYYyYY L{ ָ%Tn°"aLBD s*gV!ӹv̮vxa>SdMf@ (!D$ CT\ W t°b:-0333WF$ BHۜ@.1F l׮]wE˜ 1!a+zrrrڇ1!D$ U]]]SScF˜ 1!qaxY&55u:/BHD,IҥUUU4ʁ\yA:F˜`߾};f|8lzuԂ#*..A:F˜ZBg >Q8Ƅ ;c W^y >X;LO۠" cB)..?L2wʕ$AHzȲe>5j>NYp&1H coHz-;X>TgT:6&vs8FٵZGZ:ՆT/8ffN):Ӄ0RՆ%W$&RNΚL]!aL Hz-QL?9G;%cLfE/+F&$ƨ(;Q+#жZ[}B^P GT8p`_p*j ;=e6:^:*L#!rKyX?zk#VKk5kv537I3ʂ>nݎOLl9~'oyȢڎV&%Ʋ$c*_{VH1a( aL!;@1/ىsB f@Mäݘư-1 0kC6QY{f\>Gp!-aO)0n(i~#!?n?mׁ {'aL HzH_CLҩPP1{cdF:k$ C cBYbڇA4$ =ROCzX]NG;нA1礥ϘqۭL"z7B UVK/007o~YY j$ Q1A!0& D1A(F˜ HAnoA!5 ڗ}  c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!06+uNA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ P:' Q1A!0& D1A(F˜ HA c B#aLAb$ Q1A!0& D1A(F˜ HA c B D"H$:0&D"QJ˜H$XDZ#Ͼ2d<duUp:*Dll"\C .[![ByV!e<duUp:*Dll"_Ǟ|iqacs~sUՉc1&5'FzkFZO9Q;Ff #N8~' 1^=rܵ3j5h T$蚑Ff4jhiulkFxYO9;zęW8Nr2Up:*Dll"\C .[![ByV!e<duUp:*Dll"\C /[E@c~E߂(d9yտ0cgN:qμ~O9zQg^q˜:J8\DK75ahXrkJGrb'iWF1c~u'jWs nr2Up:*Dll"\C .[![ByV!e<duUp:*Dll"\C /[Eݑl5{'^Zxek!(*kUK1h-ȉ1ʢHEw~u'“.3~qaUs5z0WWx3SN=oo8n#sҙ̫N͈1W闟8]q9[N>Qcq'qZ}hX>n{% ؈Zל4c5\܉tc &ӯίzY>N.'#[ByV!e<duUp:*Dll"\C .[![ByV!e<d_LVʺtbVO4\~ïXW_39:c`6F޴w߻&x~ȱ,|/z,bdWuBGdNtŊ֎Rogג/:>~1q5dv9N9y3 9Ѕ?q_FFN}U2u/?|_~}DxL1k)g&17̫N:μ3=~so8kO>>W?>x∱W8ˉg]ukNwͩc97rl,{bBByV!e<duUp:*Dll"\C .[![ByV!e<duU|/ ]12۪!dfN(.w$ke. E#Ǿ2,=:IDATa+mZMN'`ta7 ?Q&ؗ 5ݑy}2VtOj8ض>e6fV*w X̽3]'6O{_sx1ן|an۷7__g%>E<wf.xጋ&y</w9w\vM?SOdf֑x:λ_{Ÿi'߼fug༿GUyGw$kis=Xl"\C .[![ByV!e<duUp:*Dll"\C .[![B!.V7ꨵvOO0Եn<gއ_1kBzuUboi] f؞vW5uݕi`^XK Ա췓cU&*[f/F5⤱N?Mh呲L8y̕9׾mn'={3>+O=cם0_zq]8/yzW O7wj¹W>z`:{=3g|ziy:RK//μ1W;m<sNU*J?+jCcHel5Y]1o.+ku_&v:yˊir6VUUzGR6 3T%AeF( j|aQΛNUωe׺Y*Ǯ߱FH3ړrC9_믧>|eSŋuMϹq#μvm9G{9:r ]pU7,y+ܫոko<-Ly3.}5ϘvٓN?Gbę7ܫN: r۾}D"H$DC\]l߇ߐu͕}rGzBs`ДؘfUpPD6 D>|üp>]1càruhlhG\hY]V1axȳ9Qg失W2~ c&Ow ;a#Ϲn{OU?>sՈ&fm;cჿ:S~w֯-v5꟏iNċ?z̯Ϻᔛ|hi8;1&<i` 9a~A]xCy1GvFβ[wE"H$DC\.ʀfdu6ud3g]M~xg_F?ixԱ7uʸ^?z'qbiO8gԩȎ<Ϲǝ&;gMy{cI\߿rٗr'r~Gvoߍ<~_'1akO:lI㯸+O8/>?7g'?›Ko8ˎ? ϾӮ;+1c"H$DA1ՕT'N!~ ¡\w4w?Qg_7 '</|oǍ>{Gϑ/9g0juN=n&pU߹9G~׌>ʓ^s9'^yOwco^~ܸ+{3'SιnY׍ȱWs%-M<iܵOu6rhc뿞z֟Ν0c.\$D"H$$ENgElm]qTFyͨ׎>g]s+G~7 Sն^4aX+.fx%$E1]ԕ> BkGv8z\>W{v::tWx'PMޑH$D"H4x$~l$.c`cEOr'}`D\X׌׌ JY5a#¿M1n"TRv_lμjکmTaxM<鬉'u-ވ3qU'Ү5H$D"hHIc&`4I9t\UeFj? $2N^Uc#NF[^ʏY-lưV}NN+GȒ[gYq]" D"H$ *bD鱆bҕZX2ieTSFK2tqվ]mh$dԆj[]SUTD"H$;śA)vl5;m[N'n}H$D"(J$~l|'5u.VmeorGVeH$D"(z$~l|2Mр+Ď٪D"H$DѯXss2>_`[wj)y=\*̸qOVo5^]gNƥL>h]BdQUB|ȗ"H$D"Q?FvwtKMA}Ǵ/RH[BmV*ve|E"H$D"Qc?oϔʽ[I*f*T~vyvEnw{YW{P|;%h70*m GM v*SIm4`Lw.vb^U+-D"H$SOm Y[R}g *4nF)k.3E5q-loU`/ҝYۦPe0z^]ۥVm+=v?2_iH$D"H k׉"y qs k4Q[w=g ʲ#G҂i'&vRNʹJY@vhTo\ٶ(H$D"H$4uqR?<^Ow|8~$ŏD"H$DEWZ$D"H$EďD"H$D"Q+ȏ0?UW$D"H$D}-/c"Q8K#PN+taH$DA=n߻n;n}4]Ռ ut[}Sp((ZxAIU]cZeSAW!a[BG"v D"H$uÏw㖢ԴmN؄B<m6@3κ{[ZC"kvBbK®?pӆuTۮcz! ďďD"H$Z"](3 6nmmyL߆e;Q5;:.cΛĶ!Kv/7> ~ᤤm%Xr˭(autscG l7|{T%c'f /+WgM? E*s܏x>t)Allg]?哓#sBKH$DA1]W7py[oӑӉ%pZ]l=J6`^VWf=tRi{ǬmY] ĬB_<gZSpsynW#(Ѽ'S\̏2Z 2hm͘B^UtIvBc-Dh^KZedYVM7e\tlYm+c"H$:} ތ֢"clB6lSWA-1mj|K7 QڒMKR:t-V%Z󸚥tS|o ۪Pt׆?>Q&Y4T9=^i-\hȮfLaUdXG~ j׌AhY E+&;ڌYB[*=$t]ue)nyJ~̨N5KSAl;IH$DA1w?qkhqֽݑہzpY^PD~nmK}66o膘at:o֎:do뗔Uf:Ť$ȽK{0cEmU'^ 9AՂC{Lg}^?h&l13aBGymn ފ2QQ:D%['!ՏQIY2yi|rV57JH$DAmn^Nĉ㡫]^[%rte5gb1˼KFQ,v+٦i$m3crܷXaF5cd2 ,wG^aeդ!kB`)lUHcݕ-?^D"H4(ճcm2s誗,ȎAm~G==DU>PS #,6[ d>{ezs?9KNB3c?~KH$DA(%P8;FmPĀ.: @XďD"H$?&H0<.[E"H$ďD"H$D"??$   %AAAc   1AAAA    ~LAAa`?&  00AAAď   AAAc   1AAAA    ~LAAa`?&  00AAAď   AAAc   1AAAA    ~LAAa`?&  00AAAď   AA!_SahZ=B   cCc  Y:AABA   D]}%O^0լ~aKܸ(in޳2Qfw=v[Ur%]:s.lޓZVF=j?ws_yc+E!V|0AA!Sf,௬tPM.0E%1ls'ƈAAȢ/mrM'tUz0s?'㞛+k1AAA,zչL.[@/7:vOO0Z?&  E~L4AABA   DdžAA!?6t?&  i{an@   D"vSǑK   D"c  0$?AA!A(~l{u. g]n>,zQhYoLwN۟jď  K?36,{V&Qj^37LX%~LAAP5+ys5n^5In57+V+kcT򄹨Tp1ՌB=Zw`D~lWBAAL{eNz0Ț.˚:"bY .4q[؞Ɓn*G`l̊1AAAt5LdgծC6Lo'e3m1"ec_l٥`~ұKzYoTԀa.ď  [L,Eۉ|ď  g~LSď  @XnAABA   DdžAA!?6t?&  5K7g ~LAA" c)G%~LAAc1AAA@ď  K?aKxfsJ>g %ByKg\I󞔩F+AAaHХ#3 ]:ۼF=Y<yyœԗ.urVHq .Yv{a`m:vQcc@5^զ?A   c&)2]۞0UF Xbfjɬ`x9=luMXZ&iצ?\9*?&  C.Uhd3F&G^|f^թ n*ZשFdTH/k5@   B?fż[BX?&  C1e~P ď  gDŽ>E   ďE z/ݜ1AAA,ď ď  Bd!~l ~LAA" cc=n@   D"vSAA! ?AA!D   cJ<al@zCtsNU:yOTޅ3l쫹y'w6L?&  Cc:#`.q<· \`37:c  0$zu(~Ye7hk6ԨxhQ5u3Jۍ)vw)kǰ-ZnU칹[0mB;L􇁦Gʹ6%!"~LAAc~p1=afcQ1Avd^hOJ"X#1VsE.Q5k-T5>؎3@f>mނO]AA!AH~2TtoJ.{P"=r50xZVwՌ:v?40<S̸|T2njoFY@F{5$AA#c9?3Æ2Q &"ݏ?AADď  @XnAABA   DdžAA!?6t?&  5K7g ~LAA" c^ ~LAAc1AAA@ď   D?w=ҙhnWMtG47Y|17tˋ\ͼKz^n좏?&  C1..EN u.Ԅ2 $-XSff f Ǟx`ʦڭLVPmwh7{bcYǂv7+k_ YWuYgAA!A\f!]1j6Ɖ}m[ئ}2֏mnS6gl~>T!~LAAcM=ca_؋ <;0H;c{W͚? ԹkY ҏۦ̸m^e14y?c   tE~П4Q'^3?&6ZÁnKÀ1rV3~!}R3z?&6@% & c9x7   tT拏3k_67uߞ:AAA:@~$~LAAcCc  Y@l;tsAA!?rc  @ď  @X"~LQYYhqK/guwwnYSse% N~y_ɓ;,W47Y ?,z3יC i|>ItHj6Ў:@VEp!cې/O^ď /}puaZ_x1t& HH~)3n!)wҟMZ_w,6Lٳuɍ\̀edq\&Zo?&~L\6!jWFVO  #18a_w=1eWo+ɡ[L.*U4w5u?~;'  nM )賉PP<N.ښ:.;4! rf<DJ 0PǴ oc9Xu:Tܬfw0yusz[#/~ѲyNal~̸?fMw1A@g~,ƿlk?PoO'Z%v(Eh}_, ,7R~5^ď E~{R +Ə)륾DžrInywC?FL;5<ڱ1VZl=a+hsi?\e@rNpx_[ v*~LA~ ?Vύl(U-]x H&u[[7^ R ?pI;TӆتcSuhGjj[lnud̸:ɿؤ&~LA(c y'et~H"~L0Х{B"Dz NRj }5 ;KA~K>,ˆ:3=~]̛iܸ_՚>.W$~LA("͏ @ a ?B\Hly4MYqm^oXwǨWTrȿUTcM<c B$#~,a7{ ď Bď 1AZx<ȰQ8.3sKYYҧOAcCc0p=KfpĆo:ֲJ}pe۷o߲eKZZի׬YiӦ]OAz1Ax<XuZ;-!Y :M`2334>v؊Bۍ7*WUUYYA:BXbX3?&۷_e˖-al z,Gzz:ڬ czǬU^fdd8N]˃뒒 m6^n[A*"vStGa0K|'|\ه[OhCqq. c&4p;W.((EQEmm-N8N ^̴4x6XMq\0rMa#~,?&]B+==WpbzuME}CjWTTA^ <n`sssaqສ m@ď %%%[l6 n%>8ק~ \ eZ$cIUcé[m F~y_ɓ'u577+~Qfcn&w<׼ҙ[&/F]uO({ 0BknO>n#4+~L۷!tB /٨`ͫ~c&. $55T mpBp* iii(A=+ 'es%]l+(UrYv>,zOFKy7.BTG.vO^v}j+6 Pzuv!~ >FKOO~k/sq+7ߏYy+Op֏Gfdd`TLa K~ i @{W2Yw`}6f ;xG6ȏ{'Tux.ԻtHda>?ŧ~٧͟} ?&a fퟯxu2Gyy.֏ǫ.BF{QQHPͬ):ܱ鬺 7z-I#A1}[J3 6qF +x2[`eU?vL߬T@MjZy#OSc[nwqq+^09|ohJ@ouQdfff¸br8i^p=_O\+Wt==Puی֏yL?zWI~K?{ma0?c&tfP~?1A X,-W"ײ+V*шW%/LϥK.6(,,+"Rp -[,ryJ0].G ӎxR坬hTBXkǨdʛ3%B~,\ ]'_4ܧrLRQQ_JIIxIdS]] 'Ɩ&55N ײz]ăkn9 .T `Ƹiii?618xE-**˜7?w.?̃ezjndA>W-\ %[(76oa[YY5ڛ1Aȏ >O?yPpYիWWpUWG֭c{`WG8 T0l0`)?9=?wqbYj}zw]Kתk}nwtעk*+kjk;w6x몼}Z~k??>䓏_͟QZZ6قiO聋/}aGzꍧ׬Ymҙ`+^)))Vt\Gs/9uޅ潹Dp\׮G;Tw3^}eza"'hk[&Mv{[C/]60?f-X?j>y}Zs\{mՄ.: {>};ߟ/.>}磂ҹ&U>_J>8o{~ |qKla 3^MH~E cfcBYzɱӏϚr}秪 L|. QW 05짟/[Y^S\\Bc5⮑֮Н5g|{|` ".?񿰰NO/--'kQϿc{w8ZԲ*\\ b-éڑ篼^[p]^zJ #147+67DŽ˅g?gsJwqFa&*ҝ>o.᏾y!{&׬:f16?lD(߾[<Js`'}!\TUUoݺ 0eeggu%Ŷm0}-[ Nե{[.H1G1Qxr ;vd#1(9#1!xb[bb$ G ?Cu>Ta.Q}X п@l;>}g~N?&ct? jjjJKKu'w|\.f 6_L7 :c>,V"8#d8Zeqeaj99 B#dwm嫭Êm>YA">?Ͼfŏ =s?fVE~³'j=mJo.uyi[m{o_۾[|r6N}b=aZ>_G^??6oZު<ɚm=> T A?@#V2v=֗cEqqesrr.vqƤJ;hSӪ??2ZeZ2lXX;ce55ʏѓ<X&#U"B?lUvtʟ4_?&.؈,-mo0~򥛛) >i|w?򖯚ۼi_ܬc;ˢe~Cc _"m[,* `Ÿw[:N QvM?rel_K Ul 5\e]ׯ~,bL}qY;+gUi6f' w4K3=UfQ?zm~`]}fuzٞpo=T/oV/A?5ʹ /66at Y,}*~/ˏjӬ~L*iFj c4~ֿW *;; ?@~,&X,؃NgӏU㲫- cSYnSN-|০;x-ώoQ&͟~)YB؋a.vUkrY(y=ZxLϕ-?fz$mYb`x`u؀}2z{*m13Ktr?thm~z)ٷS³c12+\V)^w fUm Y}D1ub&Z|Y'?(,m& ^W~9+ ?f3}9+cQA~~?f?t bi 1͚+?6JbcZ ?Ì sŠZv͘RO&ݢK?ּ肞SfnF.;QZ߸L-47Y|q۟xS!?!mT`vx3 Ī'557ia ?<C119_Xo}K{ͱ)qiiܦb_vlcf% 1ldU~w~csv_1uNobS1w%t}9Q>ز?u@SYla[1Κpڭ~,plF1UISz c\Y|'hW\XT+ǐ3-5mǚZ84<eX,5 ?6q7f<5:q\7BOH¬Q ;aGJ`:A7rS?۰dffSMM O؊̗lj𔣚uC1cBOo>g&X)f1ZcP~^$QǢxCv3Zw|ql =Sqwa1>`èu0F٬' * ˪J+k*ʶfggA ''#n,M? pK9A,.1:f}ccâ.dMLZ;Anm{*5 i[7n{Rx ǘ~,xAw"ijY=US}a⍫L3f}^(>5xcB/A$.,,|c$vYB\ii7xy2t| }zͶ¢kz~~/.՝5qQ?)'HTW<VkCX6]t[1d9bհluh{β1,x9a}Zuy0OC<Ǎƒ•¡)F(VZYYc Xejkȱ)VƊ@p1E |{010Wftljӈ ?FI,.P/pc-`${ }(m1kM?z;vIU/K+6uyEc?&t B# غuqsY[s?/'sʨ{FΜ5&V/  eN<=F8uxYs232|iNqՒ)ǝ> +v\Us[ᦰ>g;l-zQ=ikA?~%D,u-Ͻofe{5t/ONSY'qɟ:/,:)'4}f{{v4ռUO㯐_!=C{-޺\.d;f0fׯ_|yJJ bǶmPF ##Yyj.AD-;?5˸٥2ifa3X`Kge'X2Ԅ_Џ4hgK!UgFl~*Ǽe۽!f'ڏ ґ 6mљ!γ襪 `FFGuQw_RRf͚|j]>u o]ې!<>7YTB nO]_n4Vzk\;vԹ;6l7x})pBJKԮbC ،1YYY6lذu۷N'ZFi%\^!QH~, d= lUS[5`kM4맟Ŀ>5`6ďY?RPP`|wlm  zSSx+]0'>QzkYP.JP]qֺ<XWO C[[Xk04>d1Ϧ4H(V Ӫ:1e˖ eD%sE ֎뛘mҎ8a+t&5[~&*Pfzf>3?6AOfCc5YYYk֬-E*b`'D(ʃF0;Z>x 6\ZǬU oF~JhKZ"%JU oQJc 3v:%%% /QHὠi0-^Ĭ̘upVcVXc͟ K&~lH(5̆1+" xqX\\Lp l`E<p:OO'ԓPtUr2SJ^JH*kKChSez*΢ 5}ZZZ GqF"Qެ3̅XZ(Ag}٧cr, %HD!~̊4}WUUatݺH<uRDZa kHc 3=Gp>e t dQz7 iFXbEjj*N$Nqe_uC}ee|bsnj?;21}A""ր?fEX배"sCpavHpNuAoQ]"t>v#fiUZaXKiK.ۺukyy9V>6{Kդ޵ 70cǢXF!~̊[xaX*McHj 6]ib=@2 mO 1DR77ӍNf͚͛7íVݣp0?6ig+#="zN,RP<,2AWk"$ -Znm7p7lܸ TUU1zp;ՙ>;X]. ܮKYYYٗA_ ϗuu|Xг7H]ó@,L/9%YE_/A3fkh7,/8H#QPPrJ8a8R8Xkmչ4^#P(t foN~X 3]vt.z:C+k&7s,RXXaÆl$pd~#kM mp6Ph-mmu a*j*`wjQQŋ'-[۶f}AnUN݇W :;j!]>@ D榤^|媕[/󎄰WLx*//Ex/GOvXt)L^7`"ڲe ::%]ԔBp%\g m۶Z /yxŔ[]]s53'RmyodF=sV*NpDFyee4H~H^^?_.m QbWE i0``⤁#*@aG oc׺Z7?6t?S@. R{C d1r!fqܛ6mM=?!?ȎuNF- 5BF׳@!44Qջ`tB7a#*qP[fLzEw[+]TФ\ 5S-,D!$Wi)VpoO.˨΁ g8UD 9^;{+՘ +yRRR=t z^YAM k:x}Wxl 5>hѢ%K,[ qQ</&'u1*TTΏ!K41]~6LA60K%Z WVVV Wqq19 644 j\yC $8*1!YDXUCG&@t*VO6T 5]g Cwcх~,!~L74CW`mѭ oG.K332Vez%%%^_0U566"`c'NJ^:ܾ9SG/C-!X- P9]0i{ m^mK=Pز x ;a^KaMky:su!LA8)E..)F9~FaKཀ-]#[ 8 !\TBӁg 9kj}d0 @D`U>"^)-[ M-b@ރ^„CW4?sڿ9p8k^\Sŀxg%F\,_n-??!T꼅{B#:i%<$}skVb4 0u0I5Oy/rǧZV.oY""׏]M ڡ[@h Or(zPazث_>jd2&說*ӱ`BBԫ 8и;p; ȾYf,ྰE?z iTK+{ sN q"Xsz\ ۋqJqUUJ$]5:oÎթӊJKvxU6^└m#/^lP7n܈K^wfGp9H]RG\!R{\;]. @ݞ:TT`2jNW[ K+*Qªr:Tr54j+=M LeznQD ꕖT (Q,afDDB9H?b \NExCACVoK/ؿюU}:`%91Z>SX]]qa061cV]:[EfaJp!ɬVT1")syKSJ9?]%VL^01 Wt޿o?7С|{|"M~{kX|:(B1":ZAh5m7oZۙP}:T+>~{C_aWTC%Fj޽.q5'!0w*4I|WclфIO?=k;w߽BݣEkfbIo=3gђ(3gB6PSB{Il0s֬\ +yWEKNμY @uʀVsU ;>}w}_0?7/M s<^PWޮ;jkoI{tsϾ_i;?]1Hɝ?TK]?=?9c`{~[3Nt'\E!NE07?:g?Hwg&#s<c91n]$OfenxbgqwwWrqee;Z=nxW]e˯yn/9fU81DSd~{~{1Gm??M/c~r69w~w}l/~۞_;뼮:>UB7kA*%:wY ._á7ׯ__#D>*< ZV>PuB.宁7ĊzoF-ϫjO_߳;~ EWHKU?GJ_jI⑌H~y19߿w 3~yL;}CѺJwEc>tU (s68^!z\?VYYw^ّ#-֖hA[[[(?omEi*J*U MKkkK zGVf#6 Kq60bęӳ.v*TleKĤ3%%'%$'%$ģ0!1$&&&%'c5T< %$OOLmh $aK1ZEۉq ]Mf29>$, TPaZ7-Jj JKA&I^>O]HP2Su{=Z]zu'>q0ǤXT(13r8t,Ee3D *e\.|Gۺ Y0V8E9 w}fK$%wQɏqYE齯tp\p$$dBSDS&0rdG MAjm\@̊w8b7|]UWΥa-.oשl6ap:UUUl6ꢢk!`ƊV^xť%Ӟ?[j8@W$Iة1S1nɑ*]d6w8s |SP뫅% 88Z7RŏE8x T֛Gu> Ë9t .:HSE07䀈aB)B$o}PFo1:c( F;:|TB=7Pvؑ3w \1jnb--+}@H$vvtz%O<ddP4}dxرIq:QkpJJIq $re d5R{ӕQ.(!.))aZ2 wozXs&'?5)ajR"M1kD 6DnQY>e-_\<'V;_ .O9*v0](WB:t$!6>m:ר{FenН<o>{f^z9v"_V^^>ށ7^uw~[_qtܤ̕4ԕM\_a3YaP\ .+D0Fן)VWct/^Dp 6`ҸK ,';'---5%u \kZ*+gKqi1u)ç|7fB 9xb8M6<4PcIʦ8^zeOSuM_5ďE8uBYЛG5k'9_}?푯ߑͭG_~CvЁo:@Zh呏t @#呕C &-Pu y-K+}klD7P~ß}`7G>;DLA[}SgQOUo>#e![hT>#s7l'dee' /Ubοn4yrRr2Yq S&N[oMI.iw:%i n6{=0)9뮞LNm7zԄS>yZr\|RBrۦޕtf$N:=iSfLK>#a ࣦ݊OM4 /!qZ|iIw$'NJmjRoIN@mq>eRҭS<:ۦO8-qj3_t9n,)nzҔnN쏉HH4=!I{e p._O]дo**}U. 3. \QM…cdpI)$_sKGlWbDG̤PHďE\ u{ݦu={LJ<nNr59qKX\"n5gUշmoQqPYSNzEW` ÄC_L+sUw5e˖}c%֦۰qÖ̒r(9LCRQ ~Fш8MG è3Gu׬O%${y&8ӹvOЏ &ďExɴS W@)عŕ rտ{%c_9 OGzv/AniZ -+>YZٽa***~衇.V+w JKZkWͻrzg?ˬ'tUi/}Sϼ6fi'{s3cŊu VCѠʱl﮿{0 coۛu%nlHUy~7~n)r؉5% CciQ|&sk?;}/UjUؔXDQ*I;5ZJūr\r#HeecJ,9xٲWP\1fKtL wv97#= :sWFfMP7Wyԩf [nSO55?ۇ5A Džan&\YC|v5r۩m?FiŨ6x c^2m!~lUJJ#p@oͻ$qre6J4-S ۡޥ󼗲[Iv"զ.+\NۨYXKYo le3^¤}T;ßս:{>7Mضa[ _}YT{9ߌ60iq'{ ֿ_rr ~lK~M=Q͢f}cf5g?vY;oW6f=_|^,Żէ[צ=3w`c0cP1$>1d}_?&Os [_JޡzCU ~,`VUomcmܽo9=z)Jle?36ɸ`H1Q8l5'_w#j-{0$lǏ/ݎFs<3۪Uu<ά 2ToJc;zkӦy& uHjU9O*Bj.oq9)qg K6u8yㅪ2|GvgcJo)]:DT 3d3{ƍ>h[A>iӷAwִRI=~׾rJNl]~cʽ߿C~O?j#-Ok׏YjXwhq=vg3>6gҼ4kK{~ջ{v2t$Pwɞ}\Н>zcov`#H`àp]i/ YlYmϴj u>˴a䲼mcJ V\wvk3l=k6?.ɃMSȭcNkةڏ=1XeMe-݄bN6>H [չ6nXȏNLɼ5 Cc,bG%_ Ҵ}3;SϽRuM_'#3?N~LQň:DKM]dZe钾 `"~c}i"[_p5ٮ͏E"ďƌA܏)E#]`zZ6mKf_B2o2vb&8&:s0N }q敮юu[L2惈|ٲ5:U7؏׼ꪗ/)1:JO_?cC ӁOuLE?xٜ6a@3E~1НRRgn\RZZY]wu>VNZhUpCR#~l~,==p jQW(4?8{+J {**"ߏ=C>{f^~%v"_cϼ 3C'\cz啕6nCQ1PDUNJpz>5AGƌ Q ϾbUu]StN] SOXZBԣ^fܵngYJH?SiP)Kd:+!a's;f؏F.hB^ca }鮡_Cj+*p1~}ذ!=77nvm566Х1(tN ~l~o%TRO!T?(!OJ/|=4-exK DkkKkC~akl*IJ-8]ڝIe\Zܢ*[Q-}]yW\\V_ E7g cϙ>mڴĄxуy U^COWOa,ȒU$oL$K>-aFRz$=HNC(4Ӱ={JNH^'&HLNާ_F qjvt(9@MQE*KHj>jMm-A{=>o}}KS:<<ԞrZ@j4%v.6[<? E?n{f?Խ6ႇkY~'Nr?osۯE4d F_uUZrwFG>!AS0Vfn9b}0= 12.V87;boB oϯzKT~1~4%JbY+:%D5+w~]Ɲߣg$5eÆoÉi@Ꮙ]5Pgcwc ssBeT~wں.g "OOu[>8 n,'''==}ʕk֬Aْ*Xl`:4@F2lސď "׏QT\\ZV" M PY [*h9ZC/xbWmDqj>Xxw֍S /nt}%nkJJ22lnڱs]55NL4jnÁݱcً/3g3g- ӎai\~VI3ƿ&UzNI3Ocst;1S5WzRT%QFM@Ug{_3g ׭_tt} ކzO}.`>8s&͙j)Ι|SL|kqW>qX[1i򫓧Ι2Em{s:ҹ27D6^r#|{ݙ[8' Lqr]|K`u]ߘ9#H;|TVV-XOu[m%i+dtpaK5,M}|}ڿINVDO2HsCM S^25OBL2< Ug汫ng{zs[swhlUWVmڲnݺ|$u!L 31!やTkhB6=uŅ|N럹o@:U Ec44eN\IX{+\ ^haG q :y>q͌|^ZIU;UU*..˜ܺ5t]4$a5 #A}z>kHcí/_|Æ [nݾ};g,A  .=\&i_.f5kj\մ4Ɏ~Wm>>`}Js5܈~t" =| 0٥$`sS퀦jtd\nt,놬ZVt*lS]VԺ=8 zhfZtG BpPـ uiXTUWWT9k0Yz_BSVVx`gӦM8]:#𕯇 BnzpA}SmC& ,tr䂜NL#C*}} ו QME ZgYxSlNvKr O[SZVZUUi36% P0rNBQKQDTW_8=7nWWfNFgFۃUU28aLtQD^Cx=A}S)((.)),q (tbX˜?-W+gd{kW6oe @1E.`Y1 SЖ/((zv6ZdH]tJl>j(TaOEF!N)tWV3cp@mU`1 QR3QC'?EBB;ק1zk. 6ioʪk ȨN!T|OR~ Gf"Xjvz25YBrd1`B1|/'\#_!5ݣ.t:O==ռWKuЦnXmOk(br۶mŝ4$X]be̽ 8.7B@Wx(`41rTchDTCǍÃixM7AC.;Lإv׈F+i@ tÆ k֬ǀ4"aubu MVTTe 4NMMŻ Qr[A 0bFŵLmVfoU0YBsPe<*FO1v fG}Ӡ2PoCq mR@Iگ"9n444lݺp:@"\qfdd_^p0[dvxR"?A4@|/SuesR__%6\'j˜5xS@ K${s~R'5_aII?k0zqab g;vE3^=۠ tpG?J=ԐF<1H8.8%c fu4 ƴ[GKOۍh4Y Rnna;wzo mBD!艮$=ev OkC糽v g q]( É)"USW?7mJj{Z_B[1 ?^[d@ *ғ'Wq}I4 X )xkjG TTkV\⢶V Tpii).7oތW|L]vʨm! @P9=x+ِ!Cӹ~L#(lW=IcTDsNII $)++j< MP;۸qcJJNg% J؏ a{ХB. Bzە~2T|d@SXXzj\P|0[d!I#لeu ݣsk3t.t8|R`n \v܉,>,Y%(;؊f`=n"_0K2fLdiDzNg 9Xzm;aK.ci(ڲeŋD lᐥ- 7QO[KOOs ٟ"c 5_itwA$ }U@"UVT Lyfa avvvjjjyy.c[d!cL:11%x6c c4}5,zqɋ.d}mݺu͚56lpIIy VH2ՠsnW62MX$+^< I"3mTCax08R $Q~~>͛sssj`AO fAfddxDN?F`C޽ Nvq<@d@*((΢pl эBrZZƍOCЏE}#%o#ko=HЍZW`fcpz۶m=~HS}nѫHc:;xHKB{Ӧt^&0eܼAhVcv,A9&0&a~081~Y1=t"az!bFcVIq׮]|͑]TTiT@$PL?JJJRRRrrr0M?fEW<$"pΝ 6== .myb5,SS?컐4QQPP܈'7͑`x[.rNp050_ N/W~xű ڢB HE(1u E~((ā o+oB?&Ⴇ}/իW\r˖-[jUn.=3B:TUU"///Aaa K.]x˗,Y^7پ}&Ś5k0qz B]:F,T^\~m+؆ W)HbccTO&=A\*JKK11j 8F!AtƵ~?_kK_]D:OoӦx`û/V5w뼵 Z@mۆظq#^ц﫯\o.&dĬ6 9G󚾐z윥K.YdѢYYƟ+z Bqa2IOOץCӹb }áqf*({$\ c|vkk6oXM-8yy[U5wBI;Sr%i= ,FpܹV1UWWÃUlXf-Y8;vNE t'\Bg>LJvઝ-g[+RMS CZff&E-[:[6} B9abiy`A,(( j?&D%*T嘈)7!ruNG 'hGWjꚥKeg \qӥf26zܗ_xʕ+"< :?@DZ/]Tz72.q5Shf0ŭ%cu\MoiZZ%K7m\SlG hH38 fҏZVP:%e[p))o1D]3*gT=3O,Km!SS9%b+|:/A bgz-MQnMO5Dq,k׮[@]japT7H_?4}W'%&TMt䤤Clܸ1\G8\jC 8B5DlS'&}&VN׀Xuǎ]\dTrw[|[ ^:==IkD 7ocǙ6oF=@dWN#}"++t:3JlS<X\aH766 NS\-XYN Whtnڹ{ݕ9ٹ+V_dҥ^ܚtaPg]cwא1!NnMT1'sGӎF>—>C^/@x𢘃A$J<H\ʳsk|׳dF,ǎGlv|vNAA+ϕ R5k`WݨrJLPc AY07m۶-\GMLL#ªx`QaB<%'"BK#$tk䄋ッ?8BV+KSVLx%|16u؈FۊԵ=Œ3X$%%͚5{eammۊo{tzݻ7???++ _ ͟=~nj*ةJH Ĕ)qS iV3mVZWB}|7nܤ>{ٓVy2x[R j>gWq|Z08cJrr67w3裏d唔3x U6f.Zry˰_yuP ~Ln8ϟ0@RRr*Q'%'+%M X;0g,Z_|fs>,,S'&wl*~k 5^x|pϞFkMZ--\ o߾K ә%KIJL4JD̙Iw\H(ߝlνFF\:^qΚ9+5uMyyyBY 4* FwLr<x_WdcxYN8"uPtHƑVUU)x;i[a8rV\5~|^G}g!.VgSď ^<<]}"`OR HTtXͮ~`U ^϶{;px9Ѩ{Fen87.#cCgfø{OFfuCݻwgggiիW'Ӎ#L_xFE23(&p*=!&Q!L9e(SRRps9$a1dB^ґeўeG X>!=csƖpC}~KX.;#0cBb",9tcc#&?PSq/Վ68]/?{;ďE;z ]  \4 O|9+Xӣ1yͮ\ cEi{ҪV?f%Z`[999]^ 2xُ$a4 ‚1aRTTk/>=Yp2B>"Nڷ౅X?5EW5HH~f:w,ߗ΄+Vk:cG7_h ]?\߻o+ďY܏󩮯g^ڿ5w6ϢMT1".^-fl ܢC~Õt%Zeo|fלΧ氪i坴nZobn}Vom+WN/UVx{xT}H@l'q쵝n46n}M>>my6q}_c 㤵_i':N67#W$>3IȀ`L93 0+_F |>9hV?{HVJwweeJUzNJ'fQqI f?7S'ev̱ο+yZ]t j* l='jܿf$,})644N&'7|Z9nz,#64w_>?y敵,ím,ylOcoLؕYc+&J?.c'\i/;[OcGaha1,417\c^%KW _n'f[Ap *ҫ&oێ=n4M+7$D19bkȲdfQ[6䓁3NDUxvjQNFLm' Guϴ<fݻ& _H|%U!0yěGƖjautN >c;CջL<ƒ8}TĪ_鴥b4yKo q b1Uënj<:OS$a66hhS" IŐ^֤Oos<fb6N?:Tyˇ?]*~2+527e!-TW:CfXY;~c$VPiK.ipޢĦcF}5jP%8׹yN=nr4HĪ鴥b4yKo q b1Uënj<:OS$a66hhS ):\8sPOǡt:OS>w<c͕}N,t$o}7ުVnVQ3 򺯸FcZ;wS3aLOjw-c+gy ~\ҖĪ_c4yKo iq b1g>^5LRu7<gp w]OG"5K^9`VKۑcst\'Ti&7 ܠVGϔRy}"g7[_xwqwc&M<d'lRz\%<K+7L |L.;˔<6k45VֶRKZ~޹\Swn0]|LFdc:[cN2KSTFӋfX4DG=L1^Z dP7p%D-oNTyu7cL2_>mse1DcfSRqvz^YzL8/ܨcO K*yÒ+3<1'kTdV5ljGuffg&Sd,c:[cN2KSTFӋ<f~\Mmtgn&SN/7y2N?_VKĭ6%ɛ1Ik&hgc<f1߯KksOTKS|̍:6J$eI1|̮|̓ǜeKP>NewX4vLՎ\HL"a=] npy o3b*T;[߱O^XV,]Np/7ylaYtM[Uy Mww~C`ۼ%kylڦssg\rSOg+E"+cfkj9ujρ-FDzu\V^y}"SR<hС7(}=;&)5Km|~/2s #a*.)_OO~o;E=3x.ۿw[yM!#,]ʿ;MG"vV[[X4Fhs|rͫs"&t{M}8媮]g?{z9Yt5:6n?Cӧzf+ tX0o(<ēs|H488XQYysɦ͋ l).Ӏ ֮kz-[֒2z֕d$ٲgiVY_q=#ERٖҌ/YJ*z{gOwwO}C6-ojhlU,.)+,*<.s3mi7y_ںFe|^]/Ş݋N-۞=kg׮]%/[J6<gUUUv)vU]]]YY!)se>A 2l߾BY4!YȈijZgܑ̗<AYooo]]]YYY[[[~`v1>T}}} Z[[l+@Vc˛eٶy .<appP3 i3pc|K臇[ZZ./ y ?6[0IFY[[ij^: fΝ6ma[H$^YYY[[w^UXc(aL^B'+J0ATTUUXc ee\sg{ G"V}CCaQQFޝsa 0(EM'xs{yX,f/A6˖8Ʊ[y @|SaUW"z1eHf¼u/go[mzs-͋Um퟼pf{y eyE y lylSgd!bp|һiZ69vha (9|^PcM7YS教c]vd^5/?)W8n/dO!8QW_}( y ,4lrdWB]'R+:erx)O8ylrE)od̓sr^2`fs&;poMfg:̐^r&L*JIX:[ӓ5EO JV=>lFnf<M:) .G?=yR69H(}RɮML=RLR^y !S>J-i<fܼ{򘮳1:Tu$ج<lcO՜HcLdG|-BvlGfrǞհ̡H*J1SһUgCpX*Mɇs\=;r9+lV8 M/kF3ƧuumyB]΋񟺻{zUX,~C|?()O?808h pI*+-P<Z5u[vo<"Hն Z3x֒7fϧXIffm,dl:[u< ;[^^i1X,UUUU[[{!JJJR544gmxxضsD0/CCCv3MpX<`N$?Hd2) vԴs'9{ =IEJ@ww$՚IbH$eI$gyeigsssOOYvXc"  ý3ve]uAnii$/7gbbe[m(g=qi*dA`0888::*;Jw G253 3\9ؘz%ʗMQQʲLlbbB.Xv{,7W[UfF *}U$IlxxJ6Z}7ijeF s6\aͲeY޽n۶m4$ʵa.fL`3±r̰rF!dr5 $W|-u/nE<mTIsJ– cBY▼ʪ:n[JH3}f6;zkV ɟeN<!DupsiOOgAɂ_c[邑CL$9;6yȔ F ry``\*?{Xlckk*ؒFYʓd0Y*wƒ:${DigfW>Y*̹{Kg6ʬ ,54LWw0>3Tr,ܞp9'5e̳XVͲxbrDݰ۴UxXTcb1&;jUrO=*&IniLiP)nRFvҢPݹsg}}8p@";xu?PsHhI?HԢڢ;)\zƶdF"tQF}pFZ.*s4}Z[[Qڄcnq[\1gP sHg9ICCC^p M_cvb y Ylļ !rQ*'KXa1˫,tKH]vͮߕޔ,;m$SM-Mt;-uM/%'iݬLL^r(Jjfs@#ǐe-rޟ3tPl̲jC{YOc"Uy5oذaݺuɜ9!@<,01g*/V fNhl,≑[?*}2{ɂP!Fr1cǶmUre˖[Jܵ˂7& =#j~f5駷32ۑҍNݒ4eWԣF %MJP1$wIr#~~ *en1 S3]qVEF{Y+s.<n#={JKK7n޼}.s`f>;un>m7g&ǀ\ZcϒH276&͒:~H$U U#2[ᨳza]5qo(2;Ըy-ŕk[f͚&I&rKofFrnT2Uf9EEtUʨH$S?%dP}PۻY}䪨$l3@^*,̼?:=Gڊ "&*2:<t42[IbT\GGGaQ|rMP[;Ȃ08e9.Au/Id֮p1!>KFG}P$wO_WGwGsw[ݮm ]mm m;ڛv7WYnloƆֆ憶FݭqG,4JշJiټaƊ[6E41_RdSOē Uevyli'# 㣒Hrbb|xdu{WuEC}up:T5e*g&Vj)}wIuu5h9kp`h|l_2ݽdg6H6{1d1n\ooowwwMMMyyEʊʭBWTy.KS=Y)+/.UqұLvUTa#zm*J 6%ܪf_=RMDJi(DuuTȦ5TssK__ʍgś*Iv?޾N~{H<cckC~ pg pW^T,rp*YW*ɭU% LYki`U򗬼{ oJ?GI3 b 5OFQ.9"alt_R%nO<˾]/X3%eιM|UiyEo[~;:jJʊ7mX_^[⒒=i_c~z$=ǯ⊀ )/ٍTiWtɺU͆:\8 9m1";Zl'Z6a 5,OPRQJw'4W]uO?s?0688yf\%o]կF-t V𝁐`kyf@p-Yv0Bw_ ^ҊH<WOI$;[715^Wew sѩ,kRӓw2MvgJBK̗T%PPe8l867Y[K{:zyZ̷I0z% S$C=rZFޱ+5Ť2:Z68C8cϳsr=sw.Ɇ 6o+\꺌l<.1>̺Cw=*WC+B*{|-;yLrGH_K6 ޓw #K$\kJ:{K((+GcilLQ?#K]'Gb>jd9p@"Ӗʹ UMet6e&/H:8|K,P(Q\D2P*$1%Xl|||ƍ_B'K*ErP0\ tȇt\@^~@dP@ͰF($?^&{Tg7,Rj|PNRJԫCpn_9XXM;$3LuқsPLv`0Ofe6 p^85[i / /P8,ȓ m޶l)HJ9"; cF\$A4$wɫy tkCYnp+KsSk7gɆM 4o%_EQAkEx%%=]9yp~X~շŪ>X,~՚ϭ R2=yX#~У+B?[.g|d{"/ƾ*y5gQ:hW.>Y|>6<}<ľIS̕fE7}o╡/[#eG(=);pjZr?>f)uoxf+y,HOZAӟ/K*e=y+j `< f&cﻯU|FISQ=|U0Ѵ( hN5''9j<W)ofNߨtÝ:uZ3~tP?9}j/T=tjujsCR*cre/VP'ފ#X;ؙYk.Ex%ş/|^:7|r*{g3Ihnlr/~_^'L3CM"-}#pLʏcN(rH*2<fd\8E fn.NtE_1eFpZj$2 Q*\ y<K}("c_4X1y x|5wm U]yUiS{q,SE]8sh<k(] R.fMJqQ=8~rZs,<l ڻa?0f_1\^w)\Ἧ,yMr(#lkH?x7B+/ K5;=p=)ߺ52'}fg63鑌F##cبoɻCRe09)3=~~pO^w}^&r=LT{T |-bҕ)M#X4GbIaNV_F֮]{׆60N( ~A]P3}p~^=E0/ f|dn ~CI5ʚ #yy]ˡ^Wqj%"2T>j:yE! ]C^!u~GйXsa}ւwqqɕ~$#). Y; @|6t8[ }-``m%÷Ic xzzYPnn o 6%Vmy[7n oܱ4|{xm% 6ǞDX<%wwWqF'ɱK_xxC^%w.Z~yr\ԩu ʉHo /yiޭCyrBaNSޙ@_=;wGbDlDzgL$s{zzJT KvW̼㼔,H Kkl_"]۽6U ' $ՅJ,&/ɗ*1IHPRٔӲ $_,]Y4?򥁥A~8_jjG&ӑ,V^$/5KJ{HVwE W, ,.CK+< X* lաɫk/% <搯:f:Ղflٲ󙚿H$~ˆ|=C+?ls[ y Yr$>7_bپ:Z뚚kjZZ[ۤNVdAZvW#=KmSKMSv]P"%:Zw3$abed{l$UGL21Lcc}Muumu- jkMԪFUMu͵RҭAtyRWCIM3Hݶ]uc}0i~c~:.n*blhhؾ}۶V-u9)Mmj[U%SmQSuTVTTlwӣT#!͂JW63oQn۶JFeKjOM1Y689.Zv5<1O{ϩ*+VTTf4{ј=03 hl(Ehb"OFbG"%.r`褖e4ϷԲ4d2:*5*K_jS<&;9D6H8'ۤWt$E<d\桾w񘌚2GJLUv%c#17g-#8#ѸDp,վ#J&q')5܋ }\Y h}K>nJ:~K؞{zaޮ.m; nYm體6ZQA<%3vpKҥ<My(H␈B\rN䝘eZe#InC+'bⒶd<nT7UE&&LtTL1՝ G>[Q̝nfqHtUVoiN1h(r[zaZjgJ`Ӕ3M3ԜK.| 2,?Ǫ'TO,툆^-kʴ/E 6AMMuI#<ޛ\[Vzbnݞқ<*QVD <S9{fZTMft L쾗 g}O_ؘ_,IdՅFdy ;iRԊm75eV*K''ʍRs8եO2- ]H$رaϞ=c:y>|9 c@N%̚!62%J0)8u#YڼX~V,Vċ/811Q[[k.Մ19Fdy ȉ t O=L 3y̴G_XwwwMMMkklZ}  [email protected]$1Y%ݫB  c@.$a$IFv񁁁uɫ,9{3"9_ 'Onv_򋋋+**zzz|wy\w*cGss"$eEѡ!IbF+((v`4440V]]m[/HH}aE1dJv!Č-%7d\%Vʧ~<UZZ&јSop#ܦo,tu `Ak$e1uu|gV-zO>{Q2Tm=;O}5k'~~$nd[~ y 6oO^ooر'z۶ď6,zk׮#@+_;aaz{q:W˿d(;/o?z1xc{ޙ(g|yx_~6f<3ra<σvP-Gy7}+dohZZ_8z;Vy[qª<p){} Kt9Ӂ՚cgE<GQ>^+cc/JL+jLLW˿eZd *U~oѐJ۩w'^x ;R!ʉW&^8:u[1vMOĥƹсC}%ϼdFuN::d>'чNYf{;}-ԝ up苧Nx3IRWe>d<fQC!Js;+<mPtyssZcCCOܻj}vO `+<ěw_EщH{T=a’Ĥ㿒ɟ␓ X:y'MOIPr엲t^jz:L>oV|Л'N79T6ܺCO KSN 2y GSroVu2Q]RI_}OF I5H^8Xy 9 W .=<.Đ!-i'Z }[y]2jXA+m(QRݼ֧_O5tV咭%J9z>f.ILRM1=%YI뀥IzD3̰Al5%s0QMx&󘙒;H7ԙ< y f~E?Ǎ Bz32StA>qV;g\_)˓܇BG1C}NM}& {eL hb]_jV~G=qjQm<nw?g|; oNSywyA{R=UU' ~Ly'1ϻ;\v3wƹcӳ]rXO(y 6\C,ߞ7_02]np , 1>hjl?_ g?GMM?o[68mTx~6 cQVV/dٱ@}K7'~ʳaxxp<`Cɢo~`coo(Ky bX__޽+^Ч72Hjpp^@1y A$Ktsy ;s)< ?c< ?c< ?cTWR1 < ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?c< ?Ry| @n1y A1y A1y A1Gf(((r\1(((<FQEQEQG-ve/m[IENDB`
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IDynamicObjectCreationExpression.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IDynamicObjectCreationExpression : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicObjectCreation_DynamicArgument() { string source = @" class C { public C(int i) { } void M(dynamic d) { var x = /*<bind>*/new C(d)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C) (Syntax: 'new C(d)') Arguments(1): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(0) ArgumentRefKinds(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicObjectCreation_MultipleApplicableSymbols() { string source = @" class C { public C(int i) { } public C(long i) { } void M(dynamic d) { var x = /*<bind>*/new C(d)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C) (Syntax: 'new C(d)') Arguments(1): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(0) ArgumentRefKinds(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicObjectCreation_MultipleArgumentsAndApplicableSymbols() { string source = @" class C { public C(int i, char c) { } public C(long i, char c) { } void M(dynamic d) { char c = 'c'; var x = /*<bind>*/new C(d, c)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C) (Syntax: 'new C(d, c)') Arguments(2): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Char) (Syntax: 'c') ArgumentNames(0) ArgumentRefKinds(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicObjectCreation_ArgumentNames() { string source = @" class C { public C(int i, char c) { } public C(long i, char c) { } void M(dynamic d, dynamic e) { var x = /*<bind>*/new C(i: d, c: e)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C) (Syntax: 'new C(i: d, c: e)') Arguments(2): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'e') ArgumentNames(2): ""i"" ""c"" ArgumentRefKinds(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicObjectCreation_ArgumentRefKinds() { string source = @" class C { public C(ref object i, out int j, char c) { j = 0; } void M(object d, dynamic e) { int k; var x = /*<bind>*/new C(ref d, out k, e)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C) (Syntax: 'new C(ref d, out k, e)') Arguments(3): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'd') ILocalReferenceOperation: k (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'k') IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'e') ArgumentNames(0) ArgumentRefKinds(3): Ref Out None Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicObjectCreation_Initializer() { string source = @" class C { public int X; public C(char c) { } void M(dynamic d) { var x = /*<bind>*/new C(d) { X = 0 }/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C) (Syntax: 'new C(d) { X = 0 }') Arguments(1): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(0) ArgumentRefKinds(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ X = 0 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 0') Left: IFieldReferenceOperation: System.Int32 C.X (OperationKind.FieldReference, 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: 0) (Syntax: '0') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicObjectCreation_AllFields() { string source = @" class C { public int X; public C(ref int i, char c) { } public C(ref int i, long c) { } void M(dynamic d) { int i = 0; var x = /*<bind>*/new C(ref i, c: d) { X = 0 }/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C) (Syntax: 'new C(ref i ... ) { X = 0 }') Arguments(2): ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(2): ""null"" ""c"" ArgumentRefKinds(2): Ref None Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ X = 0 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 0') Left: IFieldReferenceOperation: System.Int32 C.X (OperationKind.FieldReference, 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: 0) (Syntax: '0') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicObjectCreation_ErrorBadDynamicMethodArgLambda() { string source = @" using System; class C { static void Main() { dynamic y = null; /*<bind>*/new C(delegate { }, y)/*</bind>*/; } public C(Action a, Action y) { } } "; string expectedOperationTree = @" IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C, IsInvalid) (Syntax: 'new C(delegate { }, y)') Arguments(2): IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'delegate { }') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ }') IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '{ }') ReturnedValue: null ILocalReferenceOperation: y (OperationKind.LocalReference, Type: dynamic) (Syntax: 'y') ArgumentNames(0) ArgumentRefKinds(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. // /*<bind>*/new C(delegate { }, y)/*</bind>*/; Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "delegate { }").WithLocation(9, 25) }; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicObjectCreation_OVerloadResolutionFailure() { string source = @" class C { public C() { } public C(int i, int j) { } void M(dynamic d) { var x = /*<bind>*/new C(d)/*</bind>*/; } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: C, IsInvalid) (Syntax: 'new C(d)') Children(1): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS7036: There is no argument given that corresponds to the required formal parameter 'j' of 'C.C(int, int)' // var x = /*<bind>*/new C(d)/*</bind>*/; Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("j", "C.C(int, int)").WithLocation(14, 31) }; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicObjectCreationFlow_01() { string source = @" class C1 { C1(int i) { } /*<bind>*/void M(C1 c1, dynamic d) { c1 = new C1(d); }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c1 = new C1(d);') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1) (Syntax: 'c1 = new C1(d)') Left: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1) (Syntax: 'c1') Right: IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C1) (Syntax: 'new C1(d)') Arguments(1): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(0) ArgumentRefKinds(0) Initializer: null Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<MethodDeclarationSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicObjectCreationFlow_02() { string source = @" class C1 { C1(int i) { } /*<bind>*/void M(C1 c1, dynamic d, bool b) { c1 = new C1(d) { I1 = 1, I2 = b ? 2 : 3 }; }/*</bind>*/ int I1 { get; set; } int I2 { get; set; } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1) (Syntax: 'c1') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }') Value: IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C1) (Syntax: 'new C1(d) { ... b ? 2 : 3 }') Arguments(1): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(0) ArgumentRefKinds(0) Initializer: null ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'I1 = 1') Left: IPropertyReferenceOperation: System.Int32 C1.I1 { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'I1') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B4] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B5] Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'I2 = b ? 2 : 3') Left: IPropertyReferenceOperation: System.Int32 C1.I2 { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'I2') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ? 2 : 3') Next (Regular) Block[B6] Leaving: {R2} } Block[B6] - Block Predecessors: [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c1 = new C1 ... ? 2 : 3 };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1) (Syntax: 'c1 = new C1 ... b ? 2 : 3 }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }') Next (Regular) Block[B7] Leaving: {R1} } Block[B7] - Exit Predecessors: [B6] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<MethodDeclarationSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicObjectCreationFlow_03() { string source = @" using System.Collections; using System.Collections.Generic; class C1 : IEnumerable<int> { C1(int i) { } /*<bind>*/void M(C1 c1, dynamic d, bool b) { c1 = new C1(d) { 1, b ? 2 : 3 }; }/*</bind>*/ public IEnumerator<int> GetEnumerator() => throw new System.NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new System.NotImplementedException(); public void Add(int i) { } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1) (Syntax: 'c1') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }') Value: IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C1) (Syntax: 'new C1(d) { ... b ? 2 : 3 }') Arguments(1): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(0) ArgumentRefKinds(0) Initializer: null IInvocationOperation ( void C1.Add(System.Int32 i)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '1') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null, IsImplicit) (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) Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B4] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B5] Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IInvocationOperation ( void C1.Add(System.Int32 i)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'b ? 2 : 3') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'b ? 2 : 3') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ? 2 : 3') 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[B6] Leaving: {R2} } Block[B6] - Block Predecessors: [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c1 = new C1 ... ? 2 : 3 };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1) (Syntax: 'c1 = new C1 ... b ? 2 : 3 }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }') Next (Regular) Block[B7] Leaving: {R1} } Block[B7] - Exit Predecessors: [B6] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<MethodDeclarationSyntax>(source, expectedFlowGraph, expectedDiagnostics); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IDynamicObjectCreationExpression : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicObjectCreation_DynamicArgument() { string source = @" class C { public C(int i) { } void M(dynamic d) { var x = /*<bind>*/new C(d)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C) (Syntax: 'new C(d)') Arguments(1): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(0) ArgumentRefKinds(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicObjectCreation_MultipleApplicableSymbols() { string source = @" class C { public C(int i) { } public C(long i) { } void M(dynamic d) { var x = /*<bind>*/new C(d)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C) (Syntax: 'new C(d)') Arguments(1): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(0) ArgumentRefKinds(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicObjectCreation_MultipleArgumentsAndApplicableSymbols() { string source = @" class C { public C(int i, char c) { } public C(long i, char c) { } void M(dynamic d) { char c = 'c'; var x = /*<bind>*/new C(d, c)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C) (Syntax: 'new C(d, c)') Arguments(2): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Char) (Syntax: 'c') ArgumentNames(0) ArgumentRefKinds(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicObjectCreation_ArgumentNames() { string source = @" class C { public C(int i, char c) { } public C(long i, char c) { } void M(dynamic d, dynamic e) { var x = /*<bind>*/new C(i: d, c: e)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C) (Syntax: 'new C(i: d, c: e)') Arguments(2): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'e') ArgumentNames(2): ""i"" ""c"" ArgumentRefKinds(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicObjectCreation_ArgumentRefKinds() { string source = @" class C { public C(ref object i, out int j, char c) { j = 0; } void M(object d, dynamic e) { int k; var x = /*<bind>*/new C(ref d, out k, e)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C) (Syntax: 'new C(ref d, out k, e)') Arguments(3): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'd') ILocalReferenceOperation: k (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'k') IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'e') ArgumentNames(0) ArgumentRefKinds(3): Ref Out None Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicObjectCreation_Initializer() { string source = @" class C { public int X; public C(char c) { } void M(dynamic d) { var x = /*<bind>*/new C(d) { X = 0 }/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C) (Syntax: 'new C(d) { X = 0 }') Arguments(1): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(0) ArgumentRefKinds(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ X = 0 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 0') Left: IFieldReferenceOperation: System.Int32 C.X (OperationKind.FieldReference, 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: 0) (Syntax: '0') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicObjectCreation_AllFields() { string source = @" class C { public int X; public C(ref int i, char c) { } public C(ref int i, long c) { } void M(dynamic d) { int i = 0; var x = /*<bind>*/new C(ref i, c: d) { X = 0 }/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C) (Syntax: 'new C(ref i ... ) { X = 0 }') Arguments(2): ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(2): ""null"" ""c"" ArgumentRefKinds(2): Ref None Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ X = 0 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 0') Left: IFieldReferenceOperation: System.Int32 C.X (OperationKind.FieldReference, 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: 0) (Syntax: '0') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicObjectCreation_ErrorBadDynamicMethodArgLambda() { string source = @" using System; class C { static void Main() { dynamic y = null; /*<bind>*/new C(delegate { }, y)/*</bind>*/; } public C(Action a, Action y) { } } "; string expectedOperationTree = @" IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C, IsInvalid) (Syntax: 'new C(delegate { }, y)') Arguments(2): IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'delegate { }') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ }') IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '{ }') ReturnedValue: null ILocalReferenceOperation: y (OperationKind.LocalReference, Type: dynamic) (Syntax: 'y') ArgumentNames(0) ArgumentRefKinds(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. // /*<bind>*/new C(delegate { }, y)/*</bind>*/; Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "delegate { }").WithLocation(9, 25) }; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicObjectCreation_OVerloadResolutionFailure() { string source = @" class C { public C() { } public C(int i, int j) { } void M(dynamic d) { var x = /*<bind>*/new C(d)/*</bind>*/; } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: C, IsInvalid) (Syntax: 'new C(d)') Children(1): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS7036: There is no argument given that corresponds to the required formal parameter 'j' of 'C.C(int, int)' // var x = /*<bind>*/new C(d)/*</bind>*/; Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("j", "C.C(int, int)").WithLocation(14, 31) }; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicObjectCreationFlow_01() { string source = @" class C1 { C1(int i) { } /*<bind>*/void M(C1 c1, dynamic d) { c1 = new C1(d); }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c1 = new C1(d);') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1) (Syntax: 'c1 = new C1(d)') Left: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1) (Syntax: 'c1') Right: IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C1) (Syntax: 'new C1(d)') Arguments(1): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(0) ArgumentRefKinds(0) Initializer: null Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<MethodDeclarationSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicObjectCreationFlow_02() { string source = @" class C1 { C1(int i) { } /*<bind>*/void M(C1 c1, dynamic d, bool b) { c1 = new C1(d) { I1 = 1, I2 = b ? 2 : 3 }; }/*</bind>*/ int I1 { get; set; } int I2 { get; set; } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1) (Syntax: 'c1') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }') Value: IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C1) (Syntax: 'new C1(d) { ... b ? 2 : 3 }') Arguments(1): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(0) ArgumentRefKinds(0) Initializer: null ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'I1 = 1') Left: IPropertyReferenceOperation: System.Int32 C1.I1 { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'I1') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B4] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B5] Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'I2 = b ? 2 : 3') Left: IPropertyReferenceOperation: System.Int32 C1.I2 { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'I2') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ? 2 : 3') Next (Regular) Block[B6] Leaving: {R2} } Block[B6] - Block Predecessors: [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c1 = new C1 ... ? 2 : 3 };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1) (Syntax: 'c1 = new C1 ... b ? 2 : 3 }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }') Next (Regular) Block[B7] Leaving: {R1} } Block[B7] - Exit Predecessors: [B6] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<MethodDeclarationSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicObjectCreationFlow_03() { string source = @" using System.Collections; using System.Collections.Generic; class C1 : IEnumerable<int> { C1(int i) { } /*<bind>*/void M(C1 c1, dynamic d, bool b) { c1 = new C1(d) { 1, b ? 2 : 3 }; }/*</bind>*/ public IEnumerator<int> GetEnumerator() => throw new System.NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new System.NotImplementedException(); public void Add(int i) { } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1) (Syntax: 'c1') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }') Value: IDynamicObjectCreationOperation (OperationKind.DynamicObjectCreation, Type: C1) (Syntax: 'new C1(d) { ... b ? 2 : 3 }') Arguments(1): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(0) ArgumentRefKinds(0) Initializer: null IInvocationOperation ( void C1.Add(System.Int32 i)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '1') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null, IsImplicit) (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) Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B4] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B5] Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IInvocationOperation ( void C1.Add(System.Int32 i)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'b ? 2 : 3') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'b ? 2 : 3') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ? 2 : 3') 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[B6] Leaving: {R2} } Block[B6] - Block Predecessors: [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c1 = new C1 ... ? 2 : 3 };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1) (Syntax: 'c1 = new C1 ... b ? 2 : 3 }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'new C1(d) { ... b ? 2 : 3 }') Next (Regular) Block[B7] Leaving: {R1} } Block[B7] - Exit Predecessors: [B6] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<MethodDeclarationSyntax>(source, expectedFlowGraph, expectedDiagnostics); } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Features/Core/Portable/ChangeSignature/ChangeSignatureResult.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.ChangeSignature { internal sealed class ChangeSignatureResult { [MemberNotNullWhen(true, nameof(UpdatedSolution))] public bool Succeeded { get; } public Solution? UpdatedSolution { get; } public Glyph? Glyph { get; } public bool PreviewChanges { get; } public ChangeSignatureFailureKind? ChangeSignatureFailureKind { get; } public string? ConfirmationMessage { get; } /// <summary> /// Name of the symbol. Needed here for the Preview Changes dialog. /// </summary> public string? Name { get; } public ChangeSignatureResult( bool succeeded, Solution? updatedSolution = null, string? name = null, Glyph? glyph = null, bool previewChanges = false, ChangeSignatureFailureKind? changeSignatureFailureKind = null, string? confirmationMessage = null) { Succeeded = succeeded; UpdatedSolution = updatedSolution; Name = name; Glyph = glyph; PreviewChanges = previewChanges; ChangeSignatureFailureKind = changeSignatureFailureKind; ConfirmationMessage = confirmationMessage; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.ChangeSignature { internal sealed class ChangeSignatureResult { [MemberNotNullWhen(true, nameof(UpdatedSolution))] public bool Succeeded { get; } public Solution? UpdatedSolution { get; } public Glyph? Glyph { get; } public bool PreviewChanges { get; } public ChangeSignatureFailureKind? ChangeSignatureFailureKind { get; } public string? ConfirmationMessage { get; } /// <summary> /// Name of the symbol. Needed here for the Preview Changes dialog. /// </summary> public string? Name { get; } public ChangeSignatureResult( bool succeeded, Solution? updatedSolution = null, string? name = null, Glyph? glyph = null, bool previewChanges = false, ChangeSignatureFailureKind? changeSignatureFailureKind = null, string? confirmationMessage = null) { Succeeded = succeeded; UpdatedSolution = updatedSolution; Name = name; Glyph = glyph; PreviewChanges = previewChanges; ChangeSignatureFailureKind = changeSignatureFailureKind; ConfirmationMessage = confirmationMessage; } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/Test/Resources/Core/SymbolsTests/MultiTargeting/Source7Module.netmodule
MZ@ !L!This program cannot be run in DOS mode. $PELׁ)L N" @@ `@!S@  H.textT  `.reloc @@B0"H` ( *( *BSJB v4.0.30319l#~ L#Stringsl#USt#GUID#BlobG%31"P ) X )  )  /<Module>mscorlibC7C8`1SystemObject.ctorTSource7Module.netmodule bJJ@z\V4  ">" 0"_CorExeMainmscoree.dll% @ P2
MZ@ !L!This program cannot be run in DOS mode. $PELׁ)L N" @@ `@!S@  H.textT  `.reloc @@B0"H` ( *( *BSJB v4.0.30319l#~ L#Stringsl#USt#GUID#BlobG%31"P ) X )  )  /<Module>mscorlibC7C8`1SystemObject.ctorTSource7Module.netmodule bJJ@z\V4  ">" 0"_CorExeMainmscoree.dll% @ P2
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/EditorFeatures/CSharpTest/KeywordHighlighting/IfStatementHighlighterTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting { public class IfStatementHighlighterTests : AbstractCSharpKeywordHighlighterTests { internal override Type GetHighlighterType() => typeof(IfStatementHighlighter); [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestIfStatementWithIfAndSingleElse1() { await TestAsync( @"public class C { public void Goo() { int a = 10; {|Cursor:[|if|]|} (a < 5) { // blah } [|else|] { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestIfStatementWithIfAndSingleElse2() { await TestAsync( @"public class C { public void Goo() { int a = 10; [|if|] (a < 5) { // blah } {|Cursor:[|else|]|} { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestIfStatementWithIfAndElseIfAndElse1() { await TestAsync( @"public class C { public void Goo() { int a = 10; {|Cursor:[|if|]|} (a < 5) { // blah } [|else if|] (a == 10) { // blah } [|else|] { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestIfStatementWithIfAndElseIfAndElse2() { await TestAsync( @"public class C { public void Goo() { int a = 10; [|if|] (a < 5) { // blah } {|Cursor:[|else if|]|} (a == 10) { // blah } [|else|] { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestIfStatementWithIfAndElseIfAndElse3() { await TestAsync( @"public class C { public void Goo() { int a = 10; [|if|] (a < 5) { // blah } [|else if|] (a == 10) { // blah } {|Cursor:[|else|]|} { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestIfStatementWithElseIfOnDifferentLines1() { await TestAsync( @"public class C { public void Goo() { int a = 10; {|Cursor:[|if|]|} (a < 5) { // blah } [|else|] [|if|] (a == 10) { // blah } [|else|] { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestIfStatementWithElseIfOnDifferentLines2() { await TestAsync( @"public class C { public void Goo() { int a = 10; [|if|] (a < 5) { // blah } {|Cursor:[|else|]|} [|if|] (a == 10) { // blah } [|else|] { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestIfStatementWithElseIfOnDifferentLines3() { await TestAsync( @"public class C { public void Goo() { int a = 10; [|if|] (a < 5) { // blah } [|else|] {|Cursor:[|if|]|} (a == 10) { // blah } [|else|] { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestIfStatementWithElseIfOnDifferentLines4() { await TestAsync( @"public class C { public void Goo() { int a = 10; [|if|] (a < 5) { // blah } [|else|] [|if|] (a == 10) { // blah } {|Cursor:[|else|]|} { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestIfStatementWithIfAndElseIfAndElseTouching1() { await TestAsync( @"public class C { public void Goo() { int a = 10; {|Cursor:[|if|]|}(a < 5) { // blah } [|else if|](a == 10) { // blah } [|else|]{ // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestIfStatementWithIfAndElseIfAndElseTouching2() { await TestAsync( @"public class C { public void Goo() { int a = 10; [|if|](a < 5) { // blah } {|Cursor:[|else if|]|}(a == 10) { // blah } [|else|]{ // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestIfStatementWithIfAndElseIfAndElseTouching3() { await TestAsync( @"public class C { public void Goo() { int a = 10; [|if|](a < 5) { // blah } [|else if|](a == 10) { // blah } {|Cursor:[|else|]|}{ // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExtraSpacesBetweenElseAndIf1() { await TestAsync( @"public class C { public void Goo() { int a = 10; {|Cursor:[|if|]|} (a < 5) { // blah } [|else if|] (a == 10) { // blah } [|else|] { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExtraSpacesBetweenElseAndIf2() { await TestAsync( @"public class C { public void Goo() { int a = 10; [|if|] (a < 5) { // blah } {|Cursor:[|else if|]|} (a == 10) { // blah } [|else|] { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExtraSpacesBetweenElseAndIf3() { await TestAsync( @"public class C { public void Goo() { int a = 10; [|if|] (a < 5) { // blah } [|else if|] (a == 10) { // blah } {|Cursor:[|else|]|} { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestCommentBetweenElseIf1() { await TestAsync( @"public class C { public void Goo() { int a = 10; {|Cursor:[|if|]|} (a < 5) { // blah } [|else|] /* test */ [|if|] (a == 10) { // blah } [|else|] { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestCommentBetweenElseIf2() { await TestAsync( @"public class C { public void Goo() { int a = 10; [|if|] (a < 5) { // blah } {|Cursor:[|else|]|} /* test */ [|if|] (a == 10) { // blah } [|else|] { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestCommentBetweenElseIf3() { await TestAsync( @"public class C { public void Goo() { int a = 10; [|if|] (a < 5) { // blah } [|else|] /* test */ {|Cursor:[|if|]|} (a == 10) { // blah } [|else|] { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestCommentBetweenElseIf4() { await TestAsync( @"public class C { public void Goo() { int a = 10; [|if|] (a < 5) { // blah } [|else|] /* test */ [|if|] (a == 10) { // blah } {|Cursor:[|else|]|} { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedIfDoesNotHighlight1() { await TestAsync( @"public class C { public void Goo() { int a = 10; int b = 15; {|Cursor:[|if|]|} (a < 5) { // blah if (b < 15) b = 15; else b = 14; } [|else if|] (a == 10) { // blah } [|else|] { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedIfDoesNotHighlight2() { await TestAsync( @"public class C { public void Goo() { int a = 10; int b = 15; [|if|] (a < 5) { // blah if (b < 15) b = 15; else b = 14; } {|Cursor:[|else if|]|} (a == 10) { // blah } [|else|] { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedIfDoesNotHighlight3() { await TestAsync( @"public class C { public void Goo() { int a = 10; int b = 15; [|if|] (a < 5) { // blah if (b < 15) b = 15; else b = 14; } [|else if|] (a == 10) { // blah } {|Cursor:[|else|]|} { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_1() { await TestAsync( @"class C { void M() { {|Cursor:[|if|]|} (x) { if (y) { F(); } else if (z) { G(); } else { H(); } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample2_1() { await TestAsync( @"class C { void M() { if (x) { {|Cursor:[|if|]|} (y) { F(); } [|else if|] (z) { G(); } [|else|] { H(); } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample2_2() { await TestAsync( @"class C { void M() { if (x) { [|if|] (y) { F(); } {|Cursor:[|else if|]|} (z) { G(); } [|else|] { H(); } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample2_3() { await TestAsync( @"class C { void M() { if (x) { [|if|] (y) { F(); } [|else if|] (z) { G(); } {|Cursor:[|else|]|} { H(); } } } }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting { public class IfStatementHighlighterTests : AbstractCSharpKeywordHighlighterTests { internal override Type GetHighlighterType() => typeof(IfStatementHighlighter); [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestIfStatementWithIfAndSingleElse1() { await TestAsync( @"public class C { public void Goo() { int a = 10; {|Cursor:[|if|]|} (a < 5) { // blah } [|else|] { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestIfStatementWithIfAndSingleElse2() { await TestAsync( @"public class C { public void Goo() { int a = 10; [|if|] (a < 5) { // blah } {|Cursor:[|else|]|} { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestIfStatementWithIfAndElseIfAndElse1() { await TestAsync( @"public class C { public void Goo() { int a = 10; {|Cursor:[|if|]|} (a < 5) { // blah } [|else if|] (a == 10) { // blah } [|else|] { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestIfStatementWithIfAndElseIfAndElse2() { await TestAsync( @"public class C { public void Goo() { int a = 10; [|if|] (a < 5) { // blah } {|Cursor:[|else if|]|} (a == 10) { // blah } [|else|] { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestIfStatementWithIfAndElseIfAndElse3() { await TestAsync( @"public class C { public void Goo() { int a = 10; [|if|] (a < 5) { // blah } [|else if|] (a == 10) { // blah } {|Cursor:[|else|]|} { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestIfStatementWithElseIfOnDifferentLines1() { await TestAsync( @"public class C { public void Goo() { int a = 10; {|Cursor:[|if|]|} (a < 5) { // blah } [|else|] [|if|] (a == 10) { // blah } [|else|] { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestIfStatementWithElseIfOnDifferentLines2() { await TestAsync( @"public class C { public void Goo() { int a = 10; [|if|] (a < 5) { // blah } {|Cursor:[|else|]|} [|if|] (a == 10) { // blah } [|else|] { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestIfStatementWithElseIfOnDifferentLines3() { await TestAsync( @"public class C { public void Goo() { int a = 10; [|if|] (a < 5) { // blah } [|else|] {|Cursor:[|if|]|} (a == 10) { // blah } [|else|] { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestIfStatementWithElseIfOnDifferentLines4() { await TestAsync( @"public class C { public void Goo() { int a = 10; [|if|] (a < 5) { // blah } [|else|] [|if|] (a == 10) { // blah } {|Cursor:[|else|]|} { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestIfStatementWithIfAndElseIfAndElseTouching1() { await TestAsync( @"public class C { public void Goo() { int a = 10; {|Cursor:[|if|]|}(a < 5) { // blah } [|else if|](a == 10) { // blah } [|else|]{ // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestIfStatementWithIfAndElseIfAndElseTouching2() { await TestAsync( @"public class C { public void Goo() { int a = 10; [|if|](a < 5) { // blah } {|Cursor:[|else if|]|}(a == 10) { // blah } [|else|]{ // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestIfStatementWithIfAndElseIfAndElseTouching3() { await TestAsync( @"public class C { public void Goo() { int a = 10; [|if|](a < 5) { // blah } [|else if|](a == 10) { // blah } {|Cursor:[|else|]|}{ // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExtraSpacesBetweenElseAndIf1() { await TestAsync( @"public class C { public void Goo() { int a = 10; {|Cursor:[|if|]|} (a < 5) { // blah } [|else if|] (a == 10) { // blah } [|else|] { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExtraSpacesBetweenElseAndIf2() { await TestAsync( @"public class C { public void Goo() { int a = 10; [|if|] (a < 5) { // blah } {|Cursor:[|else if|]|} (a == 10) { // blah } [|else|] { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExtraSpacesBetweenElseAndIf3() { await TestAsync( @"public class C { public void Goo() { int a = 10; [|if|] (a < 5) { // blah } [|else if|] (a == 10) { // blah } {|Cursor:[|else|]|} { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestCommentBetweenElseIf1() { await TestAsync( @"public class C { public void Goo() { int a = 10; {|Cursor:[|if|]|} (a < 5) { // blah } [|else|] /* test */ [|if|] (a == 10) { // blah } [|else|] { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestCommentBetweenElseIf2() { await TestAsync( @"public class C { public void Goo() { int a = 10; [|if|] (a < 5) { // blah } {|Cursor:[|else|]|} /* test */ [|if|] (a == 10) { // blah } [|else|] { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestCommentBetweenElseIf3() { await TestAsync( @"public class C { public void Goo() { int a = 10; [|if|] (a < 5) { // blah } [|else|] /* test */ {|Cursor:[|if|]|} (a == 10) { // blah } [|else|] { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestCommentBetweenElseIf4() { await TestAsync( @"public class C { public void Goo() { int a = 10; [|if|] (a < 5) { // blah } [|else|] /* test */ [|if|] (a == 10) { // blah } {|Cursor:[|else|]|} { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedIfDoesNotHighlight1() { await TestAsync( @"public class C { public void Goo() { int a = 10; int b = 15; {|Cursor:[|if|]|} (a < 5) { // blah if (b < 15) b = 15; else b = 14; } [|else if|] (a == 10) { // blah } [|else|] { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedIfDoesNotHighlight2() { await TestAsync( @"public class C { public void Goo() { int a = 10; int b = 15; [|if|] (a < 5) { // blah if (b < 15) b = 15; else b = 14; } {|Cursor:[|else if|]|} (a == 10) { // blah } [|else|] { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedIfDoesNotHighlight3() { await TestAsync( @"public class C { public void Goo() { int a = 10; int b = 15; [|if|] (a < 5) { // blah if (b < 15) b = 15; else b = 14; } [|else if|] (a == 10) { // blah } {|Cursor:[|else|]|} { // blah } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_1() { await TestAsync( @"class C { void M() { {|Cursor:[|if|]|} (x) { if (y) { F(); } else if (z) { G(); } else { H(); } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample2_1() { await TestAsync( @"class C { void M() { if (x) { {|Cursor:[|if|]|} (y) { F(); } [|else if|] (z) { G(); } [|else|] { H(); } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample2_2() { await TestAsync( @"class C { void M() { if (x) { [|if|] (y) { F(); } {|Cursor:[|else if|]|} (z) { G(); } [|else|] { H(); } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample2_3() { await TestAsync( @"class C { void M() { if (x) { [|if|] (y) { F(); } [|else if|] (z) { G(); } {|Cursor:[|else|]|} { H(); } } } }"); } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrObjectFavoritesInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; namespace Microsoft.VisualStudio.Debugger.Evaluation { public class DkmClrObjectFavoritesInfo { public DkmClrObjectFavoritesInfo(IList<string> favorites, string displayString = null, string simpleDisplayString = null) { Favorites = new ReadOnlyCollection<string>(favorites); DisplayString = displayString; SimpleDisplayString = simpleDisplayString; } public string DisplayString { get; } public string SimpleDisplayString { get; } public ReadOnlyCollection<string> Favorites { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; namespace Microsoft.VisualStudio.Debugger.Evaluation { public class DkmClrObjectFavoritesInfo { public DkmClrObjectFavoritesInfo(IList<string> favorites, string displayString = null, string simpleDisplayString = null) { Favorites = new ReadOnlyCollection<string>(favorites); DisplayString = displayString; SimpleDisplayString = simpleDisplayString; } public string DisplayString { get; } public string SimpleDisplayString { get; } public ReadOnlyCollection<string> Favorites { get; } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/CSharp/Test/Semantic/Semantics/RecordStructTests.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; 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 { [CompilerTrait(CompilerFeature.RecordStructs)] public class RecordStructTests : 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] public void StructRecord1() { var src = @" record struct Point(int X, int Y);"; var verifier = CompileAndVerify(src).VerifyDiagnostics(); verifier.VerifyIL("Point.Equals(object)", @" { // Code size 23 (0x17) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""Point"" IL_0006: brfalse.s IL_0015 IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: unbox.any ""Point"" IL_000f: call ""readonly bool Point.Equals(Point)"" IL_0014: ret IL_0015: ldc.i4.0 IL_0016: ret }"); verifier.VerifyIL("Point.Equals(Point)", @" { // Code size 49 (0x31) .maxstack 3 IL_0000: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0005: ldarg.0 IL_0006: ldfld ""int Point.<X>k__BackingField"" IL_000b: ldarg.1 IL_000c: ldfld ""int Point.<X>k__BackingField"" IL_0011: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0016: brfalse.s IL_002f IL_0018: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001d: ldarg.0 IL_001e: ldfld ""int Point.<Y>k__BackingField"" IL_0023: ldarg.1 IL_0024: ldfld ""int Point.<Y>k__BackingField"" IL_0029: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_002e: ret IL_002f: ldc.i4.0 IL_0030: ret }"); } [Fact] public void StructRecord2() { var src = @" using System; record struct S(int X, int Y) { public static void Main() { var s1 = new S(0, 1); var s2 = new S(0, 1); Console.WriteLine(s1.X); Console.WriteLine(s1.Y); Console.WriteLine(s1.Equals(s2)); Console.WriteLine(s1.Equals(new S(1, 0))); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"0 1 True False").VerifyDiagnostics(); } [Fact] public void StructRecord3() { var src = @" using System; record struct S(int X, int Y) { public bool Equals(S s) => false; public static void Main() { var s1 = new S(0, 1); Console.WriteLine(s1.Equals(s1)); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"False") .VerifyDiagnostics( // (5,17): warning CS8851: 'S' defines 'Equals' but not 'GetHashCode' // public bool Equals(S s) => false; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("S").WithLocation(5, 17)); verifier.VerifyIL("S.Main", @" { // Code size 23 (0x17) .maxstack 3 .locals init (S V_0) //s1 IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.1 IL_0004: call ""S..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldloc.0 IL_000c: call ""bool S.Equals(S)"" IL_0011: call ""void System.Console.WriteLine(bool)"" IL_0016: ret }"); } [Fact] public void StructRecord5() { var src = @" using System; record struct S(int X, int Y) { public bool Equals(S s) { Console.Write(""s""); return true; } public static void Main() { var s1 = new S(0, 1); s1.Equals((object)s1); s1.Equals(s1); } }"; CompileAndVerify(src, expectedOutput: @"ss") .VerifyDiagnostics( // (5,17): warning CS8851: 'S' defines 'Equals' but not 'GetHashCode' // public bool Equals(S s) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("S").WithLocation(5, 17)); } [Fact] public void StructRecordDefaultCtor() { const string src = @" public record struct S(int X);"; const string src2 = @" class C { public S M() => new S(); }"; var comp = CreateCompilation(src + src2); comp.VerifyDiagnostics(); comp = CreateCompilation(src); var comp2 = CreateCompilation(src2, references: new[] { comp.EmitToImageReference() }); comp2.VerifyDiagnostics(); } [Fact] public void Equality_01() { var source = @"using static System.Console; record struct S; class Program { static void Main() { var x = new S(); var y = new S(); WriteLine(x.Equals(y)); WriteLine(((object)x).Equals(y)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"True True").VerifyDiagnostics(); verifier.VerifyIL("S.Equals(S)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret }"); verifier.VerifyIL("S.Equals(object)", @" { // Code size 23 (0x17) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""S"" IL_0006: brfalse.s IL_0015 IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: unbox.any ""S"" IL_000f: call ""readonly bool S.Equals(S)"" IL_0014: ret IL_0015: ldc.i4.0 IL_0016: ret }"); } [Fact] public void RecordStructLanguageVersion() { var src1 = @" struct Point(int x, int y); "; var src2 = @" record struct Point { } "; var src3 = @" record struct Point(int x, int y); "; var comp = CreateCompilation(new[] { src1, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,13): error CS1514: { expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 13), // (2,13): error CS1513: } expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 13), // (2,13): error CS8803: Top-level statements must precede namespace and type declarations. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 13), // (2,13): error CS8805: Program using top-level statements must be an executable. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 13), // (2,13): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 13), // (2,14): error CS8185: A declaration is not allowed in this context. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 14), // (2,14): error CS0165: Use of unassigned local variable 'x' // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 14), // (2,21): error CS8185: A declaration is not allowed in this context. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 21), // (2,21): error CS0165: Use of unassigned local variable 'y' // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 21) ); comp = CreateCompilation(new[] { src2, 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 struct Point { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(2, 8) ); comp = CreateCompilation(new[] { src3, 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 struct Point { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(2, 8) ); comp = CreateCompilation(new[] { src1, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,13): error CS1514: { expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 13), // (2,13): error CS1513: } expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 13), // (2,13): error CS8803: Top-level statements must precede namespace and type declarations. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 13), // (2,13): error CS8805: Program using top-level statements must be an executable. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 13), // (2,13): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 13), // (2,14): error CS8185: A declaration is not allowed in this context. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 14), // (2,14): error CS0165: Use of unassigned local variable 'x' // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 14), // (2,21): error CS8185: A declaration is not allowed in this context. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 21), // (2,21): error CS0165: Use of unassigned local variable 'y' // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 21) ); comp = CreateCompilation(new[] { src2, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { src3, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics(); } [Fact] public void RecordStructLanguageVersion_Nested() { var src1 = @" class C { struct Point(int x, int y); } "; var src2 = @" class D { record struct Point { } } "; var src3 = @" struct E { record struct Point(int x, int y); } "; var src4 = @" namespace NS { record struct Point { } } "; var comp = CreateCompilation(src1, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,17): error CS1514: { expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(4, 17), // (4,17): error CS1513: } expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(4, 17), // (4,31): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 31), // (4,31): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 31) ); comp = CreateCompilation(new[] { src2, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,12): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct Point { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(4, 12) ); comp = CreateCompilation(new[] { src3, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,12): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct Point(int x, int y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(4, 12) ); comp = CreateCompilation(src4, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,12): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct Point { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(4, 12) ); comp = CreateCompilation(src1); comp.VerifyDiagnostics( // (4,17): error CS1514: { expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(4, 17), // (4,17): error CS1513: } expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(4, 17), // (4,31): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 31), // (4,31): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 31) ); comp = CreateCompilation(src2); comp.VerifyDiagnostics(); comp = CreateCompilation(src3); comp.VerifyDiagnostics(); comp = CreateCompilation(src4); comp.VerifyDiagnostics(); } [Fact] public void TypeDeclaration_IsStruct() { var src = @" record struct Point(int x, int y); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, symbolValidator: validateModule, sourceSymbolValidator: validateModule); Assert.True(SyntaxFacts.IsTypeDeclaration(SyntaxKind.RecordStructDeclaration)); static void validateModule(ModuleSymbol module) { var isSourceSymbol = module is SourceModuleSymbol; var point = module.GlobalNamespace.GetTypeMember("Point"); Assert.True(point.IsValueType); Assert.False(point.IsReferenceType); Assert.False(point.IsRecord); Assert.Equal(TypeKind.Struct, point.TypeKind); Assert.Equal(SpecialType.System_ValueType, point.BaseTypeNoUseSiteDiagnostics.SpecialType); Assert.Equal("Point", point.ToTestDisplayString()); if (isSourceSymbol) { Assert.True(point is SourceNamedTypeSymbol); Assert.True(point.IsRecordStruct); Assert.True(point.GetPublicSymbol().IsRecord); Assert.Equal("record struct Point", point.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } else { Assert.True(point is PENamedTypeSymbol); Assert.False(point.IsRecordStruct); Assert.False(point.GetPublicSymbol().IsRecord); Assert.Equal("struct Point", point.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } } } [Fact] public void TypeDeclaration_IsStruct_InConstraints() { var src = @" record struct Point(int x, int y); class C<T> where T : struct { void M(C<Point> c) { } } class C2<T> where T : new() { void M(C2<Point> c) { } } class C3<T> where T : class { void M(C3<Point> c) { } // 1 } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (16,22): error CS0452: The type 'Point' must be a reference type in order to use it as parameter 'T' in the generic type or method 'C3<T>' // void M(C3<Point> c) { } // 1 Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "c").WithArguments("C3<T>", "T", "Point").WithLocation(16, 22) ); } [Fact] public void TypeDeclaration_IsStruct_Unmanaged() { var src = @" record struct Point(int x, int y); record struct Point2(string x, string y); class C<T> where T : unmanaged { void M(C<Point> c) { } void M2(C<Point2> c) { } // 1 } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,23): error CS8377: The type 'Point2' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'C<T>' // void M2(C<Point2> c) { } // 1 Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "c").WithArguments("C<T>", "T", "Point2").WithLocation(8, 23) ); } [Fact] public void IsRecord_Generic() { var src = @" record struct Point<T>(T x, T y); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, symbolValidator: validateModule, sourceSymbolValidator: validateModule); static void validateModule(ModuleSymbol module) { var isSourceSymbol = module is SourceModuleSymbol; var point = module.GlobalNamespace.GetTypeMember("Point"); Assert.True(point.IsValueType); Assert.False(point.IsReferenceType); Assert.False(point.IsRecord); Assert.Equal(TypeKind.Struct, point.TypeKind); Assert.Equal(SpecialType.System_ValueType, point.BaseTypeNoUseSiteDiagnostics.SpecialType); Assert.True(SyntaxFacts.IsTypeDeclaration(SyntaxKind.RecordStructDeclaration)); if (isSourceSymbol) { Assert.True(point is SourceNamedTypeSymbol); Assert.True(point.IsRecordStruct); Assert.True(point.GetPublicSymbol().IsRecord); } else { Assert.True(point is PENamedTypeSymbol); Assert.False(point.IsRecordStruct); Assert.False(point.GetPublicSymbol().IsRecord); } } } [Fact] public void IsRecord_Retargeting() { var src = @" public record struct Point(int x, int y); "; var comp = CreateCompilation(src, targetFramework: TargetFramework.Mscorlib40); var comp2 = CreateCompilation("", targetFramework: TargetFramework.Mscorlib46, references: new[] { comp.ToMetadataReference() }); var point = comp2.GlobalNamespace.GetTypeMember("Point"); Assert.Equal("Point", point.ToTestDisplayString()); Assert.IsType<RetargetingNamedTypeSymbol>(point); Assert.True(point.IsRecordStruct); Assert.True(point.GetPublicSymbol().IsRecord); } [Fact] public void IsRecord_AnonymousType() { var src = @" class C { void M() { var x = new { X = 1 }; } } "; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var creation = tree.GetRoot().DescendantNodes().OfType<AnonymousObjectCreationExpressionSyntax>().Single(); var type = model.GetTypeInfo(creation).Type!; Assert.Equal("<anonymous type: System.Int32 X>", type.ToTestDisplayString()); Assert.IsType<AnonymousTypeManager.AnonymousTypePublicSymbol>(((Symbols.PublicModel.NonErrorNamedTypeSymbol)type).UnderlyingNamedTypeSymbol); Assert.False(type.IsRecord); } [Fact] public void IsRecord_ErrorType() { var src = @" class C { Error M() => throw null; } "; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var method = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); var type = model.GetDeclaredSymbol(method)!.ReturnType; Assert.Equal("Error", type.ToTestDisplayString()); Assert.IsType<ExtendedErrorTypeSymbol>(((Symbols.PublicModel.ErrorTypeSymbol)type).UnderlyingNamedTypeSymbol); Assert.False(type.IsRecord); } [Fact] public void IsRecord_Pointer() { var src = @" class C { int* M() => throw null; } "; var comp = CreateCompilation(src, options: TestOptions.UnsafeReleaseDll); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var method = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); var type = model.GetDeclaredSymbol(method)!.ReturnType; Assert.Equal("System.Int32*", type.ToTestDisplayString()); Assert.IsType<PointerTypeSymbol>(((Symbols.PublicModel.PointerTypeSymbol)type).UnderlyingTypeSymbol); Assert.False(type.IsRecord); } [Fact] public void IsRecord_Dynamic() { var src = @" class C { void M(dynamic d) { } } "; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var method = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); var type = model.GetDeclaredSymbol(method)!.GetParameterType(0); Assert.Equal("dynamic", type.ToTestDisplayString()); Assert.IsType<DynamicTypeSymbol>(((Symbols.PublicModel.DynamicTypeSymbol)type).UnderlyingTypeSymbol); Assert.False(type.IsRecord); } [Fact] public void TypeDeclaration_MayNotHaveBaseType() { var src = @" record struct Point(int x, int y) : object; record struct Point2(int x, int y) : System.ValueType; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,37): error CS0527: Type 'object' in interface list is not an interface // record struct Point(int x, int y) : object; Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "object").WithArguments("object").WithLocation(2, 37), // (3,38): error CS0527: Type 'ValueType' in interface list is not an interface // record struct Point2(int x, int y) : System.ValueType; Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "System.ValueType").WithArguments("System.ValueType").WithLocation(3, 38) ); } [Fact] public void TypeDeclaration_MayNotHaveTypeConstraintsWithoutTypeParameters() { var src = @" record struct Point(int x, int y) where T : struct; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,35): error CS0080: Constraints are not allowed on non-generic declarations // record struct Point(int x, int y) where T : struct; Diagnostic(ErrorCode.ERR_ConstraintOnlyAllowedOnGenericDecl, "where").WithLocation(2, 35) ); } [Fact] public void TypeDeclaration_AllowedModifiers() { var src = @" readonly partial record struct S1; public record struct S2; internal record struct S3; public class Base { public int S6; } public class C : Base { private protected record struct S4; protected internal record struct S5; new record struct S6; } unsafe record struct S7; "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics(); Assert.Equal(Accessibility.Internal, comp.GlobalNamespace.GetTypeMember("S1").DeclaredAccessibility); Assert.Equal(Accessibility.Public, comp.GlobalNamespace.GetTypeMember("S2").DeclaredAccessibility); Assert.Equal(Accessibility.Internal, comp.GlobalNamespace.GetTypeMember("S3").DeclaredAccessibility); Assert.Equal(Accessibility.ProtectedAndInternal, comp.GlobalNamespace.GetTypeMember("C").GetTypeMember("S4").DeclaredAccessibility); Assert.Equal(Accessibility.ProtectedOrInternal, comp.GlobalNamespace.GetTypeMember("C").GetTypeMember("S5").DeclaredAccessibility); } [Fact] public void TypeDeclaration_DisallowedModifiers() { var src = @" abstract record struct S1; volatile record struct S2; extern record struct S3; virtual record struct S4; override record struct S5; async record struct S6; ref record struct S7; unsafe record struct S8; static record struct S9; sealed record struct S10; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,24): error CS0106: The modifier 'abstract' is not valid for this item // abstract record struct S1; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S1").WithArguments("abstract").WithLocation(2, 24), // (3,24): error CS0106: The modifier 'volatile' is not valid for this item // volatile record struct S2; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S2").WithArguments("volatile").WithLocation(3, 24), // (4,22): error CS0106: The modifier 'extern' is not valid for this item // extern record struct S3; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S3").WithArguments("extern").WithLocation(4, 22), // (5,23): error CS0106: The modifier 'virtual' is not valid for this item // virtual record struct S4; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S4").WithArguments("virtual").WithLocation(5, 23), // (6,24): error CS0106: The modifier 'override' is not valid for this item // override record struct S5; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S5").WithArguments("override").WithLocation(6, 24), // (7,21): error CS0106: The modifier 'async' is not valid for this item // async record struct S6; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S6").WithArguments("async").WithLocation(7, 21), // (8,19): error CS0106: The modifier 'ref' is not valid for this item // ref record struct S7; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S7").WithArguments("ref").WithLocation(8, 19), // (9,22): error CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe record struct S8; Diagnostic(ErrorCode.ERR_IllegalUnsafe, "S8").WithLocation(9, 22), // (10,22): error CS0106: The modifier 'static' is not valid for this item // static record struct S9; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S9").WithArguments("static").WithLocation(10, 22), // (11,22): error CS0106: The modifier 'sealed' is not valid for this item // sealed record struct S10; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S10").WithArguments("sealed").WithLocation(11, 22) ); } [Fact] public void TypeDeclaration_DuplicatesModifiers() { var src = @" public public record struct S2; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,8): error CS1004: Duplicate 'public' modifier // public public record struct S2; Diagnostic(ErrorCode.ERR_DuplicateModifier, "public").WithArguments("public").WithLocation(2, 8) ); } [Fact] public void TypeDeclaration_BeforeTopLevelStatement() { var src = @" record struct S; System.Console.WriteLine(); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine();").WithLocation(3, 1) ); } [Fact] public void TypeDeclaration_WithTypeParameters() { var src = @" S<string> local = default; local.ToString(); record struct S<T>; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); Assert.Equal(new[] { "T" }, comp.GlobalNamespace.GetTypeMember("S").TypeParameters.ToTestDisplayStrings()); } [Fact] public void TypeDeclaration_AllowedModifiersForMembers() { var src = @" record struct S { protected int Property { get; set; } // 1 internal protected string field; // 2, 3 abstract void M(); // 4 virtual void M2() { } // 5 }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,19): error CS0666: 'S.Property': new protected member declared in struct // protected int Property { get; set; } // 1 Diagnostic(ErrorCode.ERR_ProtectedInStruct, "Property").WithArguments("S.Property").WithLocation(4, 19), // (5,31): error CS0666: 'S.field': new protected member declared in struct // internal protected string field; // 2, 3 Diagnostic(ErrorCode.ERR_ProtectedInStruct, "field").WithArguments("S.field").WithLocation(5, 31), // (5,31): warning CS0649: Field 'S.field' is never assigned to, and will always have its default value null // internal protected string field; // 2, 3 Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("S.field", "null").WithLocation(5, 31), // (6,19): error CS0621: 'S.M()': virtual or abstract members cannot be private // abstract void M(); // 4 Diagnostic(ErrorCode.ERR_VirtualPrivate, "M").WithArguments("S.M()").WithLocation(6, 19), // (7,18): error CS0621: 'S.M2()': virtual or abstract members cannot be private // virtual void M2() { } // 5 Diagnostic(ErrorCode.ERR_VirtualPrivate, "M2").WithArguments("S.M2()").WithLocation(7, 18) ); } [Fact] public void TypeDeclaration_ImplementInterface() { var src = @" I i = (I)default(S); System.Console.Write(i.M(""four"")); I i2 = (I)default(S2); System.Console.Write(i2.M(""four"")); interface I { int M(string s); } public record struct S : I { public int M(string s) => s.Length; } public record struct S2 : I { int I.M(string s) => s.Length + 1; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "45"); AssertEx.Equal(new[] { "System.Int32 S.M(System.String s)", "readonly System.String S.ToString()", "readonly System.Boolean S.PrintMembers(System.Text.StringBuilder builder)", "System.Boolean S.op_Inequality(S left, S right)", "System.Boolean S.op_Equality(S left, S right)", "readonly System.Int32 S.GetHashCode()", "readonly System.Boolean S.Equals(System.Object obj)", "readonly System.Boolean S.Equals(S other)", "S..ctor()" }, comp.GetMember<NamedTypeSymbol>("S").GetMembers().ToTestDisplayStrings()); } [Fact] public void TypeDeclaration_SatisfiesStructConstraint() { var src = @" S s = default; System.Console.Write(M(s)); static int M<T>(T t) where T : struct, I => t.Property; public interface I { int Property { get; } } public record struct S : I { public int Property => 42; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "42"); } [Fact] public void TypeDeclaration_AccessingThis() { var src = @" S s = new S(); System.Console.Write(s.M()); public record struct S { public int Property => 42; public int M() => this.Property; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("S.M", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""int S.Property.get"" IL_0006: ret } "); } [Fact] public void TypeDeclaration_NoBaseInitializer() { var src = @" public record struct S { public S(int i) : base() { } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,12): error CS0522: 'S': structs cannot call base class constructors // public S(int i) : base() { } Diagnostic(ErrorCode.ERR_StructWithBaseConstructorCall, "S").WithArguments("S").WithLocation(4, 12) ); } [Fact] public void TypeDeclaration_ParameterlessConstructor_01() { var src = @"record struct S0(); record struct S1; record struct S2 { public S2() { } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct S0(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(1, 8), // (2,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct S1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(2, 8), // (3,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct S2 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(3, 8), // (5,12): error CS8773: Feature 'parameterless struct constructors' is not available in C# 9.0. Please use language version 10.0 or greater. // public S2() { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "S2").WithArguments("parameterless struct constructors", "10.0").WithLocation(5, 12)); var verifier = CompileAndVerify(src); verifier.VerifyIL("S0..ctor()", @"{ // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); verifier.VerifyMissing("S1..ctor()"); verifier.VerifyIL("S2..ctor()", @"{ // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } [Fact] public void TypeDeclaration_ParameterlessConstructor_02() { var src = @"record struct S1 { S1() { } } record struct S2 { internal S2() { } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct S1 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(1, 8), // (3,5): error CS8773: Feature 'parameterless struct constructors' is not available in C# 9.0. Please use language version 10.0 or greater. // S1() { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "S1").WithArguments("parameterless struct constructors", "10.0").WithLocation(3, 5), // (3,5): error CS8938: The parameterless struct constructor must be 'public'. // S1() { } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "S1").WithLocation(3, 5), // (5,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct S2 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(5, 8), // (7,14): error CS8773: Feature 'parameterless struct constructors' is not available in C# 9.0. Please use language version 10.0 or greater. // internal S2() { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "S2").WithArguments("parameterless struct constructors", "10.0").WithLocation(7, 14), // (7,14): error CS8938: The parameterless struct constructor must be 'public'. // internal S2() { } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "S2").WithLocation(7, 14)); comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,5): error CS8918: The parameterless struct constructor must be 'public'. // S1() { } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "S1").WithLocation(3, 5), // (7,14): error CS8918: The parameterless struct constructor must be 'public'. // internal S2() { } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "S2").WithLocation(7, 14)); } [Fact] public void TypeDeclaration_ParameterlessConstructor_OtherConstructors() { var src = @" record struct S1 { public S1() { } S1(object o) { } // ok because no record parameter list } record struct S2 { S2(object o) { } } record struct S3() { S3(object o) { } // 1 } record struct S4() { S4(object o) : this() { } } record struct S5(object o) { public S5() { } // 2 } record struct S6(object o) { public S6() : this(null) { } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,5): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // S3(object o) { } // 1 Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "S3").WithLocation(13, 5), // (21,12): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // public S5() { } // 2 Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "S5").WithLocation(21, 12) ); } [Fact] public void TypeDeclaration_ParameterlessConstructor_Initializers() { var src = @" var s1 = new S1(); var s2 = new S2(null); var s2b = new S2(); var s3 = new S3(); var s4 = new S4(new object()); var s5 = new S5(); var s6 = new S6(""s6.other""); System.Console.Write((s1.field, s2.field, s2b.field is null, s3.field, s4.field, s5.field, s6.field, s6.other)); record struct S1 { public string field = ""s1""; public S1() { } } record struct S2 { public string field = ""s2""; public S2(object o) { } } record struct S3() { public string field = ""s3""; } record struct S4 { public string field = ""s4""; public S4(object o) : this() { } } record struct S5() { public string field = ""s5""; public S5(object o) : this() { } } record struct S6(string other) { public string field = ""s6.field""; public S6() : this(""ignored"") { } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "(s1, s2, True, s3, s4, s5, s6.field, s6.other)"); } [Fact] public void TypeDeclaration_InstanceInitializers() { var src = @" public record struct S { public int field = 42; public int Property { get; set; } = 43; } "; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,15): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // public record struct S Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(2, 15), // (4,16): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public int field = 42; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "field").WithArguments("struct field initializers", "10.0").WithLocation(4, 16), // (5,16): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public int Property { get; set; } = 43; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Property").WithArguments("struct field initializers", "10.0").WithLocation(5, 16)); comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void TypeDeclaration_NoDestructor() { var src = @" public record struct S { ~S() { } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,6): error CS0575: Only class types can contain destructors // ~S() { } Diagnostic(ErrorCode.ERR_OnlyClassesCanContainDestructors, "S").WithArguments("S.~S()").WithLocation(4, 6) ); } [Fact] public void TypeDeclaration_DifferentPartials() { var src = @" partial record struct S1; partial struct S1 { } partial struct S2 { } partial record struct S2; partial record struct S3; partial record S3 { } partial record struct S4; partial record class S4 { } partial record struct S5; partial class S5 { } partial record struct S6; partial interface S6 { } partial record class C1; partial struct C1 { } partial record class C2; partial record struct C2 { } partial record class C3 { } partial record C3; partial record class C4; partial class C4 { } partial record class C5; partial interface C5 { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,16): error CS0261: Partial declarations of 'S1' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial struct S1 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S1").WithArguments("S1").WithLocation(3, 16), // (6,23): error CS0261: Partial declarations of 'S2' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial record struct S2; Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S2").WithArguments("S2").WithLocation(6, 23), // (9,16): error CS0261: Partial declarations of 'S3' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial record S3 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S3").WithArguments("S3").WithLocation(9, 16), // (12,22): error CS0261: Partial declarations of 'S4' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial record class S4 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S4").WithArguments("S4").WithLocation(12, 22), // (15,15): error CS0261: Partial declarations of 'S5' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial class S5 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S5").WithArguments("S5").WithLocation(15, 15), // (18,19): error CS0261: Partial declarations of 'S6' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial interface S6 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S6").WithArguments("S6").WithLocation(18, 19), // (21,16): error CS0261: Partial declarations of 'C1' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial struct C1 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "C1").WithArguments("C1").WithLocation(21, 16), // (24,23): error CS0261: Partial declarations of 'C2' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial record struct C2 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "C2").WithArguments("C2").WithLocation(24, 23), // (30,15): error CS0261: Partial declarations of 'C4' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial class C4 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "C4").WithArguments("C4").WithLocation(30, 15), // (33,19): error CS0261: Partial declarations of 'C5' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial interface C5 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "C5").WithArguments("C5").WithLocation(33, 19) ); } [Fact] public void PartialRecord_OnlyOnePartialHasParameterList() { var src = @" partial record struct S(int i); partial record struct S(int i); partial record struct S2(int i); partial record struct S2(); partial record struct S3(); partial record struct S3(); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,24): error CS8863: Only a single record partial declaration may have a parameter list // partial record struct S(int i); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int i)").WithLocation(3, 24), // (6,25): error CS8863: Only a single record partial declaration may have a parameter list // partial record struct S2(); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "()").WithLocation(6, 25), // (9,25): error CS8863: Only a single record partial declaration may have a parameter list // partial record struct S3(); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "()").WithLocation(9, 25) ); } [Fact] public void PartialRecord_ParametersInScopeOfBothParts() { var src = @" var c = new C(2); System.Console.Write((c.P1, c.P2)); public partial record struct C(int X) { public int P1 { get; set; } = X; } public partial record struct C { public int P2 { get; set; } = X; } "; var comp = CreateCompilation(src); CompileAndVerify(comp, expectedOutput: "(2, 2)", verify: Verification.Skipped /* init-only */) .VerifyDiagnostics( // (5,30): warning CS0282: There is no defined ordering between fields in multiple declarations of partial struct 'C'. To specify an ordering, all instance fields must be in the same declaration. // public partial record struct C(int X) Diagnostic(ErrorCode.WRN_SequentialOnPartialClass, "C").WithArguments("C").WithLocation(5, 30) ); } [Fact] public void PartialRecord_DuplicateMemberNames() { var src = @" public partial record struct C(int X) { public void M(int i) { } } public partial record struct C { public void M(string s) { } } "; var comp = CreateCompilation(src); var expectedMemberNames = new string[] { ".ctor", "<X>k__BackingField", "get_X", "set_X", "X", "M", "M", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "Deconstruct", ".ctor", }; 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 struct Nested(T T); } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "2"); } [Fact] public void PositionalMemberModifiers_RefOrOut() { var src = @" record struct R(ref int P1, out int P2); "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,15): error CS0177: The out parameter 'P2' must be assigned to before control leaves the current method // record struct R(ref int P1, out int P2); Diagnostic(ErrorCode.ERR_ParamUnassigned, "R").WithArguments("P2").WithLocation(2, 15), // (2,17): error CS0631: ref and out are not valid in this context // record struct R(ref int P1, out int P2); Diagnostic(ErrorCode.ERR_IllegalRefParam, "ref").WithLocation(2, 17), // (2,29): error CS0631: ref and out are not valid in this context // record struct R(ref int P1, out int P2); Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(2, 29) ); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberModifiers_This() { var src = @" record struct R(this int i); "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,17): error CS0027: Keyword 'this' is not available in the current context // record struct R(this int i); Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(2, 17) ); } [Fact, WorkItem(45591, "https://github.com/dotnet/roslyn/issues/45591")] public void Clone_DisallowedInSource() { var src = @" record struct C1(string Clone); // 1 record struct C2 { string Clone; // 2 } record struct C3 { string Clone { get; set; } // 3 } record struct C5 { void Clone() { } // 4 void Clone(int i) { } // 5 } record struct C6 { class Clone { } // 6 } record struct C7 { delegate void Clone(); // 7 } record struct C8 { event System.Action Clone; // 8 } record struct Clone { Clone(int i) => throw null; } record struct C9 : System.ICloneable { object System.ICloneable.Clone() => throw null; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,25): error CS8859: Members named 'Clone' are disallowed in records. // record struct C1(string Clone); // 1 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(2, 25), // (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 CS8859: Members named 'Clone' are disallowed in records. // void Clone() { } // 4 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(13, 10), // (14,10): error CS8859: Members named 'Clone' are disallowed in records. // void Clone(int i) { } // 5 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(14, 10), // (18,11): error CS8859: Members named 'Clone' are disallowed in records. // class Clone { } // 6 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(18, 11), // (22,19): error CS8859: Members named 'Clone' are disallowed in records. // delegate void Clone(); // 7 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(22, 19), // (26,25): error CS8859: Members named 'Clone' are disallowed in records. // event System.Action Clone; // 8 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(26, 25), // (26,25): warning CS0067: The event 'C8.Clone' is never used // event System.Action Clone; // 8 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Clone").WithArguments("C8.Clone").WithLocation(26, 25) ); } [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 struct 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 }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (6,22): error CS0721: 'C2': static types cannot be used as parameters // unsafe record struct C( // 1 Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "C").WithArguments("C2").WithLocation(6, 22), // (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 struct 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 }, parseOptions: TestOptions.RegularPreview, 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 struct 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 }, parseOptions: TestOptions.RegularPreview, 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 struct 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 }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeDebugExe); comp.VerifyEmitDiagnostics( // (4,29): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // unsafe record struct C(int* P1, int*[] P2, C<int*[]> P3) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(4, 29), // (4,40): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // unsafe record struct C(int* P1, int*[] P2, C<int*[]> P3) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(4, 40), // (4,54): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // unsafe record struct C(int* P1, int*[] P2, C<int*[]> P3) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(4, 54) ); 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] public void RecordProperties_01() { var src = @" using System; record struct C(int X, int Y) { int Z = 345; public static void Main() { var c = new C(1, 2); Console.Write(c.X); Console.Write(c.Y); Console.Write(c.Z); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"12345").VerifyDiagnostics(); verifier.VerifyIL("C..ctor(int, int)", @" { // Code size 26 (0x1a) .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 0x159 IL_0014: stfld ""int C.Z"" IL_0019: ret } "); var c = verifier.Compilation.GlobalNamespace.GetTypeMember("C"); Assert.False(c.IsReadOnly); var x = (IPropertySymbol)c.GetMember("X"); Assert.Equal("readonly System.Int32 C.X.get", x.GetMethod.ToTestDisplayString()); Assert.Equal("void C.X.set", x.SetMethod.ToTestDisplayString()); Assert.False(x.SetMethod!.IsInitOnly); var xBackingField = (IFieldSymbol)c.GetMember("<X>k__BackingField"); Assert.Equal("System.Int32 C.<X>k__BackingField", xBackingField.ToTestDisplayString()); Assert.False(xBackingField.IsReadOnly); } [Fact] public void RecordProperties_01_EmptyParameterList() { var src = @" using System; record struct C() { int Z = 345; public static void Main() { var c = new C(); Console.Write(c.Z); } }"; CreateCompilation(src).VerifyEmitDiagnostics(); } [Fact] public void RecordProperties_01_Readonly() { var src = @" using System; readonly record struct C(int X, int Y) { readonly int Z = 345; public static void Main() { var c = new C(1, 2); Console.Write(c.X); Console.Write(c.Y); Console.Write(c.Z); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"12345").VerifyDiagnostics(); var c = verifier.Compilation.GlobalNamespace.GetTypeMember("C"); Assert.True(c.IsReadOnly); 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_01_ReadonlyMismatch() { var src = @" readonly record struct C(int X) { public int X { get; set; } = X; // 1 } record struct C2(int X) { public int X { get; init; } = X; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,16): error CS8341: Auto-implemented instance properties in readonly structs must be readonly. // public int X { get; set; } = X; // 1 Diagnostic(ErrorCode.ERR_AutoPropsInRoStruct, "X").WithLocation(4, 16) ); } [Fact] public void RecordProperties_02() { var src = @" using System; record struct 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 struct 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); } }"; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (3,15): error CS0843: Auto-implemented property 'C.X' must be fully assigned before control is returned to the caller. // record struct C(int X, int Y) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "C").WithArguments("C.X").WithLocation(3, 15), // (3,21): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 21) ); } [Fact] public void RecordProperties_03_InitializedWithY() { var src = @" using System; record struct C(int X, int Y) { public int X { get; } = Y; public static void Main() { var c = new C(1, 2); Console.Write(c.X); Console.Write(c.Y); } }"; CompileAndVerify(src, expectedOutput: "22") .VerifyDiagnostics( // (3,21): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 21) ); } [Fact] public void RecordProperties_04() { var src = @" using System; record struct C(int X, int Y) { public int X { get; } = 3; public static void Main() { var c = new C(1, 2); Console.Write(c.X); Console.Write(c.Y); } }"; CompileAndVerify(src, expectedOutput: "32") .VerifyDiagnostics( // (3,21): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 21) ); } [Fact] public void RecordProperties_05() { var src = @" record struct C(int X, int X) { }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,28): error CS0100: The parameter name 'X' is a duplicate // record struct C(int X, int X) Diagnostic(ErrorCode.ERR_DuplicateParamName, "X").WithArguments("X").WithLocation(2, 28), // (2,28): error CS0102: The type 'C' already contains a definition for 'X' // record struct C(int X, int X) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("C", "X").WithLocation(2, 28) ); var expectedMembers = new[] { "System.Int32 C.X { get; set; }", "System.Int32 C.X { get; set; }" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings()); var expectedMemberNames = new[] { ".ctor", "<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", "Deconstruct", ".ctor" }; AssertEx.Equal(expectedMemberNames, comp.GetMember<NamedTypeSymbol>("C").GetPublicSymbol().MemberNames); } [Fact] public void RecordProperties_06() { var src = @" record struct 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,21): error CS0082: Type 'C' already reserves a member called 'get_X' with the same parameter types // record struct C(int X, int Y) Diagnostic(ErrorCode.ERR_MemberReserved, "X").WithArguments("get_X", "C").WithLocation(2, 21), // (2,28): error CS0082: Type 'C' already reserves a member called 'set_Y' with the same parameter types // record struct C(int X, int Y) Diagnostic(ErrorCode.ERR_MemberReserved, "Y").WithArguments("set_Y", "C").WithLocation(2, 28) ); var actualMembers = comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "System.Int32 C.<X>k__BackingField", "readonly System.Int32 C.X.get", "void C.X.set", "System.Int32 C.X { get; set; }", "System.Int32 C.<Y>k__BackingField", "readonly System.Int32 C.Y.get", "void C.Y.set", "System.Int32 C.Y { get; set; }", "void C.get_X()", "void C.set_X()", "System.Int32 C.get_Y(System.Int32 value)", "System.Int32 C.set_Y(System.Int32 value)", "readonly System.String C.ToString()", "readonly System.Boolean C.PrintMembers(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C left, C right)", "System.Boolean C.op_Equality(C left, C right)", "readonly System.Int32 C.GetHashCode()", "readonly System.Boolean C.Equals(System.Object obj)", "readonly System.Boolean C.Equals(C other)", "readonly void C.Deconstruct(out System.Int32 X, out System.Int32 Y)", "C..ctor()", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void RecordProperties_07() { var comp = CreateCompilation(@" record struct C1(object P, object get_P); record struct C2(object get_P, object P);"); comp.VerifyDiagnostics( // (2,25): error CS0102: The type 'C1' already contains a definition for 'get_P' // record struct C1(object P, object get_P); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C1", "get_P").WithLocation(2, 25), // (3,39): error CS0102: The type 'C2' already contains a definition for 'get_P' // record struct C2(object get_P, object P); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C2", "get_P").WithLocation(3, 39) ); } [Fact] public void RecordProperties_08() { var comp = CreateCompilation(@" record struct C1(object O1) { public object O1 { get; } = O1; public object O2 { get; } = O1; }"); comp.VerifyDiagnostics(); } [Fact] public void RecordProperties_09() { var src = @" record struct 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(src); comp.VerifyDiagnostics( // (2,24): error CS0102: The type 'C' already contains a definition for 'P1' // record struct C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P1").WithArguments("C", "P1").WithLocation(2, 24), // (2,35): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record struct C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(2, 35), // (6,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(6, 9), // (7,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(7, 9) ); } [Fact] public void RecordProperties_10() { var src = @" record struct C(object P) { const int P = 4; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,24): error CS8866: Record member 'C.P' must be a readable instance property or field of type 'object' to match positional parameter 'P'. // record struct C(object P) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("C.P", "object", "P").WithLocation(2, 24), // (2,24): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record struct C(object P) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 24) ); } [Fact] public void RecordProperties_11_UnreadPositionalParameter() { var comp = CreateCompilation(@" record struct 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; } "); comp.VerifyDiagnostics( // (2,15): error CS0843: Auto-implemented property 'C1.O1' must be fully assigned before control is returned to the caller. // record struct C1(object O1, object O2, object O3) // 1, 2 Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "C1").WithArguments("C1.O1").WithLocation(2, 15), // (2,25): warning CS8907: Parameter 'O1' is unread. Did you forget to use it to initialize the property with that name? // record struct C1(object O1, object O2, object O3) // 1, 2 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O1").WithArguments("O1").WithLocation(2, 25), // (2,47): warning CS8907: Parameter 'O3' is unread. Did you forget to use it to initialize the property with that name? // record struct C1(object O1, object O2, object O3) // 1, 2 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O3").WithArguments("O3").WithLocation(2, 47) ); } [Fact] public void RecordProperties_11_UnreadPositionalParameter_InRefOut() { var comp = CreateCompilation(@" record struct 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,47): warning CS8907: Parameter 'O3' is unread. Did you forget to use it to initialize the property with that name? // record struct C1(object O1, object O2, object O3) // 1 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O3").WithArguments("O3").WithLocation(2, 47) ); } [Fact] public void RecordProperties_SelfContainedStruct() { var comp = CreateCompilation(@" record struct C(C c); "); comp.VerifyDiagnostics( // (2,19): error CS0523: Struct member 'C.c' of type 'C' causes a cycle in the struct layout // record struct C(C c); Diagnostic(ErrorCode.ERR_StructLayoutCycle, "c").WithArguments("C.c", "C").WithLocation(2, 19) ); } [Fact] public void RecordProperties_PropertyInValueType() { var corlib_cs = @" namespace System { public class Object { public virtual bool Equals(object x) => throw null; public virtual int GetHashCode() => throw null; public virtual string ToString() => throw null; } public class Exception { } public class ValueType { public bool X { get; set; } } public class Attribute { } public class String { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { } } namespace System.Collections.Generic { public abstract class EqualityComparer<T> { public static EqualityComparer<T> Default => throw null; public abstract int GetHashCode(T t); } } 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 corlibRef = CreateEmptyCompilation(corlib_cs).EmitToImageReference(); { var src = @" record struct C(bool X) { bool M() { return X; } } "; var comp = CreateEmptyCompilation(src, parseOptions: TestOptions.RegularPreview, references: new[] { corlibRef }); comp.VerifyEmitDiagnostics( // (2,22): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(bool X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 22) ); Assert.Null(comp.GlobalNamespace.GetTypeMember("C").GetMember("X")); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var x = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single().Expression; Assert.Equal("System.Boolean System.ValueType.X { get; set; }", model.GetSymbolInfo(x!).Symbol.ToTestDisplayString()); } { var src = @" readonly record struct C(bool X) { bool M() { return X; } } "; var comp = CreateEmptyCompilation(src, parseOptions: TestOptions.RegularPreview, references: new[] { corlibRef }); comp.VerifyEmitDiagnostics( // (2,31): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // readonly record struct C(bool X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 31) ); Assert.Null(comp.GlobalNamespace.GetTypeMember("C").GetMember("X")); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var x = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single().Expression; Assert.Equal("System.Boolean System.ValueType.X { get; set; }", model.GetSymbolInfo(x!).Symbol.ToTestDisplayString()); } } [Fact] public void RecordProperties_PropertyInValueType_Static() { var corlib_cs = @" namespace System { public class Object { public virtual bool Equals(object x) => throw null; public virtual int GetHashCode() => throw null; public virtual string ToString() => throw null; } public class Exception { } public class ValueType { public static bool X { get; set; } } public class Attribute { } public class String { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { } } namespace System.Collections.Generic { public abstract class EqualityComparer<T> { public static EqualityComparer<T> Default => throw null; public abstract int GetHashCode(T t); } } 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 corlibRef = CreateEmptyCompilation(corlib_cs).EmitToImageReference(); var src = @" record struct C(bool X) { bool M() { return X; } } "; var comp = CreateEmptyCompilation(src, parseOptions: TestOptions.RegularPreview, references: new[] { corlibRef }); comp.VerifyEmitDiagnostics( // (2,22): error CS8866: Record member 'System.ValueType.X' must be a readable instance property or field of type 'bool' to match positional parameter 'X'. // record struct C(bool X) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("System.ValueType.X", "bool", "X").WithLocation(2, 22), // (2,22): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(bool X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 22) ); } [Fact] 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 }, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "static ctor", verify: Verification.Skipped /* init-only */); } [Fact] public void StaticCtor_ParameterlessPrimaryCtor() { var src = @" record struct R(int I) { static R() { } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void StaticCtor_CopyCtor() { var src = @" record struct R(int I) { 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 InterfaceImplementation_NotReadonly() { var source = @" I r = new R(42); r.P2 = 43; r.P3 = 44; System.Console.Write((r.P1, r.P2, r.P3)); interface I { int P1 { get; set; } int P2 { get; set; } int P3 { get; set; } } record struct R(int P1) : I { public int P2 { get; set; } = 0; int I.P3 { get; set; } = 0; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "(42, 43, 44)"); } [Fact] public void InterfaceImplementation_NotReadonly_InitOnlyInterface() { var source = @" interface I { int P1 { get; init; } } record struct R(int P1) : I; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (6,27): error CS8854: 'R' does not implement interface member 'I.P1.init'. 'R.P1.set' cannot implement 'I.P1.init'. // record struct R(int P1) : I; Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("R", "I.P1.init", "R.P1.set").WithLocation(6, 27) ); } [Fact] public void InterfaceImplementation_Readonly() { var source = @" I r = new R(42) { P2 = 43 }; System.Console.Write((r.P1, r.P2)); interface I { int P1 { get; init; } int P2 { get; init; } } readonly record struct R(int P1) : I { public int P2 { get; init; } = 0; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "(42, 43)", verify: Verification.Skipped /* init-only */); } [Fact] public void InterfaceImplementation_Readonly_SetInterface() { var source = @" interface I { int P1 { get; set; } } readonly record struct R(int P1) : I; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (6,36): error CS8854: 'R' does not implement interface member 'I.P1.set'. 'R.P1.init' cannot implement 'I.P1.set'. // readonly record struct R(int P1) : I; Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("R", "I.P1.set", "R.P1.init").WithLocation(6, 36) ); } [Fact] public void InterfaceImplementation_Readonly_PrivateImplementation() { var source = @" I r = new R(42) { P2 = 43, P3 = 44 }; System.Console.Write((r.P1, r.P2, r.P3)); interface I { int P1 { get; init; } int P2 { get; init; } int P3 { get; init; } } readonly record struct R(int P1) : I { public int P2 { get; init; } = 0; int I.P3 { get; init; } = 0; // not practically initializable } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,28): error CS0117: 'R' does not contain a definition for 'P3' // I r = new R(42) { P2 = 43, P3 = 44 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "P3").WithArguments("R", "P3").WithLocation(2, 28) ); } [Fact] public void Initializers_01() { var src = @" using System; record struct 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 struct 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; set; }", 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 struct 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; set; }", 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 struct 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 SynthesizedRecordPointerProperty() { var src = @" record struct 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] public void PositionalMemberModifiers_In() { var src = @" var r = new R(42); int i = 43; var r2 = new R(in i); System.Console.Write((r.P1, r2.P1)); record struct R(in int P1); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "(42, 43)"); var actualMembers = comp.GetMember<NamedTypeSymbol>("R").Constructors.ToTestDisplayStrings(); var expectedMembers = new[] { "R..ctor(in System.Int32 P1)", "R..ctor()" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void PositionalMemberModifiers_Params() { var src = @" 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])); record struct R(params int[] Array); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "(42, 43, 44, 45)"); var actualMembers = comp.GetMember<NamedTypeSymbol>("R").Constructors.ToTestDisplayStrings(); var expectedMembers = new[] { "R..ctor(params System.Int32[] Array)", "R..ctor()" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void PositionalMemberDefaultValue() { var src = @" var r = new R(); // This uses the parameterless constructor System.Console.Write(r.P); record struct R(int P = 42); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "0"); } [Fact] public void PositionalMemberDefaultValue_PassingOneArgument() { var src = @" var r = new R(41); System.Console.Write(r.O); System.Console.Write("" ""); System.Console.Write(r.P); record struct R(int O, int P = 42); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "41 42"); } [Fact] public void PositionalMemberDefaultValue_AndPropertyWithInitializer() { var src = @" var r = new R(0); System.Console.Write(r.P); record struct R(int O, int P = 1) { public int P { get; init; } = 42; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,28): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record struct R(int O, int P = 1) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(5, 28) ); var verifier = CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("R..ctor(int, int)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int R.<O>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldc.i4.s 42 IL_000a: stfld ""int R.<P>k__BackingField"" IL_000f: ret }"); } [Fact] public void PositionalMemberDefaultValue_AndPropertyWithoutInitializer() { var src = @" record struct 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(src); comp.VerifyDiagnostics( // (2,15): error CS0843: Auto-implemented property 'R.P' must be fully assigned before control is returned to the caller. // record struct R(int P = 42) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "R").WithArguments("R.P").WithLocation(2, 15), // (2,21): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record struct R(int P = 42) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 21) ); } [Fact] public void PositionalMemberDefaultValue_AndPropertyWithInitializer_CopyingParameter() { var src = @" var r = new R(0); System.Console.Write(r.P); record struct R(int O, int P = 42) { public int P { get; init; } = P; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("R..ctor(int, int)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int R.<O>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.2 IL_0009: stfld ""int R.<P>k__BackingField"" IL_000e: ret }"); } [Fact] public void RecordWithConstraints_NullableWarning() { var src = @" #nullable enable var r = new R<string?>(""R""); var r2 = new R2<string?>(""R2""); System.Console.Write((r.P, r2.P)); record struct R<T>(T P) where T : class; record struct R2<T>(T P) where T : class { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,15): 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(3, 15), // (4,17): 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(4, 17) ); CompileAndVerify(comp, expectedOutput: "(R, R2)"); } [Fact] public void RecordWithConstraints_ConstraintError() { var src = @" record struct R<T>(T P) where T : class; record struct 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 CyclicBases4() { var text = @" record struct A<T> : B<A<T>> { } record struct B<T> : A<B<T>> { A<T> F() { return null; } } "; var comp = CreateCompilation(text); comp.GetDeclarationDiagnostics().Verify( // (3,22): error CS0527: Type 'A<B<T>>' in interface list is not an interface // record struct B<T> : A<B<T>> Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "A<B<T>>").WithArguments("A<B<T>>").WithLocation(3, 22), // (2,22): error CS0527: Type 'B<A<T>>' in interface list is not an interface // record struct A<T> : B<A<T>> { } Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "B<A<T>>").WithArguments("B<A<T>>").WithLocation(2, 22) ); } [Fact] public void PartialClassWithDifferentTupleNamesInImplementedInterfaces() { var source = @" public interface I<T> { } public partial record C1 : I<(int a, int b)> { } public partial record C1 : I<(int notA, int notB)> { } public partial record C2 : I<(int a, int b)> { } public partial record C2 : I<(int, int)> { } public partial record C3 : I<(int a, int b)> { } public partial record C3 : I<(int a, int b)> { } public partial record C4 : I<(int a, int b)> { } public partial record C4 : I<(int b, int a)> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,23): error CS8140: 'I<(int notA, int notB)>' is already listed in the interface list on type 'C1' with different tuple element names, as 'I<(int a, int b)>'. // public partial record C1 : I<(int a, int b)> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C1").WithArguments("I<(int notA, int notB)>", "I<(int a, int b)>", "C1").WithLocation(3, 23), // (6,23): error CS8140: 'I<(int, int)>' is already listed in the interface list on type 'C2' with different tuple element names, as 'I<(int a, int b)>'. // public partial record C2 : I<(int a, int b)> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C2").WithArguments("I<(int, int)>", "I<(int a, int b)>", "C2").WithLocation(6, 23), // (12,23): error CS8140: 'I<(int b, int a)>' is already listed in the interface list on type 'C4' with different tuple element names, as 'I<(int a, int b)>'. // public partial record C4 : I<(int a, int b)> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C4").WithArguments("I<(int b, int a)>", "I<(int a, int b)>", "C4").WithLocation(12, 23) ); } [Fact] public void CS0267ERR_PartialMisplaced() { var test = @" partial public record struct 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 record struct C // CS0267 Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(2, 1) ); } [Fact] public void SealedStaticRecord() { var source = @" sealed static record struct R; "; CreateCompilation(source).VerifyDiagnostics( // (2,29): error CS0106: The modifier 'sealed' is not valid for this item // sealed static record struct R; Diagnostic(ErrorCode.ERR_BadMemberFlag, "R").WithArguments("sealed").WithLocation(2, 29), // (2,29): error CS0106: The modifier 'static' is not valid for this item // sealed static record struct R; Diagnostic(ErrorCode.ERR_BadMemberFlag, "R").WithArguments("static").WithLocation(2, 29) ); } [Fact] public void CS0513ERR_AbstractInConcreteClass02() { var text = @" record struct C { public abstract event System.Action E; public abstract int this[int x] { get; set; } } "; CreateCompilation(text).VerifyDiagnostics( // (5,25): error CS0106: The modifier 'abstract' is not valid for this item // public abstract int this[int x] { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("abstract").WithLocation(5, 25), // (4,41): error CS0106: The modifier 'abstract' is not valid for this item // public abstract event System.Action E; Diagnostic(ErrorCode.ERR_BadMemberFlag, "E").WithArguments("abstract").WithLocation(4, 41) ); } [Fact] public void CS0574ERR_BadDestructorName() { var test = @" public record struct iii { ~iiii(){} } "; CreateCompilation(test).VerifyDiagnostics( // (4,6): error CS0574: Name of destructor must match name of type // ~iiii(){} Diagnostic(ErrorCode.ERR_BadDestructorName, "iiii").WithLocation(4, 6), // (4,6): error CS0575: Only class types can contain destructors // ~iiii(){} Diagnostic(ErrorCode.ERR_OnlyClassesCanContainDestructors, "iiii").WithArguments("iii.~iii()").WithLocation(4, 6) ); } [Fact] public void StaticRecordWithConstructorAndDestructor() { var text = @" static record struct R(int I) { public R() : this(0) { } ~R() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (2,22): error CS0106: The modifier 'static' is not valid for this item // static record struct R(int I) Diagnostic(ErrorCode.ERR_BadMemberFlag, "R").WithArguments("static").WithLocation(2, 22), // (5,6): error CS0575: Only class types can contain destructors // ~R() { } Diagnostic(ErrorCode.ERR_OnlyClassesCanContainDestructors, "R").WithArguments("R.~R()").WithLocation(5, 6) ); } [Fact] public void RecordWithPartialMethodExplicitImplementation() { var source = @"record struct 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 RecordWithPartialMethodRequiringBody() { var source = @"partial record struct R { public partial int M(); }"; CreateCompilation(source).VerifyDiagnostics( // (3,24): error CS8795: Partial method 'R.M()' must have an implementation part because it has accessibility modifiers. // public partial int M(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "M").WithArguments("R.M()").WithLocation(3, 24) ); } [Fact] public void CanDeclareIteratorInRecord() { var source = @" using System.Collections.Generic; foreach(var i in new X(42).GetItems()) { System.Console.Write(i); } public record struct X(int a) { public IEnumerable<int> GetItems() { yield return a; yield return a + 1; } }"; var comp = CreateCompilation(source).VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "4243"); } [Fact] public void ParameterlessConstructor() { var src = @" System.Console.Write(new C().Property); record struct C() { public int Property { get; set; } = 42; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "42"); } [Fact] public void XmlDoc() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public record struct 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] public void XmlDoc_Cref() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for <see cref=""I1""/></param> public record struct 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] public void Deconstruct_Simple() { var source = @"using System; record struct 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 ""readonly int B.X.get"" IL_0007: stind.i4 IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: call ""readonly 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 struct B(int X) { public int Y { get; init; } = 0; 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( "readonly 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 struct B(int X, int Y); record struct 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 ""readonly int B.X.get"" IL_0007: stind.i4 IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: call ""readonly int B.Y.get"" IL_000f: stind.i4 IL_0010: ret }"); verifier.VerifyIL("C.Deconstruct", @" { // Code size 21 (0x15) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""readonly B C.B.get"" IL_0007: stobj ""B"" IL_000c: ldarg.2 IL_000d: ldarg.0 IL_000e: call ""readonly int C.Z.get"" IL_0013: stind.i4 IL_0014: ret }"); } [Fact] public void Deconstruct_PropertyCollision() { var source = @"using System; record struct 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,21): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct B(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 21) ); 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 struct 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( "readonly void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_FieldCollision() { var source = @" using System; record struct C(int X) { int X = 0; 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); comp.VerifyDiagnostics( // (4,21): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(int X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(4, 21), // (6,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(6, 9)); Assert.Equal( "readonly void C.Deconstruct(out System.Int32 X)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Empty() { var source = @" record struct 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_Conversion_02() { var source = @" #nullable enable using System; record struct C(string? X, string Y) { public string X { get; init; } = null!; public string? Y { get; init; } = string.Empty; 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,25): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(string? X, string Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(5, 25), // (5,35): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record struct C(string? X, string Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(5, 35) ); Assert.Equal( "readonly void C.Deconstruct(out System.String? X, out System.String Y)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Empty_WithParameterList() { var source = @" record struct 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)); AssertEx.Equal(new[] { "C..ctor()", "void C.M(C c)", "void C.Main()", "readonly System.String C.ToString()", "readonly System.Boolean C.PrintMembers(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C left, C right)", "System.Boolean C.op_Equality(C left, C right)", "readonly System.Int32 C.GetHashCode()", "readonly System.Boolean C.Equals(System.Object obj)", "readonly System.Boolean C.Equals(C other)" }, comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings()); } [Fact] public void Deconstruct_Empty_WithParameterList_UserDefined_01() { var source = @"using System; record struct C(int I) { public void Deconstruct() { } static void M(C c) { switch (c) { case C(): Console.Write(12); break; } } public static void Main() { M(new C(42)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); } [Fact] public void Deconstruct_GeneratedAsReadOnly() { var src = @" record struct A(int I, string S); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var method = comp.GetMember<SynthesizedRecordDeconstruct>("A.Deconstruct"); Assert.True(method.IsDeclaredReadOnly); } [Fact] public void Deconstruct_WihtNonReadOnlyGetter_GeneratedAsNonReadOnly() { var src = @" record struct A(int I, string S) { public int I { get => 0; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,21): warning CS8907: Parameter 'I' is unread. Did you forget to use it to initialize the property with that name? // record struct A(int I, string S) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "I").WithArguments("I").WithLocation(2, 21)); var method = comp.GetMember<SynthesizedRecordDeconstruct>("A.Deconstruct"); Assert.False(method.IsDeclaredReadOnly); } [Fact] public void Deconstruct_UserDefined() { var source = @"using System; record struct 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_02() { var source = @"using System; record struct 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)); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("internal")] public void Deconstruct_UserDefined_Accessibility_07(string accessibility) { var source = $@" record struct 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 struct 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 OutVarInPositionalParameterDefaultValue() { var source = @" record struct A(int X = A.M(out int a) + a) { public static int M(out int a) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,25): error CS1736: Default parameter value for 'X' must be a compile-time constant // record struct A(int X = A.M(out int a) + a) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "A.M(out int a) + a").WithArguments("X").WithLocation(2, 25) ); } [Fact] public void FieldConsideredUnassignedIfInitializationViaProperty() { var source = @" record struct Pos(int X) { private int x; public int X { get { return x; } set { x = value; } } = X; } record struct Pos2(int X) { private int x = X; // value isn't validated by setter public int X { get { return x; } set { x = value; } } } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,15): error CS0171: Field 'Pos.x' must be fully assigned before control is returned to the caller // record struct Pos(int X) Diagnostic(ErrorCode.ERR_UnassignedThis, "Pos").WithArguments("Pos.x").WithLocation(2, 15), // (5,16): error CS8050: Only auto-implemented properties can have initializers. // public int X { get { return x; } set { x = value; } } = X; Diagnostic(ErrorCode.ERR_InitializerOnNonAutoProperty, "X").WithArguments("Pos.X").WithLocation(5, 16) ); } [Fact] public void IEquatableT_01() { var source = @"record struct A<T>; class Program { static void F<T>(System.IEquatable<T> t) { } static void M<T>() { F(new A<T>()); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( ); } [Fact] public void IEquatableT_02() { var source = @"using System; record struct A; record struct B<T>; class Program { static bool F<T>(IEquatable<T> t, T t2) { return t.Equals(t2); } static void Main() { Console.Write(F(new A(), new A())); Console.Write(F(new B<int>(), new B<int>())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "TrueTrue").VerifyDiagnostics(); } [Fact] public void IEquatableT_02_ImplicitImplementation() { var source = @"using System; record struct A { public bool Equals(A other) { System.Console.Write(""A.Equals(A) ""); return false; } } record struct B<T> { public bool Equals(B<T> other) { System.Console.Write(""B.Equals(B) ""); return true; } } class Program { static bool F<T>(IEquatable<T> t, T t2) { return t.Equals(t2); } static void Main() { Console.Write(F(new A(), new A())); Console.Write("" ""); Console.Write(F(new B<int>(), new B<int>())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "A.Equals(A) False B.Equals(B) True").VerifyDiagnostics( // (4,17): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public bool Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 17), // (12,17): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public bool Equals(B<T> other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(12, 17) ); } [Fact] public void IEquatableT_02_ExplicitImplementation() { var source = @"using System; record struct A { bool IEquatable<A>.Equals(A other) { System.Console.Write(""A.Equals(A) ""); return false; } } record struct B<T> { bool IEquatable<B<T>>.Equals(B<T> other) { System.Console.Write(""B.Equals(B) ""); return true; } } class Program { static bool F<T>(IEquatable<T> t, T t2) { return t.Equals(t2); } static void Main() { Console.Write(F(new A(), new A())); Console.Write("" ""); Console.Write(F(new B<int>(), new B<int>())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "A.Equals(A) False B.Equals(B) True").VerifyDiagnostics(); } [Fact] public void IEquatableT_03() { var source = @" record struct A<T> : System.IEquatable<A<T>>; "; 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()); } [Fact] public void IEquatableT_MissingIEquatable() { var source = @" record struct A<T>; "; var comp = CreateCompilation(source); comp.MakeTypeMissing(WellKnownType.System_IEquatable_T); comp.VerifyEmitDiagnostics( // (2,15): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record struct A<T>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record struct A<T>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(2, 15) ); 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()); } [Fact] public void RecordEquals_01() { var source = @" var a1 = new B(); var a2 = new B(); System.Console.WriteLine(a1.Equals(a2)); record struct B { public bool Equals(B other) { System.Console.WriteLine(""B.Equals(B)""); return false; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,17): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public bool Equals(B other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(8, 17) ); CompileAndVerify(comp, expectedOutput: @" B.Equals(B) False "); } [Fact] public void RecordEquals_01_NoInParameters() { var source = @" var a1 = new B(); var a2 = new B(); System.Console.WriteLine(a1.Equals(in a2)); record struct B; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,39): error CS1615: Argument 1 may not be passed with the 'in' keyword // System.Console.WriteLine(a1.Equals(in a2)); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "a2").WithArguments("1", "in").WithLocation(4, 39) ); } [Theory] [InlineData("protected")] [InlineData("private protected")] [InlineData("internal protected")] public void RecordEquals_10(string accessibility) { var source = $@" record struct A {{ { accessibility } bool Equals(A x) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; }} "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,29): error CS0666: 'A.Equals(A)': new protected member declared in struct // internal protected bool Equals(A x) Diagnostic(ErrorCode.ERR_ProtectedInStruct, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 11 + accessibility.Length), // (4,29): error CS8873: Record member 'A.Equals(A)' must be public. // internal protected bool Equals(A x) Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 11 + accessibility.Length), // (4,29): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // internal protected bool Equals(A x) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 11 + accessibility.Length) ); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("internal")] public void RecordEquals_11(string accessibility) { var source = $@" record struct A {{ { accessibility } bool Equals(A x) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; }} "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,...): error CS8873: Record member 'A.Equals(A)' must be public. // { accessibility } bool Equals(A x) Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 11 + accessibility.Length), // (4,11): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // bool Equals(A x) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 11 + accessibility.Length) ); } [Fact] public void RecordEquals_12() { var source = @" A a1 = new A(); A a2 = new A(); System.Console.Write(a1.Equals(a2)); System.Console.Write(a1.Equals((object)a2)); record struct A { public bool Equals(B other) => throw null; } class B { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "TrueTrue"); verifier.VerifyIL("A.Equals(A)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret }"); verifier.VerifyIL("A.Equals(object)", @" { // Code size 23 (0x17) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""A"" IL_0006: brfalse.s IL_0015 IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: unbox.any ""A"" IL_000f: call ""readonly bool A.Equals(A)"" IL_0014: ret IL_0015: ldc.i4.0 IL_0016: ret }"); verifier.VerifyIL("A.GetHashCode()", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret }"); var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("readonly 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); var objectEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordObjEquals>().Single(); Assert.Equal("readonly System.Boolean A.Equals(System.Object obj)", objectEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, objectEquals.DeclaredAccessibility); Assert.False(objectEquals.IsAbstract); Assert.False(objectEquals.IsVirtual); Assert.True(objectEquals.IsOverride); Assert.False(objectEquals.IsSealed); Assert.True(objectEquals.IsImplicitlyDeclared); MethodSymbol gethashCode = comp.GetMembers("A." + WellKnownMemberNames.ObjectGetHashCode).OfType<SynthesizedRecordGetHashCode>().Single(); Assert.Equal("readonly System.Int32 A.GetHashCode()", gethashCode.ToTestDisplayString()); Assert.Equal(Accessibility.Public, gethashCode.DeclaredAccessibility); Assert.False(gethashCode.IsStatic); Assert.False(gethashCode.IsAbstract); Assert.False(gethashCode.IsVirtual); Assert.True(gethashCode.IsOverride); Assert.False(gethashCode.IsSealed); Assert.True(gethashCode.IsImplicitlyDeclared); } [Fact] public void RecordEquals_13() { var source = @" record struct A { public int Equals(A other) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,16): error CS8874: Record member 'A.Equals(A)' must return 'bool'. // public int Equals(A other) Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "Equals").WithArguments("A.Equals(A)", "bool").WithLocation(4, 16), // (4,16): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public int Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 16) ); } [Fact] public void RecordEquals_14() { var source = @" record struct A { public bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; } "; var comp = CreateCompilation(source); comp.MakeTypeMissing(SpecialType.System_Boolean); comp.VerifyEmitDiagnostics( // (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record struct A { public 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 struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record struct A { public bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; }").WithArguments("System.Boolean").WithLocation(2, 1), // (2,15): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 15), // (4,12): error CS0518: Predefined type 'System.Boolean' is not defined or imported // public bool Equals(A other) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "bool").WithArguments("System.Boolean").WithLocation(4, 12), // (4,17): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public bool Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 17) ); } [Fact] public void RecordEquals_19() { var source = @" record struct A { public static bool Equals(A x) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,15): error CS0736: 'A' does not implement interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement an interface member because it is static. // record struct 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 RecordEquals_RecordEqualsInValueType() { var src = @" public record struct A; namespace System { public class Object { public virtual bool Equals(object x) => throw null; public virtual int GetHashCode() => throw null; public virtual string ToString() => throw null; } public class Exception { } public class ValueType { public bool Equals(A x) => throw null; } public class Attribute { } public class String { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { } } namespace System.Collections.Generic { public abstract class EqualityComparer<T> { public static EqualityComparer<T> Default => throw null; public abstract int GetHashCode(T t); } } 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(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1) ); var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("readonly System.Boolean A.Equals(A other)", recordEquals.ToTestDisplayString()); } [Fact] public void RecordEquals_FourFields() { var source = @" A a1 = new A(1, ""hello""); System.Console.Write(a1.Equals(a1)); System.Console.Write(a1.Equals((object)a1)); System.Console.Write("" - ""); A a2 = new A(1, ""hello"") { fieldI = 100 }; System.Console.Write(a1.Equals(a2)); System.Console.Write(a1.Equals((object)a2)); System.Console.Write(a2.Equals(a1)); System.Console.Write(a2.Equals((object)a1)); System.Console.Write("" - ""); A a3 = new A(1, ""world""); System.Console.Write(a1.Equals(a3)); System.Console.Write(a1.Equals((object)a3)); System.Console.Write(a3.Equals(a1)); System.Console.Write(a3.Equals((object)a1)); record struct A(int I, string S) { public int fieldI = 42; public string fieldS = ""hello""; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "TrueTrue - FalseFalseFalseFalse - FalseFalseFalseFalse"); verifier.VerifyIL("A.Equals(A)", @" { // Code size 97 (0x61) .maxstack 3 IL_0000: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0005: ldarg.0 IL_0006: ldfld ""int A.<I>k__BackingField"" IL_000b: ldarg.1 IL_000c: ldfld ""int A.<I>k__BackingField"" IL_0011: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0016: brfalse.s IL_005f IL_0018: call ""System.Collections.Generic.EqualityComparer<string> System.Collections.Generic.EqualityComparer<string>.Default.get"" IL_001d: ldarg.0 IL_001e: ldfld ""string A.<S>k__BackingField"" IL_0023: ldarg.1 IL_0024: ldfld ""string A.<S>k__BackingField"" IL_0029: callvirt ""bool System.Collections.Generic.EqualityComparer<string>.Equals(string, string)"" IL_002e: brfalse.s IL_005f IL_0030: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0035: ldarg.0 IL_0036: ldfld ""int A.fieldI"" IL_003b: ldarg.1 IL_003c: ldfld ""int A.fieldI"" IL_0041: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0046: brfalse.s IL_005f IL_0048: call ""System.Collections.Generic.EqualityComparer<string> System.Collections.Generic.EqualityComparer<string>.Default.get"" IL_004d: ldarg.0 IL_004e: ldfld ""string A.fieldS"" IL_0053: ldarg.1 IL_0054: ldfld ""string A.fieldS"" IL_0059: callvirt ""bool System.Collections.Generic.EqualityComparer<string>.Equals(string, string)"" IL_005e: ret IL_005f: ldc.i4.0 IL_0060: ret }"); verifier.VerifyIL("A.Equals(object)", @" { // Code size 23 (0x17) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""A"" IL_0006: brfalse.s IL_0015 IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: unbox.any ""A"" IL_000f: call ""readonly bool A.Equals(A)"" IL_0014: ret IL_0015: ldc.i4.0 IL_0016: ret }"); verifier.VerifyIL("A.GetHashCode()", @" { // Code size 86 (0x56) .maxstack 3 IL_0000: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0005: ldarg.0 IL_0006: ldfld ""int A.<I>k__BackingField"" IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<int>.GetHashCode(int)"" IL_0010: ldc.i4 0xa5555529 IL_0015: mul IL_0016: call ""System.Collections.Generic.EqualityComparer<string> System.Collections.Generic.EqualityComparer<string>.Default.get"" IL_001b: ldarg.0 IL_001c: ldfld ""string A.<S>k__BackingField"" IL_0021: callvirt ""int System.Collections.Generic.EqualityComparer<string>.GetHashCode(string)"" IL_0026: add IL_0027: ldc.i4 0xa5555529 IL_002c: mul IL_002d: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0032: ldarg.0 IL_0033: ldfld ""int A.fieldI"" IL_0038: callvirt ""int System.Collections.Generic.EqualityComparer<int>.GetHashCode(int)"" IL_003d: add IL_003e: ldc.i4 0xa5555529 IL_0043: mul IL_0044: call ""System.Collections.Generic.EqualityComparer<string> System.Collections.Generic.EqualityComparer<string>.Default.get"" IL_0049: ldarg.0 IL_004a: ldfld ""string A.fieldS"" IL_004f: callvirt ""int System.Collections.Generic.EqualityComparer<string>.GetHashCode(string)"" IL_0054: add IL_0055: ret }"); } [Fact] public void RecordEquals_StaticField() { var source = @" record struct A { public static int field = 42; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp); verifier.VerifyIL("A.Equals(A)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret }"); verifier.VerifyIL("A.GetHashCode()", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret }"); } [Fact] public void RecordEquals_GeneratedAsReadOnly() { var src = @" record struct A(int I, string S); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.True(recordEquals.IsDeclaredReadOnly); } [Fact] public void ObjectEquals_06() { var source = @" record struct A { public static new bool Equals(object obj) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,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(4, 28) ); } [Fact] public void ObjectEquals_UserDefined() { var source = @" record struct A { public override bool Equals(object obj) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,26): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types // public override bool Equals(object obj) => throw null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(4, 26) ); } [Fact] public void ObjectEquals_GeneratedAsReadOnly() { var src = @" record struct A(int I, string S); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var objectEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordObjEquals>().Single(); Assert.True(objectEquals.IsDeclaredReadOnly); } [Fact] public void GetHashCode_UserDefined() { var source = @" System.Console.Write(new A().GetHashCode()); record struct A { public override int GetHashCode() => 42; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "42"); } [Fact] public void GetHashCode_GetHashCodeInValueType() { var src = @" public record struct A; namespace System { public class Object { public virtual bool Equals(object x) => throw null; public virtual string ToString() => throw null; } public class Exception { } public class ValueType { public virtual int GetHashCode() => throw null; } public class Attribute { } public class String { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { } } namespace System.Collections.Generic { public abstract class EqualityComparer<T> { public static EqualityComparer<T> Default => throw null; public abstract int GetHashCode(T t); } } 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(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1), // (2,22): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'. // public record struct A; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "A").WithArguments("A.GetHashCode()").WithLocation(2, 22) ); } [Fact] public void GetHashCode_MissingEqualityComparer_EmptyRecord() { var src = @" public record struct A; "; var comp = CreateCompilation(src); comp.MakeTypeMissing(WellKnownType.System_Collections_Generic_EqualityComparer_T); comp.VerifyEmitDiagnostics(); } [Fact] public void GetHashCode_MissingEqualityComparer_NonEmptyRecord() { var src = @" public record struct A(int I); "; var comp = CreateCompilation(src); comp.MakeTypeMissing(WellKnownType.System_Collections_Generic_EqualityComparer_T); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.GetHashCode' // public record struct A(int I); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "public record struct A(int I);").WithArguments("System.Collections.Generic.EqualityComparer`1", "GetHashCode").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.get_Default' // public record struct A(int I); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "public record struct A(int I);").WithArguments("System.Collections.Generic.EqualityComparer`1", "get_Default").WithLocation(2, 1) ); } [Fact] public void GetHashCode_GeneratedAsReadOnly() { var src = @" record struct A(int I, string S); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var method = comp.GetMember<SynthesizedRecordGetHashCode>("A.GetHashCode"); Assert.True(method.IsDeclaredReadOnly); } [Fact] public void GetHashCodeIsDefinedButEqualsIsNot() { var src = @" public record struct C { public object Data; public override int GetHashCode() { return 0; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void EqualsIsDefinedButGetHashCodeIsNot() { var src = @" public record struct 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] public void EqualityOperators_01() { var source = @" record struct A(int X) { public bool Equals(ref A other) => throw null; static void Main() { Test(default, default); Test(default, 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); } static void Test(A a1, A a2) { System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == a2, a2 == a1, a1 != a2, a2 != a1); } } "; var verifier = CompileAndVerify(source, expectedOutput: @" True True False False True True False False 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 9 (0x9) .maxstack 2 IL_0000: ldarga.s V_0 IL_0002: ldarg.1 IL_0003: call ""readonly bool A.Equals(A)"" IL_0008: 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 struct 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 struct 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 struct 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 struct 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 struct A { public static bool Equals(A other) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,15): error CS0736: 'A' does not implement interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement an interface member because it is static. // record struct 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 other) 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 other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24) ); } [Theory] [CombinatorialData] public void EqualityOperators_09(bool useImageReference) { var source1 = @" public record struct A(int X); "; var comp1 = CreateCompilation(source1); var source2 = @" class Program { static void Main() { Test(default, default); Test(default, 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 True True False False True True False False False False True True ").VerifyDiagnostics(); } [Fact] public void GetSimpleNonTypeMembers_DirectApiCheck() { var src = @" public record struct 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] public void ToString_NestedRecord() { var src = @" var c1 = new Outer.C1(42); System.Console.Write(c1.ToString()); public class Outer { public record struct C1(int I1); } "; var compDebug = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); var compRelease = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(compDebug, expectedOutput: "C1 { I1 = 42 }"); compDebug.VerifyEmitDiagnostics(); CompileAndVerify(compRelease, expectedOutput: "C1 { I1 = 42 }"); compRelease.VerifyEmitDiagnostics(); } [Fact] public void ToString_TopLevelRecord_Empty() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record struct C1; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); var v = 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); 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: call ""readonly 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_MissingStringBuilder() { var src = @" record struct 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 struct C1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "record struct C1;").WithArguments("System.Text.StringBuilder").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder..ctor' // record struct C1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record struct C1;").WithArguments("System.Text.StringBuilder", ".ctor").WithLocation(2, 1), // (2,15): error CS0518: Predefined type 'System.Text.StringBuilder' is not defined or imported // record struct C1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "C1").WithArguments("System.Text.StringBuilder").WithLocation(2, 15) ); } [Fact] public void ToString_TopLevelRecord_MissingStringBuilderCtor() { var src = @" record struct 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 struct C1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record struct C1;").WithArguments("System.Text.StringBuilder", ".ctor").WithLocation(2, 1) ); } [Fact] public void ToString_TopLevelRecord_MissingStringBuilderAppendString() { var src = @" record struct 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 struct C1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record struct C1;").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1) ); } [Fact] public void ToString_TopLevelRecord_OneProperty_MissingStringBuilderAppendString() { var src = @" record struct 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 struct C1(int P); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record struct C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record struct C1(int P); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record struct C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1) ); } [Fact] public void ToString_RecordWithIndexer() { var src = @" var c1 = new C1(42); System.Console.Write(c1.ToString()); record struct C1(int I1) { private int field = 44; public int this[int i] => 0; public int PropertyWithoutGetter { set { } } public int P2 { get => 43; } public event System.Action a = null; private int field1 = 100; internal int field2 = 100; private int Property1 { get; set; } = 100; internal int Property2 { get; set; } = 100; } "; var comp = CreateCompilation(src); CompileAndVerify(comp, expectedOutput: "C1 { I1 = 42, P2 = 43 }"); comp.VerifyEmitDiagnostics( // (7,17): warning CS0414: The field 'C1.field' is assigned but its value is never used // private int field = 44; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field").WithArguments("C1.field").WithLocation(7, 17), // (11,32): warning CS0414: The field 'C1.a' is assigned but its value is never used // public event System.Action a = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "a").WithArguments("C1.a").WithLocation(11, 32), // (13,17): warning CS0414: The field 'C1.field1' is assigned but its value is never used // private int field1 = 100; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field1").WithArguments("C1.field1").WithLocation(13, 17) ); } [Fact] public void ToString_PrivateGetter() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record struct C1 { public int P1 { private get => 43; set => throw null; } } "; var comp = CreateCompilation(src); CompileAndVerify(comp, expectedOutput: "C1 { P1 = 43 }"); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_TopLevelRecord_OneField_ValueType() { var src = @" var c1 = new C1() { field = 42 }; System.Console.Write(c1.ToString()); record struct C1 { public int field; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = 42 }"); 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); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 38 (0x26) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldstr ""field = "" 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 ""int C1.field"" IL_0013: constrained. ""int"" 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] public void ToString_TopLevelRecord_OneField_ConstrainedValueType() { var src = @" var c1 = new C1<int>() { field = 42 }; System.Console.Write(c1.ToString()); record struct C1<T> where T : struct { public T field; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = 42 }"); v.VerifyIL("C1<T>." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 41 (0x29) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.1 IL_0001: ldstr ""field = "" IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_000b: pop IL_000c: ldarg.1 IL_000d: ldarg.0 IL_000e: ldfld ""T C1<T>.field"" IL_0013: stloc.0 IL_0014: ldloca.s V_0 IL_0016: constrained. ""T"" IL_001c: callvirt ""string object.ToString()"" IL_0021: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0026: pop IL_0027: ldc.i4.1 IL_0028: ret } "); } [Fact] public void ToString_TopLevelRecord_OneField_ReferenceType() { var src = @" var c1 = new C1() { field = ""hello"" }; System.Console.Write(c1.ToString()); record struct C1 { public string field; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = hello }"); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 27 (0x1b) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldstr ""field = "" IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_000b: pop IL_000c: ldarg.1 IL_000d: ldarg.0 IL_000e: ldfld ""string C1.field"" IL_0013: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_0018: pop IL_0019: ldc.i4.1 IL_001a: ret } "); } [Fact] public void ToString_TopLevelRecord_TwoFields_ReferenceType() { var src = @" var c1 = new C1(42) { field1 = ""hi"", field2 = null }; System.Console.Write(c1.ToString()); record struct C1(int I) { public string field1 = null; public string field2 = null; private string field3 = null; internal string field4 = null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (10,20): warning CS0414: The field 'C1.field3' is assigned but its value is never used // private string field3 = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field3").WithArguments("C1.field3").WithLocation(10, 20) ); var v = CompileAndVerify(comp, expectedOutput: "C1 { I = 42, field1 = hi, field2 = }"); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 91 (0x5b) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldstr ""I = "" IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_000b: pop IL_000c: ldarg.1 IL_000d: ldarg.0 IL_000e: call ""readonly int C1.I.get"" IL_0013: stloc.0 IL_0014: ldloca.s V_0 IL_0016: constrained. ""int"" IL_001c: callvirt ""string object.ToString()"" IL_0021: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0026: pop IL_0027: ldarg.1 IL_0028: ldstr "", field1 = "" IL_002d: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0032: pop IL_0033: ldarg.1 IL_0034: ldarg.0 IL_0035: ldfld ""string C1.field1"" IL_003a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_003f: pop IL_0040: ldarg.1 IL_0041: ldstr "", field2 = "" IL_0046: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_004b: pop IL_004c: ldarg.1 IL_004d: ldarg.0 IL_004e: ldfld ""string C1.field2"" IL_0053: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_0058: pop IL_0059: ldc.i4.1 IL_005a: ret } "); } [Fact] public void ToString_TopLevelRecord_Readonly() { var src = @" var c1 = new C1(42); System.Console.Write(c1.ToString()); readonly record struct C1(int I); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { I = 42 }", verify: Verification.Skipped /* init-only */); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 41 (0x29) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldstr ""I = "" IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_000b: pop IL_000c: ldarg.1 IL_000d: ldarg.0 IL_000e: call ""int C1.I.get"" IL_0013: stloc.0 IL_0014: ldloca.s V_0 IL_0016: constrained. ""int"" IL_001c: callvirt ""string object.ToString()"" IL_0021: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0026: pop IL_0027: ldc.i4.1 IL_0028: 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: call ""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_UserDefinedToString() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record struct C1 { public override string ToString() => ""RAN""; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal("readonly System.Boolean C1." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", print.ToTestDisplayString()); } [Fact] public void ToString_TopLevelRecord_UserDefinedToString_New() { var src = @" record struct C1 { public new string ToString() => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,23): error CS8869: 'C1.ToString()' does not override expected method from 'object'. // public new string ToString() => throw null; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "ToString").WithArguments("C1.ToString()").WithLocation(4, 23) ); } [Fact] public void ToString_TopLevelRecord_UserDefinedToString_Sealed() { var src = @" record struct C1 { public sealed override string ToString() => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,35): error CS0106: The modifier 'sealed' is not valid for this item // public sealed override string ToString() => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "ToString").WithArguments("sealed").WithLocation(4, 35) ); } [Fact] public void ToString_UserDefinedPrintMembers_WithNullableStringBuilder() { var src = @" #nullable enable record struct C1 { private bool PrintMembers(System.Text.StringBuilder? builder) => throw null!; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_UserDefinedPrintMembers_ErrorReturnType() { var src = @" record struct C1 { private Error PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,13): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?) // private Error PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(4, 13) ); } [Fact] public void ToString_UserDefinedPrintMembers_WrongReturnType() { var src = @" record struct C1 { private int PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,17): error CS8874: Record member 'C1.PrintMembers(StringBuilder)' must return 'bool'. // private int PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)", "bool").WithLocation(4, 17) ); } [Fact] public void ToString_UserDefinedPrintMembers() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); System.Console.Write("" - ""); c1.M(); record struct C1 { private bool PrintMembers(System.Text.StringBuilder builder) { builder.Append(""RAN""); return true; } public void M() { var builder = new System.Text.StringBuilder(); if (PrintMembers(builder)) { System.Console.Write(builder.ToString()); } } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { RAN } - RAN"); } [Fact] public void ToString_CallingSynthesizedPrintMembers() { var src = @" var c1 = new C1(1, 2, 3); System.Console.Write(c1.ToString()); System.Console.Write("" - ""); c1.M(); record struct C1(int I, int I2, int I3) { public void M() { var builder = new System.Text.StringBuilder(); if (PrintMembers(builder)) { System.Console.Write(builder.ToString()); } } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { I = 1, I2 = 2, I3 = 3 } - I = 1, I2 = 2, I3 = 3"); } [Fact] public void ToString_UserDefinedPrintMembers_WrongAccessibility() { var src = @" var c = new C1(); System.Console.Write(c.ToString()); record struct C1 { internal bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (7,19): error CS8879: Record member 'C1.PrintMembers(StringBuilder)' must be private. // internal bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_NonPrivateAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(7, 19) ); } [Fact] public void ToString_UserDefinedPrintMembers_Static() { var src = @" record struct C1 { static private bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,25): error CS8877: Record member 'C1.PrintMembers(StringBuilder)' may not be static. // static private bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 25) ); } [Fact] public void ToString_GeneratedAsReadOnly() { var src = @" record struct A(int I, string S); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var method = comp.GetMember<SynthesizedRecordToString>("A.ToString"); Assert.True(method.IsDeclaredReadOnly); } [Fact] public void ToString_WihtNonReadOnlyGetter_GeneratedAsNonReadOnly() { var src = @" record struct A(int I, string S) { public double T => 0.1; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var method = comp.GetMember<SynthesizedRecordToString>("A.ToString"); Assert.False(method.IsDeclaredReadOnly); } [Fact] public void AmbigCtor_WithPropertyInitializer() { // Scenario causes ambiguous ctor for record class, but not record struct var src = @" record struct R(R X) { public R X { get; init; } = X; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,14): error CS0523: Struct member 'R.X' of type 'R' causes a cycle in the struct layout // public R X { get; init; } = X; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "X").WithArguments("R.X", "R").WithLocation(4, 14) ); 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()); var src2 = @" record struct R(R X); "; var comp2 = CreateCompilation(src2); comp2.VerifyEmitDiagnostics( // (2,19): error CS0523: Struct member 'R.X' of type 'R' causes a cycle in the struct layout // record struct R(R X); Diagnostic(ErrorCode.ERR_StructLayoutCycle, "X").WithArguments("R.X", "R").WithLocation(2, 19) ); } [Fact] public void GetDeclaredSymbolOnAnOutLocalInPropertyInitializer() { var src = @" record struct R(int I) { public int I { get; init; } = M(out int i); static int M(out int i) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,21): warning CS8907: Parameter 'I' is unread. Did you forget to use it to initialize the property with that name? // record struct R(int I) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "I").WithArguments("I").WithLocation(2, 21) ); 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] public void AnalyzerActions_01() { // Test RegisterSyntaxNodeAction var text1 = @" record struct A([Attr1]int X = 0) : I1 { private int M() => 3; A(string S) : this(4) => throw null; } interface I1 {} class Attr1 : 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.FireCountRecordStructDeclarationA); Assert.Equal(1, analyzer.FireCountRecordStructDeclarationACtor); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCountSimpleBaseTypeI1onA); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCountParameterListAPrimaryCtor); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCountConstructorDeclaration); Assert.Equal(1, analyzer.FireCountStringParameterList); Assert.Equal(1, analyzer.FireCountThisConstructorInitializer); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); } private class AnalyzerActions_01_Analyzer : DiagnosticAnalyzer { public int FireCount0; public int FireCountRecordStructDeclarationA; public int FireCountRecordStructDeclarationACtor; public int FireCount3; public int FireCountSimpleBaseTypeI1onA; public int FireCount5; public int FireCountParameterListAPrimaryCtor; public int FireCount7; public int FireCountConstructorDeclaration; public int FireCountStringParameterList; public int FireCountThisConstructorInitializer; 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.RegisterSyntaxNodeAction(Handle1, SyntaxKind.NumericLiteralExpression); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.EqualsValueClause); context.RegisterSyntaxNodeAction(Fail, SyntaxKind.BaseConstructorInitializer); context.RegisterSyntaxNodeAction(Handle3, SyntaxKind.ThisConstructorInitializer); context.RegisterSyntaxNodeAction(Handle4, SyntaxKind.ConstructorDeclaration); context.RegisterSyntaxNodeAction(Fail, SyntaxKind.PrimaryConstructorBaseType); context.RegisterSyntaxNodeAction(Handle6, SyntaxKind.RecordStructDeclaration); 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 "3": Interlocked.Increment(ref FireCount7); Assert.Equal("System.Int32 A.M()", context.ContainingSymbol.ToTestDisplayString()); break; case "4": Interlocked.Increment(ref FireCount12); Assert.Equal("A..ctor(System.String S)", 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 FireCount3); Assert.Equal("A..ctor([System.Int32 X = 0])", 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 ": this(4)": Interlocked.Increment(ref FireCountThisConstructorInitializer); Assert.Equal("A..ctor(System.String S)", 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 FireCountConstructorDeclaration); Assert.Equal("A..ctor(System.String S)", context.ContainingSymbol.ToTestDisplayString()); } protected void Fail(SyntaxNodeAnalysisContext context) { Assert.True(false); } protected void Handle6(SyntaxNodeAnalysisContext context) { var record = (RecordDeclarationSyntax)context.Node; Assert.Equal(SyntaxKind.RecordStructDeclaration, record.Kind()); switch (context.ContainingSymbol.ToTestDisplayString()) { case "A": Interlocked.Increment(ref FireCountRecordStructDeclarationA); break; case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCountRecordStructDeclarationACtor); 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 "Attr1": Interlocked.Increment(ref FireCount5); Assert.Equal("A..ctor([System.Int32 X = 0])", 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 FireCountSimpleBaseTypeI1onA); 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 FireCountParameterListAPrimaryCtor); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; case "(string S)": Interlocked.Increment(ref FireCountStringParameterList); Assert.Equal("A..ctor(System.String S)", 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 "(4)": Interlocked.Increment(ref FireCount11); Assert.Equal("A..ctor(System.String S)", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_02() { // Test RegisterSymbolAction var text1 = @" record struct A(int X = 0) {} record struct 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; set; }": 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() { // Test RegisterSymbolStartAction var text1 = @" readonly record struct A(int X = 0) {} readonly record struct 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() { // Test RegisterOperationAction var text1 = @" record struct A([Attr1(100)]int X = 0) : I1 {} 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.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount14); } private class AnalyzerActions_04_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount6; public int FireCount7; public int FireCount14; 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(HandleConstructorBody, OperationKind.ConstructorBody); context.RegisterOperationAction(HandleInvocation, OperationKind.Invocation); context.RegisterOperationAction(HandleLiteral, OperationKind.Literal); context.RegisterOperationAction(HandleParameterInitializer, OperationKind.ParameterInitializer); context.RegisterOperationAction(Fail, OperationKind.PropertyInitializer); context.RegisterOperationAction(Fail, OperationKind.FieldInitializer); } protected void HandleConstructorBody(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()); VerifyOperationTree((CSharpCompilation)context.Compilation, context.Operation, @""); break; default: Assert.True(false); break; } } protected void HandleInvocation(OperationAnalysisContext context) { Assert.True(false); } protected void HandleLiteral(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; default: Assert.True(false); break; } } protected void HandleParameterInitializer(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; default: Assert.True(false); break; } } protected void Fail(OperationAnalysisContext context) { Assert.True(false); } } [Fact] public void AnalyzerActions_05() { // Test RegisterOperationBlockAction var text1 = @" record struct A([Attr1(100)]int X = 0) : I1 {} interface I1 {} "; var analyzer = new AnalyzerActions_05_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); } private class AnalyzerActions_05_Analyzer : DiagnosticAnalyzer { public int FireCount1; 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; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_07() { // Test RegisterCodeBlockAction var text1 = @" record struct A([Attr1(100)]int X = 0) : I1 { int M() => 3; } 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.FireCount4); } private class AnalyzerActions_07_Analyzer : DiagnosticAnalyzer { public int FireCount1; 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 "System.Int32 A.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() { // Test RegisterCodeBlockStartAction var text1 = @" record struct A([Attr1]int X = 0) : I1 { private int M() => 3; A(string S) : this(4) => throw null; } 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.FireCount400); Assert.Equal(1, analyzer.FireCount500); Assert.Equal(1, analyzer.FireCount0); Assert.Equal(0, analyzer.FireCountRecordStructDeclarationA); Assert.Equal(0, analyzer.FireCountRecordStructDeclarationACtor); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(0, analyzer.FireCountSimpleBaseTypeI1onA); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(0, analyzer.FireCountParameterListAPrimaryCtor); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(0, analyzer.FireCountConstructorDeclaration); Assert.Equal(0, analyzer.FireCountStringParameterList); Assert.Equal(1, analyzer.FireCountThisConstructorInitializer); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); Assert.Equal(1, analyzer.FireCount1000); Assert.Equal(1, analyzer.FireCount4000); Assert.Equal(1, analyzer.FireCount5000); } private class AnalyzerActions_08_Analyzer : AnalyzerActions_01_Analyzer { public int FireCount100; public int FireCount400; public int FireCount500; public int FireCount1000; public int FireCount4000; public int FireCount5000; 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 "System.Int32 A.M()": switch (context.CodeBlock) { case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }: Interlocked.Increment(ref FireCount400); break; default: Assert.True(false); break; } break; case "A..ctor(System.String S)": switch (context.CodeBlock) { case ConstructorDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount500); break; default: Assert.True(false); break; } break; default: Assert.True(false); break; } context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.NumericLiteralExpression); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.EqualsValueClause); context.RegisterSyntaxNodeAction(Fail, SyntaxKind.BaseConstructorInitializer); context.RegisterSyntaxNodeAction(Handle3, SyntaxKind.ThisConstructorInitializer); context.RegisterSyntaxNodeAction(Handle4, SyntaxKind.ConstructorDeclaration); context.RegisterSyntaxNodeAction(Fail, SyntaxKind.PrimaryConstructorBaseType); context.RegisterSyntaxNodeAction(Handle6, SyntaxKind.RecordStructDeclaration); 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 "System.Int32 A.M()": switch (context.CodeBlock) { case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }: Interlocked.Increment(ref FireCount4000); break; default: Assert.True(false); break; } break; case "A..ctor(System.String S)": switch (context.CodeBlock) { case ConstructorDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount5000); 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] public void WithExprOnStruct_LangVersion() { var src = @" var b = new B() { X = 1 }; var b2 = b.M(); System.Console.Write(b2.X); System.Console.Write("" ""); System.Console.Write(b.X); public struct B { public int X { get; set; } public B M() /*<bind>*/{ return this with { X = 42 }; }/*</bind>*/ }"; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (13,16): error CS8773: Feature 'with on structs' is not available in C# 9.0. Please use language version 10.0 or greater. // return this with { X = 42 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "this with { X = 42 }").WithArguments("with on structs", "10.0").WithLocation(13, 16) ); comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42 1"); verifier.VerifyIL("B.M", @" { // Code size 18 (0x12) .maxstack 2 .locals init (B V_0) IL_0000: ldarg.0 IL_0001: ldobj ""B"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: ldc.i4.s 42 IL_000b: call ""void B.X.set"" IL_0010: ldloc.0 IL_0011: ret }"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var with = tree.GetRoot().DescendantNodes().OfType<WithExpressionSyntax>().Single(); var type = model.GetTypeInfo(with); Assert.Equal("B", type.Type.ToTestDisplayString()); var operation = model.GetOperation(with); VerifyOperationTree(comp, operation, @" IWithOperation (OperationKind.With, Type: B) (Syntax: 'this with { X = 42 }') Operand: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') CloneMethod: null Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: B) (Syntax: '{ X = 42 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 42') Left: IPropertyReferenceOperation: System.Int32 B.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'X') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 42') Left: IPropertyReferenceOperation: System.Int32 B.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') Next (Return) Block[B2] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExprOnStruct_ControlFlow_DuplicateInitialization() { var src = @" public struct B { public int X { get; set; } public B M() /*<bind>*/{ return this with { X = 42, X = 43 }; }/*</bind>*/ }"; var expectedDiagnostics = new[] { // (8,36): error CS1912: Duplicate initialization of member 'X' // return this with { X = 42, X = 43 }; Diagnostic(ErrorCode.ERR_MemberAlreadyInitialized, "X").WithArguments("X").WithLocation(8, 36) }; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 42') Left: IPropertyReferenceOperation: System.Int32 B.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'X = 43') Left: IPropertyReferenceOperation: System.Int32 B.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 43) (Syntax: '43') Next (Return) Block[B2] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExprOnStruct_ControlFlow_NestedInitializer() { var src = @" public struct C { public int Y { get; set; } } public struct B { public C X { get; set; } public B M() /*<bind>*/{ return this with { X = { Y = 1 } }; }/*</bind>*/ }"; var expectedDiagnostics = new[] { // (12,32): error CS1525: Invalid expression term '{' // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "{").WithArguments("{").WithLocation(12, 32), // (12,32): error CS1513: } expected // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_RbraceExpected, "{").WithLocation(12, 32), // (12,32): error CS1002: ; expected // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(12, 32), // (12,34): error CS0103: The name 'Y' does not exist in the current context // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_NameNotInContext, "Y").WithArguments("Y").WithLocation(12, 34), // (12,34): warning CS0162: Unreachable code detected // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.WRN_UnreachableCode, "Y").WithLocation(12, 34), // (12,40): error CS1002: ; expected // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(12, 40), // (12,43): error CS1597: Semicolon after method or accessor block is not valid // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(12, 43), // (14,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(14, 1) }; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsInvalid) (Syntax: 'X = ') Left: IPropertyReferenceOperation: C B.X { get; set; } (OperationKind.PropertyReference, Type: C) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Right: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Next (Return) Block[B3] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Leaving: {R1} } Block[B2] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Y = 1 ') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'Y = 1') Left: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Y') Children(0) Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExprOnStruct_ControlFlow_NonAssignmentExpression() { var src = @" public struct B { public int X { get; set; } public B M(int i, int j) /*<bind>*/{ return this with { i, j++, M2(), X = 2}; }/*</bind>*/ static int M2() => 0; }"; var expectedDiagnostics = new[] { // (8,28): error CS0747: Invalid initializer member declarator // return this with { i, j++, M2(), X = 2}; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "i").WithLocation(8, 28), // (8,31): error CS0747: Invalid initializer member declarator // return this with { i, j++, M2(), X = 2}; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "j++").WithLocation(8, 31), // (8,36): error CS0747: Invalid initializer member declarator // return this with { i, j++, M2(), X = 2}; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "M2()").WithLocation(8, 36) }; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Children(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'i') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'j++') Children(1): IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32, IsInvalid) (Syntax: 'j++') Target: IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'j') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M2()') Children(1): IInvocationOperation (System.Int32 B.M2()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M2()') Instance Receiver: null Arguments(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 2') Left: IPropertyReferenceOperation: System.Int32 B.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Return) Block[B2] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void ObjectCreationInitializer_ControlFlow_WithCoalescingExpressionForValue() { var src = @" public struct B { public string X; public void M(string hello) /*<bind>*/{ var x = new B() { X = Identity((string)null) ?? Identity(hello) }; }/*</bind>*/ T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [B x] CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new B() { X ... ty(hello) }') Value: IObjectCreationOperation (Constructor: B..ctor()) (OperationKind.ObjectCreation, Type: B) (Syntax: 'new B() { X ... ty(hello) }') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .locals {R2} { CaptureIds: [2] .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity((string)null)') Value: IInvocationOperation ( System.String B.Identity<System.String>(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity((string)null)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Identity') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '(string)null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null) (Syntax: '(string)null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') 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) Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'Identity((string)null)') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((string)null)') Leaving: {R3} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity((string)null)') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((string)null)') Next (Regular) Block[B5] Leaving: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(hello)') Value: IInvocationOperation ( System.String B.Identity<System.String>(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity(hello)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Identity') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'hello') IParameterReferenceOperation: hello (OperationKind.ParameterReference, Type: System.String) (Syntax: 'hello') 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[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'X = Identit ... tity(hello)') Left: IFieldReferenceOperation: System.String B.X (OperationKind.FieldReference, Type: System.String) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'new B() { X ... ty(hello) }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((s ... tity(hello)') Next (Regular) Block[B6] Leaving: {R2} } Block[B6] - Block Predecessors: [B5] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: B, IsImplicit) (Syntax: 'x = new B() ... ty(hello) }') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: B, IsImplicit) (Syntax: 'x = new B() ... ty(hello) }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'new B() { X ... ty(hello) }') Next (Regular) Block[B7] Leaving: {R1} } Block[B7] - Exit Predecessors: [B6] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics); } [Fact] public void WithExprOnStruct_ControlFlow_WithCoalescingExpressionForValue() { var src = @" var b = new B() { X = string.Empty }; var b2 = b.M(""hello""); System.Console.Write(b2.X); public struct B { public string X; public B M(string hello) /*<bind>*/{ return Identity(this) with { X = Identity((string)null) ?? Identity(hello) }; }/*</bind>*/ T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "hello"); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(this)') Value: IInvocationOperation ( B B.Identity<B>(B t)) (OperationKind.Invocation, Type: B) (Syntax: 'Identity(this)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Identity') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'this') IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') 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] Entering: {R2} {R3} .locals {R2} { CaptureIds: [2] .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity((string)null)') Value: IInvocationOperation ( System.String B.Identity<System.String>(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity((string)null)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Identity') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '(string)null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null) (Syntax: '(string)null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') 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) Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'Identity((string)null)') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((string)null)') Leaving: {R3} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity((string)null)') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((string)null)') Next (Regular) Block[B5] Leaving: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(hello)') Value: IInvocationOperation ( System.String B.Identity<System.String>(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity(hello)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Identity') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'hello') IParameterReferenceOperation: hello (OperationKind.ParameterReference, Type: System.String) (Syntax: 'hello') 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[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'X = Identit ... tity(hello)') Left: IFieldReferenceOperation: System.String B.X (OperationKind.FieldReference, Type: System.String) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'Identity(this)') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((s ... tity(hello)') Next (Regular) Block[B6] Leaving: {R2} } Block[B6] - Block Predecessors: [B5] Statements (0) Next (Return) Block[B7] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'Identity(this)') Leaving: {R1} } Block[B7] - Exit Predecessors: [B6] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExprOnStruct_OnParameter() { var src = @" var b = new B() { X = 1 }; var b2 = B.M(b); System.Console.Write(b2.X); public struct B { public int X { get; set; } public static B M(B b) { return b with { X = 42 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("B.M", @" { // Code size 13 (0xd) .maxstack 2 .locals init (B V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: call ""void B.X.set"" IL_000b: ldloc.0 IL_000c: ret }"); } [Fact] public void WithExprOnStruct_OnThis() { var src = @" record struct C { public int X { get; set; } C(string ignored) { _ = this with { X = 42 }; // 1 this = default; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,13): error CS0188: The 'this' object cannot be used before all of its fields have been assigned // _ = this with { X = 42 }; // 1 Diagnostic(ErrorCode.ERR_UseDefViolationThis, "this").WithArguments("this").WithLocation(8, 13) ); } [Fact] public void WithExprOnStruct_OnTStructParameter() { var src = @" var b = new B() { X = 1 }; var b2 = B.M(b); System.Console.Write(b2.X); public interface I { int X { get; set; } } public struct B : I { public int X { get; set; } public static T M<T>(T b) where T : struct, I { return b with { X = 42 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("B.M<T>(T)", @" { // Code size 19 (0x13) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: constrained. ""T"" IL_000c: callvirt ""void I.X.set"" IL_0011: ldloc.0 IL_0012: ret }"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var with = tree.GetRoot().DescendantNodes().OfType<WithExpressionSyntax>().Single(); var type = model.GetTypeInfo(with); Assert.Equal("T", type.Type.ToTestDisplayString()); } [Fact] public void WithExprOnStruct_OnRecordStructParameter() { var src = @" var b = new B(1); var b2 = B.M(b); System.Console.Write(b2.X); public record struct B(int X) { public static B M(B b) { return b with { X = 42 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("B.M", @" { // Code size 13 (0xd) .maxstack 2 .locals init (B V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: call ""void B.X.set"" IL_000b: ldloc.0 IL_000c: ret }"); } [Fact] public void WithExprOnStruct_OnRecordStructParameter_Readonly() { var src = @" var b = new B(1, 2); var b2 = B.M(b); System.Console.Write(b2.X); System.Console.Write(b2.Y); public readonly record struct B(int X, int Y) { public static B M(B b) { return b with { X = 42, Y = 43 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "4243", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("B.M", @" { // Code size 22 (0x16) .maxstack 2 .locals init (B V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: call ""void B.X.init"" IL_000b: ldloca.s V_0 IL_000d: ldc.i4.s 43 IL_000f: call ""void B.Y.init"" IL_0014: ldloc.0 IL_0015: ret }"); } [Fact] public void WithExprOnStruct_OnTuple() { var src = @" class C { static void Main() { var b = (1, 2); var b2 = M(b); System.Console.Write(b2.Item1); System.Console.Write(b2.Item2); } static (int, int) M((int, int) b) { return b with { Item1 = 42, Item2 = 43 }; } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "4243"); verifier.VerifyIL("C.M", @" { // Code size 22 (0x16) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: stfld ""int System.ValueTuple<int, int>.Item1"" IL_000b: ldloca.s V_0 IL_000d: ldc.i4.s 43 IL_000f: stfld ""int System.ValueTuple<int, int>.Item2"" IL_0014: ldloc.0 IL_0015: ret }"); } [Fact] public void WithExprOnStruct_OnTuple_WithNames() { var src = @" var b = (1, 2); var b2 = M(b); System.Console.Write(b2.Item1); System.Console.Write(b2.Item2); static (int, int) M((int X, int Y) b) { return b with { X = 42, Y = 43 }; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "4243"); verifier.VerifyIL("Program.<<Main>$>g__M|0_0(System.ValueTuple<int, int>)", @" { // Code size 22 (0x16) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: stfld ""int System.ValueTuple<int, int>.Item1"" IL_000b: ldloca.s V_0 IL_000d: ldc.i4.s 43 IL_000f: stfld ""int System.ValueTuple<int, int>.Item2"" IL_0014: ldloc.0 IL_0015: ret }"); } [Fact] public void WithExprOnStruct_OnTuple_LongTuple() { var src = @" var b = (1, 2, 3, 4, 5, 6, 7, 8); var b2 = M(b); System.Console.Write(b2.Item7); System.Console.Write(b2.Item8); static (int, int, int, int, int, int, int, int) M((int, int, int, int, int, int, int, int) b) { return b with { Item7 = 42, Item8 = 43 }; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "4243"); verifier.VerifyIL("Program.<<Main>$>g__M|0_0(System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>)", @" { // Code size 27 (0x1b) .maxstack 2 .locals init (System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>> V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: stfld ""int System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Item7"" IL_000b: ldloca.s V_0 IL_000d: ldflda ""System.ValueTuple<int> System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Rest"" IL_0012: ldc.i4.s 43 IL_0014: stfld ""int System.ValueTuple<int>.Item1"" IL_0019: ldloc.0 IL_001a: ret }"); } [Fact] public void WithExprOnStruct_OnReadonlyField() { var src = @" var b = new B { X = 1 }; // 1 public struct B { public readonly int X; public B M() { return this with { X = 42 }; // 2 } public static B M2(B b) { return b with { X = 42 }; // 3 } public B(int i) { this = default; _ = this with { X = 42 }; // 4 } }"; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,17): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // var b = new B { X = 1 }; // 1 Diagnostic(ErrorCode.ERR_AssgReadonly, "X").WithLocation(2, 17), // (9,28): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // return this with { X = 42 }; // 2 Diagnostic(ErrorCode.ERR_AssgReadonly, "X").WithLocation(9, 28), // (13,25): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // return b with { X = 42 }; // 3 Diagnostic(ErrorCode.ERR_AssgReadonly, "X").WithLocation(13, 25), // (18,25): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // _ = this with { X = 42 }; // 4 Diagnostic(ErrorCode.ERR_AssgReadonly, "X").WithLocation(18, 25) ); } [Fact] public void WithExprOnStruct_OnEnum() { var src = @" public enum E { } class C { static E M(E e) { return e with { }; } }"; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void WithExprOnStruct_OnPointer() { var src = @" unsafe class C { static int* M(int* i) { return i with { }; } }"; var comp = CreateCompilation(src, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (6,16): error CS8858: The receiver type 'int*' is not a valid record type and is not a struct type. // return i with { }; Diagnostic(ErrorCode.ERR_CannotClone, "i").WithArguments("int*").WithLocation(6, 16) ); } [Fact] public void WithExprOnStruct_OnInterface() { var src = @" public interface I { int X { get; set; } } class C { static I M(I i) { return i with { X = 42 }; } }"; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (10,16): error CS8858: The receiver type 'I' is not a valid record type and is not a value type. // return i with { X = 42 }; Diagnostic(ErrorCode.ERR_CannotClone, "i").WithArguments("I").WithLocation(10, 16) ); } [Fact] public void WithExprOnStruct_OnRefStruct() { // Similar to test RefLikeObjInitializers but with `with` expressions var text = @" using System; class Program { static S2 Test1() { S1 outer = default; S1 inner = stackalloc int[1]; // error return new S2() with { Field1 = outer, Field2 = inner }; } static S2 Test2() { S1 outer = default; S1 inner = stackalloc int[1]; S2 result; // error result = new S2() with { Field1 = inner, Field2 = outer }; return result; } static S2 Test3() { S1 outer = default; S1 inner = stackalloc int[1]; return new S2() with { Field1 = outer, Field2 = outer }; } public ref struct S1 { public static implicit operator S1(Span<int> o) => default; } public ref struct S2 { public S1 Field1; public S1 Field2; } } "; CreateCompilationWithMscorlibAndSpan(text, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics( // (12,48): error CS8352: Cannot use local 'inner' in this context because it may expose referenced variables outside of their declaration scope // return new S2() with { Field1 = outer, Field2 = inner }; Diagnostic(ErrorCode.ERR_EscapeLocal, "Field2 = inner").WithArguments("inner").WithLocation(12, 48), // (23,34): error CS8352: Cannot use local 'inner' in this context because it may expose referenced variables outside of their declaration scope // result = new S2() with { Field1 = inner, Field2 = outer }; Diagnostic(ErrorCode.ERR_EscapeLocal, "Field1 = inner").WithArguments("inner").WithLocation(23, 34) ); } [Fact] public void WithExprOnStruct_OnRefStruct_ReceiverMayWrap() { // Similar to test LocalWithNoInitializerEscape but wrapping method is used as receiver for `with` expression var text = @" using System; class Program { static void Main() { S1 sp; Span<int> local = stackalloc int[1]; sp = MayWrap(ref local) with { }; // 1, 2 } static S1 MayWrap(ref Span<int> arg) { return default; } ref struct S1 { public ref int this[int i] => throw null; } } "; CreateCompilationWithMscorlibAndSpan(text, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics( // (9,26): error CS8352: Cannot use local 'local' in this context because it may expose referenced variables outside of their declaration scope // sp = MayWrap(ref local) with { }; // 1, 2 Diagnostic(ErrorCode.ERR_EscapeLocal, "local").WithArguments("local").WithLocation(9, 26), // (9,14): error CS8347: Cannot use a result of 'Program.MayWrap(ref Span<int>)' in this context because it may expose variables referenced by parameter 'arg' outside of their declaration scope // sp = MayWrap(ref local) with { }; // 1, 2 Diagnostic(ErrorCode.ERR_EscapeCall, "MayWrap(ref local)").WithArguments("Program.MayWrap(ref System.Span<int>)", "arg").WithLocation(9, 14) ); } [Fact] public void WithExprOnStruct_OnRefStruct_ReceiverMayWrap_02() { var text = @" using System; class Program { static void Main() { Span<int> local = stackalloc int[1]; S1 sp = MayWrap(ref local) with { }; } static S1 MayWrap(ref Span<int> arg) { return default; } ref struct S1 { public ref int this[int i] => throw null; } } "; CreateCompilationWithMscorlibAndSpan(text, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics(); } [Fact] public void WithExpr_NullableAnalysis_01() { var src = @" #nullable enable record struct 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 struct 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 struct 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, WorkItem(44763, "https://github.com/dotnet/roslyn/issues/44763")] public void WithExpr_NullableAnalysis_05() { var src = @" #nullable enable record struct 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 struct 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] public void WithExprAssignToRef1() { var src = @" using System; record struct 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 59 (0x3b) .maxstack 2 .locals init (C V_0, //c C V_1) IL_0000: ldloca.s V_1 IL_0002: ldc.i4.0 IL_0003: call ""C..ctor(int)"" IL_0008: ldloca.s V_1 IL_000a: call ""ref int C.X.get"" IL_000f: ldc.i4.5 IL_0010: stind.i4 IL_0011: ldloc.1 IL_0012: stloc.0 IL_0013: ldloca.s V_0 IL_0015: call ""ref int C.X.get"" IL_001a: ldind.i4 IL_001b: call ""void System.Console.WriteLine(int)"" IL_0020: ldloc.0 IL_0021: stloc.1 IL_0022: ldloca.s V_1 IL_0024: call ""ref int C.X.get"" IL_0029: ldc.i4.1 IL_002a: stind.i4 IL_002b: ldloc.1 IL_002c: stloc.0 IL_002d: ldloca.s V_0 IL_002f: call ""ref int C.X.get"" IL_0034: ldind.i4 IL_0035: call ""void System.Console.WriteLine(int)"" IL_003a: ret }"); } [Fact] public void WithExpressionSameLHS() { var comp = CreateCompilation(@" record struct 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_AnonymousType_ChangeAllProperties() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = Identity(a) with { A = Identity(30), B = Identity(40) }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) { System.Console.Write($""Identity({t}) ""); return t; } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (9,17): error CS8773: Feature 'with on anonymous types' is not available in C# 9.0. Please use language version 10.0 or greater. // var b = Identity(a) with { A = Identity(30), B = Identity(40) }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Identity(a) with { A = Identity(30), B = Identity(40) }").WithArguments("with on anonymous types", "10.0").WithLocation(9, 17) ); comp = CreateCompilation(src, parseOptions: TestOptions.Regular10); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "Identity({ A = 10, B = 20 }) Identity(30) Identity(40) { A = 30, B = 40 }"); verifier.VerifyIL("C.M", @" { // Code size 42 (0x2a) .maxstack 2 .locals init (int V_0) IL_0000: ldc.i4.s 10 IL_0002: ldc.i4.s 20 IL_0004: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0009: call ""<anonymous type: int A, int B> C.Identity<<anonymous type: int A, int B>>(<anonymous type: int A, int B>)"" IL_000e: pop IL_000f: ldc.i4.s 30 IL_0011: call ""int C.Identity<int>(int)"" IL_0016: ldc.i4.s 40 IL_0018: call ""int C.Identity<int>(int)"" IL_001d: stloc.0 IL_001e: ldloc.0 IL_001f: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0024: call ""void System.Console.Write(object)"" IL_0029: ret } "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [2] [3] Block[B2] - Block Predecessors: [B1] Statements (4) IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.Identity<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (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) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(30)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') 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) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(40)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(40)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '40') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 40) (Syntax: '40') 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: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... ntity(40) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... ntity(40) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a) ... ntity(40) }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B3] Leaving: {R3} } Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') 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[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeAllProperties_ReverseOrder() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = Identity(a) with { B = Identity(40), A = Identity(30) }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) { System.Console.Write($""Identity({t}) ""); return t; } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "Identity({ A = 10, B = 20 }) Identity(40) Identity(30) { A = 30, B = 40 }"); verifier.VerifyIL("C.M", @" { // Code size 42 (0x2a) .maxstack 2 .locals init (int V_0) IL_0000: ldc.i4.s 10 IL_0002: ldc.i4.s 20 IL_0004: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0009: call ""<anonymous type: int A, int B> C.Identity<<anonymous type: int A, int B>>(<anonymous type: int A, int B>)"" IL_000e: pop IL_000f: ldc.i4.s 40 IL_0011: call ""int C.Identity<int>(int)"" IL_0016: stloc.0 IL_0017: ldc.i4.s 30 IL_0019: call ""int C.Identity<int>(int)"" IL_001e: ldloc.0 IL_001f: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0024: call ""void System.Console.Write(object)"" IL_0029: ret } "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [2] [3] Block[B2] - Block Predecessors: [B1] Statements (4) IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.Identity<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (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) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(40)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(40)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '40') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 40) (Syntax: '40') 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) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(30)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') 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: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... ntity(30) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... ntity(30) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a) ... ntity(30) }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B3] Leaving: {R3} } Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') 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[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeNoProperty() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = M2(a) with { }; System.Console.Write(b); }/*</bind>*/ static T M2<T>(T t) { System.Console.Write(""M2 ""); return t; } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "M2 { A = 10, B = 20 }"); verifier.VerifyIL("C.M", @" { // Code size 38 (0x26) .maxstack 2 .locals init (<>f__AnonymousType0<int, int> V_0) IL_0000: ldc.i4.s 10 IL_0002: ldc.i4.s 20 IL_0004: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0009: call ""<anonymous type: int A, int B> C.M2<<anonymous type: int A, int B>>(<anonymous type: int A, int B>)"" IL_000e: stloc.0 IL_000f: ldloc.0 IL_0010: callvirt ""int <>f__AnonymousType0<int, int>.A.get"" IL_0015: ldloc.0 IL_0016: callvirt ""int <>f__AnonymousType0<int, int>.B.get"" IL_001b: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0020: call ""void System.Console.Write(object)"" IL_0025: ret } "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [3] [4] .locals {R4} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2(a)') Value: IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.M2<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'M2(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (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) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2(a) with { }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a)') IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2(a) with { }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a)') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = M2(a) with { }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = M2(a) with { }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'M2(a) with { }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a) with { }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a) with { }') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a)') Next (Regular) Block[B4] Leaving: {R3} } Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') 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[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeOneProperty() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = a with { B = Identity(30) }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "{ A = 10, B = 30 }"); verifier.VerifyIL("C.M", @" { // Code size 34 (0x22) .maxstack 2 .locals init (int V_0) IL_0000: ldc.i4.s 10 IL_0002: ldc.i4.s 20 IL_0004: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0009: ldc.i4.s 30 IL_000b: call ""int C.Identity<int>(int)"" IL_0010: stloc.0 IL_0011: callvirt ""int <>f__AnonymousType0<int, int>.A.get"" IL_0016: ldloc.0 IL_0017: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_001c: call ""void System.Console.Write(object)"" IL_0021: ret } "); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var withExpr = tree.GetRoot().DescendantNodes().OfType<WithExpressionSyntax>().Single(); var operation = model.GetOperation(withExpr); VerifyOperationTree(comp, operation, @" IWithOperation (OperationKind.With, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a with { B ... ntity(30) }') Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') CloneMethod: null Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: '{ B = Identity(30) }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'B = Identity(30)') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'B') Right: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') 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 expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [3] [4] .locals {R4} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(30)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') 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) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = a with ... ntity(30) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = a with ... ntity(30) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a with { B ... ntity(30) }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R3} } Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') 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[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeOneProperty_WithMethodCallForTarget() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = Identity(a) with { B = 30 }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "{ A = 10, B = 30 }"); verifier.VerifyIL("C.M", @" { // Code size 34 (0x22) .maxstack 2 .locals init (int V_0) IL_0000: ldc.i4.s 10 IL_0002: ldc.i4.s 20 IL_0004: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0009: call ""<anonymous type: int A, int B> C.Identity<<anonymous type: int A, int B>>(<anonymous type: int A, int B>)"" IL_000e: ldc.i4.s 30 IL_0010: stloc.0 IL_0011: callvirt ""int <>f__AnonymousType0<int, int>.A.get"" IL_0016: ldloc.0 IL_0017: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_001c: call ""void System.Console.Write(object)"" IL_0021: ret } "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [3] [4] .locals {R4} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a)') Value: IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.Identity<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (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) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '30') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... { B = 30 }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... { B = 30 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a) ... { B = 30 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B4] Leaving: {R3} } Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') 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[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeOneProperty_WithCoalescingExpressionForTarget() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = (Identity(a) ?? Identity2(a)) with { B = 30 }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) => t; static T Identity2<T>(T t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "{ A = 10, B = 30 }"); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} {R5} } .locals {R3} { CaptureIds: [4] [5] .locals {R4} { CaptureIds: [2] .locals {R5} { CaptureIds: [3] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a)') Value: IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.Identity<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (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) Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'Identity(a)') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Leaving: {R5} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a)') Value: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B5] Leaving: {R5} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity2(a)') Value: IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.Identity2<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity2(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (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) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (2) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '30') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... dentity2(a)') Next (Regular) Block[B6] Leaving: {R4} } Block[B6] - Block Predecessors: [B5] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = (Identi ... { B = 30 }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = (Identi ... { B = 30 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: '(Identity(a ... { B = 30 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... dentity2(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... dentity2(a)') Next (Regular) Block[B7] Leaving: {R3} } Block[B7] - Block Predecessors: [B6] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') 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[B8] Leaving: {R1} } Block[B8] - Exit Predecessors: [B7] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeOneProperty_WithCoalescingExpressionForValue() { var src = @" C.M(""hello"", ""world""); public class C { public static void M(string hello, string world) /*<bind>*/{ var x = new { A = hello, B = string.Empty }; var y = x with { B = Identity(null) ?? Identity2(world) }; System.Console.Write(y); }/*</bind>*/ static string Identity(string t) => t; static string Identity2(string t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "{ A = hello, B = world }"); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.String A, System.String B> x] [<anonymous type: System.String A, System.String B> y] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'hello') Value: IParameterReferenceOperation: hello (OperationKind.ParameterReference, Type: System.String) (Syntax: 'hello') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'string.Empty') Value: IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String) (Syntax: 'string.Empty') Instance Receiver: null ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x = new { A ... ing.Empty }') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x = new { A ... ing.Empty }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.String A, System.String B>) (Syntax: 'new { A = h ... ing.Empty }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'A = hello') Left: IPropertyReferenceOperation: System.String <anonymous type: System.String A, System.String B>.A { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'new { A = h ... ing.Empty }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'hello') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'B = string.Empty') Left: IPropertyReferenceOperation: System.String <anonymous type: System.String A, System.String B>.B { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'new { A = h ... ing.Empty }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'string.Empty') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [3] [5] .locals {R4} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: <anonymous type: System.String A, System.String B>) (Syntax: 'x') Next (Regular) Block[B3] Entering: {R5} .locals {R5} { CaptureIds: [4] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(null)') Value: IInvocationOperation (System.String C.Identity(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity(null)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') 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) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'Identity(null)') Operand: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity(null)') Leaving: {R5} Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(null)') Value: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity(null)') Next (Regular) Block[B6] Leaving: {R5} } Block[B5] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity2(world)') Value: IInvocationOperation (System.String C.Identity2(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity2(world)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'world') IParameterReferenceOperation: world (OperationKind.ParameterReference, Type: System.String) (Syntax: 'world') 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[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Value: IPropertyReferenceOperation: System.String <anonymous type: System.String A, System.String B>.A { get; } (OperationKind.PropertyReference, Type: System.String, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x') Next (Regular) Block[B7] Leaving: {R4} } Block[B7] - Block Predecessors: [B6] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'y = x with ... y2(world) }') Left: ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'y = x with ... y2(world) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.String A, System.String B>) (Syntax: 'x with { B ... y2(world) }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Left: IPropertyReferenceOperation: System.String <anonymous type: System.String A, System.String B>.A { get; } (OperationKind.PropertyReference, Type: System.String, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Left: IPropertyReferenceOperation: System.String <anonymous type: System.String A, System.String B>.B { get; } (OperationKind.PropertyReference, Type: System.String, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x') Next (Regular) Block[B8] Leaving: {R3} } Block[B8] - Block Predecessors: [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(y);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(y)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'y') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: <anonymous type: System.String A, System.String B>) (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[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ErrorMember() { var src = @" public class C { public static void M() /*<bind>*/{ var a = new { A = 10 }; var b = a with { Error = Identity(20) }; }/*</bind>*/ static T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); var expectedDiagnostics = new[] { // (7,26): error CS0117: '<anonymous type: int A>' does not contain a definition for 'Error' // var b = a with { Error = Identity(20) }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Error").WithArguments("<anonymous type: int A>", "Error").WithLocation(7, 26) }; comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> a] [<anonymous type: System.Int32 A> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [2] .locals {R4} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'a') IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(20)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '20') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') 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) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'a with { Er ... ntity(20) }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { Er ... ntity(20) }') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ntity(20) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ntity(20) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>, IsInvalid) (Syntax: 'a with { Er ... ntity(20) }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { Er ... ntity(20) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { Er ... ntity(20) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { Er ... ntity(20) }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R3} {R1} } } Block[B4] - Exit Predecessors: [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ToString() { var src = @" public class C { public static void M() /*<bind>*/{ var a = new { A = 10 }; var b = a with { ToString = Identity(20) }; }/*</bind>*/ static T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); var expectedDiagnostics = new[] { // (7,26): error CS1913: Member 'ToString' cannot be initialized. It is not a field or property. // var b = a with { ToString = Identity(20) }; Diagnostic(ErrorCode.ERR_MemberCannotBeInitialized, "ToString").WithArguments("ToString").WithLocation(7, 26) }; comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> a] [<anonymous type: System.Int32 A> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [2] .locals {R4} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'a') IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(20)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '20') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') 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) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'a with { To ... ntity(20) }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { To ... ntity(20) }') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ntity(20) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ntity(20) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>, IsInvalid) (Syntax: 'a with { To ... ntity(20) }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { To ... ntity(20) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { To ... ntity(20) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { To ... ntity(20) }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R3} {R1} } } Block[B4] - Exit Predecessors: [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_NestedInitializer() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var nested = new { A = 10 }; var a = new { Nested = nested }; var b = a with { Nested = { A = 20 } }; System.Console.Write(b); }/*</bind>*/ }"; var expectedDiagnostics = new[] { // (10,35): error CS1525: Invalid expression term '{' // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "{").WithArguments("{").WithLocation(10, 35), // (10,35): error CS1513: } expected // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_RbraceExpected, "{").WithLocation(10, 35), // (10,35): error CS1002: ; expected // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(10, 35), // (10,37): error CS0103: The name 'A' does not exist in the current context // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_NameNotInContext, "A").WithArguments("A").WithLocation(10, 37), // (10,44): error CS1002: ; expected // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(10, 44), // (10,47): error CS1597: Semicolon after method or accessor block is not valid // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(10, 47), // (11,29): error CS1519: Invalid token '(' in class, record, struct, or interface member declaration // System.Console.Write(b); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "(").WithArguments("(").WithLocation(11, 29), // (11,31): error CS8124: Tuple must contain at least two elements. // System.Console.Write(b); Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(11, 31), // (11,32): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // System.Console.Write(b); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(11, 32), // (13,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(13, 1) }; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> nested] [<anonymous type: <anonymous type: System.Int32 A> Nested> a] [<anonymous type: <anonymous type: System.Int32 A> Nested> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'nested = new { A = 10 }') Left: ILocalReferenceOperation: nested (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'nested = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (2) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'nested') Value: ILocalReferenceOperation: nested (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'nested') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsImplicit) (Syntax: 'a = new { N ... = nested }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsImplicit) (Syntax: 'a = new { N ... = nested }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>) (Syntax: 'new { Nested = nested }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>) (Syntax: 'Nested = nested') Left: IPropertyReferenceOperation: <anonymous type: System.Int32 A> <anonymous type: <anonymous type: System.Int32 A> Nested>.Nested { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'Nested') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsImplicit) (Syntax: 'new { Nested = nested }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'nested') Next (Regular) Block[B3] Leaving: {R3} Entering: {R4} } .locals {R4} { CaptureIds: [2] Block[B3] - Block Predecessors: [B2] Statements (3) ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>) (Syntax: 'a') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '') Value: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsInvalid, IsImplicit) (Syntax: 'b = a with { Nested = ') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsInvalid, IsImplicit) (Syntax: 'b = a with { Nested = ') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsInvalid) (Syntax: 'a with { Nested = ') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { Nested = ') Left: IPropertyReferenceOperation: <anonymous type: System.Int32 A> <anonymous type: <anonymous type: System.Int32 A> Nested>.Nested { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { Nested = ') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsInvalid, IsImplicit) (Syntax: 'a with { Nested = ') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R4} } Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'A = 20 ') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'A = 20') Left: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'A') Children(0) Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_NonAssignmentExpression() { var src = @" public class C { public static void M(int i, int j) /*<bind>*/{ var a = new { A = 10 }; var b = a with { i, j++, M2(), A = 20 }; }/*</bind>*/ static int M2() => 0; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); var expectedDiagnostics = new[] { // (7,26): error CS0747: Invalid initializer member declarator // var b = a with { i, j++, M2(), A = 20 }; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "i").WithLocation(7, 26), // (7,29): error CS0747: Invalid initializer member declarator // var b = a with { i, j++, M2(), A = 20 }; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "j++").WithLocation(7, 29), // (7,34): error CS0747: Invalid initializer member declarator // var b = a with { i, j++, M2(), A = 20 }; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "M2()").WithLocation(7, 34) }; comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> a] [<anonymous type: System.Int32 A> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (6) ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'a') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Children(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'i') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'j++') Children(1): IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32, IsInvalid) (Syntax: 'j++') Target: IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'j') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M2()') Children(1): IInvocationOperation (System.Int32 C.M2()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M2()') Instance Receiver: null Arguments(0) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ), A = 20 }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ), A = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>, IsInvalid) (Syntax: 'a with { i, ... ), A = 20 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { i, ... ), A = 20 }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { i, ... ), A = 20 }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { i, ... ), A = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R3} {R1} } } Block[B3] - Exit Predecessors: [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_IndexerAccess() { var src = @" public class C { public static void M() /*<bind>*/{ var a = new { A = 10 }; var b = a with { [0] = 20 }; }/*</bind>*/ }"; var expectedDiagnostics = new[] { // (7,26): error CS1513: } expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_RbraceExpected, "[").WithLocation(7, 26), // (7,26): error CS1002: ; expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "[").WithLocation(7, 26), // (7,26): error CS7014: Attributes are not valid in this context. // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[").WithLocation(7, 26), // (7,27): error CS1001: Identifier expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_IdentifierExpected, "0").WithLocation(7, 27), // (7,27): error CS1003: Syntax error, ']' expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_SyntaxError, "0").WithArguments("]", "").WithLocation(7, 27), // (7,28): error CS1002: ; expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "]").WithLocation(7, 28), // (7,28): error CS1513: } expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_RbraceExpected, "]").WithLocation(7, 28), // (7,30): error CS1525: Invalid expression term '=' // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "=").WithArguments("=").WithLocation(7, 30), // (7,35): error CS1002: ; expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(7, 35), // (7,36): error CS1597: Semicolon after method or accessor block is not valid // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(7, 36), // (9,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(9, 1) }; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> a] [<anonymous type: System.Int32 A> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [2] .locals {R4} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (2) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'a') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'a with { ') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { ') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with { ') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with { ') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>, IsInvalid) (Syntax: 'a with { ') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { ') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { ') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { ') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R3} } Block[B4] - Block Predecessors: [B3] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '[0') Expression: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '= 20 ') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '= 20') Left: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_CannotSet() { var src = @" public class C { public static void M() { var a = new { A = 10 }; a.A = 20; var b = new { B = a }; b.B.A = 30; } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (7,9): error CS0200: Property or indexer '<anonymous type: int A>.A' cannot be assigned to -- it is read only // a.A = 20; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "a.A").WithArguments("<anonymous type: int A>.A").WithLocation(7, 9), // (10,9): error CS0200: Property or indexer '<anonymous type: int A>.A' cannot be assigned to -- it is read only // b.B.A = 30; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "b.B.A").WithArguments("<anonymous type: int A>.A").WithLocation(10, 9) ); } [Fact] public void WithExpr_AnonymousType_DuplicateMemberInDeclaration() { var src = @" public class C { public static void M() /*<bind>*/{ var a = new { A = 10, A = 20 }; var b = Identity(a) with { A = Identity(30) }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) => t; }"; var expectedDiagnostics = new[] { // (6,31): error CS0833: An anonymous type cannot have multiple properties with the same name // var a = new { A = 10, A = 20 }; Diagnostic(ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, "A = 20").WithLocation(6, 31) }; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 $1> a] [<anonymous type: System.Int32 A, System.Int32 $1> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20, IsInvalid) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsInvalid, IsImplicit) (Syntax: 'a = new { A ... 0, A = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsInvalid, IsImplicit) (Syntax: 'a = new { A ... 0, A = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsInvalid) (Syntax: 'new { A = 10, A = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 $1>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsInvalid, IsImplicit) (Syntax: 'new { A = 10, A = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20, IsInvalid) (Syntax: 'A = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 $1>.$1 { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsInvalid, IsImplicit) (Syntax: 'new { A = 10, A = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsInvalid, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [3] [4] .locals {R4} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a)') Value: IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 $1> C.Identity<<anonymous type: System.Int32 A, System.Int32 $1>>(<anonymous type: System.Int32 A, System.Int32 $1> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 $1>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>) (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) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(30)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') 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) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 $1>.$1 { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'b = Identit ... ntity(30) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'b = Identit ... ntity(30) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 $1>) (Syntax: 'Identity(a) ... ntity(30) }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 $1>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'Identity(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 $1>.$1 { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B4] Leaving: {R3} } Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>) (Syntax: 'b') 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[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_DuplicateInitialization() { var src = @" public class C { public static void M() /*<bind>*/{ var a = new { A = 10 }; var b = Identity(a) with { A = Identity(30), A = Identity(40) }; }/*</bind>*/ static T Identity<T>(T t) => t; }"; var expectedDiagnostics = new[] { // (7,54): error CS1912: Duplicate initialization of member 'A' // var b = Identity(a) with { A = Identity(30), A = Identity(40) }; Diagnostic(ErrorCode.ERR_MemberAlreadyInitialized, "A").WithArguments("A").WithLocation(7, 54) }; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> a] [<anonymous type: System.Int32 A> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (4) IInvocationOperation (<anonymous type: System.Int32 A> C.Identity<<anonymous type: System.Int32 A>>(<anonymous type: System.Int32 A> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 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) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(30)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') 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) IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(40)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '40') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 40) (Syntax: '40') 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: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = Identit ... ntity(40) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = Identit ... ntity(40) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>, IsInvalid) (Syntax: 'Identity(a) ... ntity(40) }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B3] Leaving: {R3} {R1} } } Block[B3] - Exit Predecessors: [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact, WorkItem(53849, "https://github.com/dotnet/roslyn/issues/53849")] public void WithExpr_AnonymousType_ValueIsLoweredToo() { var src = @" var x = new { Property = 42 }; var adjusted = x with { Property = x.Property + 2 }; System.Console.WriteLine(adjusted); "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); var verifier = CompileAndVerify(comp, expectedOutput: "{ Property = 44 }"); verifier.VerifyDiagnostics(); } [Fact, WorkItem(53849, "https://github.com/dotnet/roslyn/issues/53849")] public void WithExpr_AnonymousType_ValueIsLoweredToo_NestedWith() { var src = @" var x = new { Property = 42 }; var container = new { Item = x }; var adjusted = container with { Item = x with { Property = x.Property + 2 } }; System.Console.WriteLine(adjusted); "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); var verifier = CompileAndVerify(comp, expectedOutput: "{ Item = { Property = 44 } }"); verifier.VerifyDiagnostics(); } [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 readonly record struct 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.RegularPreview, // 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 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 struct A(int X) { public int X = X; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct A(int X) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(8, 8), // (8,17): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct A(int X) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int X").WithArguments("positional fields in records", "10.0").WithLocation(8, 17) ); 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_Readonly() { var source = @" readonly record struct A(int X) { public int X = X; // 1 } readonly record struct B(int X) { public readonly int X = X; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,16): error CS8340: Instance fields of readonly structs must be readonly. // public int X = X; // 1 Diagnostic(ErrorCode.ERR_FieldsInRoStruct, "X").WithLocation(4, 16) ); } [Fact] public void FieldAsPositionalMember_Fixed() { var src = @" unsafe record struct C(int[] P) { public fixed int P[2]; public int[] X = P; }"; var comp = CreateCompilation(src, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (2,30): error CS8866: Record member 'C.P' must be a readable instance property or field of type 'int[]' to match positional parameter 'P'. // unsafe record struct C(int[] P) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("C.P", "int[]", "P").WithLocation(2, 30), // (4,22): error CS8908: The type 'int*' may not be used for a field of a record. // public fixed int P[2]; Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P").WithArguments("int*").WithLocation(4, 22) ); } [Fact] public void FieldAsPositionalMember_WrongType() { var source = @" record struct A(int X) { public string X = null; public int Y = X; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (2,21): error CS8866: Record member 'A.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'. // record struct A(int X) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("A.X", "int", "X").WithLocation(2, 21) ); } [Fact] public void FieldAsPositionalMember_DuplicateFields() { var source = @" record struct A(int X) { public int X = 0; public int X = 0; public int Y = X; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,16): error CS0102: The type 'A' already contains a definition for 'X' // public int X = 0; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("A", "X").WithLocation(5, 16) ); } [Fact] public void SyntaxFactory_TypeDeclaration() { var expected = @"record struct Point { }"; AssertEx.AssertEqualToleratingWhitespaceDifferences(expected, SyntaxFactory.TypeDeclaration(SyntaxKind.RecordStructDeclaration, "Point").NormalizeWhitespace().ToString()); } [Fact] public void InterfaceWithParameters() { var src = @" public interface I { } record struct R(int X) : I() { } record struct R2(int X) : I(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,27): error CS8861: Unexpected argument list. // record struct R(int X) : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 27), // (10,28): error CS8861: Unexpected argument list. // record struct R2(int X) : I(X) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(10, 28) ); } [Fact] public void InterfaceWithParameters_NoPrimaryConstructor() { var src = @" public interface I { } record struct R : I() { } record struct R2 : I(0) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,20): error CS8861: Unexpected argument list. // record struct R : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 20), // (10,21): error CS8861: Unexpected argument list. // record struct R2 : I(0) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(0)").WithLocation(10, 21) ); } [Fact] public void InterfaceWithParameters_Struct() { var src = @" public interface I { } struct C : I() { } struct C2 : I(0) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,13): error CS8861: Unexpected argument list. // struct C : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 13), // (10,14): error CS8861: Unexpected argument list. // struct C2 : I(0) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(0)").WithLocation(10, 14) ); } [Fact] public void BaseArguments_Speculation() { var src = @" record struct R1(int X) : Error1(0, 1) { } record struct R2(int X) : Error2() { } record struct R3(int X) : Error3 { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,27): error CS0246: The type or namespace name 'Error1' could not be found (are you missing a using directive or an assembly reference?) // record struct R1(int X) : Error1(0, 1) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error1").WithArguments("Error1").WithLocation(2, 27), // (2,33): error CS8861: Unexpected argument list. // record struct R1(int X) : Error1(0, 1) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(0, 1)").WithLocation(2, 33), // (5,27): error CS0246: The type or namespace name 'Error2' could not be found (are you missing a using directive or an assembly reference?) // record struct R2(int X) : Error2() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error2").WithArguments("Error2").WithLocation(5, 27), // (5,33): error CS8861: Unexpected argument list. // record struct R2(int X) : Error2() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(5, 33), // (8,27): error CS0246: The type or namespace name 'Error3' could not be found (are you missing a using directive or an assembly reference?) // record struct R3(int X) : Error3 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error3").WithArguments("Error3").WithLocation(8, 27) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var baseWithargs = tree.GetRoot().DescendantNodes().OfType<PrimaryConstructorBaseTypeSyntax>().First(); Assert.Equal("Error1(0, 1)", baseWithargs.ToString()); var speculativeBase = baseWithargs.WithArgumentList(baseWithargs.ArgumentList.WithArguments(baseWithargs.ArgumentList.Arguments.RemoveAt(1))); Assert.Equal("Error1(0)", speculativeBase.ToString()); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBase, out _)); var baseWithoutargs = tree.GetRoot().DescendantNodes().OfType<PrimaryConstructorBaseTypeSyntax>().Skip(1).First(); Assert.Equal("Error2()", baseWithoutargs.ToString()); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithoutargs.ArgumentList.OpenParenToken.SpanStart, speculativeBase, out _)); var baseWithoutParens = tree.GetRoot().DescendantNodes().OfType<SimpleBaseTypeSyntax>().Single(); Assert.Equal("Error3", baseWithoutParens.ToString()); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithoutParens.SpanStart + 2, speculativeBase, out _)); } [Fact, WorkItem(54413, "https://github.com/dotnet/roslyn/issues/54413")] public void ValueTypeCopyConstructorLike_NoThisInitializer() { var src = @" record struct Value(string Text) { private Value(int X) { } // 1 private Value(Value original) { } // 2 } record class Boxed(string Text) { private Boxed(int X) { } // 3 private Boxed(Boxed original) { } // 4 } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,13): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // private Value(int X) { } // 1 Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "Value").WithLocation(4, 13), // (5,13): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // private Value(Value original) { } // 2 Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "Value").WithLocation(5, 13), // (10,13): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // private Boxed(int X) { } // 3 Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "Boxed").WithLocation(10, 13), // (11,13): error CS8878: A copy constructor 'Boxed.Boxed(Boxed)' must be public or protected because the record is not sealed. // private Boxed(Boxed original) { } // 4 Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "Boxed").WithArguments("Boxed.Boxed(Boxed)").WithLocation(11, 13) ); } [Fact] public void ValueTypeCopyConstructorLike() { var src = @" System.Console.Write(new Value(new Value(0))); record struct Value(int I) { public Value(Value original) : this(42) { } } "; var comp = CreateCompilation(src); CompileAndVerify(comp, expectedOutput: "Value { I = 42 }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; 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 { [CompilerTrait(CompilerFeature.RecordStructs)] public class RecordStructTests : 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] public void StructRecord1() { var src = @" record struct Point(int X, int Y);"; var verifier = CompileAndVerify(src).VerifyDiagnostics(); verifier.VerifyIL("Point.Equals(object)", @" { // Code size 23 (0x17) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""Point"" IL_0006: brfalse.s IL_0015 IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: unbox.any ""Point"" IL_000f: call ""readonly bool Point.Equals(Point)"" IL_0014: ret IL_0015: ldc.i4.0 IL_0016: ret }"); verifier.VerifyIL("Point.Equals(Point)", @" { // Code size 49 (0x31) .maxstack 3 IL_0000: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0005: ldarg.0 IL_0006: ldfld ""int Point.<X>k__BackingField"" IL_000b: ldarg.1 IL_000c: ldfld ""int Point.<X>k__BackingField"" IL_0011: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0016: brfalse.s IL_002f IL_0018: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001d: ldarg.0 IL_001e: ldfld ""int Point.<Y>k__BackingField"" IL_0023: ldarg.1 IL_0024: ldfld ""int Point.<Y>k__BackingField"" IL_0029: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_002e: ret IL_002f: ldc.i4.0 IL_0030: ret }"); } [Fact] public void StructRecord2() { var src = @" using System; record struct S(int X, int Y) { public static void Main() { var s1 = new S(0, 1); var s2 = new S(0, 1); Console.WriteLine(s1.X); Console.WriteLine(s1.Y); Console.WriteLine(s1.Equals(s2)); Console.WriteLine(s1.Equals(new S(1, 0))); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"0 1 True False").VerifyDiagnostics(); } [Fact] public void StructRecord3() { var src = @" using System; record struct S(int X, int Y) { public bool Equals(S s) => false; public static void Main() { var s1 = new S(0, 1); Console.WriteLine(s1.Equals(s1)); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"False") .VerifyDiagnostics( // (5,17): warning CS8851: 'S' defines 'Equals' but not 'GetHashCode' // public bool Equals(S s) => false; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("S").WithLocation(5, 17)); verifier.VerifyIL("S.Main", @" { // Code size 23 (0x17) .maxstack 3 .locals init (S V_0) //s1 IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.1 IL_0004: call ""S..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldloc.0 IL_000c: call ""bool S.Equals(S)"" IL_0011: call ""void System.Console.WriteLine(bool)"" IL_0016: ret }"); } [Fact] public void StructRecord5() { var src = @" using System; record struct S(int X, int Y) { public bool Equals(S s) { Console.Write(""s""); return true; } public static void Main() { var s1 = new S(0, 1); s1.Equals((object)s1); s1.Equals(s1); } }"; CompileAndVerify(src, expectedOutput: @"ss") .VerifyDiagnostics( // (5,17): warning CS8851: 'S' defines 'Equals' but not 'GetHashCode' // public bool Equals(S s) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("S").WithLocation(5, 17)); } [Fact] public void StructRecordDefaultCtor() { const string src = @" public record struct S(int X);"; const string src2 = @" class C { public S M() => new S(); }"; var comp = CreateCompilation(src + src2); comp.VerifyDiagnostics(); comp = CreateCompilation(src); var comp2 = CreateCompilation(src2, references: new[] { comp.EmitToImageReference() }); comp2.VerifyDiagnostics(); } [Fact] public void Equality_01() { var source = @"using static System.Console; record struct S; class Program { static void Main() { var x = new S(); var y = new S(); WriteLine(x.Equals(y)); WriteLine(((object)x).Equals(y)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"True True").VerifyDiagnostics(); verifier.VerifyIL("S.Equals(S)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret }"); verifier.VerifyIL("S.Equals(object)", @" { // Code size 23 (0x17) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""S"" IL_0006: brfalse.s IL_0015 IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: unbox.any ""S"" IL_000f: call ""readonly bool S.Equals(S)"" IL_0014: ret IL_0015: ldc.i4.0 IL_0016: ret }"); } [Fact] public void RecordStructLanguageVersion() { var src1 = @" struct Point(int x, int y); "; var src2 = @" record struct Point { } "; var src3 = @" record struct Point(int x, int y); "; var comp = CreateCompilation(new[] { src1, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,13): error CS1514: { expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 13), // (2,13): error CS1513: } expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 13), // (2,13): error CS8803: Top-level statements must precede namespace and type declarations. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 13), // (2,13): error CS8805: Program using top-level statements must be an executable. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 13), // (2,13): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 13), // (2,14): error CS8185: A declaration is not allowed in this context. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 14), // (2,14): error CS0165: Use of unassigned local variable 'x' // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 14), // (2,21): error CS8185: A declaration is not allowed in this context. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 21), // (2,21): error CS0165: Use of unassigned local variable 'y' // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 21) ); comp = CreateCompilation(new[] { src2, 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 struct Point { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(2, 8) ); comp = CreateCompilation(new[] { src3, 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 struct Point { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(2, 8) ); comp = CreateCompilation(new[] { src1, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,13): error CS1514: { expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 13), // (2,13): error CS1513: } expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 13), // (2,13): error CS8803: Top-level statements must precede namespace and type declarations. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 13), // (2,13): error CS8805: Program using top-level statements must be an executable. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 13), // (2,13): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 13), // (2,14): error CS8185: A declaration is not allowed in this context. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 14), // (2,14): error CS0165: Use of unassigned local variable 'x' // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 14), // (2,21): error CS8185: A declaration is not allowed in this context. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 21), // (2,21): error CS0165: Use of unassigned local variable 'y' // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 21) ); comp = CreateCompilation(new[] { src2, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { src3, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics(); } [Fact] public void RecordStructLanguageVersion_Nested() { var src1 = @" class C { struct Point(int x, int y); } "; var src2 = @" class D { record struct Point { } } "; var src3 = @" struct E { record struct Point(int x, int y); } "; var src4 = @" namespace NS { record struct Point { } } "; var comp = CreateCompilation(src1, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,17): error CS1514: { expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(4, 17), // (4,17): error CS1513: } expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(4, 17), // (4,31): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 31), // (4,31): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 31) ); comp = CreateCompilation(new[] { src2, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,12): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct Point { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(4, 12) ); comp = CreateCompilation(new[] { src3, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,12): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct Point(int x, int y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(4, 12) ); comp = CreateCompilation(src4, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,12): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct Point { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(4, 12) ); comp = CreateCompilation(src1); comp.VerifyDiagnostics( // (4,17): error CS1514: { expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(4, 17), // (4,17): error CS1513: } expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(4, 17), // (4,31): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 31), // (4,31): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 31) ); comp = CreateCompilation(src2); comp.VerifyDiagnostics(); comp = CreateCompilation(src3); comp.VerifyDiagnostics(); comp = CreateCompilation(src4); comp.VerifyDiagnostics(); } [Fact] public void TypeDeclaration_IsStruct() { var src = @" record struct Point(int x, int y); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, symbolValidator: validateModule, sourceSymbolValidator: validateModule); Assert.True(SyntaxFacts.IsTypeDeclaration(SyntaxKind.RecordStructDeclaration)); static void validateModule(ModuleSymbol module) { var isSourceSymbol = module is SourceModuleSymbol; var point = module.GlobalNamespace.GetTypeMember("Point"); Assert.True(point.IsValueType); Assert.False(point.IsReferenceType); Assert.False(point.IsRecord); Assert.Equal(TypeKind.Struct, point.TypeKind); Assert.Equal(SpecialType.System_ValueType, point.BaseTypeNoUseSiteDiagnostics.SpecialType); Assert.Equal("Point", point.ToTestDisplayString()); if (isSourceSymbol) { Assert.True(point is SourceNamedTypeSymbol); Assert.True(point.IsRecordStruct); Assert.True(point.GetPublicSymbol().IsRecord); Assert.Equal("record struct Point", point.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } else { Assert.True(point is PENamedTypeSymbol); Assert.False(point.IsRecordStruct); Assert.False(point.GetPublicSymbol().IsRecord); Assert.Equal("struct Point", point.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } } } [Fact] public void TypeDeclaration_IsStruct_InConstraints() { var src = @" record struct Point(int x, int y); class C<T> where T : struct { void M(C<Point> c) { } } class C2<T> where T : new() { void M(C2<Point> c) { } } class C3<T> where T : class { void M(C3<Point> c) { } // 1 } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (16,22): error CS0452: The type 'Point' must be a reference type in order to use it as parameter 'T' in the generic type or method 'C3<T>' // void M(C3<Point> c) { } // 1 Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "c").WithArguments("C3<T>", "T", "Point").WithLocation(16, 22) ); } [Fact] public void TypeDeclaration_IsStruct_Unmanaged() { var src = @" record struct Point(int x, int y); record struct Point2(string x, string y); class C<T> where T : unmanaged { void M(C<Point> c) { } void M2(C<Point2> c) { } // 1 } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,23): error CS8377: The type 'Point2' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'C<T>' // void M2(C<Point2> c) { } // 1 Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "c").WithArguments("C<T>", "T", "Point2").WithLocation(8, 23) ); } [Fact] public void IsRecord_Generic() { var src = @" record struct Point<T>(T x, T y); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, symbolValidator: validateModule, sourceSymbolValidator: validateModule); static void validateModule(ModuleSymbol module) { var isSourceSymbol = module is SourceModuleSymbol; var point = module.GlobalNamespace.GetTypeMember("Point"); Assert.True(point.IsValueType); Assert.False(point.IsReferenceType); Assert.False(point.IsRecord); Assert.Equal(TypeKind.Struct, point.TypeKind); Assert.Equal(SpecialType.System_ValueType, point.BaseTypeNoUseSiteDiagnostics.SpecialType); Assert.True(SyntaxFacts.IsTypeDeclaration(SyntaxKind.RecordStructDeclaration)); if (isSourceSymbol) { Assert.True(point is SourceNamedTypeSymbol); Assert.True(point.IsRecordStruct); Assert.True(point.GetPublicSymbol().IsRecord); } else { Assert.True(point is PENamedTypeSymbol); Assert.False(point.IsRecordStruct); Assert.False(point.GetPublicSymbol().IsRecord); } } } [Fact] public void IsRecord_Retargeting() { var src = @" public record struct Point(int x, int y); "; var comp = CreateCompilation(src, targetFramework: TargetFramework.Mscorlib40); var comp2 = CreateCompilation("", targetFramework: TargetFramework.Mscorlib46, references: new[] { comp.ToMetadataReference() }); var point = comp2.GlobalNamespace.GetTypeMember("Point"); Assert.Equal("Point", point.ToTestDisplayString()); Assert.IsType<RetargetingNamedTypeSymbol>(point); Assert.True(point.IsRecordStruct); Assert.True(point.GetPublicSymbol().IsRecord); } [Fact] public void IsRecord_AnonymousType() { var src = @" class C { void M() { var x = new { X = 1 }; } } "; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var creation = tree.GetRoot().DescendantNodes().OfType<AnonymousObjectCreationExpressionSyntax>().Single(); var type = model.GetTypeInfo(creation).Type!; Assert.Equal("<anonymous type: System.Int32 X>", type.ToTestDisplayString()); Assert.IsType<AnonymousTypeManager.AnonymousTypePublicSymbol>(((Symbols.PublicModel.NonErrorNamedTypeSymbol)type).UnderlyingNamedTypeSymbol); Assert.False(type.IsRecord); } [Fact] public void IsRecord_ErrorType() { var src = @" class C { Error M() => throw null; } "; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var method = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); var type = model.GetDeclaredSymbol(method)!.ReturnType; Assert.Equal("Error", type.ToTestDisplayString()); Assert.IsType<ExtendedErrorTypeSymbol>(((Symbols.PublicModel.ErrorTypeSymbol)type).UnderlyingNamedTypeSymbol); Assert.False(type.IsRecord); } [Fact] public void IsRecord_Pointer() { var src = @" class C { int* M() => throw null; } "; var comp = CreateCompilation(src, options: TestOptions.UnsafeReleaseDll); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var method = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); var type = model.GetDeclaredSymbol(method)!.ReturnType; Assert.Equal("System.Int32*", type.ToTestDisplayString()); Assert.IsType<PointerTypeSymbol>(((Symbols.PublicModel.PointerTypeSymbol)type).UnderlyingTypeSymbol); Assert.False(type.IsRecord); } [Fact] public void IsRecord_Dynamic() { var src = @" class C { void M(dynamic d) { } } "; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var method = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); var type = model.GetDeclaredSymbol(method)!.GetParameterType(0); Assert.Equal("dynamic", type.ToTestDisplayString()); Assert.IsType<DynamicTypeSymbol>(((Symbols.PublicModel.DynamicTypeSymbol)type).UnderlyingTypeSymbol); Assert.False(type.IsRecord); } [Fact] public void TypeDeclaration_MayNotHaveBaseType() { var src = @" record struct Point(int x, int y) : object; record struct Point2(int x, int y) : System.ValueType; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,37): error CS0527: Type 'object' in interface list is not an interface // record struct Point(int x, int y) : object; Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "object").WithArguments("object").WithLocation(2, 37), // (3,38): error CS0527: Type 'ValueType' in interface list is not an interface // record struct Point2(int x, int y) : System.ValueType; Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "System.ValueType").WithArguments("System.ValueType").WithLocation(3, 38) ); } [Fact] public void TypeDeclaration_MayNotHaveTypeConstraintsWithoutTypeParameters() { var src = @" record struct Point(int x, int y) where T : struct; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,35): error CS0080: Constraints are not allowed on non-generic declarations // record struct Point(int x, int y) where T : struct; Diagnostic(ErrorCode.ERR_ConstraintOnlyAllowedOnGenericDecl, "where").WithLocation(2, 35) ); } [Fact] public void TypeDeclaration_AllowedModifiers() { var src = @" readonly partial record struct S1; public record struct S2; internal record struct S3; public class Base { public int S6; } public class C : Base { private protected record struct S4; protected internal record struct S5; new record struct S6; } unsafe record struct S7; "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics(); Assert.Equal(Accessibility.Internal, comp.GlobalNamespace.GetTypeMember("S1").DeclaredAccessibility); Assert.Equal(Accessibility.Public, comp.GlobalNamespace.GetTypeMember("S2").DeclaredAccessibility); Assert.Equal(Accessibility.Internal, comp.GlobalNamespace.GetTypeMember("S3").DeclaredAccessibility); Assert.Equal(Accessibility.ProtectedAndInternal, comp.GlobalNamespace.GetTypeMember("C").GetTypeMember("S4").DeclaredAccessibility); Assert.Equal(Accessibility.ProtectedOrInternal, comp.GlobalNamespace.GetTypeMember("C").GetTypeMember("S5").DeclaredAccessibility); } [Fact] public void TypeDeclaration_DisallowedModifiers() { var src = @" abstract record struct S1; volatile record struct S2; extern record struct S3; virtual record struct S4; override record struct S5; async record struct S6; ref record struct S7; unsafe record struct S8; static record struct S9; sealed record struct S10; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,24): error CS0106: The modifier 'abstract' is not valid for this item // abstract record struct S1; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S1").WithArguments("abstract").WithLocation(2, 24), // (3,24): error CS0106: The modifier 'volatile' is not valid for this item // volatile record struct S2; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S2").WithArguments("volatile").WithLocation(3, 24), // (4,22): error CS0106: The modifier 'extern' is not valid for this item // extern record struct S3; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S3").WithArguments("extern").WithLocation(4, 22), // (5,23): error CS0106: The modifier 'virtual' is not valid for this item // virtual record struct S4; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S4").WithArguments("virtual").WithLocation(5, 23), // (6,24): error CS0106: The modifier 'override' is not valid for this item // override record struct S5; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S5").WithArguments("override").WithLocation(6, 24), // (7,21): error CS0106: The modifier 'async' is not valid for this item // async record struct S6; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S6").WithArguments("async").WithLocation(7, 21), // (8,19): error CS0106: The modifier 'ref' is not valid for this item // ref record struct S7; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S7").WithArguments("ref").WithLocation(8, 19), // (9,22): error CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe record struct S8; Diagnostic(ErrorCode.ERR_IllegalUnsafe, "S8").WithLocation(9, 22), // (10,22): error CS0106: The modifier 'static' is not valid for this item // static record struct S9; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S9").WithArguments("static").WithLocation(10, 22), // (11,22): error CS0106: The modifier 'sealed' is not valid for this item // sealed record struct S10; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S10").WithArguments("sealed").WithLocation(11, 22) ); } [Fact] public void TypeDeclaration_DuplicatesModifiers() { var src = @" public public record struct S2; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,8): error CS1004: Duplicate 'public' modifier // public public record struct S2; Diagnostic(ErrorCode.ERR_DuplicateModifier, "public").WithArguments("public").WithLocation(2, 8) ); } [Fact] public void TypeDeclaration_BeforeTopLevelStatement() { var src = @" record struct S; System.Console.WriteLine(); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine();").WithLocation(3, 1) ); } [Fact] public void TypeDeclaration_WithTypeParameters() { var src = @" S<string> local = default; local.ToString(); record struct S<T>; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); Assert.Equal(new[] { "T" }, comp.GlobalNamespace.GetTypeMember("S").TypeParameters.ToTestDisplayStrings()); } [Fact] public void TypeDeclaration_AllowedModifiersForMembers() { var src = @" record struct S { protected int Property { get; set; } // 1 internal protected string field; // 2, 3 abstract void M(); // 4 virtual void M2() { } // 5 }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,19): error CS0666: 'S.Property': new protected member declared in struct // protected int Property { get; set; } // 1 Diagnostic(ErrorCode.ERR_ProtectedInStruct, "Property").WithArguments("S.Property").WithLocation(4, 19), // (5,31): error CS0666: 'S.field': new protected member declared in struct // internal protected string field; // 2, 3 Diagnostic(ErrorCode.ERR_ProtectedInStruct, "field").WithArguments("S.field").WithLocation(5, 31), // (5,31): warning CS0649: Field 'S.field' is never assigned to, and will always have its default value null // internal protected string field; // 2, 3 Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("S.field", "null").WithLocation(5, 31), // (6,19): error CS0621: 'S.M()': virtual or abstract members cannot be private // abstract void M(); // 4 Diagnostic(ErrorCode.ERR_VirtualPrivate, "M").WithArguments("S.M()").WithLocation(6, 19), // (7,18): error CS0621: 'S.M2()': virtual or abstract members cannot be private // virtual void M2() { } // 5 Diagnostic(ErrorCode.ERR_VirtualPrivate, "M2").WithArguments("S.M2()").WithLocation(7, 18) ); } [Fact] public void TypeDeclaration_ImplementInterface() { var src = @" I i = (I)default(S); System.Console.Write(i.M(""four"")); I i2 = (I)default(S2); System.Console.Write(i2.M(""four"")); interface I { int M(string s); } public record struct S : I { public int M(string s) => s.Length; } public record struct S2 : I { int I.M(string s) => s.Length + 1; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "45"); AssertEx.Equal(new[] { "System.Int32 S.M(System.String s)", "readonly System.String S.ToString()", "readonly System.Boolean S.PrintMembers(System.Text.StringBuilder builder)", "System.Boolean S.op_Inequality(S left, S right)", "System.Boolean S.op_Equality(S left, S right)", "readonly System.Int32 S.GetHashCode()", "readonly System.Boolean S.Equals(System.Object obj)", "readonly System.Boolean S.Equals(S other)", "S..ctor()" }, comp.GetMember<NamedTypeSymbol>("S").GetMembers().ToTestDisplayStrings()); } [Fact] public void TypeDeclaration_SatisfiesStructConstraint() { var src = @" S s = default; System.Console.Write(M(s)); static int M<T>(T t) where T : struct, I => t.Property; public interface I { int Property { get; } } public record struct S : I { public int Property => 42; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "42"); } [Fact] public void TypeDeclaration_AccessingThis() { var src = @" S s = new S(); System.Console.Write(s.M()); public record struct S { public int Property => 42; public int M() => this.Property; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("S.M", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""int S.Property.get"" IL_0006: ret } "); } [Fact] public void TypeDeclaration_NoBaseInitializer() { var src = @" public record struct S { public S(int i) : base() { } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,12): error CS0522: 'S': structs cannot call base class constructors // public S(int i) : base() { } Diagnostic(ErrorCode.ERR_StructWithBaseConstructorCall, "S").WithArguments("S").WithLocation(4, 12) ); } [Fact] public void TypeDeclaration_ParameterlessConstructor_01() { var src = @"record struct S0(); record struct S1; record struct S2 { public S2() { } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct S0(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(1, 8), // (2,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct S1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(2, 8), // (3,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct S2 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(3, 8), // (5,12): error CS8773: Feature 'parameterless struct constructors' is not available in C# 9.0. Please use language version 10.0 or greater. // public S2() { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "S2").WithArguments("parameterless struct constructors", "10.0").WithLocation(5, 12)); var verifier = CompileAndVerify(src); verifier.VerifyIL("S0..ctor()", @"{ // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); verifier.VerifyMissing("S1..ctor()"); verifier.VerifyIL("S2..ctor()", @"{ // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } [Fact] public void TypeDeclaration_ParameterlessConstructor_02() { var src = @"record struct S1 { S1() { } } record struct S2 { internal S2() { } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct S1 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(1, 8), // (3,5): error CS8773: Feature 'parameterless struct constructors' is not available in C# 9.0. Please use language version 10.0 or greater. // S1() { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "S1").WithArguments("parameterless struct constructors", "10.0").WithLocation(3, 5), // (3,5): error CS8938: The parameterless struct constructor must be 'public'. // S1() { } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "S1").WithLocation(3, 5), // (5,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct S2 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(5, 8), // (7,14): error CS8773: Feature 'parameterless struct constructors' is not available in C# 9.0. Please use language version 10.0 or greater. // internal S2() { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "S2").WithArguments("parameterless struct constructors", "10.0").WithLocation(7, 14), // (7,14): error CS8938: The parameterless struct constructor must be 'public'. // internal S2() { } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "S2").WithLocation(7, 14)); comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,5): error CS8918: The parameterless struct constructor must be 'public'. // S1() { } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "S1").WithLocation(3, 5), // (7,14): error CS8918: The parameterless struct constructor must be 'public'. // internal S2() { } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "S2").WithLocation(7, 14)); } [Fact] public void TypeDeclaration_ParameterlessConstructor_OtherConstructors() { var src = @" record struct S1 { public S1() { } S1(object o) { } // ok because no record parameter list } record struct S2 { S2(object o) { } } record struct S3() { S3(object o) { } // 1 } record struct S4() { S4(object o) : this() { } } record struct S5(object o) { public S5() { } // 2 } record struct S6(object o) { public S6() : this(null) { } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,5): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // S3(object o) { } // 1 Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "S3").WithLocation(13, 5), // (21,12): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // public S5() { } // 2 Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "S5").WithLocation(21, 12) ); } [Fact] public void TypeDeclaration_ParameterlessConstructor_Initializers() { var src = @" var s1 = new S1(); var s2 = new S2(null); var s2b = new S2(); var s3 = new S3(); var s4 = new S4(new object()); var s5 = new S5(); var s6 = new S6(""s6.other""); System.Console.Write((s1.field, s2.field, s2b.field is null, s3.field, s4.field, s5.field, s6.field, s6.other)); record struct S1 { public string field = ""s1""; public S1() { } } record struct S2 { public string field = ""s2""; public S2(object o) { } } record struct S3() { public string field = ""s3""; } record struct S4 { public string field = ""s4""; public S4(object o) : this() { } } record struct S5() { public string field = ""s5""; public S5(object o) : this() { } } record struct S6(string other) { public string field = ""s6.field""; public S6() : this(""ignored"") { } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "(s1, s2, True, s3, s4, s5, s6.field, s6.other)"); } [Fact] public void TypeDeclaration_InstanceInitializers() { var src = @" public record struct S { public int field = 42; public int Property { get; set; } = 43; } "; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,15): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // public record struct S Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(2, 15), // (4,16): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public int field = 42; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "field").WithArguments("struct field initializers", "10.0").WithLocation(4, 16), // (5,16): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public int Property { get; set; } = 43; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Property").WithArguments("struct field initializers", "10.0").WithLocation(5, 16)); comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void TypeDeclaration_NoDestructor() { var src = @" public record struct S { ~S() { } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,6): error CS0575: Only class types can contain destructors // ~S() { } Diagnostic(ErrorCode.ERR_OnlyClassesCanContainDestructors, "S").WithArguments("S.~S()").WithLocation(4, 6) ); } [Fact] public void TypeDeclaration_DifferentPartials() { var src = @" partial record struct S1; partial struct S1 { } partial struct S2 { } partial record struct S2; partial record struct S3; partial record S3 { } partial record struct S4; partial record class S4 { } partial record struct S5; partial class S5 { } partial record struct S6; partial interface S6 { } partial record class C1; partial struct C1 { } partial record class C2; partial record struct C2 { } partial record class C3 { } partial record C3; partial record class C4; partial class C4 { } partial record class C5; partial interface C5 { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,16): error CS0261: Partial declarations of 'S1' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial struct S1 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S1").WithArguments("S1").WithLocation(3, 16), // (6,23): error CS0261: Partial declarations of 'S2' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial record struct S2; Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S2").WithArguments("S2").WithLocation(6, 23), // (9,16): error CS0261: Partial declarations of 'S3' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial record S3 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S3").WithArguments("S3").WithLocation(9, 16), // (12,22): error CS0261: Partial declarations of 'S4' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial record class S4 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S4").WithArguments("S4").WithLocation(12, 22), // (15,15): error CS0261: Partial declarations of 'S5' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial class S5 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S5").WithArguments("S5").WithLocation(15, 15), // (18,19): error CS0261: Partial declarations of 'S6' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial interface S6 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S6").WithArguments("S6").WithLocation(18, 19), // (21,16): error CS0261: Partial declarations of 'C1' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial struct C1 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "C1").WithArguments("C1").WithLocation(21, 16), // (24,23): error CS0261: Partial declarations of 'C2' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial record struct C2 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "C2").WithArguments("C2").WithLocation(24, 23), // (30,15): error CS0261: Partial declarations of 'C4' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial class C4 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "C4").WithArguments("C4").WithLocation(30, 15), // (33,19): error CS0261: Partial declarations of 'C5' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial interface C5 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "C5").WithArguments("C5").WithLocation(33, 19) ); } [Fact] public void PartialRecord_OnlyOnePartialHasParameterList() { var src = @" partial record struct S(int i); partial record struct S(int i); partial record struct S2(int i); partial record struct S2(); partial record struct S3(); partial record struct S3(); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,24): error CS8863: Only a single record partial declaration may have a parameter list // partial record struct S(int i); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int i)").WithLocation(3, 24), // (6,25): error CS8863: Only a single record partial declaration may have a parameter list // partial record struct S2(); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "()").WithLocation(6, 25), // (9,25): error CS8863: Only a single record partial declaration may have a parameter list // partial record struct S3(); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "()").WithLocation(9, 25) ); } [Fact] public void PartialRecord_ParametersInScopeOfBothParts() { var src = @" var c = new C(2); System.Console.Write((c.P1, c.P2)); public partial record struct C(int X) { public int P1 { get; set; } = X; } public partial record struct C { public int P2 { get; set; } = X; } "; var comp = CreateCompilation(src); CompileAndVerify(comp, expectedOutput: "(2, 2)", verify: Verification.Skipped /* init-only */) .VerifyDiagnostics( // (5,30): warning CS0282: There is no defined ordering between fields in multiple declarations of partial struct 'C'. To specify an ordering, all instance fields must be in the same declaration. // public partial record struct C(int X) Diagnostic(ErrorCode.WRN_SequentialOnPartialClass, "C").WithArguments("C").WithLocation(5, 30) ); } [Fact] public void PartialRecord_DuplicateMemberNames() { var src = @" public partial record struct C(int X) { public void M(int i) { } } public partial record struct C { public void M(string s) { } } "; var comp = CreateCompilation(src); var expectedMemberNames = new string[] { ".ctor", "<X>k__BackingField", "get_X", "set_X", "X", "M", "M", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "Deconstruct", ".ctor", }; 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 struct Nested(T T); } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "2"); } [Fact] public void PositionalMemberModifiers_RefOrOut() { var src = @" record struct R(ref int P1, out int P2); "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,15): error CS0177: The out parameter 'P2' must be assigned to before control leaves the current method // record struct R(ref int P1, out int P2); Diagnostic(ErrorCode.ERR_ParamUnassigned, "R").WithArguments("P2").WithLocation(2, 15), // (2,17): error CS0631: ref and out are not valid in this context // record struct R(ref int P1, out int P2); Diagnostic(ErrorCode.ERR_IllegalRefParam, "ref").WithLocation(2, 17), // (2,29): error CS0631: ref and out are not valid in this context // record struct R(ref int P1, out int P2); Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(2, 29) ); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberModifiers_This() { var src = @" record struct R(this int i); "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,17): error CS0027: Keyword 'this' is not available in the current context // record struct R(this int i); Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(2, 17) ); } [Fact, WorkItem(45591, "https://github.com/dotnet/roslyn/issues/45591")] public void Clone_DisallowedInSource() { var src = @" record struct C1(string Clone); // 1 record struct C2 { string Clone; // 2 } record struct C3 { string Clone { get; set; } // 3 } record struct C5 { void Clone() { } // 4 void Clone(int i) { } // 5 } record struct C6 { class Clone { } // 6 } record struct C7 { delegate void Clone(); // 7 } record struct C8 { event System.Action Clone; // 8 } record struct Clone { Clone(int i) => throw null; } record struct C9 : System.ICloneable { object System.ICloneable.Clone() => throw null; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,25): error CS8859: Members named 'Clone' are disallowed in records. // record struct C1(string Clone); // 1 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(2, 25), // (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 CS8859: Members named 'Clone' are disallowed in records. // void Clone() { } // 4 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(13, 10), // (14,10): error CS8859: Members named 'Clone' are disallowed in records. // void Clone(int i) { } // 5 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(14, 10), // (18,11): error CS8859: Members named 'Clone' are disallowed in records. // class Clone { } // 6 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(18, 11), // (22,19): error CS8859: Members named 'Clone' are disallowed in records. // delegate void Clone(); // 7 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(22, 19), // (26,25): error CS8859: Members named 'Clone' are disallowed in records. // event System.Action Clone; // 8 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(26, 25), // (26,25): warning CS0067: The event 'C8.Clone' is never used // event System.Action Clone; // 8 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Clone").WithArguments("C8.Clone").WithLocation(26, 25) ); } [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 struct 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 }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (6,22): error CS0721: 'C2': static types cannot be used as parameters // unsafe record struct C( // 1 Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "C").WithArguments("C2").WithLocation(6, 22), // (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 struct 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 }, parseOptions: TestOptions.RegularPreview, 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 struct 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 }, parseOptions: TestOptions.RegularPreview, 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 struct 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 }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeDebugExe); comp.VerifyEmitDiagnostics( // (4,29): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // unsafe record struct C(int* P1, int*[] P2, C<int*[]> P3) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(4, 29), // (4,40): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // unsafe record struct C(int* P1, int*[] P2, C<int*[]> P3) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(4, 40), // (4,54): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // unsafe record struct C(int* P1, int*[] P2, C<int*[]> P3) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(4, 54) ); 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] public void RecordProperties_01() { var src = @" using System; record struct C(int X, int Y) { int Z = 345; public static void Main() { var c = new C(1, 2); Console.Write(c.X); Console.Write(c.Y); Console.Write(c.Z); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"12345").VerifyDiagnostics(); verifier.VerifyIL("C..ctor(int, int)", @" { // Code size 26 (0x1a) .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 0x159 IL_0014: stfld ""int C.Z"" IL_0019: ret } "); var c = verifier.Compilation.GlobalNamespace.GetTypeMember("C"); Assert.False(c.IsReadOnly); var x = (IPropertySymbol)c.GetMember("X"); Assert.Equal("readonly System.Int32 C.X.get", x.GetMethod.ToTestDisplayString()); Assert.Equal("void C.X.set", x.SetMethod.ToTestDisplayString()); Assert.False(x.SetMethod!.IsInitOnly); var xBackingField = (IFieldSymbol)c.GetMember("<X>k__BackingField"); Assert.Equal("System.Int32 C.<X>k__BackingField", xBackingField.ToTestDisplayString()); Assert.False(xBackingField.IsReadOnly); } [Fact] public void RecordProperties_01_EmptyParameterList() { var src = @" using System; record struct C() { int Z = 345; public static void Main() { var c = new C(); Console.Write(c.Z); } }"; CreateCompilation(src).VerifyEmitDiagnostics(); } [Fact] public void RecordProperties_01_Readonly() { var src = @" using System; readonly record struct C(int X, int Y) { readonly int Z = 345; public static void Main() { var c = new C(1, 2); Console.Write(c.X); Console.Write(c.Y); Console.Write(c.Z); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"12345").VerifyDiagnostics(); var c = verifier.Compilation.GlobalNamespace.GetTypeMember("C"); Assert.True(c.IsReadOnly); 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_01_ReadonlyMismatch() { var src = @" readonly record struct C(int X) { public int X { get; set; } = X; // 1 } record struct C2(int X) { public int X { get; init; } = X; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,16): error CS8341: Auto-implemented instance properties in readonly structs must be readonly. // public int X { get; set; } = X; // 1 Diagnostic(ErrorCode.ERR_AutoPropsInRoStruct, "X").WithLocation(4, 16) ); } [Fact] public void RecordProperties_02() { var src = @" using System; record struct 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 struct 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); } }"; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (3,15): error CS0843: Auto-implemented property 'C.X' must be fully assigned before control is returned to the caller. // record struct C(int X, int Y) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "C").WithArguments("C.X").WithLocation(3, 15), // (3,21): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 21) ); } [Fact] public void RecordProperties_03_InitializedWithY() { var src = @" using System; record struct C(int X, int Y) { public int X { get; } = Y; public static void Main() { var c = new C(1, 2); Console.Write(c.X); Console.Write(c.Y); } }"; CompileAndVerify(src, expectedOutput: "22") .VerifyDiagnostics( // (3,21): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 21) ); } [Fact] public void RecordProperties_04() { var src = @" using System; record struct C(int X, int Y) { public int X { get; } = 3; public static void Main() { var c = new C(1, 2); Console.Write(c.X); Console.Write(c.Y); } }"; CompileAndVerify(src, expectedOutput: "32") .VerifyDiagnostics( // (3,21): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 21) ); } [Fact] public void RecordProperties_05() { var src = @" record struct C(int X, int X) { }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,28): error CS0100: The parameter name 'X' is a duplicate // record struct C(int X, int X) Diagnostic(ErrorCode.ERR_DuplicateParamName, "X").WithArguments("X").WithLocation(2, 28), // (2,28): error CS0102: The type 'C' already contains a definition for 'X' // record struct C(int X, int X) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("C", "X").WithLocation(2, 28) ); var expectedMembers = new[] { "System.Int32 C.X { get; set; }", "System.Int32 C.X { get; set; }" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings()); var expectedMemberNames = new[] { ".ctor", "<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", "Deconstruct", ".ctor" }; AssertEx.Equal(expectedMemberNames, comp.GetMember<NamedTypeSymbol>("C").GetPublicSymbol().MemberNames); } [Fact] public void RecordProperties_06() { var src = @" record struct 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,21): error CS0082: Type 'C' already reserves a member called 'get_X' with the same parameter types // record struct C(int X, int Y) Diagnostic(ErrorCode.ERR_MemberReserved, "X").WithArguments("get_X", "C").WithLocation(2, 21), // (2,28): error CS0082: Type 'C' already reserves a member called 'set_Y' with the same parameter types // record struct C(int X, int Y) Diagnostic(ErrorCode.ERR_MemberReserved, "Y").WithArguments("set_Y", "C").WithLocation(2, 28) ); var actualMembers = comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "System.Int32 C.<X>k__BackingField", "readonly System.Int32 C.X.get", "void C.X.set", "System.Int32 C.X { get; set; }", "System.Int32 C.<Y>k__BackingField", "readonly System.Int32 C.Y.get", "void C.Y.set", "System.Int32 C.Y { get; set; }", "void C.get_X()", "void C.set_X()", "System.Int32 C.get_Y(System.Int32 value)", "System.Int32 C.set_Y(System.Int32 value)", "readonly System.String C.ToString()", "readonly System.Boolean C.PrintMembers(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C left, C right)", "System.Boolean C.op_Equality(C left, C right)", "readonly System.Int32 C.GetHashCode()", "readonly System.Boolean C.Equals(System.Object obj)", "readonly System.Boolean C.Equals(C other)", "readonly void C.Deconstruct(out System.Int32 X, out System.Int32 Y)", "C..ctor()", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void RecordProperties_07() { var comp = CreateCompilation(@" record struct C1(object P, object get_P); record struct C2(object get_P, object P);"); comp.VerifyDiagnostics( // (2,25): error CS0102: The type 'C1' already contains a definition for 'get_P' // record struct C1(object P, object get_P); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C1", "get_P").WithLocation(2, 25), // (3,39): error CS0102: The type 'C2' already contains a definition for 'get_P' // record struct C2(object get_P, object P); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C2", "get_P").WithLocation(3, 39) ); } [Fact] public void RecordProperties_08() { var comp = CreateCompilation(@" record struct C1(object O1) { public object O1 { get; } = O1; public object O2 { get; } = O1; }"); comp.VerifyDiagnostics(); } [Fact] public void RecordProperties_09() { var src = @" record struct 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(src); comp.VerifyDiagnostics( // (2,24): error CS0102: The type 'C' already contains a definition for 'P1' // record struct C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P1").WithArguments("C", "P1").WithLocation(2, 24), // (2,35): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record struct C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(2, 35), // (6,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(6, 9), // (7,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(7, 9) ); } [Fact] public void RecordProperties_10() { var src = @" record struct C(object P) { const int P = 4; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,24): error CS8866: Record member 'C.P' must be a readable instance property or field of type 'object' to match positional parameter 'P'. // record struct C(object P) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("C.P", "object", "P").WithLocation(2, 24), // (2,24): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record struct C(object P) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 24) ); } [Fact] public void RecordProperties_11_UnreadPositionalParameter() { var comp = CreateCompilation(@" record struct 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; } "); comp.VerifyDiagnostics( // (2,15): error CS0843: Auto-implemented property 'C1.O1' must be fully assigned before control is returned to the caller. // record struct C1(object O1, object O2, object O3) // 1, 2 Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "C1").WithArguments("C1.O1").WithLocation(2, 15), // (2,25): warning CS8907: Parameter 'O1' is unread. Did you forget to use it to initialize the property with that name? // record struct C1(object O1, object O2, object O3) // 1, 2 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O1").WithArguments("O1").WithLocation(2, 25), // (2,47): warning CS8907: Parameter 'O3' is unread. Did you forget to use it to initialize the property with that name? // record struct C1(object O1, object O2, object O3) // 1, 2 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O3").WithArguments("O3").WithLocation(2, 47) ); } [Fact] public void RecordProperties_11_UnreadPositionalParameter_InRefOut() { var comp = CreateCompilation(@" record struct 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,47): warning CS8907: Parameter 'O3' is unread. Did you forget to use it to initialize the property with that name? // record struct C1(object O1, object O2, object O3) // 1 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O3").WithArguments("O3").WithLocation(2, 47) ); } [Fact] public void RecordProperties_SelfContainedStruct() { var comp = CreateCompilation(@" record struct C(C c); "); comp.VerifyDiagnostics( // (2,19): error CS0523: Struct member 'C.c' of type 'C' causes a cycle in the struct layout // record struct C(C c); Diagnostic(ErrorCode.ERR_StructLayoutCycle, "c").WithArguments("C.c", "C").WithLocation(2, 19) ); } [Fact] public void RecordProperties_PropertyInValueType() { var corlib_cs = @" namespace System { public class Object { public virtual bool Equals(object x) => throw null; public virtual int GetHashCode() => throw null; public virtual string ToString() => throw null; } public class Exception { } public class ValueType { public bool X { get; set; } } public class Attribute { } public class String { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { } } namespace System.Collections.Generic { public abstract class EqualityComparer<T> { public static EqualityComparer<T> Default => throw null; public abstract int GetHashCode(T t); } } 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 corlibRef = CreateEmptyCompilation(corlib_cs).EmitToImageReference(); { var src = @" record struct C(bool X) { bool M() { return X; } } "; var comp = CreateEmptyCompilation(src, parseOptions: TestOptions.RegularPreview, references: new[] { corlibRef }); comp.VerifyEmitDiagnostics( // (2,22): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(bool X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 22) ); Assert.Null(comp.GlobalNamespace.GetTypeMember("C").GetMember("X")); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var x = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single().Expression; Assert.Equal("System.Boolean System.ValueType.X { get; set; }", model.GetSymbolInfo(x!).Symbol.ToTestDisplayString()); } { var src = @" readonly record struct C(bool X) { bool M() { return X; } } "; var comp = CreateEmptyCompilation(src, parseOptions: TestOptions.RegularPreview, references: new[] { corlibRef }); comp.VerifyEmitDiagnostics( // (2,31): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // readonly record struct C(bool X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 31) ); Assert.Null(comp.GlobalNamespace.GetTypeMember("C").GetMember("X")); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var x = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single().Expression; Assert.Equal("System.Boolean System.ValueType.X { get; set; }", model.GetSymbolInfo(x!).Symbol.ToTestDisplayString()); } } [Fact] public void RecordProperties_PropertyInValueType_Static() { var corlib_cs = @" namespace System { public class Object { public virtual bool Equals(object x) => throw null; public virtual int GetHashCode() => throw null; public virtual string ToString() => throw null; } public class Exception { } public class ValueType { public static bool X { get; set; } } public class Attribute { } public class String { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { } } namespace System.Collections.Generic { public abstract class EqualityComparer<T> { public static EqualityComparer<T> Default => throw null; public abstract int GetHashCode(T t); } } 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 corlibRef = CreateEmptyCompilation(corlib_cs).EmitToImageReference(); var src = @" record struct C(bool X) { bool M() { return X; } } "; var comp = CreateEmptyCompilation(src, parseOptions: TestOptions.RegularPreview, references: new[] { corlibRef }); comp.VerifyEmitDiagnostics( // (2,22): error CS8866: Record member 'System.ValueType.X' must be a readable instance property or field of type 'bool' to match positional parameter 'X'. // record struct C(bool X) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("System.ValueType.X", "bool", "X").WithLocation(2, 22), // (2,22): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(bool X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 22) ); } [Fact] 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 }, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "static ctor", verify: Verification.Skipped /* init-only */); } [Fact] public void StaticCtor_ParameterlessPrimaryCtor() { var src = @" record struct R(int I) { static R() { } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void StaticCtor_CopyCtor() { var src = @" record struct R(int I) { 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 InterfaceImplementation_NotReadonly() { var source = @" I r = new R(42); r.P2 = 43; r.P3 = 44; System.Console.Write((r.P1, r.P2, r.P3)); interface I { int P1 { get; set; } int P2 { get; set; } int P3 { get; set; } } record struct R(int P1) : I { public int P2 { get; set; } = 0; int I.P3 { get; set; } = 0; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "(42, 43, 44)"); } [Fact] public void InterfaceImplementation_NotReadonly_InitOnlyInterface() { var source = @" interface I { int P1 { get; init; } } record struct R(int P1) : I; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (6,27): error CS8854: 'R' does not implement interface member 'I.P1.init'. 'R.P1.set' cannot implement 'I.P1.init'. // record struct R(int P1) : I; Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("R", "I.P1.init", "R.P1.set").WithLocation(6, 27) ); } [Fact] public void InterfaceImplementation_Readonly() { var source = @" I r = new R(42) { P2 = 43 }; System.Console.Write((r.P1, r.P2)); interface I { int P1 { get; init; } int P2 { get; init; } } readonly record struct R(int P1) : I { public int P2 { get; init; } = 0; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "(42, 43)", verify: Verification.Skipped /* init-only */); } [Fact] public void InterfaceImplementation_Readonly_SetInterface() { var source = @" interface I { int P1 { get; set; } } readonly record struct R(int P1) : I; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (6,36): error CS8854: 'R' does not implement interface member 'I.P1.set'. 'R.P1.init' cannot implement 'I.P1.set'. // readonly record struct R(int P1) : I; Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("R", "I.P1.set", "R.P1.init").WithLocation(6, 36) ); } [Fact] public void InterfaceImplementation_Readonly_PrivateImplementation() { var source = @" I r = new R(42) { P2 = 43, P3 = 44 }; System.Console.Write((r.P1, r.P2, r.P3)); interface I { int P1 { get; init; } int P2 { get; init; } int P3 { get; init; } } readonly record struct R(int P1) : I { public int P2 { get; init; } = 0; int I.P3 { get; init; } = 0; // not practically initializable } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,28): error CS0117: 'R' does not contain a definition for 'P3' // I r = new R(42) { P2 = 43, P3 = 44 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "P3").WithArguments("R", "P3").WithLocation(2, 28) ); } [Fact] public void Initializers_01() { var src = @" using System; record struct 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 struct 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; set; }", 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 struct 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; set; }", 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 struct 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 SynthesizedRecordPointerProperty() { var src = @" record struct 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] public void PositionalMemberModifiers_In() { var src = @" var r = new R(42); int i = 43; var r2 = new R(in i); System.Console.Write((r.P1, r2.P1)); record struct R(in int P1); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "(42, 43)"); var actualMembers = comp.GetMember<NamedTypeSymbol>("R").Constructors.ToTestDisplayStrings(); var expectedMembers = new[] { "R..ctor(in System.Int32 P1)", "R..ctor()" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void PositionalMemberModifiers_Params() { var src = @" 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])); record struct R(params int[] Array); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "(42, 43, 44, 45)"); var actualMembers = comp.GetMember<NamedTypeSymbol>("R").Constructors.ToTestDisplayStrings(); var expectedMembers = new[] { "R..ctor(params System.Int32[] Array)", "R..ctor()" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void PositionalMemberDefaultValue() { var src = @" var r = new R(); // This uses the parameterless constructor System.Console.Write(r.P); record struct R(int P = 42); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "0"); } [Fact] public void PositionalMemberDefaultValue_PassingOneArgument() { var src = @" var r = new R(41); System.Console.Write(r.O); System.Console.Write("" ""); System.Console.Write(r.P); record struct R(int O, int P = 42); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "41 42"); } [Fact] public void PositionalMemberDefaultValue_AndPropertyWithInitializer() { var src = @" var r = new R(0); System.Console.Write(r.P); record struct R(int O, int P = 1) { public int P { get; init; } = 42; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,28): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record struct R(int O, int P = 1) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(5, 28) ); var verifier = CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("R..ctor(int, int)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int R.<O>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldc.i4.s 42 IL_000a: stfld ""int R.<P>k__BackingField"" IL_000f: ret }"); } [Fact] public void PositionalMemberDefaultValue_AndPropertyWithoutInitializer() { var src = @" record struct 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(src); comp.VerifyDiagnostics( // (2,15): error CS0843: Auto-implemented property 'R.P' must be fully assigned before control is returned to the caller. // record struct R(int P = 42) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "R").WithArguments("R.P").WithLocation(2, 15), // (2,21): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record struct R(int P = 42) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 21) ); } [Fact] public void PositionalMemberDefaultValue_AndPropertyWithInitializer_CopyingParameter() { var src = @" var r = new R(0); System.Console.Write(r.P); record struct R(int O, int P = 42) { public int P { get; init; } = P; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("R..ctor(int, int)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int R.<O>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.2 IL_0009: stfld ""int R.<P>k__BackingField"" IL_000e: ret }"); } [Fact] public void RecordWithConstraints_NullableWarning() { var src = @" #nullable enable var r = new R<string?>(""R""); var r2 = new R2<string?>(""R2""); System.Console.Write((r.P, r2.P)); record struct R<T>(T P) where T : class; record struct R2<T>(T P) where T : class { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,15): 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(3, 15), // (4,17): 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(4, 17) ); CompileAndVerify(comp, expectedOutput: "(R, R2)"); } [Fact] public void RecordWithConstraints_ConstraintError() { var src = @" record struct R<T>(T P) where T : class; record struct 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 CyclicBases4() { var text = @" record struct A<T> : B<A<T>> { } record struct B<T> : A<B<T>> { A<T> F() { return null; } } "; var comp = CreateCompilation(text); comp.GetDeclarationDiagnostics().Verify( // (3,22): error CS0527: Type 'A<B<T>>' in interface list is not an interface // record struct B<T> : A<B<T>> Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "A<B<T>>").WithArguments("A<B<T>>").WithLocation(3, 22), // (2,22): error CS0527: Type 'B<A<T>>' in interface list is not an interface // record struct A<T> : B<A<T>> { } Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "B<A<T>>").WithArguments("B<A<T>>").WithLocation(2, 22) ); } [Fact] public void PartialClassWithDifferentTupleNamesInImplementedInterfaces() { var source = @" public interface I<T> { } public partial record C1 : I<(int a, int b)> { } public partial record C1 : I<(int notA, int notB)> { } public partial record C2 : I<(int a, int b)> { } public partial record C2 : I<(int, int)> { } public partial record C3 : I<(int a, int b)> { } public partial record C3 : I<(int a, int b)> { } public partial record C4 : I<(int a, int b)> { } public partial record C4 : I<(int b, int a)> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,23): error CS8140: 'I<(int notA, int notB)>' is already listed in the interface list on type 'C1' with different tuple element names, as 'I<(int a, int b)>'. // public partial record C1 : I<(int a, int b)> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C1").WithArguments("I<(int notA, int notB)>", "I<(int a, int b)>", "C1").WithLocation(3, 23), // (6,23): error CS8140: 'I<(int, int)>' is already listed in the interface list on type 'C2' with different tuple element names, as 'I<(int a, int b)>'. // public partial record C2 : I<(int a, int b)> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C2").WithArguments("I<(int, int)>", "I<(int a, int b)>", "C2").WithLocation(6, 23), // (12,23): error CS8140: 'I<(int b, int a)>' is already listed in the interface list on type 'C4' with different tuple element names, as 'I<(int a, int b)>'. // public partial record C4 : I<(int a, int b)> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C4").WithArguments("I<(int b, int a)>", "I<(int a, int b)>", "C4").WithLocation(12, 23) ); } [Fact] public void CS0267ERR_PartialMisplaced() { var test = @" partial public record struct 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 record struct C // CS0267 Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(2, 1) ); } [Fact] public void SealedStaticRecord() { var source = @" sealed static record struct R; "; CreateCompilation(source).VerifyDiagnostics( // (2,29): error CS0106: The modifier 'sealed' is not valid for this item // sealed static record struct R; Diagnostic(ErrorCode.ERR_BadMemberFlag, "R").WithArguments("sealed").WithLocation(2, 29), // (2,29): error CS0106: The modifier 'static' is not valid for this item // sealed static record struct R; Diagnostic(ErrorCode.ERR_BadMemberFlag, "R").WithArguments("static").WithLocation(2, 29) ); } [Fact] public void CS0513ERR_AbstractInConcreteClass02() { var text = @" record struct C { public abstract event System.Action E; public abstract int this[int x] { get; set; } } "; CreateCompilation(text).VerifyDiagnostics( // (5,25): error CS0106: The modifier 'abstract' is not valid for this item // public abstract int this[int x] { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("abstract").WithLocation(5, 25), // (4,41): error CS0106: The modifier 'abstract' is not valid for this item // public abstract event System.Action E; Diagnostic(ErrorCode.ERR_BadMemberFlag, "E").WithArguments("abstract").WithLocation(4, 41) ); } [Fact] public void CS0574ERR_BadDestructorName() { var test = @" public record struct iii { ~iiii(){} } "; CreateCompilation(test).VerifyDiagnostics( // (4,6): error CS0574: Name of destructor must match name of type // ~iiii(){} Diagnostic(ErrorCode.ERR_BadDestructorName, "iiii").WithLocation(4, 6), // (4,6): error CS0575: Only class types can contain destructors // ~iiii(){} Diagnostic(ErrorCode.ERR_OnlyClassesCanContainDestructors, "iiii").WithArguments("iii.~iii()").WithLocation(4, 6) ); } [Fact] public void StaticRecordWithConstructorAndDestructor() { var text = @" static record struct R(int I) { public R() : this(0) { } ~R() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (2,22): error CS0106: The modifier 'static' is not valid for this item // static record struct R(int I) Diagnostic(ErrorCode.ERR_BadMemberFlag, "R").WithArguments("static").WithLocation(2, 22), // (5,6): error CS0575: Only class types can contain destructors // ~R() { } Diagnostic(ErrorCode.ERR_OnlyClassesCanContainDestructors, "R").WithArguments("R.~R()").WithLocation(5, 6) ); } [Fact] public void RecordWithPartialMethodExplicitImplementation() { var source = @"record struct 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 RecordWithPartialMethodRequiringBody() { var source = @"partial record struct R { public partial int M(); }"; CreateCompilation(source).VerifyDiagnostics( // (3,24): error CS8795: Partial method 'R.M()' must have an implementation part because it has accessibility modifiers. // public partial int M(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "M").WithArguments("R.M()").WithLocation(3, 24) ); } [Fact] public void CanDeclareIteratorInRecord() { var source = @" using System.Collections.Generic; foreach(var i in new X(42).GetItems()) { System.Console.Write(i); } public record struct X(int a) { public IEnumerable<int> GetItems() { yield return a; yield return a + 1; } }"; var comp = CreateCompilation(source).VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "4243"); } [Fact] public void ParameterlessConstructor() { var src = @" System.Console.Write(new C().Property); record struct C() { public int Property { get; set; } = 42; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "42"); } [Fact] public void XmlDoc() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public record struct 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] public void XmlDoc_Cref() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for <see cref=""I1""/></param> public record struct 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] public void Deconstruct_Simple() { var source = @"using System; record struct 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 ""readonly int B.X.get"" IL_0007: stind.i4 IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: call ""readonly 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 struct B(int X) { public int Y { get; init; } = 0; 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( "readonly 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 struct B(int X, int Y); record struct 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 ""readonly int B.X.get"" IL_0007: stind.i4 IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: call ""readonly int B.Y.get"" IL_000f: stind.i4 IL_0010: ret }"); verifier.VerifyIL("C.Deconstruct", @" { // Code size 21 (0x15) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""readonly B C.B.get"" IL_0007: stobj ""B"" IL_000c: ldarg.2 IL_000d: ldarg.0 IL_000e: call ""readonly int C.Z.get"" IL_0013: stind.i4 IL_0014: ret }"); } [Fact] public void Deconstruct_PropertyCollision() { var source = @"using System; record struct 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,21): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct B(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 21) ); 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 struct 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( "readonly void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_FieldCollision() { var source = @" using System; record struct C(int X) { int X = 0; 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); comp.VerifyDiagnostics( // (4,21): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(int X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(4, 21), // (6,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(6, 9)); Assert.Equal( "readonly void C.Deconstruct(out System.Int32 X)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Empty() { var source = @" record struct 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_Conversion_02() { var source = @" #nullable enable using System; record struct C(string? X, string Y) { public string X { get; init; } = null!; public string? Y { get; init; } = string.Empty; 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,25): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(string? X, string Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(5, 25), // (5,35): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record struct C(string? X, string Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(5, 35) ); Assert.Equal( "readonly void C.Deconstruct(out System.String? X, out System.String Y)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Empty_WithParameterList() { var source = @" record struct 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)); AssertEx.Equal(new[] { "C..ctor()", "void C.M(C c)", "void C.Main()", "readonly System.String C.ToString()", "readonly System.Boolean C.PrintMembers(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C left, C right)", "System.Boolean C.op_Equality(C left, C right)", "readonly System.Int32 C.GetHashCode()", "readonly System.Boolean C.Equals(System.Object obj)", "readonly System.Boolean C.Equals(C other)" }, comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings()); } [Fact] public void Deconstruct_Empty_WithParameterList_UserDefined_01() { var source = @"using System; record struct C(int I) { public void Deconstruct() { } static void M(C c) { switch (c) { case C(): Console.Write(12); break; } } public static void Main() { M(new C(42)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); } [Fact] public void Deconstruct_GeneratedAsReadOnly() { var src = @" record struct A(int I, string S); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var method = comp.GetMember<SynthesizedRecordDeconstruct>("A.Deconstruct"); Assert.True(method.IsDeclaredReadOnly); } [Fact] public void Deconstruct_WihtNonReadOnlyGetter_GeneratedAsNonReadOnly() { var src = @" record struct A(int I, string S) { public int I { get => 0; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,21): warning CS8907: Parameter 'I' is unread. Did you forget to use it to initialize the property with that name? // record struct A(int I, string S) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "I").WithArguments("I").WithLocation(2, 21)); var method = comp.GetMember<SynthesizedRecordDeconstruct>("A.Deconstruct"); Assert.False(method.IsDeclaredReadOnly); } [Fact] public void Deconstruct_UserDefined() { var source = @"using System; record struct 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_02() { var source = @"using System; record struct 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)); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("internal")] public void Deconstruct_UserDefined_Accessibility_07(string accessibility) { var source = $@" record struct 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 struct 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 OutVarInPositionalParameterDefaultValue() { var source = @" record struct A(int X = A.M(out int a) + a) { public static int M(out int a) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,25): error CS1736: Default parameter value for 'X' must be a compile-time constant // record struct A(int X = A.M(out int a) + a) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "A.M(out int a) + a").WithArguments("X").WithLocation(2, 25) ); } [Fact] public void FieldConsideredUnassignedIfInitializationViaProperty() { var source = @" record struct Pos(int X) { private int x; public int X { get { return x; } set { x = value; } } = X; } record struct Pos2(int X) { private int x = X; // value isn't validated by setter public int X { get { return x; } set { x = value; } } } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,15): error CS0171: Field 'Pos.x' must be fully assigned before control is returned to the caller // record struct Pos(int X) Diagnostic(ErrorCode.ERR_UnassignedThis, "Pos").WithArguments("Pos.x").WithLocation(2, 15), // (5,16): error CS8050: Only auto-implemented properties can have initializers. // public int X { get { return x; } set { x = value; } } = X; Diagnostic(ErrorCode.ERR_InitializerOnNonAutoProperty, "X").WithArguments("Pos.X").WithLocation(5, 16) ); } [Fact] public void IEquatableT_01() { var source = @"record struct A<T>; class Program { static void F<T>(System.IEquatable<T> t) { } static void M<T>() { F(new A<T>()); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( ); } [Fact] public void IEquatableT_02() { var source = @"using System; record struct A; record struct B<T>; class Program { static bool F<T>(IEquatable<T> t, T t2) { return t.Equals(t2); } static void Main() { Console.Write(F(new A(), new A())); Console.Write(F(new B<int>(), new B<int>())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "TrueTrue").VerifyDiagnostics(); } [Fact] public void IEquatableT_02_ImplicitImplementation() { var source = @"using System; record struct A { public bool Equals(A other) { System.Console.Write(""A.Equals(A) ""); return false; } } record struct B<T> { public bool Equals(B<T> other) { System.Console.Write(""B.Equals(B) ""); return true; } } class Program { static bool F<T>(IEquatable<T> t, T t2) { return t.Equals(t2); } static void Main() { Console.Write(F(new A(), new A())); Console.Write("" ""); Console.Write(F(new B<int>(), new B<int>())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "A.Equals(A) False B.Equals(B) True").VerifyDiagnostics( // (4,17): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public bool Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 17), // (12,17): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public bool Equals(B<T> other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(12, 17) ); } [Fact] public void IEquatableT_02_ExplicitImplementation() { var source = @"using System; record struct A { bool IEquatable<A>.Equals(A other) { System.Console.Write(""A.Equals(A) ""); return false; } } record struct B<T> { bool IEquatable<B<T>>.Equals(B<T> other) { System.Console.Write(""B.Equals(B) ""); return true; } } class Program { static bool F<T>(IEquatable<T> t, T t2) { return t.Equals(t2); } static void Main() { Console.Write(F(new A(), new A())); Console.Write("" ""); Console.Write(F(new B<int>(), new B<int>())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "A.Equals(A) False B.Equals(B) True").VerifyDiagnostics(); } [Fact] public void IEquatableT_03() { var source = @" record struct A<T> : System.IEquatable<A<T>>; "; 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()); } [Fact] public void IEquatableT_MissingIEquatable() { var source = @" record struct A<T>; "; var comp = CreateCompilation(source); comp.MakeTypeMissing(WellKnownType.System_IEquatable_T); comp.VerifyEmitDiagnostics( // (2,15): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record struct A<T>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record struct A<T>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(2, 15) ); 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()); } [Fact] public void RecordEquals_01() { var source = @" var a1 = new B(); var a2 = new B(); System.Console.WriteLine(a1.Equals(a2)); record struct B { public bool Equals(B other) { System.Console.WriteLine(""B.Equals(B)""); return false; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,17): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public bool Equals(B other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(8, 17) ); CompileAndVerify(comp, expectedOutput: @" B.Equals(B) False "); } [Fact] public void RecordEquals_01_NoInParameters() { var source = @" var a1 = new B(); var a2 = new B(); System.Console.WriteLine(a1.Equals(in a2)); record struct B; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,39): error CS1615: Argument 1 may not be passed with the 'in' keyword // System.Console.WriteLine(a1.Equals(in a2)); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "a2").WithArguments("1", "in").WithLocation(4, 39) ); } [Theory] [InlineData("protected")] [InlineData("private protected")] [InlineData("internal protected")] public void RecordEquals_10(string accessibility) { var source = $@" record struct A {{ { accessibility } bool Equals(A x) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; }} "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,29): error CS0666: 'A.Equals(A)': new protected member declared in struct // internal protected bool Equals(A x) Diagnostic(ErrorCode.ERR_ProtectedInStruct, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 11 + accessibility.Length), // (4,29): error CS8873: Record member 'A.Equals(A)' must be public. // internal protected bool Equals(A x) Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 11 + accessibility.Length), // (4,29): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // internal protected bool Equals(A x) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 11 + accessibility.Length) ); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("internal")] public void RecordEquals_11(string accessibility) { var source = $@" record struct A {{ { accessibility } bool Equals(A x) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; }} "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,...): error CS8873: Record member 'A.Equals(A)' must be public. // { accessibility } bool Equals(A x) Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 11 + accessibility.Length), // (4,11): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // bool Equals(A x) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 11 + accessibility.Length) ); } [Fact] public void RecordEquals_12() { var source = @" A a1 = new A(); A a2 = new A(); System.Console.Write(a1.Equals(a2)); System.Console.Write(a1.Equals((object)a2)); record struct A { public bool Equals(B other) => throw null; } class B { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "TrueTrue"); verifier.VerifyIL("A.Equals(A)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret }"); verifier.VerifyIL("A.Equals(object)", @" { // Code size 23 (0x17) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""A"" IL_0006: brfalse.s IL_0015 IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: unbox.any ""A"" IL_000f: call ""readonly bool A.Equals(A)"" IL_0014: ret IL_0015: ldc.i4.0 IL_0016: ret }"); verifier.VerifyIL("A.GetHashCode()", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret }"); var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("readonly 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); var objectEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordObjEquals>().Single(); Assert.Equal("readonly System.Boolean A.Equals(System.Object obj)", objectEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, objectEquals.DeclaredAccessibility); Assert.False(objectEquals.IsAbstract); Assert.False(objectEquals.IsVirtual); Assert.True(objectEquals.IsOverride); Assert.False(objectEquals.IsSealed); Assert.True(objectEquals.IsImplicitlyDeclared); MethodSymbol gethashCode = comp.GetMembers("A." + WellKnownMemberNames.ObjectGetHashCode).OfType<SynthesizedRecordGetHashCode>().Single(); Assert.Equal("readonly System.Int32 A.GetHashCode()", gethashCode.ToTestDisplayString()); Assert.Equal(Accessibility.Public, gethashCode.DeclaredAccessibility); Assert.False(gethashCode.IsStatic); Assert.False(gethashCode.IsAbstract); Assert.False(gethashCode.IsVirtual); Assert.True(gethashCode.IsOverride); Assert.False(gethashCode.IsSealed); Assert.True(gethashCode.IsImplicitlyDeclared); } [Fact] public void RecordEquals_13() { var source = @" record struct A { public int Equals(A other) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,16): error CS8874: Record member 'A.Equals(A)' must return 'bool'. // public int Equals(A other) Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "Equals").WithArguments("A.Equals(A)", "bool").WithLocation(4, 16), // (4,16): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public int Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 16) ); } [Fact] public void RecordEquals_14() { var source = @" record struct A { public bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; } "; var comp = CreateCompilation(source); comp.MakeTypeMissing(SpecialType.System_Boolean); comp.VerifyEmitDiagnostics( // (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record struct A { public 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 struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record struct A { public bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; }").WithArguments("System.Boolean").WithLocation(2, 1), // (2,15): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 15), // (4,12): error CS0518: Predefined type 'System.Boolean' is not defined or imported // public bool Equals(A other) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "bool").WithArguments("System.Boolean").WithLocation(4, 12), // (4,17): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public bool Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 17) ); } [Fact] public void RecordEquals_19() { var source = @" record struct A { public static bool Equals(A x) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,15): error CS0736: 'A' does not implement interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement an interface member because it is static. // record struct 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 RecordEquals_RecordEqualsInValueType() { var src = @" public record struct A; namespace System { public class Object { public virtual bool Equals(object x) => throw null; public virtual int GetHashCode() => throw null; public virtual string ToString() => throw null; } public class Exception { } public class ValueType { public bool Equals(A x) => throw null; } public class Attribute { } public class String { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { } } namespace System.Collections.Generic { public abstract class EqualityComparer<T> { public static EqualityComparer<T> Default => throw null; public abstract int GetHashCode(T t); } } 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(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1) ); var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("readonly System.Boolean A.Equals(A other)", recordEquals.ToTestDisplayString()); } [Fact] public void RecordEquals_FourFields() { var source = @" A a1 = new A(1, ""hello""); System.Console.Write(a1.Equals(a1)); System.Console.Write(a1.Equals((object)a1)); System.Console.Write("" - ""); A a2 = new A(1, ""hello"") { fieldI = 100 }; System.Console.Write(a1.Equals(a2)); System.Console.Write(a1.Equals((object)a2)); System.Console.Write(a2.Equals(a1)); System.Console.Write(a2.Equals((object)a1)); System.Console.Write("" - ""); A a3 = new A(1, ""world""); System.Console.Write(a1.Equals(a3)); System.Console.Write(a1.Equals((object)a3)); System.Console.Write(a3.Equals(a1)); System.Console.Write(a3.Equals((object)a1)); record struct A(int I, string S) { public int fieldI = 42; public string fieldS = ""hello""; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "TrueTrue - FalseFalseFalseFalse - FalseFalseFalseFalse"); verifier.VerifyIL("A.Equals(A)", @" { // Code size 97 (0x61) .maxstack 3 IL_0000: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0005: ldarg.0 IL_0006: ldfld ""int A.<I>k__BackingField"" IL_000b: ldarg.1 IL_000c: ldfld ""int A.<I>k__BackingField"" IL_0011: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0016: brfalse.s IL_005f IL_0018: call ""System.Collections.Generic.EqualityComparer<string> System.Collections.Generic.EqualityComparer<string>.Default.get"" IL_001d: ldarg.0 IL_001e: ldfld ""string A.<S>k__BackingField"" IL_0023: ldarg.1 IL_0024: ldfld ""string A.<S>k__BackingField"" IL_0029: callvirt ""bool System.Collections.Generic.EqualityComparer<string>.Equals(string, string)"" IL_002e: brfalse.s IL_005f IL_0030: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0035: ldarg.0 IL_0036: ldfld ""int A.fieldI"" IL_003b: ldarg.1 IL_003c: ldfld ""int A.fieldI"" IL_0041: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0046: brfalse.s IL_005f IL_0048: call ""System.Collections.Generic.EqualityComparer<string> System.Collections.Generic.EqualityComparer<string>.Default.get"" IL_004d: ldarg.0 IL_004e: ldfld ""string A.fieldS"" IL_0053: ldarg.1 IL_0054: ldfld ""string A.fieldS"" IL_0059: callvirt ""bool System.Collections.Generic.EqualityComparer<string>.Equals(string, string)"" IL_005e: ret IL_005f: ldc.i4.0 IL_0060: ret }"); verifier.VerifyIL("A.Equals(object)", @" { // Code size 23 (0x17) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""A"" IL_0006: brfalse.s IL_0015 IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: unbox.any ""A"" IL_000f: call ""readonly bool A.Equals(A)"" IL_0014: ret IL_0015: ldc.i4.0 IL_0016: ret }"); verifier.VerifyIL("A.GetHashCode()", @" { // Code size 86 (0x56) .maxstack 3 IL_0000: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0005: ldarg.0 IL_0006: ldfld ""int A.<I>k__BackingField"" IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<int>.GetHashCode(int)"" IL_0010: ldc.i4 0xa5555529 IL_0015: mul IL_0016: call ""System.Collections.Generic.EqualityComparer<string> System.Collections.Generic.EqualityComparer<string>.Default.get"" IL_001b: ldarg.0 IL_001c: ldfld ""string A.<S>k__BackingField"" IL_0021: callvirt ""int System.Collections.Generic.EqualityComparer<string>.GetHashCode(string)"" IL_0026: add IL_0027: ldc.i4 0xa5555529 IL_002c: mul IL_002d: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0032: ldarg.0 IL_0033: ldfld ""int A.fieldI"" IL_0038: callvirt ""int System.Collections.Generic.EqualityComparer<int>.GetHashCode(int)"" IL_003d: add IL_003e: ldc.i4 0xa5555529 IL_0043: mul IL_0044: call ""System.Collections.Generic.EqualityComparer<string> System.Collections.Generic.EqualityComparer<string>.Default.get"" IL_0049: ldarg.0 IL_004a: ldfld ""string A.fieldS"" IL_004f: callvirt ""int System.Collections.Generic.EqualityComparer<string>.GetHashCode(string)"" IL_0054: add IL_0055: ret }"); } [Fact] public void RecordEquals_StaticField() { var source = @" record struct A { public static int field = 42; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp); verifier.VerifyIL("A.Equals(A)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret }"); verifier.VerifyIL("A.GetHashCode()", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret }"); } [Fact] public void RecordEquals_GeneratedAsReadOnly() { var src = @" record struct A(int I, string S); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.True(recordEquals.IsDeclaredReadOnly); } [Fact] public void ObjectEquals_06() { var source = @" record struct A { public static new bool Equals(object obj) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,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(4, 28) ); } [Fact] public void ObjectEquals_UserDefined() { var source = @" record struct A { public override bool Equals(object obj) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,26): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types // public override bool Equals(object obj) => throw null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(4, 26) ); } [Fact] public void ObjectEquals_GeneratedAsReadOnly() { var src = @" record struct A(int I, string S); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var objectEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordObjEquals>().Single(); Assert.True(objectEquals.IsDeclaredReadOnly); } [Fact] public void GetHashCode_UserDefined() { var source = @" System.Console.Write(new A().GetHashCode()); record struct A { public override int GetHashCode() => 42; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "42"); } [Fact] public void GetHashCode_GetHashCodeInValueType() { var src = @" public record struct A; namespace System { public class Object { public virtual bool Equals(object x) => throw null; public virtual string ToString() => throw null; } public class Exception { } public class ValueType { public virtual int GetHashCode() => throw null; } public class Attribute { } public class String { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { } } namespace System.Collections.Generic { public abstract class EqualityComparer<T> { public static EqualityComparer<T> Default => throw null; public abstract int GetHashCode(T t); } } 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(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1), // (2,22): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'. // public record struct A; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "A").WithArguments("A.GetHashCode()").WithLocation(2, 22) ); } [Fact] public void GetHashCode_MissingEqualityComparer_EmptyRecord() { var src = @" public record struct A; "; var comp = CreateCompilation(src); comp.MakeTypeMissing(WellKnownType.System_Collections_Generic_EqualityComparer_T); comp.VerifyEmitDiagnostics(); } [Fact] public void GetHashCode_MissingEqualityComparer_NonEmptyRecord() { var src = @" public record struct A(int I); "; var comp = CreateCompilation(src); comp.MakeTypeMissing(WellKnownType.System_Collections_Generic_EqualityComparer_T); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.GetHashCode' // public record struct A(int I); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "public record struct A(int I);").WithArguments("System.Collections.Generic.EqualityComparer`1", "GetHashCode").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.get_Default' // public record struct A(int I); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "public record struct A(int I);").WithArguments("System.Collections.Generic.EqualityComparer`1", "get_Default").WithLocation(2, 1) ); } [Fact] public void GetHashCode_GeneratedAsReadOnly() { var src = @" record struct A(int I, string S); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var method = comp.GetMember<SynthesizedRecordGetHashCode>("A.GetHashCode"); Assert.True(method.IsDeclaredReadOnly); } [Fact] public void GetHashCodeIsDefinedButEqualsIsNot() { var src = @" public record struct C { public object Data; public override int GetHashCode() { return 0; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void EqualsIsDefinedButGetHashCodeIsNot() { var src = @" public record struct 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] public void EqualityOperators_01() { var source = @" record struct A(int X) { public bool Equals(ref A other) => throw null; static void Main() { Test(default, default); Test(default, 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); } static void Test(A a1, A a2) { System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == a2, a2 == a1, a1 != a2, a2 != a1); } } "; var verifier = CompileAndVerify(source, expectedOutput: @" True True False False True True False False 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 9 (0x9) .maxstack 2 IL_0000: ldarga.s V_0 IL_0002: ldarg.1 IL_0003: call ""readonly bool A.Equals(A)"" IL_0008: 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 struct 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 struct 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 struct 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 struct 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 struct A { public static bool Equals(A other) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,15): error CS0736: 'A' does not implement interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement an interface member because it is static. // record struct 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 other) 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 other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24) ); } [Theory] [CombinatorialData] public void EqualityOperators_09(bool useImageReference) { var source1 = @" public record struct A(int X); "; var comp1 = CreateCompilation(source1); var source2 = @" class Program { static void Main() { Test(default, default); Test(default, 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 True True False False True True False False False False True True ").VerifyDiagnostics(); } [Fact] public void GetSimpleNonTypeMembers_DirectApiCheck() { var src = @" public record struct 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] public void ToString_NestedRecord() { var src = @" var c1 = new Outer.C1(42); System.Console.Write(c1.ToString()); public class Outer { public record struct C1(int I1); } "; var compDebug = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); var compRelease = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(compDebug, expectedOutput: "C1 { I1 = 42 }"); compDebug.VerifyEmitDiagnostics(); CompileAndVerify(compRelease, expectedOutput: "C1 { I1 = 42 }"); compRelease.VerifyEmitDiagnostics(); } [Fact] public void ToString_TopLevelRecord_Empty() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record struct C1; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); var v = 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); 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: call ""readonly 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_MissingStringBuilder() { var src = @" record struct 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 struct C1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "record struct C1;").WithArguments("System.Text.StringBuilder").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder..ctor' // record struct C1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record struct C1;").WithArguments("System.Text.StringBuilder", ".ctor").WithLocation(2, 1), // (2,15): error CS0518: Predefined type 'System.Text.StringBuilder' is not defined or imported // record struct C1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "C1").WithArguments("System.Text.StringBuilder").WithLocation(2, 15) ); } [Fact] public void ToString_TopLevelRecord_MissingStringBuilderCtor() { var src = @" record struct 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 struct C1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record struct C1;").WithArguments("System.Text.StringBuilder", ".ctor").WithLocation(2, 1) ); } [Fact] public void ToString_TopLevelRecord_MissingStringBuilderAppendString() { var src = @" record struct 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 struct C1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record struct C1;").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1) ); } [Fact] public void ToString_TopLevelRecord_OneProperty_MissingStringBuilderAppendString() { var src = @" record struct 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 struct C1(int P); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record struct C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record struct C1(int P); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record struct C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1) ); } [Fact] public void ToString_RecordWithIndexer() { var src = @" var c1 = new C1(42); System.Console.Write(c1.ToString()); record struct C1(int I1) { private int field = 44; public int this[int i] => 0; public int PropertyWithoutGetter { set { } } public int P2 { get => 43; } public event System.Action a = null; private int field1 = 100; internal int field2 = 100; private int Property1 { get; set; } = 100; internal int Property2 { get; set; } = 100; } "; var comp = CreateCompilation(src); CompileAndVerify(comp, expectedOutput: "C1 { I1 = 42, P2 = 43 }"); comp.VerifyEmitDiagnostics( // (7,17): warning CS0414: The field 'C1.field' is assigned but its value is never used // private int field = 44; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field").WithArguments("C1.field").WithLocation(7, 17), // (11,32): warning CS0414: The field 'C1.a' is assigned but its value is never used // public event System.Action a = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "a").WithArguments("C1.a").WithLocation(11, 32), // (13,17): warning CS0414: The field 'C1.field1' is assigned but its value is never used // private int field1 = 100; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field1").WithArguments("C1.field1").WithLocation(13, 17) ); } [Fact] public void ToString_PrivateGetter() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record struct C1 { public int P1 { private get => 43; set => throw null; } } "; var comp = CreateCompilation(src); CompileAndVerify(comp, expectedOutput: "C1 { P1 = 43 }"); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_TopLevelRecord_OneField_ValueType() { var src = @" var c1 = new C1() { field = 42 }; System.Console.Write(c1.ToString()); record struct C1 { public int field; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = 42 }"); 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); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 38 (0x26) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldstr ""field = "" 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 ""int C1.field"" IL_0013: constrained. ""int"" 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] public void ToString_TopLevelRecord_OneField_ConstrainedValueType() { var src = @" var c1 = new C1<int>() { field = 42 }; System.Console.Write(c1.ToString()); record struct C1<T> where T : struct { public T field; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = 42 }"); v.VerifyIL("C1<T>." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 41 (0x29) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.1 IL_0001: ldstr ""field = "" IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_000b: pop IL_000c: ldarg.1 IL_000d: ldarg.0 IL_000e: ldfld ""T C1<T>.field"" IL_0013: stloc.0 IL_0014: ldloca.s V_0 IL_0016: constrained. ""T"" IL_001c: callvirt ""string object.ToString()"" IL_0021: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0026: pop IL_0027: ldc.i4.1 IL_0028: ret } "); } [Fact] public void ToString_TopLevelRecord_OneField_ReferenceType() { var src = @" var c1 = new C1() { field = ""hello"" }; System.Console.Write(c1.ToString()); record struct C1 { public string field; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = hello }"); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 27 (0x1b) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldstr ""field = "" IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_000b: pop IL_000c: ldarg.1 IL_000d: ldarg.0 IL_000e: ldfld ""string C1.field"" IL_0013: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_0018: pop IL_0019: ldc.i4.1 IL_001a: ret } "); } [Fact] public void ToString_TopLevelRecord_TwoFields_ReferenceType() { var src = @" var c1 = new C1(42) { field1 = ""hi"", field2 = null }; System.Console.Write(c1.ToString()); record struct C1(int I) { public string field1 = null; public string field2 = null; private string field3 = null; internal string field4 = null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (10,20): warning CS0414: The field 'C1.field3' is assigned but its value is never used // private string field3 = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field3").WithArguments("C1.field3").WithLocation(10, 20) ); var v = CompileAndVerify(comp, expectedOutput: "C1 { I = 42, field1 = hi, field2 = }"); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 91 (0x5b) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldstr ""I = "" IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_000b: pop IL_000c: ldarg.1 IL_000d: ldarg.0 IL_000e: call ""readonly int C1.I.get"" IL_0013: stloc.0 IL_0014: ldloca.s V_0 IL_0016: constrained. ""int"" IL_001c: callvirt ""string object.ToString()"" IL_0021: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0026: pop IL_0027: ldarg.1 IL_0028: ldstr "", field1 = "" IL_002d: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0032: pop IL_0033: ldarg.1 IL_0034: ldarg.0 IL_0035: ldfld ""string C1.field1"" IL_003a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_003f: pop IL_0040: ldarg.1 IL_0041: ldstr "", field2 = "" IL_0046: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_004b: pop IL_004c: ldarg.1 IL_004d: ldarg.0 IL_004e: ldfld ""string C1.field2"" IL_0053: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_0058: pop IL_0059: ldc.i4.1 IL_005a: ret } "); } [Fact] public void ToString_TopLevelRecord_Readonly() { var src = @" var c1 = new C1(42); System.Console.Write(c1.ToString()); readonly record struct C1(int I); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { I = 42 }", verify: Verification.Skipped /* init-only */); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 41 (0x29) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldstr ""I = "" IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_000b: pop IL_000c: ldarg.1 IL_000d: ldarg.0 IL_000e: call ""int C1.I.get"" IL_0013: stloc.0 IL_0014: ldloca.s V_0 IL_0016: constrained. ""int"" IL_001c: callvirt ""string object.ToString()"" IL_0021: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0026: pop IL_0027: ldc.i4.1 IL_0028: 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: call ""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_UserDefinedToString() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record struct C1 { public override string ToString() => ""RAN""; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal("readonly System.Boolean C1." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", print.ToTestDisplayString()); } [Fact] public void ToString_TopLevelRecord_UserDefinedToString_New() { var src = @" record struct C1 { public new string ToString() => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,23): error CS8869: 'C1.ToString()' does not override expected method from 'object'. // public new string ToString() => throw null; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "ToString").WithArguments("C1.ToString()").WithLocation(4, 23) ); } [Fact] public void ToString_TopLevelRecord_UserDefinedToString_Sealed() { var src = @" record struct C1 { public sealed override string ToString() => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,35): error CS0106: The modifier 'sealed' is not valid for this item // public sealed override string ToString() => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "ToString").WithArguments("sealed").WithLocation(4, 35) ); } [Fact] public void ToString_UserDefinedPrintMembers_WithNullableStringBuilder() { var src = @" #nullable enable record struct C1 { private bool PrintMembers(System.Text.StringBuilder? builder) => throw null!; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_UserDefinedPrintMembers_ErrorReturnType() { var src = @" record struct C1 { private Error PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,13): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?) // private Error PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(4, 13) ); } [Fact] public void ToString_UserDefinedPrintMembers_WrongReturnType() { var src = @" record struct C1 { private int PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,17): error CS8874: Record member 'C1.PrintMembers(StringBuilder)' must return 'bool'. // private int PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)", "bool").WithLocation(4, 17) ); } [Fact] public void ToString_UserDefinedPrintMembers() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); System.Console.Write("" - ""); c1.M(); record struct C1 { private bool PrintMembers(System.Text.StringBuilder builder) { builder.Append(""RAN""); return true; } public void M() { var builder = new System.Text.StringBuilder(); if (PrintMembers(builder)) { System.Console.Write(builder.ToString()); } } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { RAN } - RAN"); } [Fact] public void ToString_CallingSynthesizedPrintMembers() { var src = @" var c1 = new C1(1, 2, 3); System.Console.Write(c1.ToString()); System.Console.Write("" - ""); c1.M(); record struct C1(int I, int I2, int I3) { public void M() { var builder = new System.Text.StringBuilder(); if (PrintMembers(builder)) { System.Console.Write(builder.ToString()); } } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { I = 1, I2 = 2, I3 = 3 } - I = 1, I2 = 2, I3 = 3"); } [Fact] public void ToString_UserDefinedPrintMembers_WrongAccessibility() { var src = @" var c = new C1(); System.Console.Write(c.ToString()); record struct C1 { internal bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (7,19): error CS8879: Record member 'C1.PrintMembers(StringBuilder)' must be private. // internal bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_NonPrivateAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(7, 19) ); } [Fact] public void ToString_UserDefinedPrintMembers_Static() { var src = @" record struct C1 { static private bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,25): error CS8877: Record member 'C1.PrintMembers(StringBuilder)' may not be static. // static private bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 25) ); } [Fact] public void ToString_GeneratedAsReadOnly() { var src = @" record struct A(int I, string S); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var method = comp.GetMember<SynthesizedRecordToString>("A.ToString"); Assert.True(method.IsDeclaredReadOnly); } [Fact] public void ToString_WihtNonReadOnlyGetter_GeneratedAsNonReadOnly() { var src = @" record struct A(int I, string S) { public double T => 0.1; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var method = comp.GetMember<SynthesizedRecordToString>("A.ToString"); Assert.False(method.IsDeclaredReadOnly); } [Fact] public void AmbigCtor_WithPropertyInitializer() { // Scenario causes ambiguous ctor for record class, but not record struct var src = @" record struct R(R X) { public R X { get; init; } = X; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,14): error CS0523: Struct member 'R.X' of type 'R' causes a cycle in the struct layout // public R X { get; init; } = X; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "X").WithArguments("R.X", "R").WithLocation(4, 14) ); 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()); var src2 = @" record struct R(R X); "; var comp2 = CreateCompilation(src2); comp2.VerifyEmitDiagnostics( // (2,19): error CS0523: Struct member 'R.X' of type 'R' causes a cycle in the struct layout // record struct R(R X); Diagnostic(ErrorCode.ERR_StructLayoutCycle, "X").WithArguments("R.X", "R").WithLocation(2, 19) ); } [Fact] public void GetDeclaredSymbolOnAnOutLocalInPropertyInitializer() { var src = @" record struct R(int I) { public int I { get; init; } = M(out int i); static int M(out int i) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,21): warning CS8907: Parameter 'I' is unread. Did you forget to use it to initialize the property with that name? // record struct R(int I) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "I").WithArguments("I").WithLocation(2, 21) ); 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] public void AnalyzerActions_01() { // Test RegisterSyntaxNodeAction var text1 = @" record struct A([Attr1]int X = 0) : I1 { private int M() => 3; A(string S) : this(4) => throw null; } interface I1 {} class Attr1 : 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.FireCountRecordStructDeclarationA); Assert.Equal(1, analyzer.FireCountRecordStructDeclarationACtor); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCountSimpleBaseTypeI1onA); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCountParameterListAPrimaryCtor); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCountConstructorDeclaration); Assert.Equal(1, analyzer.FireCountStringParameterList); Assert.Equal(1, analyzer.FireCountThisConstructorInitializer); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); } private class AnalyzerActions_01_Analyzer : DiagnosticAnalyzer { public int FireCount0; public int FireCountRecordStructDeclarationA; public int FireCountRecordStructDeclarationACtor; public int FireCount3; public int FireCountSimpleBaseTypeI1onA; public int FireCount5; public int FireCountParameterListAPrimaryCtor; public int FireCount7; public int FireCountConstructorDeclaration; public int FireCountStringParameterList; public int FireCountThisConstructorInitializer; 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.RegisterSyntaxNodeAction(Handle1, SyntaxKind.NumericLiteralExpression); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.EqualsValueClause); context.RegisterSyntaxNodeAction(Fail, SyntaxKind.BaseConstructorInitializer); context.RegisterSyntaxNodeAction(Handle3, SyntaxKind.ThisConstructorInitializer); context.RegisterSyntaxNodeAction(Handle4, SyntaxKind.ConstructorDeclaration); context.RegisterSyntaxNodeAction(Fail, SyntaxKind.PrimaryConstructorBaseType); context.RegisterSyntaxNodeAction(Handle6, SyntaxKind.RecordStructDeclaration); 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 "3": Interlocked.Increment(ref FireCount7); Assert.Equal("System.Int32 A.M()", context.ContainingSymbol.ToTestDisplayString()); break; case "4": Interlocked.Increment(ref FireCount12); Assert.Equal("A..ctor(System.String S)", 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 FireCount3); Assert.Equal("A..ctor([System.Int32 X = 0])", 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 ": this(4)": Interlocked.Increment(ref FireCountThisConstructorInitializer); Assert.Equal("A..ctor(System.String S)", 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 FireCountConstructorDeclaration); Assert.Equal("A..ctor(System.String S)", context.ContainingSymbol.ToTestDisplayString()); } protected void Fail(SyntaxNodeAnalysisContext context) { Assert.True(false); } protected void Handle6(SyntaxNodeAnalysisContext context) { var record = (RecordDeclarationSyntax)context.Node; Assert.Equal(SyntaxKind.RecordStructDeclaration, record.Kind()); switch (context.ContainingSymbol.ToTestDisplayString()) { case "A": Interlocked.Increment(ref FireCountRecordStructDeclarationA); break; case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCountRecordStructDeclarationACtor); 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 "Attr1": Interlocked.Increment(ref FireCount5); Assert.Equal("A..ctor([System.Int32 X = 0])", 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 FireCountSimpleBaseTypeI1onA); 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 FireCountParameterListAPrimaryCtor); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; case "(string S)": Interlocked.Increment(ref FireCountStringParameterList); Assert.Equal("A..ctor(System.String S)", 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 "(4)": Interlocked.Increment(ref FireCount11); Assert.Equal("A..ctor(System.String S)", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_02() { // Test RegisterSymbolAction var text1 = @" record struct A(int X = 0) {} record struct 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; set; }": 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() { // Test RegisterSymbolStartAction var text1 = @" readonly record struct A(int X = 0) {} readonly record struct 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() { // Test RegisterOperationAction var text1 = @" record struct A([Attr1(100)]int X = 0) : I1 {} 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.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount14); } private class AnalyzerActions_04_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount6; public int FireCount7; public int FireCount14; 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(HandleConstructorBody, OperationKind.ConstructorBody); context.RegisterOperationAction(HandleInvocation, OperationKind.Invocation); context.RegisterOperationAction(HandleLiteral, OperationKind.Literal); context.RegisterOperationAction(HandleParameterInitializer, OperationKind.ParameterInitializer); context.RegisterOperationAction(Fail, OperationKind.PropertyInitializer); context.RegisterOperationAction(Fail, OperationKind.FieldInitializer); } protected void HandleConstructorBody(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()); VerifyOperationTree((CSharpCompilation)context.Compilation, context.Operation, @""); break; default: Assert.True(false); break; } } protected void HandleInvocation(OperationAnalysisContext context) { Assert.True(false); } protected void HandleLiteral(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; default: Assert.True(false); break; } } protected void HandleParameterInitializer(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; default: Assert.True(false); break; } } protected void Fail(OperationAnalysisContext context) { Assert.True(false); } } [Fact] public void AnalyzerActions_05() { // Test RegisterOperationBlockAction var text1 = @" record struct A([Attr1(100)]int X = 0) : I1 {} interface I1 {} "; var analyzer = new AnalyzerActions_05_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); } private class AnalyzerActions_05_Analyzer : DiagnosticAnalyzer { public int FireCount1; 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; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_07() { // Test RegisterCodeBlockAction var text1 = @" record struct A([Attr1(100)]int X = 0) : I1 { int M() => 3; } 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.FireCount4); } private class AnalyzerActions_07_Analyzer : DiagnosticAnalyzer { public int FireCount1; 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 "System.Int32 A.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() { // Test RegisterCodeBlockStartAction var text1 = @" record struct A([Attr1]int X = 0) : I1 { private int M() => 3; A(string S) : this(4) => throw null; } 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.FireCount400); Assert.Equal(1, analyzer.FireCount500); Assert.Equal(1, analyzer.FireCount0); Assert.Equal(0, analyzer.FireCountRecordStructDeclarationA); Assert.Equal(0, analyzer.FireCountRecordStructDeclarationACtor); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(0, analyzer.FireCountSimpleBaseTypeI1onA); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(0, analyzer.FireCountParameterListAPrimaryCtor); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(0, analyzer.FireCountConstructorDeclaration); Assert.Equal(0, analyzer.FireCountStringParameterList); Assert.Equal(1, analyzer.FireCountThisConstructorInitializer); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); Assert.Equal(1, analyzer.FireCount1000); Assert.Equal(1, analyzer.FireCount4000); Assert.Equal(1, analyzer.FireCount5000); } private class AnalyzerActions_08_Analyzer : AnalyzerActions_01_Analyzer { public int FireCount100; public int FireCount400; public int FireCount500; public int FireCount1000; public int FireCount4000; public int FireCount5000; 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 "System.Int32 A.M()": switch (context.CodeBlock) { case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }: Interlocked.Increment(ref FireCount400); break; default: Assert.True(false); break; } break; case "A..ctor(System.String S)": switch (context.CodeBlock) { case ConstructorDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount500); break; default: Assert.True(false); break; } break; default: Assert.True(false); break; } context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.NumericLiteralExpression); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.EqualsValueClause); context.RegisterSyntaxNodeAction(Fail, SyntaxKind.BaseConstructorInitializer); context.RegisterSyntaxNodeAction(Handle3, SyntaxKind.ThisConstructorInitializer); context.RegisterSyntaxNodeAction(Handle4, SyntaxKind.ConstructorDeclaration); context.RegisterSyntaxNodeAction(Fail, SyntaxKind.PrimaryConstructorBaseType); context.RegisterSyntaxNodeAction(Handle6, SyntaxKind.RecordStructDeclaration); 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 "System.Int32 A.M()": switch (context.CodeBlock) { case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }: Interlocked.Increment(ref FireCount4000); break; default: Assert.True(false); break; } break; case "A..ctor(System.String S)": switch (context.CodeBlock) { case ConstructorDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount5000); 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] public void WithExprOnStruct_LangVersion() { var src = @" var b = new B() { X = 1 }; var b2 = b.M(); System.Console.Write(b2.X); System.Console.Write("" ""); System.Console.Write(b.X); public struct B { public int X { get; set; } public B M() /*<bind>*/{ return this with { X = 42 }; }/*</bind>*/ }"; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (13,16): error CS8773: Feature 'with on structs' is not available in C# 9.0. Please use language version 10.0 or greater. // return this with { X = 42 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "this with { X = 42 }").WithArguments("with on structs", "10.0").WithLocation(13, 16) ); comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42 1"); verifier.VerifyIL("B.M", @" { // Code size 18 (0x12) .maxstack 2 .locals init (B V_0) IL_0000: ldarg.0 IL_0001: ldobj ""B"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: ldc.i4.s 42 IL_000b: call ""void B.X.set"" IL_0010: ldloc.0 IL_0011: ret }"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var with = tree.GetRoot().DescendantNodes().OfType<WithExpressionSyntax>().Single(); var type = model.GetTypeInfo(with); Assert.Equal("B", type.Type.ToTestDisplayString()); var operation = model.GetOperation(with); VerifyOperationTree(comp, operation, @" IWithOperation (OperationKind.With, Type: B) (Syntax: 'this with { X = 42 }') Operand: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') CloneMethod: null Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: B) (Syntax: '{ X = 42 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 42') Left: IPropertyReferenceOperation: System.Int32 B.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'X') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 42') Left: IPropertyReferenceOperation: System.Int32 B.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') Next (Return) Block[B2] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExprOnStruct_ControlFlow_DuplicateInitialization() { var src = @" public struct B { public int X { get; set; } public B M() /*<bind>*/{ return this with { X = 42, X = 43 }; }/*</bind>*/ }"; var expectedDiagnostics = new[] { // (8,36): error CS1912: Duplicate initialization of member 'X' // return this with { X = 42, X = 43 }; Diagnostic(ErrorCode.ERR_MemberAlreadyInitialized, "X").WithArguments("X").WithLocation(8, 36) }; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 42') Left: IPropertyReferenceOperation: System.Int32 B.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'X = 43') Left: IPropertyReferenceOperation: System.Int32 B.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 43) (Syntax: '43') Next (Return) Block[B2] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExprOnStruct_ControlFlow_NestedInitializer() { var src = @" public struct C { public int Y { get; set; } } public struct B { public C X { get; set; } public B M() /*<bind>*/{ return this with { X = { Y = 1 } }; }/*</bind>*/ }"; var expectedDiagnostics = new[] { // (12,32): error CS1525: Invalid expression term '{' // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "{").WithArguments("{").WithLocation(12, 32), // (12,32): error CS1513: } expected // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_RbraceExpected, "{").WithLocation(12, 32), // (12,32): error CS1002: ; expected // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(12, 32), // (12,34): error CS0103: The name 'Y' does not exist in the current context // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_NameNotInContext, "Y").WithArguments("Y").WithLocation(12, 34), // (12,34): warning CS0162: Unreachable code detected // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.WRN_UnreachableCode, "Y").WithLocation(12, 34), // (12,40): error CS1002: ; expected // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(12, 40), // (12,43): error CS1597: Semicolon after method or accessor block is not valid // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(12, 43), // (14,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(14, 1) }; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsInvalid) (Syntax: 'X = ') Left: IPropertyReferenceOperation: C B.X { get; set; } (OperationKind.PropertyReference, Type: C) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Right: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Next (Return) Block[B3] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Leaving: {R1} } Block[B2] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Y = 1 ') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'Y = 1') Left: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Y') Children(0) Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExprOnStruct_ControlFlow_NonAssignmentExpression() { var src = @" public struct B { public int X { get; set; } public B M(int i, int j) /*<bind>*/{ return this with { i, j++, M2(), X = 2}; }/*</bind>*/ static int M2() => 0; }"; var expectedDiagnostics = new[] { // (8,28): error CS0747: Invalid initializer member declarator // return this with { i, j++, M2(), X = 2}; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "i").WithLocation(8, 28), // (8,31): error CS0747: Invalid initializer member declarator // return this with { i, j++, M2(), X = 2}; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "j++").WithLocation(8, 31), // (8,36): error CS0747: Invalid initializer member declarator // return this with { i, j++, M2(), X = 2}; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "M2()").WithLocation(8, 36) }; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Children(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'i') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'j++') Children(1): IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32, IsInvalid) (Syntax: 'j++') Target: IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'j') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M2()') Children(1): IInvocationOperation (System.Int32 B.M2()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M2()') Instance Receiver: null Arguments(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 2') Left: IPropertyReferenceOperation: System.Int32 B.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Return) Block[B2] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void ObjectCreationInitializer_ControlFlow_WithCoalescingExpressionForValue() { var src = @" public struct B { public string X; public void M(string hello) /*<bind>*/{ var x = new B() { X = Identity((string)null) ?? Identity(hello) }; }/*</bind>*/ T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [B x] CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new B() { X ... ty(hello) }') Value: IObjectCreationOperation (Constructor: B..ctor()) (OperationKind.ObjectCreation, Type: B) (Syntax: 'new B() { X ... ty(hello) }') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .locals {R2} { CaptureIds: [2] .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity((string)null)') Value: IInvocationOperation ( System.String B.Identity<System.String>(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity((string)null)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Identity') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '(string)null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null) (Syntax: '(string)null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') 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) Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'Identity((string)null)') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((string)null)') Leaving: {R3} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity((string)null)') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((string)null)') Next (Regular) Block[B5] Leaving: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(hello)') Value: IInvocationOperation ( System.String B.Identity<System.String>(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity(hello)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Identity') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'hello') IParameterReferenceOperation: hello (OperationKind.ParameterReference, Type: System.String) (Syntax: 'hello') 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[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'X = Identit ... tity(hello)') Left: IFieldReferenceOperation: System.String B.X (OperationKind.FieldReference, Type: System.String) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'new B() { X ... ty(hello) }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((s ... tity(hello)') Next (Regular) Block[B6] Leaving: {R2} } Block[B6] - Block Predecessors: [B5] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: B, IsImplicit) (Syntax: 'x = new B() ... ty(hello) }') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: B, IsImplicit) (Syntax: 'x = new B() ... ty(hello) }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'new B() { X ... ty(hello) }') Next (Regular) Block[B7] Leaving: {R1} } Block[B7] - Exit Predecessors: [B6] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics); } [Fact] public void WithExprOnStruct_ControlFlow_WithCoalescingExpressionForValue() { var src = @" var b = new B() { X = string.Empty }; var b2 = b.M(""hello""); System.Console.Write(b2.X); public struct B { public string X; public B M(string hello) /*<bind>*/{ return Identity(this) with { X = Identity((string)null) ?? Identity(hello) }; }/*</bind>*/ T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "hello"); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(this)') Value: IInvocationOperation ( B B.Identity<B>(B t)) (OperationKind.Invocation, Type: B) (Syntax: 'Identity(this)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Identity') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'this') IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') 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] Entering: {R2} {R3} .locals {R2} { CaptureIds: [2] .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity((string)null)') Value: IInvocationOperation ( System.String B.Identity<System.String>(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity((string)null)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Identity') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '(string)null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null) (Syntax: '(string)null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') 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) Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'Identity((string)null)') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((string)null)') Leaving: {R3} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity((string)null)') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((string)null)') Next (Regular) Block[B5] Leaving: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(hello)') Value: IInvocationOperation ( System.String B.Identity<System.String>(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity(hello)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Identity') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'hello') IParameterReferenceOperation: hello (OperationKind.ParameterReference, Type: System.String) (Syntax: 'hello') 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[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'X = Identit ... tity(hello)') Left: IFieldReferenceOperation: System.String B.X (OperationKind.FieldReference, Type: System.String) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'Identity(this)') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((s ... tity(hello)') Next (Regular) Block[B6] Leaving: {R2} } Block[B6] - Block Predecessors: [B5] Statements (0) Next (Return) Block[B7] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'Identity(this)') Leaving: {R1} } Block[B7] - Exit Predecessors: [B6] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExprOnStruct_OnParameter() { var src = @" var b = new B() { X = 1 }; var b2 = B.M(b); System.Console.Write(b2.X); public struct B { public int X { get; set; } public static B M(B b) { return b with { X = 42 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("B.M", @" { // Code size 13 (0xd) .maxstack 2 .locals init (B V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: call ""void B.X.set"" IL_000b: ldloc.0 IL_000c: ret }"); } [Fact] public void WithExprOnStruct_OnThis() { var src = @" record struct C { public int X { get; set; } C(string ignored) { _ = this with { X = 42 }; // 1 this = default; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,13): error CS0188: The 'this' object cannot be used before all of its fields have been assigned // _ = this with { X = 42 }; // 1 Diagnostic(ErrorCode.ERR_UseDefViolationThis, "this").WithArguments("this").WithLocation(8, 13) ); } [Fact] public void WithExprOnStruct_OnTStructParameter() { var src = @" var b = new B() { X = 1 }; var b2 = B.M(b); System.Console.Write(b2.X); public interface I { int X { get; set; } } public struct B : I { public int X { get; set; } public static T M<T>(T b) where T : struct, I { return b with { X = 42 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("B.M<T>(T)", @" { // Code size 19 (0x13) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: constrained. ""T"" IL_000c: callvirt ""void I.X.set"" IL_0011: ldloc.0 IL_0012: ret }"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var with = tree.GetRoot().DescendantNodes().OfType<WithExpressionSyntax>().Single(); var type = model.GetTypeInfo(with); Assert.Equal("T", type.Type.ToTestDisplayString()); } [Fact] public void WithExprOnStruct_OnRecordStructParameter() { var src = @" var b = new B(1); var b2 = B.M(b); System.Console.Write(b2.X); public record struct B(int X) { public static B M(B b) { return b with { X = 42 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("B.M", @" { // Code size 13 (0xd) .maxstack 2 .locals init (B V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: call ""void B.X.set"" IL_000b: ldloc.0 IL_000c: ret }"); } [Fact] public void WithExprOnStruct_OnRecordStructParameter_Readonly() { var src = @" var b = new B(1, 2); var b2 = B.M(b); System.Console.Write(b2.X); System.Console.Write(b2.Y); public readonly record struct B(int X, int Y) { public static B M(B b) { return b with { X = 42, Y = 43 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "4243", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("B.M", @" { // Code size 22 (0x16) .maxstack 2 .locals init (B V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: call ""void B.X.init"" IL_000b: ldloca.s V_0 IL_000d: ldc.i4.s 43 IL_000f: call ""void B.Y.init"" IL_0014: ldloc.0 IL_0015: ret }"); } [Fact] public void WithExprOnStruct_OnTuple() { var src = @" class C { static void Main() { var b = (1, 2); var b2 = M(b); System.Console.Write(b2.Item1); System.Console.Write(b2.Item2); } static (int, int) M((int, int) b) { return b with { Item1 = 42, Item2 = 43 }; } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "4243"); verifier.VerifyIL("C.M", @" { // Code size 22 (0x16) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: stfld ""int System.ValueTuple<int, int>.Item1"" IL_000b: ldloca.s V_0 IL_000d: ldc.i4.s 43 IL_000f: stfld ""int System.ValueTuple<int, int>.Item2"" IL_0014: ldloc.0 IL_0015: ret }"); } [Fact] public void WithExprOnStruct_OnTuple_WithNames() { var src = @" var b = (1, 2); var b2 = M(b); System.Console.Write(b2.Item1); System.Console.Write(b2.Item2); static (int, int) M((int X, int Y) b) { return b with { X = 42, Y = 43 }; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "4243"); verifier.VerifyIL("Program.<<Main>$>g__M|0_0(System.ValueTuple<int, int>)", @" { // Code size 22 (0x16) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: stfld ""int System.ValueTuple<int, int>.Item1"" IL_000b: ldloca.s V_0 IL_000d: ldc.i4.s 43 IL_000f: stfld ""int System.ValueTuple<int, int>.Item2"" IL_0014: ldloc.0 IL_0015: ret }"); } [Fact] public void WithExprOnStruct_OnTuple_LongTuple() { var src = @" var b = (1, 2, 3, 4, 5, 6, 7, 8); var b2 = M(b); System.Console.Write(b2.Item7); System.Console.Write(b2.Item8); static (int, int, int, int, int, int, int, int) M((int, int, int, int, int, int, int, int) b) { return b with { Item7 = 42, Item8 = 43 }; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "4243"); verifier.VerifyIL("Program.<<Main>$>g__M|0_0(System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>)", @" { // Code size 27 (0x1b) .maxstack 2 .locals init (System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>> V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: stfld ""int System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Item7"" IL_000b: ldloca.s V_0 IL_000d: ldflda ""System.ValueTuple<int> System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Rest"" IL_0012: ldc.i4.s 43 IL_0014: stfld ""int System.ValueTuple<int>.Item1"" IL_0019: ldloc.0 IL_001a: ret }"); } [Fact] public void WithExprOnStruct_OnReadonlyField() { var src = @" var b = new B { X = 1 }; // 1 public struct B { public readonly int X; public B M() { return this with { X = 42 }; // 2 } public static B M2(B b) { return b with { X = 42 }; // 3 } public B(int i) { this = default; _ = this with { X = 42 }; // 4 } }"; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,17): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // var b = new B { X = 1 }; // 1 Diagnostic(ErrorCode.ERR_AssgReadonly, "X").WithLocation(2, 17), // (9,28): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // return this with { X = 42 }; // 2 Diagnostic(ErrorCode.ERR_AssgReadonly, "X").WithLocation(9, 28), // (13,25): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // return b with { X = 42 }; // 3 Diagnostic(ErrorCode.ERR_AssgReadonly, "X").WithLocation(13, 25), // (18,25): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // _ = this with { X = 42 }; // 4 Diagnostic(ErrorCode.ERR_AssgReadonly, "X").WithLocation(18, 25) ); } [Fact] public void WithExprOnStruct_OnEnum() { var src = @" public enum E { } class C { static E M(E e) { return e with { }; } }"; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void WithExprOnStruct_OnPointer() { var src = @" unsafe class C { static int* M(int* i) { return i with { }; } }"; var comp = CreateCompilation(src, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (6,16): error CS8858: The receiver type 'int*' is not a valid record type and is not a struct type. // return i with { }; Diagnostic(ErrorCode.ERR_CannotClone, "i").WithArguments("int*").WithLocation(6, 16) ); } [Fact] public void WithExprOnStruct_OnInterface() { var src = @" public interface I { int X { get; set; } } class C { static I M(I i) { return i with { X = 42 }; } }"; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (10,16): error CS8858: The receiver type 'I' is not a valid record type and is not a value type. // return i with { X = 42 }; Diagnostic(ErrorCode.ERR_CannotClone, "i").WithArguments("I").WithLocation(10, 16) ); } [Fact] public void WithExprOnStruct_OnRefStruct() { // Similar to test RefLikeObjInitializers but with `with` expressions var text = @" using System; class Program { static S2 Test1() { S1 outer = default; S1 inner = stackalloc int[1]; // error return new S2() with { Field1 = outer, Field2 = inner }; } static S2 Test2() { S1 outer = default; S1 inner = stackalloc int[1]; S2 result; // error result = new S2() with { Field1 = inner, Field2 = outer }; return result; } static S2 Test3() { S1 outer = default; S1 inner = stackalloc int[1]; return new S2() with { Field1 = outer, Field2 = outer }; } public ref struct S1 { public static implicit operator S1(Span<int> o) => default; } public ref struct S2 { public S1 Field1; public S1 Field2; } } "; CreateCompilationWithMscorlibAndSpan(text, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics( // (12,48): error CS8352: Cannot use local 'inner' in this context because it may expose referenced variables outside of their declaration scope // return new S2() with { Field1 = outer, Field2 = inner }; Diagnostic(ErrorCode.ERR_EscapeLocal, "Field2 = inner").WithArguments("inner").WithLocation(12, 48), // (23,34): error CS8352: Cannot use local 'inner' in this context because it may expose referenced variables outside of their declaration scope // result = new S2() with { Field1 = inner, Field2 = outer }; Diagnostic(ErrorCode.ERR_EscapeLocal, "Field1 = inner").WithArguments("inner").WithLocation(23, 34) ); } [Fact] public void WithExprOnStruct_OnRefStruct_ReceiverMayWrap() { // Similar to test LocalWithNoInitializerEscape but wrapping method is used as receiver for `with` expression var text = @" using System; class Program { static void Main() { S1 sp; Span<int> local = stackalloc int[1]; sp = MayWrap(ref local) with { }; // 1, 2 } static S1 MayWrap(ref Span<int> arg) { return default; } ref struct S1 { public ref int this[int i] => throw null; } } "; CreateCompilationWithMscorlibAndSpan(text, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics( // (9,26): error CS8352: Cannot use local 'local' in this context because it may expose referenced variables outside of their declaration scope // sp = MayWrap(ref local) with { }; // 1, 2 Diagnostic(ErrorCode.ERR_EscapeLocal, "local").WithArguments("local").WithLocation(9, 26), // (9,14): error CS8347: Cannot use a result of 'Program.MayWrap(ref Span<int>)' in this context because it may expose variables referenced by parameter 'arg' outside of their declaration scope // sp = MayWrap(ref local) with { }; // 1, 2 Diagnostic(ErrorCode.ERR_EscapeCall, "MayWrap(ref local)").WithArguments("Program.MayWrap(ref System.Span<int>)", "arg").WithLocation(9, 14) ); } [Fact] public void WithExprOnStruct_OnRefStruct_ReceiverMayWrap_02() { var text = @" using System; class Program { static void Main() { Span<int> local = stackalloc int[1]; S1 sp = MayWrap(ref local) with { }; } static S1 MayWrap(ref Span<int> arg) { return default; } ref struct S1 { public ref int this[int i] => throw null; } } "; CreateCompilationWithMscorlibAndSpan(text, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics(); } [Fact] public void WithExpr_NullableAnalysis_01() { var src = @" #nullable enable record struct 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 struct 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 struct 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, WorkItem(44763, "https://github.com/dotnet/roslyn/issues/44763")] public void WithExpr_NullableAnalysis_05() { var src = @" #nullable enable record struct 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 struct 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] public void WithExprAssignToRef1() { var src = @" using System; record struct 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 59 (0x3b) .maxstack 2 .locals init (C V_0, //c C V_1) IL_0000: ldloca.s V_1 IL_0002: ldc.i4.0 IL_0003: call ""C..ctor(int)"" IL_0008: ldloca.s V_1 IL_000a: call ""ref int C.X.get"" IL_000f: ldc.i4.5 IL_0010: stind.i4 IL_0011: ldloc.1 IL_0012: stloc.0 IL_0013: ldloca.s V_0 IL_0015: call ""ref int C.X.get"" IL_001a: ldind.i4 IL_001b: call ""void System.Console.WriteLine(int)"" IL_0020: ldloc.0 IL_0021: stloc.1 IL_0022: ldloca.s V_1 IL_0024: call ""ref int C.X.get"" IL_0029: ldc.i4.1 IL_002a: stind.i4 IL_002b: ldloc.1 IL_002c: stloc.0 IL_002d: ldloca.s V_0 IL_002f: call ""ref int C.X.get"" IL_0034: ldind.i4 IL_0035: call ""void System.Console.WriteLine(int)"" IL_003a: ret }"); } [Fact] public void WithExpressionSameLHS() { var comp = CreateCompilation(@" record struct 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_AnonymousType_ChangeAllProperties() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = Identity(a) with { A = Identity(30), B = Identity(40) }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) { System.Console.Write($""Identity({t}) ""); return t; } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (9,17): error CS8773: Feature 'with on anonymous types' is not available in C# 9.0. Please use language version 10.0 or greater. // var b = Identity(a) with { A = Identity(30), B = Identity(40) }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Identity(a) with { A = Identity(30), B = Identity(40) }").WithArguments("with on anonymous types", "10.0").WithLocation(9, 17) ); comp = CreateCompilation(src, parseOptions: TestOptions.Regular10); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "Identity({ A = 10, B = 20 }) Identity(30) Identity(40) { A = 30, B = 40 }"); verifier.VerifyIL("C.M", @" { // Code size 42 (0x2a) .maxstack 2 .locals init (int V_0) IL_0000: ldc.i4.s 10 IL_0002: ldc.i4.s 20 IL_0004: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0009: call ""<anonymous type: int A, int B> C.Identity<<anonymous type: int A, int B>>(<anonymous type: int A, int B>)"" IL_000e: pop IL_000f: ldc.i4.s 30 IL_0011: call ""int C.Identity<int>(int)"" IL_0016: ldc.i4.s 40 IL_0018: call ""int C.Identity<int>(int)"" IL_001d: stloc.0 IL_001e: ldloc.0 IL_001f: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0024: call ""void System.Console.Write(object)"" IL_0029: ret } "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [2] [3] Block[B2] - Block Predecessors: [B1] Statements (4) IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.Identity<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (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) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(30)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') 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) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(40)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(40)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '40') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 40) (Syntax: '40') 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: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... ntity(40) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... ntity(40) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a) ... ntity(40) }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B3] Leaving: {R3} } Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') 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[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeAllProperties_ReverseOrder() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = Identity(a) with { B = Identity(40), A = Identity(30) }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) { System.Console.Write($""Identity({t}) ""); return t; } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "Identity({ A = 10, B = 20 }) Identity(40) Identity(30) { A = 30, B = 40 }"); verifier.VerifyIL("C.M", @" { // Code size 42 (0x2a) .maxstack 2 .locals init (int V_0) IL_0000: ldc.i4.s 10 IL_0002: ldc.i4.s 20 IL_0004: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0009: call ""<anonymous type: int A, int B> C.Identity<<anonymous type: int A, int B>>(<anonymous type: int A, int B>)"" IL_000e: pop IL_000f: ldc.i4.s 40 IL_0011: call ""int C.Identity<int>(int)"" IL_0016: stloc.0 IL_0017: ldc.i4.s 30 IL_0019: call ""int C.Identity<int>(int)"" IL_001e: ldloc.0 IL_001f: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0024: call ""void System.Console.Write(object)"" IL_0029: ret } "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [2] [3] Block[B2] - Block Predecessors: [B1] Statements (4) IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.Identity<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (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) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(40)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(40)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '40') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 40) (Syntax: '40') 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) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(30)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') 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: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... ntity(30) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... ntity(30) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a) ... ntity(30) }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B3] Leaving: {R3} } Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') 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[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeNoProperty() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = M2(a) with { }; System.Console.Write(b); }/*</bind>*/ static T M2<T>(T t) { System.Console.Write(""M2 ""); return t; } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "M2 { A = 10, B = 20 }"); verifier.VerifyIL("C.M", @" { // Code size 38 (0x26) .maxstack 2 .locals init (<>f__AnonymousType0<int, int> V_0) IL_0000: ldc.i4.s 10 IL_0002: ldc.i4.s 20 IL_0004: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0009: call ""<anonymous type: int A, int B> C.M2<<anonymous type: int A, int B>>(<anonymous type: int A, int B>)"" IL_000e: stloc.0 IL_000f: ldloc.0 IL_0010: callvirt ""int <>f__AnonymousType0<int, int>.A.get"" IL_0015: ldloc.0 IL_0016: callvirt ""int <>f__AnonymousType0<int, int>.B.get"" IL_001b: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0020: call ""void System.Console.Write(object)"" IL_0025: ret } "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [3] [4] .locals {R4} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2(a)') Value: IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.M2<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'M2(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (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) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2(a) with { }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a)') IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2(a) with { }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a)') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = M2(a) with { }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = M2(a) with { }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'M2(a) with { }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a) with { }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a) with { }') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a)') Next (Regular) Block[B4] Leaving: {R3} } Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') 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[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeOneProperty() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = a with { B = Identity(30) }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "{ A = 10, B = 30 }"); verifier.VerifyIL("C.M", @" { // Code size 34 (0x22) .maxstack 2 .locals init (int V_0) IL_0000: ldc.i4.s 10 IL_0002: ldc.i4.s 20 IL_0004: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0009: ldc.i4.s 30 IL_000b: call ""int C.Identity<int>(int)"" IL_0010: stloc.0 IL_0011: callvirt ""int <>f__AnonymousType0<int, int>.A.get"" IL_0016: ldloc.0 IL_0017: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_001c: call ""void System.Console.Write(object)"" IL_0021: ret } "); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var withExpr = tree.GetRoot().DescendantNodes().OfType<WithExpressionSyntax>().Single(); var operation = model.GetOperation(withExpr); VerifyOperationTree(comp, operation, @" IWithOperation (OperationKind.With, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a with { B ... ntity(30) }') Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') CloneMethod: null Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: '{ B = Identity(30) }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'B = Identity(30)') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'B') Right: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') 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 expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [3] [4] .locals {R4} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(30)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') 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) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = a with ... ntity(30) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = a with ... ntity(30) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a with { B ... ntity(30) }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R3} } Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') 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[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeOneProperty_WithMethodCallForTarget() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = Identity(a) with { B = 30 }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "{ A = 10, B = 30 }"); verifier.VerifyIL("C.M", @" { // Code size 34 (0x22) .maxstack 2 .locals init (int V_0) IL_0000: ldc.i4.s 10 IL_0002: ldc.i4.s 20 IL_0004: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0009: call ""<anonymous type: int A, int B> C.Identity<<anonymous type: int A, int B>>(<anonymous type: int A, int B>)"" IL_000e: ldc.i4.s 30 IL_0010: stloc.0 IL_0011: callvirt ""int <>f__AnonymousType0<int, int>.A.get"" IL_0016: ldloc.0 IL_0017: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_001c: call ""void System.Console.Write(object)"" IL_0021: ret } "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [3] [4] .locals {R4} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a)') Value: IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.Identity<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (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) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '30') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... { B = 30 }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... { B = 30 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a) ... { B = 30 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B4] Leaving: {R3} } Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') 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[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeOneProperty_WithCoalescingExpressionForTarget() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = (Identity(a) ?? Identity2(a)) with { B = 30 }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) => t; static T Identity2<T>(T t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "{ A = 10, B = 30 }"); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} {R5} } .locals {R3} { CaptureIds: [4] [5] .locals {R4} { CaptureIds: [2] .locals {R5} { CaptureIds: [3] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a)') Value: IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.Identity<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (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) Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'Identity(a)') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Leaving: {R5} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a)') Value: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B5] Leaving: {R5} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity2(a)') Value: IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.Identity2<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity2(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (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) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (2) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '30') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... dentity2(a)') Next (Regular) Block[B6] Leaving: {R4} } Block[B6] - Block Predecessors: [B5] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = (Identi ... { B = 30 }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = (Identi ... { B = 30 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: '(Identity(a ... { B = 30 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... dentity2(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... dentity2(a)') Next (Regular) Block[B7] Leaving: {R3} } Block[B7] - Block Predecessors: [B6] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') 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[B8] Leaving: {R1} } Block[B8] - Exit Predecessors: [B7] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeOneProperty_WithCoalescingExpressionForValue() { var src = @" C.M(""hello"", ""world""); public class C { public static void M(string hello, string world) /*<bind>*/{ var x = new { A = hello, B = string.Empty }; var y = x with { B = Identity(null) ?? Identity2(world) }; System.Console.Write(y); }/*</bind>*/ static string Identity(string t) => t; static string Identity2(string t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "{ A = hello, B = world }"); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.String A, System.String B> x] [<anonymous type: System.String A, System.String B> y] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'hello') Value: IParameterReferenceOperation: hello (OperationKind.ParameterReference, Type: System.String) (Syntax: 'hello') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'string.Empty') Value: IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String) (Syntax: 'string.Empty') Instance Receiver: null ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x = new { A ... ing.Empty }') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x = new { A ... ing.Empty }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.String A, System.String B>) (Syntax: 'new { A = h ... ing.Empty }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'A = hello') Left: IPropertyReferenceOperation: System.String <anonymous type: System.String A, System.String B>.A { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'new { A = h ... ing.Empty }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'hello') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'B = string.Empty') Left: IPropertyReferenceOperation: System.String <anonymous type: System.String A, System.String B>.B { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'new { A = h ... ing.Empty }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'string.Empty') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [3] [5] .locals {R4} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: <anonymous type: System.String A, System.String B>) (Syntax: 'x') Next (Regular) Block[B3] Entering: {R5} .locals {R5} { CaptureIds: [4] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(null)') Value: IInvocationOperation (System.String C.Identity(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity(null)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') 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) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'Identity(null)') Operand: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity(null)') Leaving: {R5} Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(null)') Value: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity(null)') Next (Regular) Block[B6] Leaving: {R5} } Block[B5] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity2(world)') Value: IInvocationOperation (System.String C.Identity2(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity2(world)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'world') IParameterReferenceOperation: world (OperationKind.ParameterReference, Type: System.String) (Syntax: 'world') 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[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Value: IPropertyReferenceOperation: System.String <anonymous type: System.String A, System.String B>.A { get; } (OperationKind.PropertyReference, Type: System.String, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x') Next (Regular) Block[B7] Leaving: {R4} } Block[B7] - Block Predecessors: [B6] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'y = x with ... y2(world) }') Left: ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'y = x with ... y2(world) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.String A, System.String B>) (Syntax: 'x with { B ... y2(world) }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Left: IPropertyReferenceOperation: System.String <anonymous type: System.String A, System.String B>.A { get; } (OperationKind.PropertyReference, Type: System.String, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Left: IPropertyReferenceOperation: System.String <anonymous type: System.String A, System.String B>.B { get; } (OperationKind.PropertyReference, Type: System.String, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x') Next (Regular) Block[B8] Leaving: {R3} } Block[B8] - Block Predecessors: [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(y);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(y)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'y') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: <anonymous type: System.String A, System.String B>) (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[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ErrorMember() { var src = @" public class C { public static void M() /*<bind>*/{ var a = new { A = 10 }; var b = a with { Error = Identity(20) }; }/*</bind>*/ static T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); var expectedDiagnostics = new[] { // (7,26): error CS0117: '<anonymous type: int A>' does not contain a definition for 'Error' // var b = a with { Error = Identity(20) }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Error").WithArguments("<anonymous type: int A>", "Error").WithLocation(7, 26) }; comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> a] [<anonymous type: System.Int32 A> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [2] .locals {R4} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'a') IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(20)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '20') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') 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) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'a with { Er ... ntity(20) }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { Er ... ntity(20) }') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ntity(20) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ntity(20) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>, IsInvalid) (Syntax: 'a with { Er ... ntity(20) }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { Er ... ntity(20) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { Er ... ntity(20) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { Er ... ntity(20) }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R3} {R1} } } Block[B4] - Exit Predecessors: [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ToString() { var src = @" public class C { public static void M() /*<bind>*/{ var a = new { A = 10 }; var b = a with { ToString = Identity(20) }; }/*</bind>*/ static T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); var expectedDiagnostics = new[] { // (7,26): error CS1913: Member 'ToString' cannot be initialized. It is not a field or property. // var b = a with { ToString = Identity(20) }; Diagnostic(ErrorCode.ERR_MemberCannotBeInitialized, "ToString").WithArguments("ToString").WithLocation(7, 26) }; comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> a] [<anonymous type: System.Int32 A> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [2] .locals {R4} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'a') IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(20)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '20') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') 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) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'a with { To ... ntity(20) }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { To ... ntity(20) }') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ntity(20) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ntity(20) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>, IsInvalid) (Syntax: 'a with { To ... ntity(20) }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { To ... ntity(20) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { To ... ntity(20) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { To ... ntity(20) }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R3} {R1} } } Block[B4] - Exit Predecessors: [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_NestedInitializer() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var nested = new { A = 10 }; var a = new { Nested = nested }; var b = a with { Nested = { A = 20 } }; System.Console.Write(b); }/*</bind>*/ }"; var expectedDiagnostics = new[] { // (10,35): error CS1525: Invalid expression term '{' // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "{").WithArguments("{").WithLocation(10, 35), // (10,35): error CS1513: } expected // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_RbraceExpected, "{").WithLocation(10, 35), // (10,35): error CS1002: ; expected // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(10, 35), // (10,37): error CS0103: The name 'A' does not exist in the current context // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_NameNotInContext, "A").WithArguments("A").WithLocation(10, 37), // (10,44): error CS1002: ; expected // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(10, 44), // (10,47): error CS1597: Semicolon after method or accessor block is not valid // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(10, 47), // (11,29): error CS1519: Invalid token '(' in class, record, struct, or interface member declaration // System.Console.Write(b); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "(").WithArguments("(").WithLocation(11, 29), // (11,31): error CS8124: Tuple must contain at least two elements. // System.Console.Write(b); Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(11, 31), // (11,32): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // System.Console.Write(b); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(11, 32), // (13,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(13, 1) }; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> nested] [<anonymous type: <anonymous type: System.Int32 A> Nested> a] [<anonymous type: <anonymous type: System.Int32 A> Nested> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'nested = new { A = 10 }') Left: ILocalReferenceOperation: nested (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'nested = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (2) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'nested') Value: ILocalReferenceOperation: nested (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'nested') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsImplicit) (Syntax: 'a = new { N ... = nested }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsImplicit) (Syntax: 'a = new { N ... = nested }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>) (Syntax: 'new { Nested = nested }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>) (Syntax: 'Nested = nested') Left: IPropertyReferenceOperation: <anonymous type: System.Int32 A> <anonymous type: <anonymous type: System.Int32 A> Nested>.Nested { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'Nested') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsImplicit) (Syntax: 'new { Nested = nested }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'nested') Next (Regular) Block[B3] Leaving: {R3} Entering: {R4} } .locals {R4} { CaptureIds: [2] Block[B3] - Block Predecessors: [B2] Statements (3) ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>) (Syntax: 'a') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '') Value: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsInvalid, IsImplicit) (Syntax: 'b = a with { Nested = ') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsInvalid, IsImplicit) (Syntax: 'b = a with { Nested = ') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsInvalid) (Syntax: 'a with { Nested = ') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { Nested = ') Left: IPropertyReferenceOperation: <anonymous type: System.Int32 A> <anonymous type: <anonymous type: System.Int32 A> Nested>.Nested { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { Nested = ') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsInvalid, IsImplicit) (Syntax: 'a with { Nested = ') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R4} } Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'A = 20 ') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'A = 20') Left: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'A') Children(0) Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_NonAssignmentExpression() { var src = @" public class C { public static void M(int i, int j) /*<bind>*/{ var a = new { A = 10 }; var b = a with { i, j++, M2(), A = 20 }; }/*</bind>*/ static int M2() => 0; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); var expectedDiagnostics = new[] { // (7,26): error CS0747: Invalid initializer member declarator // var b = a with { i, j++, M2(), A = 20 }; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "i").WithLocation(7, 26), // (7,29): error CS0747: Invalid initializer member declarator // var b = a with { i, j++, M2(), A = 20 }; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "j++").WithLocation(7, 29), // (7,34): error CS0747: Invalid initializer member declarator // var b = a with { i, j++, M2(), A = 20 }; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "M2()").WithLocation(7, 34) }; comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> a] [<anonymous type: System.Int32 A> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (6) ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'a') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Children(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'i') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'j++') Children(1): IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32, IsInvalid) (Syntax: 'j++') Target: IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'j') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M2()') Children(1): IInvocationOperation (System.Int32 C.M2()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M2()') Instance Receiver: null Arguments(0) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ), A = 20 }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ), A = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>, IsInvalid) (Syntax: 'a with { i, ... ), A = 20 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { i, ... ), A = 20 }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { i, ... ), A = 20 }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { i, ... ), A = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R3} {R1} } } Block[B3] - Exit Predecessors: [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_IndexerAccess() { var src = @" public class C { public static void M() /*<bind>*/{ var a = new { A = 10 }; var b = a with { [0] = 20 }; }/*</bind>*/ }"; var expectedDiagnostics = new[] { // (7,26): error CS1513: } expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_RbraceExpected, "[").WithLocation(7, 26), // (7,26): error CS1002: ; expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "[").WithLocation(7, 26), // (7,26): error CS7014: Attributes are not valid in this context. // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[").WithLocation(7, 26), // (7,27): error CS1001: Identifier expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_IdentifierExpected, "0").WithLocation(7, 27), // (7,27): error CS1003: Syntax error, ']' expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_SyntaxError, "0").WithArguments("]", "").WithLocation(7, 27), // (7,28): error CS1002: ; expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "]").WithLocation(7, 28), // (7,28): error CS1513: } expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_RbraceExpected, "]").WithLocation(7, 28), // (7,30): error CS1525: Invalid expression term '=' // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "=").WithArguments("=").WithLocation(7, 30), // (7,35): error CS1002: ; expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(7, 35), // (7,36): error CS1597: Semicolon after method or accessor block is not valid // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(7, 36), // (9,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(9, 1) }; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> a] [<anonymous type: System.Int32 A> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [2] .locals {R4} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (2) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'a') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'a with { ') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { ') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with { ') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with { ') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>, IsInvalid) (Syntax: 'a with { ') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { ') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { ') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { ') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R3} } Block[B4] - Block Predecessors: [B3] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '[0') Expression: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '= 20 ') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '= 20') Left: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_CannotSet() { var src = @" public class C { public static void M() { var a = new { A = 10 }; a.A = 20; var b = new { B = a }; b.B.A = 30; } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (7,9): error CS0200: Property or indexer '<anonymous type: int A>.A' cannot be assigned to -- it is read only // a.A = 20; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "a.A").WithArguments("<anonymous type: int A>.A").WithLocation(7, 9), // (10,9): error CS0200: Property or indexer '<anonymous type: int A>.A' cannot be assigned to -- it is read only // b.B.A = 30; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "b.B.A").WithArguments("<anonymous type: int A>.A").WithLocation(10, 9) ); } [Fact] public void WithExpr_AnonymousType_DuplicateMemberInDeclaration() { var src = @" public class C { public static void M() /*<bind>*/{ var a = new { A = 10, A = 20 }; var b = Identity(a) with { A = Identity(30) }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) => t; }"; var expectedDiagnostics = new[] { // (6,31): error CS0833: An anonymous type cannot have multiple properties with the same name // var a = new { A = 10, A = 20 }; Diagnostic(ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, "A = 20").WithLocation(6, 31) }; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 $1> a] [<anonymous type: System.Int32 A, System.Int32 $1> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20, IsInvalid) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsInvalid, IsImplicit) (Syntax: 'a = new { A ... 0, A = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsInvalid, IsImplicit) (Syntax: 'a = new { A ... 0, A = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsInvalid) (Syntax: 'new { A = 10, A = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 $1>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsInvalid, IsImplicit) (Syntax: 'new { A = 10, A = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20, IsInvalid) (Syntax: 'A = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 $1>.$1 { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsInvalid, IsImplicit) (Syntax: 'new { A = 10, A = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsInvalid, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [3] [4] .locals {R4} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a)') Value: IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 $1> C.Identity<<anonymous type: System.Int32 A, System.Int32 $1>>(<anonymous type: System.Int32 A, System.Int32 $1> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 $1>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>) (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) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(30)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') 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) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 $1>.$1 { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'b = Identit ... ntity(30) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'b = Identit ... ntity(30) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 $1>) (Syntax: 'Identity(a) ... ntity(30) }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 $1>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'Identity(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 $1>.$1 { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B4] Leaving: {R3} } Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>) (Syntax: 'b') 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[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_DuplicateInitialization() { var src = @" public class C { public static void M() /*<bind>*/{ var a = new { A = 10 }; var b = Identity(a) with { A = Identity(30), A = Identity(40) }; }/*</bind>*/ static T Identity<T>(T t) => t; }"; var expectedDiagnostics = new[] { // (7,54): error CS1912: Duplicate initialization of member 'A' // var b = Identity(a) with { A = Identity(30), A = Identity(40) }; Diagnostic(ErrorCode.ERR_MemberAlreadyInitialized, "A").WithArguments("A").WithLocation(7, 54) }; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> a] [<anonymous type: System.Int32 A> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (4) IInvocationOperation (<anonymous type: System.Int32 A> C.Identity<<anonymous type: System.Int32 A>>(<anonymous type: System.Int32 A> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 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) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(30)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') 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) IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(40)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '40') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 40) (Syntax: '40') 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: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = Identit ... ntity(40) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = Identit ... ntity(40) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>, IsInvalid) (Syntax: 'Identity(a) ... ntity(40) }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B3] Leaving: {R3} {R1} } } Block[B3] - Exit Predecessors: [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact, WorkItem(53849, "https://github.com/dotnet/roslyn/issues/53849")] public void WithExpr_AnonymousType_ValueIsLoweredToo() { var src = @" var x = new { Property = 42 }; var adjusted = x with { Property = x.Property + 2 }; System.Console.WriteLine(adjusted); "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); var verifier = CompileAndVerify(comp, expectedOutput: "{ Property = 44 }"); verifier.VerifyDiagnostics(); } [Fact, WorkItem(53849, "https://github.com/dotnet/roslyn/issues/53849")] public void WithExpr_AnonymousType_ValueIsLoweredToo_NestedWith() { var src = @" var x = new { Property = 42 }; var container = new { Item = x }; var adjusted = container with { Item = x with { Property = x.Property + 2 } }; System.Console.WriteLine(adjusted); "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); var verifier = CompileAndVerify(comp, expectedOutput: "{ Item = { Property = 44 } }"); verifier.VerifyDiagnostics(); } [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 readonly record struct 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.RegularPreview, // 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 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 struct A(int X) { public int X = X; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct A(int X) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(8, 8), // (8,17): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct A(int X) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int X").WithArguments("positional fields in records", "10.0").WithLocation(8, 17) ); 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_Readonly() { var source = @" readonly record struct A(int X) { public int X = X; // 1 } readonly record struct B(int X) { public readonly int X = X; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,16): error CS8340: Instance fields of readonly structs must be readonly. // public int X = X; // 1 Diagnostic(ErrorCode.ERR_FieldsInRoStruct, "X").WithLocation(4, 16) ); } [Fact] public void FieldAsPositionalMember_Fixed() { var src = @" unsafe record struct C(int[] P) { public fixed int P[2]; public int[] X = P; }"; var comp = CreateCompilation(src, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (2,30): error CS8866: Record member 'C.P' must be a readable instance property or field of type 'int[]' to match positional parameter 'P'. // unsafe record struct C(int[] P) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("C.P", "int[]", "P").WithLocation(2, 30), // (4,22): error CS8908: The type 'int*' may not be used for a field of a record. // public fixed int P[2]; Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P").WithArguments("int*").WithLocation(4, 22) ); } [Fact] public void FieldAsPositionalMember_WrongType() { var source = @" record struct A(int X) { public string X = null; public int Y = X; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (2,21): error CS8866: Record member 'A.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'. // record struct A(int X) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("A.X", "int", "X").WithLocation(2, 21) ); } [Fact] public void FieldAsPositionalMember_DuplicateFields() { var source = @" record struct A(int X) { public int X = 0; public int X = 0; public int Y = X; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,16): error CS0102: The type 'A' already contains a definition for 'X' // public int X = 0; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("A", "X").WithLocation(5, 16) ); } [Fact] public void SyntaxFactory_TypeDeclaration() { var expected = @"record struct Point { }"; AssertEx.AssertEqualToleratingWhitespaceDifferences(expected, SyntaxFactory.TypeDeclaration(SyntaxKind.RecordStructDeclaration, "Point").NormalizeWhitespace().ToString()); } [Fact] public void InterfaceWithParameters() { var src = @" public interface I { } record struct R(int X) : I() { } record struct R2(int X) : I(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,27): error CS8861: Unexpected argument list. // record struct R(int X) : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 27), // (10,28): error CS8861: Unexpected argument list. // record struct R2(int X) : I(X) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(10, 28) ); } [Fact] public void InterfaceWithParameters_NoPrimaryConstructor() { var src = @" public interface I { } record struct R : I() { } record struct R2 : I(0) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,20): error CS8861: Unexpected argument list. // record struct R : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 20), // (10,21): error CS8861: Unexpected argument list. // record struct R2 : I(0) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(0)").WithLocation(10, 21) ); } [Fact] public void InterfaceWithParameters_Struct() { var src = @" public interface I { } struct C : I() { } struct C2 : I(0) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,13): error CS8861: Unexpected argument list. // struct C : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 13), // (10,14): error CS8861: Unexpected argument list. // struct C2 : I(0) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(0)").WithLocation(10, 14) ); } [Fact] public void BaseArguments_Speculation() { var src = @" record struct R1(int X) : Error1(0, 1) { } record struct R2(int X) : Error2() { } record struct R3(int X) : Error3 { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,27): error CS0246: The type or namespace name 'Error1' could not be found (are you missing a using directive or an assembly reference?) // record struct R1(int X) : Error1(0, 1) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error1").WithArguments("Error1").WithLocation(2, 27), // (2,33): error CS8861: Unexpected argument list. // record struct R1(int X) : Error1(0, 1) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(0, 1)").WithLocation(2, 33), // (5,27): error CS0246: The type or namespace name 'Error2' could not be found (are you missing a using directive or an assembly reference?) // record struct R2(int X) : Error2() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error2").WithArguments("Error2").WithLocation(5, 27), // (5,33): error CS8861: Unexpected argument list. // record struct R2(int X) : Error2() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(5, 33), // (8,27): error CS0246: The type or namespace name 'Error3' could not be found (are you missing a using directive or an assembly reference?) // record struct R3(int X) : Error3 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error3").WithArguments("Error3").WithLocation(8, 27) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var baseWithargs = tree.GetRoot().DescendantNodes().OfType<PrimaryConstructorBaseTypeSyntax>().First(); Assert.Equal("Error1(0, 1)", baseWithargs.ToString()); var speculativeBase = baseWithargs.WithArgumentList(baseWithargs.ArgumentList.WithArguments(baseWithargs.ArgumentList.Arguments.RemoveAt(1))); Assert.Equal("Error1(0)", speculativeBase.ToString()); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBase, out _)); var baseWithoutargs = tree.GetRoot().DescendantNodes().OfType<PrimaryConstructorBaseTypeSyntax>().Skip(1).First(); Assert.Equal("Error2()", baseWithoutargs.ToString()); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithoutargs.ArgumentList.OpenParenToken.SpanStart, speculativeBase, out _)); var baseWithoutParens = tree.GetRoot().DescendantNodes().OfType<SimpleBaseTypeSyntax>().Single(); Assert.Equal("Error3", baseWithoutParens.ToString()); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithoutParens.SpanStart + 2, speculativeBase, out _)); } [Fact, WorkItem(54413, "https://github.com/dotnet/roslyn/issues/54413")] public void ValueTypeCopyConstructorLike_NoThisInitializer() { var src = @" record struct Value(string Text) { private Value(int X) { } // 1 private Value(Value original) { } // 2 } record class Boxed(string Text) { private Boxed(int X) { } // 3 private Boxed(Boxed original) { } // 4 } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,13): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // private Value(int X) { } // 1 Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "Value").WithLocation(4, 13), // (5,13): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // private Value(Value original) { } // 2 Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "Value").WithLocation(5, 13), // (10,13): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // private Boxed(int X) { } // 3 Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "Boxed").WithLocation(10, 13), // (11,13): error CS8878: A copy constructor 'Boxed.Boxed(Boxed)' must be public or protected because the record is not sealed. // private Boxed(Boxed original) { } // 4 Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "Boxed").WithArguments("Boxed.Boxed(Boxed)").WithLocation(11, 13) ); } [Fact] public void ValueTypeCopyConstructorLike() { var src = @" System.Console.Write(new Value(new Value(0))); record struct Value(int I) { public Value(Value original) : this(42) { } } "; var comp = CreateCompilation(src); CompileAndVerify(comp, expectedOutput: "Value { I = 42 }"); } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Features/VisualBasic/Portable/Debugging/VisualBasicBreakpointService.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Debugging Imports Microsoft.CodeAnalysis.ErrorReporting Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.EditAndContinue Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Debugging <ExportLanguageService(GetType(IBreakpointResolutionService), LanguageNames.VisualBasic), [Shared]> Partial Friend Class VisualBasicBreakpointResolutionService Implements IBreakpointResolutionService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Friend Shared Async Function GetBreakpointAsync(document As Document, position As Integer, length As Integer, cancellationToken As CancellationToken) As Task(Of BreakpointResolutionResult) Try Dim tree = Await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(False) ' Non-zero length means that the span is passed by the debugger and we may need validate it. ' In a rare VB case, this span may contain multiple methods, e.g., ' ' [Sub Goo() Handles A ' ' End Sub ' ' Sub Bar() Handles B] ' ' End Sub ' ' It happens when IDE services (e.g., NavBar or CodeFix) inserts a new method at the beginning of the existing one ' which happens to have a breakpoint on its head. In this situation, we should attempt to validate the span of the existing method, ' not that of a newly-prepended method. Dim descendIntoChildren As Func(Of SyntaxNode, Boolean) = Function(n) Return (Not n.IsKind(SyntaxKind.ConstructorBlock)) _ AndAlso (Not n.IsKind(SyntaxKind.SubBlock)) End Function If length > 0 Then Dim root = Await tree.GetRootAsync(cancellationToken).ConfigureAwait(False) Dim item = root.DescendantNodes(New TextSpan(position, length), descendIntoChildren:=descendIntoChildren).OfType(Of MethodBlockSyntax).Skip(1).LastOrDefault() If item IsNot Nothing Then position = item.SpanStart End If End If Dim span As TextSpan If Not BreakpointSpans.TryGetBreakpointSpan(tree, position, cancellationToken, span) Then Return Nothing End If If span.Length = 0 Then Return BreakpointResolutionResult.CreateLineResult(document) End If Return BreakpointResolutionResult.CreateSpanResult(document, span) Catch e As Exception When FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken) Return Nothing End Try End Function Public Function ResolveBreakpointAsync(document As Document, textSpan As TextSpan, Optional cancellationToken As CancellationToken = Nothing) As Task(Of BreakpointResolutionResult) Implements IBreakpointResolutionService.ResolveBreakpointAsync Return GetBreakpointAsync(document, textSpan.Start, textSpan.Length, cancellationToken) End Function Public Function ResolveBreakpointsAsync( solution As Solution, name As String, Optional cancellationToken As CancellationToken = Nothing) As Task(Of IEnumerable(Of BreakpointResolutionResult)) Implements IBreakpointResolutionService.ResolveBreakpointsAsync Return New BreakpointResolver(solution, name).DoAsync(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.Composition Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Debugging Imports Microsoft.CodeAnalysis.ErrorReporting Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.EditAndContinue Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Debugging <ExportLanguageService(GetType(IBreakpointResolutionService), LanguageNames.VisualBasic), [Shared]> Partial Friend Class VisualBasicBreakpointResolutionService Implements IBreakpointResolutionService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Friend Shared Async Function GetBreakpointAsync(document As Document, position As Integer, length As Integer, cancellationToken As CancellationToken) As Task(Of BreakpointResolutionResult) Try Dim tree = Await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(False) ' Non-zero length means that the span is passed by the debugger and we may need validate it. ' In a rare VB case, this span may contain multiple methods, e.g., ' ' [Sub Goo() Handles A ' ' End Sub ' ' Sub Bar() Handles B] ' ' End Sub ' ' It happens when IDE services (e.g., NavBar or CodeFix) inserts a new method at the beginning of the existing one ' which happens to have a breakpoint on its head. In this situation, we should attempt to validate the span of the existing method, ' not that of a newly-prepended method. Dim descendIntoChildren As Func(Of SyntaxNode, Boolean) = Function(n) Return (Not n.IsKind(SyntaxKind.ConstructorBlock)) _ AndAlso (Not n.IsKind(SyntaxKind.SubBlock)) End Function If length > 0 Then Dim root = Await tree.GetRootAsync(cancellationToken).ConfigureAwait(False) Dim item = root.DescendantNodes(New TextSpan(position, length), descendIntoChildren:=descendIntoChildren).OfType(Of MethodBlockSyntax).Skip(1).LastOrDefault() If item IsNot Nothing Then position = item.SpanStart End If End If Dim span As TextSpan If Not BreakpointSpans.TryGetBreakpointSpan(tree, position, cancellationToken, span) Then Return Nothing End If If span.Length = 0 Then Return BreakpointResolutionResult.CreateLineResult(document) End If Return BreakpointResolutionResult.CreateSpanResult(document, span) Catch e As Exception When FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken) Return Nothing End Try End Function Public Function ResolveBreakpointAsync(document As Document, textSpan As TextSpan, Optional cancellationToken As CancellationToken = Nothing) As Task(Of BreakpointResolutionResult) Implements IBreakpointResolutionService.ResolveBreakpointAsync Return GetBreakpointAsync(document, textSpan.Start, textSpan.Length, cancellationToken) End Function Public Function ResolveBreakpointsAsync( solution As Solution, name As String, Optional cancellationToken As CancellationToken = Nothing) As Task(Of IEnumerable(Of BreakpointResolutionResult)) Implements IBreakpointResolutionService.ResolveBreakpointsAsync Return New BreakpointResolver(solution, name).DoAsync(cancellationToken) End Function End Class End Namespace
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Features/VisualBasic/Portable/SignatureHelp/GetTypeExpressionSignatureHelpProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.SignatureHelp Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators Namespace Microsoft.CodeAnalysis.VisualBasic.SignatureHelp <ExportSignatureHelpProvider("GetTypeExpressionSignatureHelpProvider", LanguageNames.VisualBasic), [Shared]> Partial Friend Class GetTypeExpressionSignatureHelpProvider Inherits AbstractIntrinsicOperatorSignatureHelpProvider(Of GetTypeExpressionSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides Function GetIntrinsicOperatorDocumentationAsync(node As GetTypeExpressionSyntax, document As Document, cancellationToken As CancellationToken) As ValueTask(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation)) Return New ValueTask(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation))({New GetTypeExpressionDocumentation()}) End Function Protected Overrides Function IsTriggerToken(token As SyntaxToken) As Boolean Return token.IsChildToken(Of GetTypeExpressionSyntax)(Function(ce) ce.OpenParenToken) End Function Public Overrides Function IsTriggerCharacter(ch As Char) As Boolean Return ch = "("c End Function Public Overrides Function IsRetriggerCharacter(ch As Char) As Boolean Return ch = ")"c End Function Protected Overrides Function IsArgumentListToken(node As GetTypeExpressionSyntax, token As SyntaxToken) As Boolean Return node.GetTypeKeyword <> token AndAlso node.CloseParenToken <> token End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.SignatureHelp Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators Namespace Microsoft.CodeAnalysis.VisualBasic.SignatureHelp <ExportSignatureHelpProvider("GetTypeExpressionSignatureHelpProvider", LanguageNames.VisualBasic), [Shared]> Partial Friend Class GetTypeExpressionSignatureHelpProvider Inherits AbstractIntrinsicOperatorSignatureHelpProvider(Of GetTypeExpressionSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides Function GetIntrinsicOperatorDocumentationAsync(node As GetTypeExpressionSyntax, document As Document, cancellationToken As CancellationToken) As ValueTask(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation)) Return New ValueTask(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation))({New GetTypeExpressionDocumentation()}) End Function Protected Overrides Function IsTriggerToken(token As SyntaxToken) As Boolean Return token.IsChildToken(Of GetTypeExpressionSyntax)(Function(ce) ce.OpenParenToken) End Function Public Overrides Function IsTriggerCharacter(ch As Char) As Boolean Return ch = "("c End Function Public Overrides Function IsRetriggerCharacter(ch As Char) As Boolean Return ch = ")"c End Function Protected Overrides Function IsArgumentListToken(node As GetTypeExpressionSyntax, token As SyntaxToken) As Boolean Return node.GetTypeKeyword <> token AndAlso node.CloseParenToken <> token End Function End Class End Namespace
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Workspaces/Core/Portable/Shared/Extensions/FileLinePositionSpanExtensions.cs
// Licensed to the .NET Foundation under one or more 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.Shared.Extensions { internal static class FileLinePositionSpanExtensions { /// <summary> /// Get mapped file path if exist, otherwise return null. /// </summary> public static string? GetMappedFilePathIfExist(this FileLinePositionSpan fileLinePositionSpan) => fileLinePositionSpan.HasMappedPath ? fileLinePositionSpan.Path : 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. namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class FileLinePositionSpanExtensions { /// <summary> /// Get mapped file path if exist, otherwise return null. /// </summary> public static string? GetMappedFilePathIfExist(this FileLinePositionSpan fileLinePositionSpan) => fileLinePositionSpan.HasMappedPath ? fileLinePositionSpan.Path : null; } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/VisualBasic/Portable/Binding/SourceFileBinder.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.Concurrent Imports System.Collections.Generic Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.RuntimeMembers Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' A SourceFileBinder provides the context associated with a give source file, not including the ''' Imports statements (which have their own binders). It primarily provides the services of getting ''' locations of node, since it holds onto a SyntaxTree. ''' </summary> Friend Class SourceFileBinder Inherits Binder ' The source file this binder is associated with Private ReadOnly _sourceFile As SourceFile Public Sub New(containingBinder As Binder, sourceFile As SourceFile, tree As SyntaxTree) MyBase.New(containingBinder, tree) Debug.Assert(sourceFile IsNot Nothing) _sourceFile = sourceFile End Sub Public Overrides Function GetSyntaxReference(node As VisualBasicSyntaxNode) As SyntaxReference Return SyntaxTree.GetReference(node) End Function Public Overrides ReadOnly Property OptionStrict As OptionStrict Get ' If the source file had an option strict declaration in it, use that. Otherwise ' defer to the global options. If _sourceFile.OptionStrict.HasValue Then Return If(_sourceFile.OptionStrict.Value, OptionStrict.On, OptionStrict.Off) Else Return m_containingBinder.OptionStrict End If End Get End Property Public Overrides ReadOnly Property OptionInfer As Boolean Get ' If the source file had an option infer declaration in it, use that. Otherwise ' defer to the global options. If _sourceFile.OptionInfer.HasValue Then Return _sourceFile.OptionInfer.Value Else Return m_containingBinder.OptionInfer End If End Get End Property Public Overrides ReadOnly Property OptionExplicit As Boolean Get ' If the source file had an option explicit declaration in it, use that. Otherwise ' defer to the global options. If _sourceFile.OptionExplicit.HasValue Then Return _sourceFile.OptionExplicit.Value Else Return m_containingBinder.OptionExplicit End If End Get End Property Public Overrides ReadOnly Property OptionCompareText As Boolean Get ' If the source file had an option compare declaration in it, use that. Otherwise ' defer to the global options. If _sourceFile.OptionCompareText.HasValue Then Return _sourceFile.OptionCompareText.Value Else Return m_containingBinder.OptionCompareText End If End Get End Property Public Overrides ReadOnly Property QuickAttributeChecker As QuickAttributeChecker Get Return _sourceFile.QuickAttributeChecker 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.Concurrent Imports System.Collections.Generic Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.RuntimeMembers Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' A SourceFileBinder provides the context associated with a give source file, not including the ''' Imports statements (which have their own binders). It primarily provides the services of getting ''' locations of node, since it holds onto a SyntaxTree. ''' </summary> Friend Class SourceFileBinder Inherits Binder ' The source file this binder is associated with Private ReadOnly _sourceFile As SourceFile Public Sub New(containingBinder As Binder, sourceFile As SourceFile, tree As SyntaxTree) MyBase.New(containingBinder, tree) Debug.Assert(sourceFile IsNot Nothing) _sourceFile = sourceFile End Sub Public Overrides Function GetSyntaxReference(node As VisualBasicSyntaxNode) As SyntaxReference Return SyntaxTree.GetReference(node) End Function Public Overrides ReadOnly Property OptionStrict As OptionStrict Get ' If the source file had an option strict declaration in it, use that. Otherwise ' defer to the global options. If _sourceFile.OptionStrict.HasValue Then Return If(_sourceFile.OptionStrict.Value, OptionStrict.On, OptionStrict.Off) Else Return m_containingBinder.OptionStrict End If End Get End Property Public Overrides ReadOnly Property OptionInfer As Boolean Get ' If the source file had an option infer declaration in it, use that. Otherwise ' defer to the global options. If _sourceFile.OptionInfer.HasValue Then Return _sourceFile.OptionInfer.Value Else Return m_containingBinder.OptionInfer End If End Get End Property Public Overrides ReadOnly Property OptionExplicit As Boolean Get ' If the source file had an option explicit declaration in it, use that. Otherwise ' defer to the global options. If _sourceFile.OptionExplicit.HasValue Then Return _sourceFile.OptionExplicit.Value Else Return m_containingBinder.OptionExplicit End If End Get End Property Public Overrides ReadOnly Property OptionCompareText As Boolean Get ' If the source file had an option compare declaration in it, use that. Otherwise ' defer to the global options. If _sourceFile.OptionCompareText.HasValue Then Return _sourceFile.OptionCompareText.Value Else Return m_containingBinder.OptionCompareText End If End Get End Property Public Overrides ReadOnly Property QuickAttributeChecker As QuickAttributeChecker Get Return _sourceFile.QuickAttributeChecker End Get End Property End Class End Namespace
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryImports/CSharpRemoveUnnecessaryImportsCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.RemoveUnnecessaryImports; namespace Microsoft.CodeAnalysis.CSharp.RemoveUnnecessaryImports { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.RemoveUnnecessaryImports), Shared] [ExtensionOrder(After = PredefinedCodeFixProviderNames.AddMissingReference)] internal class CSharpRemoveUnnecessaryImportsCodeFixProvider : AbstractRemoveUnnecessaryImportsCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpRemoveUnnecessaryImportsCodeFixProvider() { } protected override string GetTitle() => CSharpCodeFixesResources.Remove_Unnecessary_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. #nullable disable using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.RemoveUnnecessaryImports; namespace Microsoft.CodeAnalysis.CSharp.RemoveUnnecessaryImports { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.RemoveUnnecessaryImports), Shared] [ExtensionOrder(After = PredefinedCodeFixProviderNames.AddMissingReference)] internal class CSharpRemoveUnnecessaryImportsCodeFixProvider : AbstractRemoveUnnecessaryImportsCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpRemoveUnnecessaryImportsCodeFixProvider() { } protected override string GetTitle() => CSharpCodeFixesResources.Remove_Unnecessary_Usings; } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Features/Core/Portable/SignatureHelp/CommonSignatureHelpUtilities.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SignatureHelp { internal static class CommonSignatureHelpUtilities { internal static SignatureHelpState GetSignatureHelpState<TArgumentList>( TArgumentList argumentList, int position, Func<TArgumentList, SyntaxToken> getOpenToken, Func<TArgumentList, SyntaxToken> getCloseToken, Func<TArgumentList, IEnumerable<SyntaxNodeOrToken>> getArgumentsWithSeparators, Func<TArgumentList, IEnumerable<string>> getArgumentNames) where TArgumentList : SyntaxNode { if (TryGetCurrentArgumentIndex(argumentList, position, getOpenToken, getCloseToken, getArgumentsWithSeparators, out var argumentIndex)) { var argumentNames = getArgumentNames(argumentList).ToList(); var argumentCount = argumentNames.Count; return new SignatureHelpState( argumentIndex, argumentCount, argumentIndex < argumentNames.Count ? argumentNames[argumentIndex] : null, argumentNames.Where(s => s != null).ToList()); } return null; } private static bool TryGetCurrentArgumentIndex<TArgumentList>( TArgumentList argumentList, int position, Func<TArgumentList, SyntaxToken> getOpenToken, Func<TArgumentList, SyntaxToken> getCloseToken, Func<TArgumentList, IEnumerable<SyntaxNodeOrToken>> getArgumentsWithSeparators, out int index) where TArgumentList : SyntaxNode { index = 0; if (position < getOpenToken(argumentList).Span.End) { return false; } var closeToken = getCloseToken(argumentList); if (!closeToken.IsMissing && position > closeToken.SpanStart) { return false; } foreach (var element in getArgumentsWithSeparators(argumentList)) { if (element.IsToken && position >= element.Span.End) { index++; } } return true; } internal static TextSpan GetSignatureHelpSpan<TArgumentList>( TArgumentList argumentList, Func<TArgumentList, SyntaxToken> getCloseToken) where TArgumentList : SyntaxNode { return GetSignatureHelpSpan(argumentList, argumentList.Parent.SpanStart, getCloseToken); } internal static TextSpan GetSignatureHelpSpan<TArgumentList>( TArgumentList argumentList, int start, Func<TArgumentList, SyntaxToken> getCloseToken) where TArgumentList : SyntaxNode { var closeToken = getCloseToken(argumentList); if (closeToken.RawKind != 0 && !closeToken.IsMissing) { return TextSpan.FromBounds(start, closeToken.SpanStart); } // Missing close paren, the span is up to the start of the next token. var lastToken = argumentList.GetLastToken(); var nextToken = lastToken.GetNextToken(); if (nextToken.RawKind == 0) { nextToken = argumentList.AncestorsAndSelf().Last().GetLastToken(includeZeroWidth: true); } return TextSpan.FromBounds(start, nextToken.SpanStart); } internal static bool TryGetSyntax<TSyntax>( SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, Func<SyntaxToken, bool> isTriggerToken, Func<TSyntax, SyntaxToken, bool> isArgumentListToken, CancellationToken cancellationToken, out TSyntax expression) where TSyntax : SyntaxNode { var token = syntaxFacts.FindTokenOnLeftOfPosition(root, position); if (triggerReason == SignatureHelpTriggerReason.TypeCharCommand) { if (isTriggerToken(token) && !syntaxFacts.IsInNonUserCode(root.SyntaxTree, position, cancellationToken)) { expression = token.GetAncestor<TSyntax>(); return true; } } else if (triggerReason == SignatureHelpTriggerReason.InvokeSignatureHelpCommand) { expression = token.Parent?.GetAncestorsOrThis<TSyntax>().SkipWhile(syntax => !isArgumentListToken(syntax, token)).FirstOrDefault(); return expression != null; } else if (triggerReason == SignatureHelpTriggerReason.RetriggerCommand) { if (!syntaxFacts.IsInNonUserCode(root.SyntaxTree, position, cancellationToken) || syntaxFacts.IsEntirelyWithinStringOrCharOrNumericLiteral(root.SyntaxTree, position, cancellationToken)) { expression = token.Parent?.AncestorsAndSelf() .TakeWhile(n => !syntaxFacts.IsAnonymousFunction(n)) .OfType<TSyntax>() .SkipWhile(syntax => !isArgumentListToken(syntax, token)) .FirstOrDefault(); return expression != null; } } expression = null; return false; } public static async Task<ImmutableArray<IMethodSymbol>> GetCollectionInitializerAddMethodsAsync( Document document, SyntaxNode initializer, CancellationToken cancellationToken) { if (initializer == null || initializer.Parent == null) { return default; } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var compilation = semanticModel.Compilation; var ienumerableType = compilation.GetTypeByMetadataName(typeof(IEnumerable).FullName); if (ienumerableType == null) { return default; } // get the regular signature help items var parentOperation = semanticModel.GetOperation(initializer.Parent, cancellationToken) as IObjectOrCollectionInitializerOperation; var parentType = parentOperation?.Type; if (parentType == null) { return default; } if (!parentType.AllInterfaces.Contains(ienumerableType)) { return default; } var position = initializer.SpanStart; var addSymbols = semanticModel.LookupSymbols( position, parentType, WellKnownMemberNames.CollectionInitializerAddMethodName, includeReducedExtensionMethods: true); var addMethods = addSymbols.OfType<IMethodSymbol>() .Where(m => m.Parameters.Length >= 1) .ToImmutableArray() .FilterToVisibleAndBrowsableSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation) .Sort(semanticModel, position); return addMethods; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SignatureHelp { internal static class CommonSignatureHelpUtilities { internal static SignatureHelpState GetSignatureHelpState<TArgumentList>( TArgumentList argumentList, int position, Func<TArgumentList, SyntaxToken> getOpenToken, Func<TArgumentList, SyntaxToken> getCloseToken, Func<TArgumentList, IEnumerable<SyntaxNodeOrToken>> getArgumentsWithSeparators, Func<TArgumentList, IEnumerable<string>> getArgumentNames) where TArgumentList : SyntaxNode { if (TryGetCurrentArgumentIndex(argumentList, position, getOpenToken, getCloseToken, getArgumentsWithSeparators, out var argumentIndex)) { var argumentNames = getArgumentNames(argumentList).ToList(); var argumentCount = argumentNames.Count; return new SignatureHelpState( argumentIndex, argumentCount, argumentIndex < argumentNames.Count ? argumentNames[argumentIndex] : null, argumentNames.Where(s => s != null).ToList()); } return null; } private static bool TryGetCurrentArgumentIndex<TArgumentList>( TArgumentList argumentList, int position, Func<TArgumentList, SyntaxToken> getOpenToken, Func<TArgumentList, SyntaxToken> getCloseToken, Func<TArgumentList, IEnumerable<SyntaxNodeOrToken>> getArgumentsWithSeparators, out int index) where TArgumentList : SyntaxNode { index = 0; if (position < getOpenToken(argumentList).Span.End) { return false; } var closeToken = getCloseToken(argumentList); if (!closeToken.IsMissing && position > closeToken.SpanStart) { return false; } foreach (var element in getArgumentsWithSeparators(argumentList)) { if (element.IsToken && position >= element.Span.End) { index++; } } return true; } internal static TextSpan GetSignatureHelpSpan<TArgumentList>( TArgumentList argumentList, Func<TArgumentList, SyntaxToken> getCloseToken) where TArgumentList : SyntaxNode { return GetSignatureHelpSpan(argumentList, argumentList.Parent.SpanStart, getCloseToken); } internal static TextSpan GetSignatureHelpSpan<TArgumentList>( TArgumentList argumentList, int start, Func<TArgumentList, SyntaxToken> getCloseToken) where TArgumentList : SyntaxNode { var closeToken = getCloseToken(argumentList); if (closeToken.RawKind != 0 && !closeToken.IsMissing) { return TextSpan.FromBounds(start, closeToken.SpanStart); } // Missing close paren, the span is up to the start of the next token. var lastToken = argumentList.GetLastToken(); var nextToken = lastToken.GetNextToken(); if (nextToken.RawKind == 0) { nextToken = argumentList.AncestorsAndSelf().Last().GetLastToken(includeZeroWidth: true); } return TextSpan.FromBounds(start, nextToken.SpanStart); } internal static bool TryGetSyntax<TSyntax>( SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, Func<SyntaxToken, bool> isTriggerToken, Func<TSyntax, SyntaxToken, bool> isArgumentListToken, CancellationToken cancellationToken, out TSyntax expression) where TSyntax : SyntaxNode { var token = syntaxFacts.FindTokenOnLeftOfPosition(root, position); if (triggerReason == SignatureHelpTriggerReason.TypeCharCommand) { if (isTriggerToken(token) && !syntaxFacts.IsInNonUserCode(root.SyntaxTree, position, cancellationToken)) { expression = token.GetAncestor<TSyntax>(); return true; } } else if (triggerReason == SignatureHelpTriggerReason.InvokeSignatureHelpCommand) { expression = token.Parent?.GetAncestorsOrThis<TSyntax>().SkipWhile(syntax => !isArgumentListToken(syntax, token)).FirstOrDefault(); return expression != null; } else if (triggerReason == SignatureHelpTriggerReason.RetriggerCommand) { if (!syntaxFacts.IsInNonUserCode(root.SyntaxTree, position, cancellationToken) || syntaxFacts.IsEntirelyWithinStringOrCharOrNumericLiteral(root.SyntaxTree, position, cancellationToken)) { expression = token.Parent?.AncestorsAndSelf() .TakeWhile(n => !syntaxFacts.IsAnonymousFunction(n)) .OfType<TSyntax>() .SkipWhile(syntax => !isArgumentListToken(syntax, token)) .FirstOrDefault(); return expression != null; } } expression = null; return false; } public static async Task<ImmutableArray<IMethodSymbol>> GetCollectionInitializerAddMethodsAsync( Document document, SyntaxNode initializer, CancellationToken cancellationToken) { if (initializer == null || initializer.Parent == null) { return default; } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var compilation = semanticModel.Compilation; var ienumerableType = compilation.GetTypeByMetadataName(typeof(IEnumerable).FullName); if (ienumerableType == null) { return default; } // get the regular signature help items var parentOperation = semanticModel.GetOperation(initializer.Parent, cancellationToken) as IObjectOrCollectionInitializerOperation; var parentType = parentOperation?.Type; if (parentType == null) { return default; } if (!parentType.AllInterfaces.Contains(ienumerableType)) { return default; } var position = initializer.SpanStart; var addSymbols = semanticModel.LookupSymbols( position, parentType, WellKnownMemberNames.CollectionInitializerAddMethodName, includeReducedExtensionMethods: true); var addMethods = addSymbols.OfType<IMethodSymbol>() .Where(m => m.Parameters.Length >= 1) .ToImmutableArray() .FilterToVisibleAndBrowsableSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation) .Sort(semanticModel, position); return addMethods; } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Workspaces/Core/Portable/Differencing/SequenceEdit.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Differencing { /// <summary> /// Represents an edit operation on a sequence of values. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal struct SequenceEdit : IEquatable<SequenceEdit> { private readonly int _oldIndex; private readonly int _newIndex; internal SequenceEdit(int oldIndex, int newIndex) { Debug.Assert(oldIndex >= -1); Debug.Assert(newIndex >= -1); Debug.Assert(newIndex != -1 || oldIndex != -1); _oldIndex = oldIndex; _newIndex = newIndex; } /// <summary> /// The kind of edit: <see cref="EditKind.Delete"/>, <see cref="EditKind.Insert"/>, or <see cref="EditKind.Update"/>. /// </summary> public EditKind Kind { get { if (_oldIndex == -1) { return EditKind.Insert; } if (_newIndex == -1) { return EditKind.Delete; } return EditKind.Update; } } /// <summary> /// Index in the old sequence, or -1 if the edit is insert. /// </summary> public int OldIndex => _oldIndex; /// <summary> /// Index in the new sequence, or -1 if the edit is delete. /// </summary> public int NewIndex => _newIndex; public bool Equals(SequenceEdit other) { return _oldIndex == other._oldIndex && _newIndex == other._newIndex; } public override bool Equals(object obj) => obj is SequenceEdit && Equals((SequenceEdit)obj); public override int GetHashCode() => Hash.Combine(_oldIndex, _newIndex); private string GetDebuggerDisplay() { var result = Kind.ToString(); switch (Kind) { case EditKind.Delete: return result + " (" + _oldIndex + ")"; case EditKind.Insert: return result + " (" + _newIndex + ")"; case EditKind.Update: return result + " (" + _oldIndex + " -> " + _newIndex + ")"; } return result; } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly SequenceEdit _sequenceEdit; public TestAccessor(SequenceEdit sequenceEdit) => _sequenceEdit = sequenceEdit; internal string GetDebuggerDisplay() => _sequenceEdit.GetDebuggerDisplay(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Differencing { /// <summary> /// Represents an edit operation on a sequence of values. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal struct SequenceEdit : IEquatable<SequenceEdit> { private readonly int _oldIndex; private readonly int _newIndex; internal SequenceEdit(int oldIndex, int newIndex) { Debug.Assert(oldIndex >= -1); Debug.Assert(newIndex >= -1); Debug.Assert(newIndex != -1 || oldIndex != -1); _oldIndex = oldIndex; _newIndex = newIndex; } /// <summary> /// The kind of edit: <see cref="EditKind.Delete"/>, <see cref="EditKind.Insert"/>, or <see cref="EditKind.Update"/>. /// </summary> public EditKind Kind { get { if (_oldIndex == -1) { return EditKind.Insert; } if (_newIndex == -1) { return EditKind.Delete; } return EditKind.Update; } } /// <summary> /// Index in the old sequence, or -1 if the edit is insert. /// </summary> public int OldIndex => _oldIndex; /// <summary> /// Index in the new sequence, or -1 if the edit is delete. /// </summary> public int NewIndex => _newIndex; public bool Equals(SequenceEdit other) { return _oldIndex == other._oldIndex && _newIndex == other._newIndex; } public override bool Equals(object obj) => obj is SequenceEdit && Equals((SequenceEdit)obj); public override int GetHashCode() => Hash.Combine(_oldIndex, _newIndex); private string GetDebuggerDisplay() { var result = Kind.ToString(); switch (Kind) { case EditKind.Delete: return result + " (" + _oldIndex + ")"; case EditKind.Insert: return result + " (" + _newIndex + ")"; case EditKind.Update: return result + " (" + _oldIndex + " -> " + _newIndex + ")"; } return result; } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly SequenceEdit _sequenceEdit; public TestAccessor(SequenceEdit sequenceEdit) => _sequenceEdit = sequenceEdit; internal string GetDebuggerDisplay() => _sequenceEdit.GetDebuggerDisplay(); } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/EditorFeatures/Test2/FindReferences/FindReferencesTests.InternalsVisibleTo.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences Partial Public Class FindReferencesTests <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestPrivateMethodNotSeenInDownstreamProjectWithoutIVT(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> public class C { private static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.Goo(); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInternalMethodNotSeenInDownstreamProjectWithoutIVT(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> public class C { internal static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.Goo(); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestPrivateMethodNotSeenInDownstreamProjectWithIVT(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("P2")] public class C { private static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="P2"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.Goo(); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInternalMethodSeenInDownstreamProjectWithIVT_SimpleString(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("P2")] public class C { internal static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="P2"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.[|Goo|](); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInternalMethodSeenInDownstreamProjectWithIVT_WithAttributeSuffix(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> using System.Runtime.CompilerServices; [assembly: InternalsVisibleToAttribute("P2")] public class C { internal static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="P2"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.[|Goo|](); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInternalMethodSeenInDownstreamProjectWithIVT_QualifiedAttributeName(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("P2")] public class C { internal static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="P2"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.[|Goo|](); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInternalMethodSeenInDownstreamProjectWithIVT_VerbatimString(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(@"P2")] public class C { internal static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="P2"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.[|Goo|](); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInternalMethodSeenInDownstreamProjectWithIVT_UsingAlias(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> using X = System.Runtime.CompilerServices.InternalsVisibleToAttribute; [assembly: X(@"P2")] public class C { internal static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="P2"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.[|Goo|](); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInternalMethodSeenInDownstreamProjectWithIVT_NonLiteralString(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("P" + "2")] public class C { internal static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="P2"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.[|Goo|](); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences Partial Public Class FindReferencesTests <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestPrivateMethodNotSeenInDownstreamProjectWithoutIVT(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> public class C { private static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.Goo(); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInternalMethodNotSeenInDownstreamProjectWithoutIVT(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> public class C { internal static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.Goo(); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestPrivateMethodNotSeenInDownstreamProjectWithIVT(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("P2")] public class C { private static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="P2"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.Goo(); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInternalMethodSeenInDownstreamProjectWithIVT_SimpleString(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("P2")] public class C { internal static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="P2"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.[|Goo|](); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInternalMethodSeenInDownstreamProjectWithIVT_WithAttributeSuffix(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> using System.Runtime.CompilerServices; [assembly: InternalsVisibleToAttribute("P2")] public class C { internal static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="P2"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.[|Goo|](); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInternalMethodSeenInDownstreamProjectWithIVT_QualifiedAttributeName(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("P2")] public class C { internal static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="P2"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.[|Goo|](); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInternalMethodSeenInDownstreamProjectWithIVT_VerbatimString(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(@"P2")] public class C { internal static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="P2"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.[|Goo|](); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInternalMethodSeenInDownstreamProjectWithIVT_UsingAlias(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> using X = System.Runtime.CompilerServices.InternalsVisibleToAttribute; [assembly: X(@"P2")] public class C { internal static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="P2"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.[|Goo|](); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInternalMethodSeenInDownstreamProjectWithIVT_NonLiteralString(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" Name="P1"> <Document> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("P" + "2")] public class C { internal static void $${|Definition:Goo|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="P2"> <ProjectReference>P1</ProjectReference> <Document> class X { void Bar() { C.[|Goo|](); } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function End Class End Namespace
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Query.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitRangeVariable(BoundRangeVariable node) { return VisitExpression(node.Value); } public override BoundNode VisitQueryClause(BoundQueryClause node) { return VisitExpression(node.Value); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitRangeVariable(BoundRangeVariable node) { return VisitExpression(node.Value); } public override BoundNode VisitQueryClause(BoundQueryClause node) { return VisitExpression(node.Value); } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/EditorFeatures/CSharp/xlf/CSharpEditorResources.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="../CSharpEditorResources.resx"> <body> <trans-unit id="Add_Missing_Usings_on_Paste"> <source>Add Missing Usings on Paste</source> <target state="translated">Beim Einfügen fehlende using-Anweisungen hinzufügen</target> <note>"usings" is a language specific term and should not be localized</note> </trans-unit> <trans-unit id="Adding_missing_usings"> <source>Adding missing usings...</source> <target state="translated">Fehlende using-Anweisungen werden hinzugefügt...</target> <note>Shown in a thread await dialog. "usings" is a language specific term and should not be localized</note> </trans-unit> <trans-unit id="Avoid_expression_statements_that_implicitly_ignore_value"> <source>Avoid expression statements that implicitly ignore value</source> <target state="translated">Ausdrucksanweisungen vermeiden, die implizit Werte ignorieren</target> <note /> </trans-unit> <trans-unit id="Avoid_unused_value_assignments"> <source>Avoid unused value assignments</source> <target state="translated">Zuweisungen nicht verwendeter Werte vermeiden</target> <note /> </trans-unit> <trans-unit id="Chosen_version_0"> <source>Chosen version: '{0}'</source> <target state="translated">Ausgewählte Version: {0}</target> <note /> </trans-unit> <trans-unit id="Complete_statement_on_semicolon"> <source>Complete statement on ;</source> <target state="translated">Anweisung abschließen bei ";"</target> <note /> </trans-unit> <trans-unit id="Could_not_find_by_name_0"> <source>Could not find by name: '{0}'</source> <target state="translated">Der Name "{0}" wurde nicht gefunden.</target> <note /> </trans-unit> <trans-unit id="Decompilation_log"> <source>Decompilation log</source> <target state="translated">Dekompilierungsprotokoll</target> <note /> </trans-unit> <trans-unit id="Discard"> <source>Discard</source> <target state="translated">Verwerfen</target> <note /> </trans-unit> <trans-unit id="Elsewhere"> <source>Elsewhere</source> <target state="translated">Anderswo</target> <note /> </trans-unit> <trans-unit id="Fix_interpolated_verbatim_string"> <source>Fix interpolated verbatim string</source> <target state="translated">Interpolierte ausführliche Zeichenfolge korrigieren</target> <note /> </trans-unit> <trans-unit id="For_built_in_types"> <source>For built-in types</source> <target state="translated">Für integrierte Typen</target> <note /> </trans-unit> <trans-unit id="Found_0_assemblies_for_1"> <source>Found '{0}' assemblies for '{1}':</source> <target state="translated">{0} Assemblys für "{1}" gefunden:</target> <note /> </trans-unit> <trans-unit id="Found_exact_match_0"> <source>Found exact match: '{0}'</source> <target state="translated">Exakte Übereinstimmung gefunden: {0}</target> <note /> </trans-unit> <trans-unit id="Found_higher_version_match_0"> <source>Found higher version match: '{0}'</source> <target state="translated">Höhere Versionsübereinstimmung gefunden: {0}</target> <note /> </trans-unit> <trans-unit id="Found_single_assembly_0"> <source>Found single assembly: '{0}'</source> <target state="translated">Einzelne Assembly gefunden: {0}</target> <note /> </trans-unit> <trans-unit id="Generate_Event_Subscription"> <source>Generate Event Subscription</source> <target state="translated">Ereignisabonnement generieren</target> <note /> </trans-unit> <trans-unit id="Ignore_spaces_in_declaration_statements"> <source>Ignore spaces in declaration statements</source> <target state="translated">Leerzeichen um Deklarationsanweisungen ignorieren</target> <note /> </trans-unit> <trans-unit id="Indent_block_contents"> <source>Indent block contents</source> <target state="translated">Blockinhalte einziehen</target> <note /> </trans-unit> <trans-unit id="Indent_case_contents"> <source>Indent case contents</source> <target state="translated">case-Inhalte einziehen</target> <note /> </trans-unit> <trans-unit id="Indent_case_contents_when_block"> <source>Indent case contents (when block)</source> <target state="translated">Case-Inhalte einziehen (bei Block)</target> <note /> </trans-unit> <trans-unit id="Indent_case_labels"> <source>Indent case labels</source> <target state="translated">case-Bezeichnungen einziehen</target> <note /> </trans-unit> <trans-unit id="Indent_open_and_close_braces"> <source>Indent open and close braces</source> <target state="translated">Öffnende und schließende geschweifte Klammern einziehen</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_cast"> <source>Insert space after cast</source> <target state="translated">Leerzeichen nach Umwandlung einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_colon_for_base_or_interface_in_type_declaration"> <source>Insert space after colon for base or interface in type declaration</source> <target state="translated">In Typdeklarationen Leerzeichen nach Doppelpunkt für Basis oder Schnittstelle einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_comma"> <source>Insert space after comma</source> <target state="translated">Leerzeichen nach Komma einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_dot"> <source>Insert space after dot</source> <target state="translated">Leerzeichen nach Punkt einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_keywords_in_control_flow_statements"> <source>Insert space after keywords in control flow statements</source> <target state="translated">Leerzeichen nach Schlüsselwörtern in Anweisungen für die Ablaufsteuerung einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_semicolon_in_for_statement"> <source>Insert space after semicolon in "for" statement</source> <target state="translated">In for-Anweisung Leerzeichen nach Semikolon einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_colon_for_base_or_interface_in_type_declaration"> <source>Insert space before colon for base or interface in type declaration</source> <target state="translated">In Typdeklarationen Leerzeichen vor Doppelpunkt für Basis oder Schnittstelle einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_comma"> <source>Insert space before comma</source> <target state="translated">Leerzeichen vor Komma einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_dot"> <source>Insert space before dot</source> <target state="translated">Leerzeichen vor Punkt einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_open_square_bracket"> <source>Insert space before open square bracket</source> <target state="translated">Leerzeichen vor öffnender eckiger Klammer einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_semicolon_in_for_statement"> <source>Insert space before semicolon in "for" statement</source> <target state="translated">In for-Anweisung Leerzeichen vor Semikolon einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis1"> <source>Insert space between method name and its opening parenthesis</source> <target state="translated">Leerzeichen zwischen Methodenname und öffnender runder Klammer einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis2"> <source>Insert space between method name and its opening parenthesis</source> <target state="translated">Leerzeichen zwischen Methodenname und öffnender runder Klammer einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_argument_list_parentheses"> <source>Insert space within argument list parentheses</source> <target state="translated">Leerzeichen zwischen runden Klammern um Argumentliste einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_argument_list_parentheses"> <source>Insert space within empty argument list parentheses</source> <target state="translated">Leerzeichen zwischen runden Klammern um leere Argumentliste einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_parameter_list_parentheses"> <source>Insert space within empty parameter list parentheses</source> <target state="translated">Leerzeichen zwischen runden Klammern in leere Parameterliste einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_square_brackets"> <source>Insert space within empty square brackets</source> <target state="translated">Leerzeichen zwischen leeren eckigen Klammern einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parameter_list_parentheses"> <source>Insert space within parameter list parentheses</source> <target state="translated">Leerzeichen zwischen runden Klammern in Parameterliste einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parentheses_of_expressions"> <source>Insert space within parentheses of expressions</source> <target state="translated">Leerzeichen zwischen runden Klammern von Ausdrücken einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parentheses_of_type_casts"> <source>Insert space within parentheses of type casts</source> <target state="translated">Leerzeichen zwischen runde Klammern für Typumwandlungen einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_spaces_within_parentheses_of_control_flow_statements"> <source>Insert spaces within parentheses of control flow statements</source> <target state="translated">Leerzeichen zwischen den Klammern von Ablaufsteuerungsanweisungen einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_spaces_within_square_brackets"> <source>Insert spaces within square brackets</source> <target state="translated">Leerzeichen zwischen eckigen Klammern einfügen</target> <note /> </trans-unit> <trans-unit id="Inside_namespace"> <source>Inside namespace</source> <target state="translated">Innerhalb des Namespaces</target> <note /> </trans-unit> <trans-unit id="Label_Indentation"> <source>Label Indentation</source> <target state="translated">Bezeichnungseinzug</target> <note /> </trans-unit> <trans-unit id="Leave_block_on_single_line"> <source>Leave block on single line</source> <target state="translated">Block auf einzelner Zeile belassen</target> <note /> </trans-unit> <trans-unit id="Leave_statements_and_member_declarations_on_the_same_line"> <source>Leave statements and member declarations on the same line</source> <target state="translated">Anweisungen und Memberdeklarationen auf der gleichen Zeile belassen</target> <note /> </trans-unit> <trans-unit id="Load_from_0"> <source>Load from: '{0}'</source> <target state="translated">Laden von: {0}</target> <note /> </trans-unit> <trans-unit id="Module_not_found"> <source>Module not found!</source> <target state="translated">Das Modul wurde nicht gefunden.</target> <note /> </trans-unit> <trans-unit id="Never"> <source>Never</source> <target state="translated">Nie</target> <note /> </trans-unit> <trans-unit id="Outside_namespace"> <source>Outside namespace</source> <target state="translated">Außerhalb des Namespaces</target> <note /> </trans-unit> <trans-unit id="Place_catch_on_new_line"> <source>Place "catch" on new line</source> <target state="translated">catch-Anweisung in neue Zeile setzen</target> <note /> </trans-unit> <trans-unit id="Place_else_on_new_line"> <source>Place "else" on new line</source> <target state="translated">else-Anweisung in neue Zeile setzen</target> <note /> </trans-unit> <trans-unit id="Place_finally_on_new_line"> <source>Place "finally" on new line</source> <target state="translated">finally-Anweisung in neue Zeile setzen</target> <note /> </trans-unit> <trans-unit id="Place_members_in_anonymous_types_on_new_line"> <source>Place members in anonymous types on new line</source> <target state="translated">Member in anonymen Typen in neue Zeile setzen</target> <note /> </trans-unit> <trans-unit id="Place_members_in_object_initializers_on_new_line"> <source>Place members in object initializers on new line</source> <target state="translated">Elemente in Objektinitialisierern in neue Zeile setzen</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_anonymous_methods"> <source>Place open brace on new line for anonymous methods</source> <target state="translated">Öffnende geschweifte Klammer für anonyme Methoden in neuer Zeile platzieren</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_anonymous_types"> <source>Place open brace on new line for anonymous types</source> <target state="translated">Öffnende geschweifte Klammer für anonyme Typen in neuer Zeile platzieren</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_control_blocks"> <source>Place open brace on new line for control blocks</source> <target state="translated">Öffnende geschweifte Klammer für Kontrollblöcke in neuer Zeile platzieren</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_lambda_expression"> <source>Place open brace on new line for lambda expression</source> <target state="translated">Öffnende geschweifte Klammer für Lambdaausdruck in neue Zeile setzen</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_methods_local_functions"> <source>Place open brace on new line for methods and local functions</source> <target state="translated">Öffnende geschweifte Klammer in neuer Zeile für Methoden und lokale Funktionen einfügen</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_object_collection_array_and_with_initializers"> <source>Place open brace on new line for object, collection, array, and with initializers</source> <target state="translated">Öffnende geschweifte Klammer für Objekt-, Sammlungs-, Array- und with-Initialisierer in neue Zeile einfügen</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_properties_indexers_and_events"> <source>Place open brace on new line for properties, indexers, and events</source> <target state="translated">Fügt eine öffnende geschweifte Klammer für Eigenschaften, Indexer und Ereignisse in einer neuen Zeile ein.</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_property_indexer_and_event_accessors"> <source>Place open brace on new line for property, indexer, and event accessors</source> <target state="translated">Fügt eine öffnende geschweifte Klammer für eine Eigenschaft, den Indexer und Ereignisaccessor in einer neuen Zeile ein.</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_types"> <source>Place open brace on new line for types</source> <target state="translated">Öffnende geschweifte Klammer für Typen in neuer Zeile platzieren</target> <note /> </trans-unit> <trans-unit id="Place_query_expression_clauses_on_new_line"> <source>Place query expression clauses on new line</source> <target state="translated">Klauseln von Abfrageausdrücken in neuer Zeile platzieren</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_delegate_call"> <source>Prefer conditional delegate call</source> <target state="translated">Bedingten Delegataufruf bevorzugen</target> <note /> </trans-unit> <trans-unit id="Prefer_deconstructed_variable_declaration"> <source>Prefer deconstructed variable declaration</source> <target state="translated">Dekonstruierte Variablendeklaration vorziehen</target> <note /> </trans-unit> <trans-unit id="Prefer_explicit_type"> <source>Prefer explicit type</source> <target state="translated">Expliziten Typ bevorzugen</target> <note /> </trans-unit> <trans-unit id="Prefer_index_operator"> <source>Prefer index operator</source> <target state="translated">Indexoperator bevorzugen</target> <note /> </trans-unit> <trans-unit id="Prefer_inlined_variable_declaration"> <source>Prefer inlined variable declaration</source> <target state="translated">Inlinevariablendeklaration vorziehen</target> <note /> </trans-unit> <trans-unit id="Prefer_local_function_over_anonymous_function"> <source>Prefer local function over anonymous function</source> <target state="translated">Lokale Funktion gegenüber anonymer Funktion bevorzugen</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching"> <source>Prefer pattern matching</source> <target state="translated">Musterabgleich bevorzugen</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_as_with_null_check"> <source>Prefer pattern matching over 'as' with 'null' check</source> <target state="translated">Bei der NULL-Überprüfung Musterabgleich gegenüber "as" bevorzugen</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_is_with_cast_check"> <source>Prefer pattern matching over 'is' with 'cast' check</source> <target state="translated">Bei der cast-Überprüfung Musterabgleich gegenüber "is" bevorzugen</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_mixed_type_check"> <source>Prefer pattern matching over mixed type check</source> <target state="translated">Musterabgleich gegenüber der Überprüfung gemischter Typen bevorzugen</target> <note /> </trans-unit> <trans-unit id="Prefer_range_operator"> <source>Prefer range operator</source> <target state="translated">Bereichsoperator bevorzugen</target> <note /> </trans-unit> <trans-unit id="Prefer_simple_default_expression"> <source>Prefer simple 'default' expression</source> <target state="translated">Einfachen "default"-Ausdruck bevorzugen</target> <note /> </trans-unit> <trans-unit id="Prefer_simple_using_statement"> <source>Prefer simple 'using' statement</source> <target state="translated">Einfache using-Anweisung bevorzugen</target> <note /> </trans-unit> <trans-unit id="Prefer_static_local_functions"> <source>Prefer static local functions</source> <target state="translated">Statische lokale Funktionen bevorzugen</target> <note /> </trans-unit> <trans-unit id="Prefer_switch_expression"> <source>Prefer switch expression</source> <target state="translated">Switch-Ausdruck bevorzugen</target> <note /> </trans-unit> <trans-unit id="Prefer_throw_expression"> <source>Prefer throw-expression</source> <target state="translated">throw-Ausdruck bevorzugen</target> <note /> </trans-unit> <trans-unit id="Prefer_var"> <source>Prefer 'var'</source> <target state="translated">"var" bevorzugen</target> <note /> </trans-unit> <trans-unit id="Preferred_using_directive_placement"> <source>Preferred 'using' directive placement</source> <target state="translated">Bevorzugte Platzierung der using-Anweisung</target> <note /> </trans-unit> <trans-unit id="Press_TAB_to_insert"> <source> (Press TAB to insert)</source> <target state="translated"> (Zum Einfügen TAB-TASTE drücken)</target> <note /> </trans-unit> <trans-unit id="Resolve_0"> <source>Resolve: '{0}'</source> <target state="translated">Auflösen: {0}</target> <note /> </trans-unit> <trans-unit id="Resolve_module_0_of_1"> <source>Resolve module: '{0}' of '{1}'</source> <target state="translated">Modul auflösen: {0} von {1}</target> <note /> </trans-unit> <trans-unit id="Set_spacing_for_operators"> <source>Set spacing for operators</source> <target state="translated">Abstände für Operatoren festlegen</target> <note /> </trans-unit> <trans-unit id="Smart_Indenting"> <source>Smart Indenting</source> <target state="translated">Intelligenter Einzug</target> <note /> </trans-unit> <trans-unit id="Split_string"> <source>Split string</source> <target state="translated">Zeichenfolge teilen</target> <note /> </trans-unit> <trans-unit id="Unused_local"> <source>Unused local</source> <target state="translated">Nicht verwendete lokale Variable</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">Ausdruckskörper für Accessoren verwenden</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">Ausdruckskörper für Konstruktoren verwenden</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">Ausdruckskörper für Indexer verwenden</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_lambdas"> <source>Use expression body for lambdas</source> <target state="translated">Ausdruckskörper für Lambdaausdrücke verwenden</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">Ausdruckstext für lokale Funktionen verwenden</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">Ausdruckskörper für Methoden verwenden</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">Ausdruckskörper für Operatoren verwenden</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">Ausdruckskörper für Eigenschaften verwenden</target> <note /> </trans-unit> <trans-unit id="WARN_Version_mismatch_Expected_0_Got_1"> <source>WARN: Version mismatch. Expected: '{0}', Got: '{1}'</source> <target state="translated">WARNUNG: Versionskonflikt. Erwartet: "{0}", erhalten: "{1}"</target> <note /> </trans-unit> <trans-unit id="When_on_single_line"> <source>When on single line</source> <target state="translated">In einzelner Zeile</target> <note /> </trans-unit> <trans-unit id="When_possible"> <source>When possible</source> <target state="translated">Wenn möglich</target> <note /> </trans-unit> <trans-unit id="When_variable_type_is_apparent"> <source>When variable type is apparent</source> <target state="translated">Wenn der Variablentyp offensichtlich ist</target> <note /> </trans-unit> <trans-unit id="_0_items_in_cache"> <source>'{0}' items in cache</source> <target state="translated">{0} Elemente im Cache</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="../CSharpEditorResources.resx"> <body> <trans-unit id="Add_Missing_Usings_on_Paste"> <source>Add Missing Usings on Paste</source> <target state="translated">Beim Einfügen fehlende using-Anweisungen hinzufügen</target> <note>"usings" is a language specific term and should not be localized</note> </trans-unit> <trans-unit id="Adding_missing_usings"> <source>Adding missing usings...</source> <target state="translated">Fehlende using-Anweisungen werden hinzugefügt...</target> <note>Shown in a thread await dialog. "usings" is a language specific term and should not be localized</note> </trans-unit> <trans-unit id="Avoid_expression_statements_that_implicitly_ignore_value"> <source>Avoid expression statements that implicitly ignore value</source> <target state="translated">Ausdrucksanweisungen vermeiden, die implizit Werte ignorieren</target> <note /> </trans-unit> <trans-unit id="Avoid_unused_value_assignments"> <source>Avoid unused value assignments</source> <target state="translated">Zuweisungen nicht verwendeter Werte vermeiden</target> <note /> </trans-unit> <trans-unit id="Chosen_version_0"> <source>Chosen version: '{0}'</source> <target state="translated">Ausgewählte Version: {0}</target> <note /> </trans-unit> <trans-unit id="Complete_statement_on_semicolon"> <source>Complete statement on ;</source> <target state="translated">Anweisung abschließen bei ";"</target> <note /> </trans-unit> <trans-unit id="Could_not_find_by_name_0"> <source>Could not find by name: '{0}'</source> <target state="translated">Der Name "{0}" wurde nicht gefunden.</target> <note /> </trans-unit> <trans-unit id="Decompilation_log"> <source>Decompilation log</source> <target state="translated">Dekompilierungsprotokoll</target> <note /> </trans-unit> <trans-unit id="Discard"> <source>Discard</source> <target state="translated">Verwerfen</target> <note /> </trans-unit> <trans-unit id="Elsewhere"> <source>Elsewhere</source> <target state="translated">Anderswo</target> <note /> </trans-unit> <trans-unit id="Fix_interpolated_verbatim_string"> <source>Fix interpolated verbatim string</source> <target state="translated">Interpolierte ausführliche Zeichenfolge korrigieren</target> <note /> </trans-unit> <trans-unit id="For_built_in_types"> <source>For built-in types</source> <target state="translated">Für integrierte Typen</target> <note /> </trans-unit> <trans-unit id="Found_0_assemblies_for_1"> <source>Found '{0}' assemblies for '{1}':</source> <target state="translated">{0} Assemblys für "{1}" gefunden:</target> <note /> </trans-unit> <trans-unit id="Found_exact_match_0"> <source>Found exact match: '{0}'</source> <target state="translated">Exakte Übereinstimmung gefunden: {0}</target> <note /> </trans-unit> <trans-unit id="Found_higher_version_match_0"> <source>Found higher version match: '{0}'</source> <target state="translated">Höhere Versionsübereinstimmung gefunden: {0}</target> <note /> </trans-unit> <trans-unit id="Found_single_assembly_0"> <source>Found single assembly: '{0}'</source> <target state="translated">Einzelne Assembly gefunden: {0}</target> <note /> </trans-unit> <trans-unit id="Generate_Event_Subscription"> <source>Generate Event Subscription</source> <target state="translated">Ereignisabonnement generieren</target> <note /> </trans-unit> <trans-unit id="Ignore_spaces_in_declaration_statements"> <source>Ignore spaces in declaration statements</source> <target state="translated">Leerzeichen um Deklarationsanweisungen ignorieren</target> <note /> </trans-unit> <trans-unit id="Indent_block_contents"> <source>Indent block contents</source> <target state="translated">Blockinhalte einziehen</target> <note /> </trans-unit> <trans-unit id="Indent_case_contents"> <source>Indent case contents</source> <target state="translated">case-Inhalte einziehen</target> <note /> </trans-unit> <trans-unit id="Indent_case_contents_when_block"> <source>Indent case contents (when block)</source> <target state="translated">Case-Inhalte einziehen (bei Block)</target> <note /> </trans-unit> <trans-unit id="Indent_case_labels"> <source>Indent case labels</source> <target state="translated">case-Bezeichnungen einziehen</target> <note /> </trans-unit> <trans-unit id="Indent_open_and_close_braces"> <source>Indent open and close braces</source> <target state="translated">Öffnende und schließende geschweifte Klammern einziehen</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_cast"> <source>Insert space after cast</source> <target state="translated">Leerzeichen nach Umwandlung einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_colon_for_base_or_interface_in_type_declaration"> <source>Insert space after colon for base or interface in type declaration</source> <target state="translated">In Typdeklarationen Leerzeichen nach Doppelpunkt für Basis oder Schnittstelle einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_comma"> <source>Insert space after comma</source> <target state="translated">Leerzeichen nach Komma einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_dot"> <source>Insert space after dot</source> <target state="translated">Leerzeichen nach Punkt einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_keywords_in_control_flow_statements"> <source>Insert space after keywords in control flow statements</source> <target state="translated">Leerzeichen nach Schlüsselwörtern in Anweisungen für die Ablaufsteuerung einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_semicolon_in_for_statement"> <source>Insert space after semicolon in "for" statement</source> <target state="translated">In for-Anweisung Leerzeichen nach Semikolon einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_colon_for_base_or_interface_in_type_declaration"> <source>Insert space before colon for base or interface in type declaration</source> <target state="translated">In Typdeklarationen Leerzeichen vor Doppelpunkt für Basis oder Schnittstelle einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_comma"> <source>Insert space before comma</source> <target state="translated">Leerzeichen vor Komma einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_dot"> <source>Insert space before dot</source> <target state="translated">Leerzeichen vor Punkt einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_open_square_bracket"> <source>Insert space before open square bracket</source> <target state="translated">Leerzeichen vor öffnender eckiger Klammer einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_semicolon_in_for_statement"> <source>Insert space before semicolon in "for" statement</source> <target state="translated">In for-Anweisung Leerzeichen vor Semikolon einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis1"> <source>Insert space between method name and its opening parenthesis</source> <target state="translated">Leerzeichen zwischen Methodenname und öffnender runder Klammer einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis2"> <source>Insert space between method name and its opening parenthesis</source> <target state="translated">Leerzeichen zwischen Methodenname und öffnender runder Klammer einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_argument_list_parentheses"> <source>Insert space within argument list parentheses</source> <target state="translated">Leerzeichen zwischen runden Klammern um Argumentliste einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_argument_list_parentheses"> <source>Insert space within empty argument list parentheses</source> <target state="translated">Leerzeichen zwischen runden Klammern um leere Argumentliste einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_parameter_list_parentheses"> <source>Insert space within empty parameter list parentheses</source> <target state="translated">Leerzeichen zwischen runden Klammern in leere Parameterliste einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_square_brackets"> <source>Insert space within empty square brackets</source> <target state="translated">Leerzeichen zwischen leeren eckigen Klammern einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parameter_list_parentheses"> <source>Insert space within parameter list parentheses</source> <target state="translated">Leerzeichen zwischen runden Klammern in Parameterliste einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parentheses_of_expressions"> <source>Insert space within parentheses of expressions</source> <target state="translated">Leerzeichen zwischen runden Klammern von Ausdrücken einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parentheses_of_type_casts"> <source>Insert space within parentheses of type casts</source> <target state="translated">Leerzeichen zwischen runde Klammern für Typumwandlungen einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_spaces_within_parentheses_of_control_flow_statements"> <source>Insert spaces within parentheses of control flow statements</source> <target state="translated">Leerzeichen zwischen den Klammern von Ablaufsteuerungsanweisungen einfügen</target> <note /> </trans-unit> <trans-unit id="Insert_spaces_within_square_brackets"> <source>Insert spaces within square brackets</source> <target state="translated">Leerzeichen zwischen eckigen Klammern einfügen</target> <note /> </trans-unit> <trans-unit id="Inside_namespace"> <source>Inside namespace</source> <target state="translated">Innerhalb des Namespaces</target> <note /> </trans-unit> <trans-unit id="Label_Indentation"> <source>Label Indentation</source> <target state="translated">Bezeichnungseinzug</target> <note /> </trans-unit> <trans-unit id="Leave_block_on_single_line"> <source>Leave block on single line</source> <target state="translated">Block auf einzelner Zeile belassen</target> <note /> </trans-unit> <trans-unit id="Leave_statements_and_member_declarations_on_the_same_line"> <source>Leave statements and member declarations on the same line</source> <target state="translated">Anweisungen und Memberdeklarationen auf der gleichen Zeile belassen</target> <note /> </trans-unit> <trans-unit id="Load_from_0"> <source>Load from: '{0}'</source> <target state="translated">Laden von: {0}</target> <note /> </trans-unit> <trans-unit id="Module_not_found"> <source>Module not found!</source> <target state="translated">Das Modul wurde nicht gefunden.</target> <note /> </trans-unit> <trans-unit id="Never"> <source>Never</source> <target state="translated">Nie</target> <note /> </trans-unit> <trans-unit id="Outside_namespace"> <source>Outside namespace</source> <target state="translated">Außerhalb des Namespaces</target> <note /> </trans-unit> <trans-unit id="Place_catch_on_new_line"> <source>Place "catch" on new line</source> <target state="translated">catch-Anweisung in neue Zeile setzen</target> <note /> </trans-unit> <trans-unit id="Place_else_on_new_line"> <source>Place "else" on new line</source> <target state="translated">else-Anweisung in neue Zeile setzen</target> <note /> </trans-unit> <trans-unit id="Place_finally_on_new_line"> <source>Place "finally" on new line</source> <target state="translated">finally-Anweisung in neue Zeile setzen</target> <note /> </trans-unit> <trans-unit id="Place_members_in_anonymous_types_on_new_line"> <source>Place members in anonymous types on new line</source> <target state="translated">Member in anonymen Typen in neue Zeile setzen</target> <note /> </trans-unit> <trans-unit id="Place_members_in_object_initializers_on_new_line"> <source>Place members in object initializers on new line</source> <target state="translated">Elemente in Objektinitialisierern in neue Zeile setzen</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_anonymous_methods"> <source>Place open brace on new line for anonymous methods</source> <target state="translated">Öffnende geschweifte Klammer für anonyme Methoden in neuer Zeile platzieren</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_anonymous_types"> <source>Place open brace on new line for anonymous types</source> <target state="translated">Öffnende geschweifte Klammer für anonyme Typen in neuer Zeile platzieren</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_control_blocks"> <source>Place open brace on new line for control blocks</source> <target state="translated">Öffnende geschweifte Klammer für Kontrollblöcke in neuer Zeile platzieren</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_lambda_expression"> <source>Place open brace on new line for lambda expression</source> <target state="translated">Öffnende geschweifte Klammer für Lambdaausdruck in neue Zeile setzen</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_methods_local_functions"> <source>Place open brace on new line for methods and local functions</source> <target state="translated">Öffnende geschweifte Klammer in neuer Zeile für Methoden und lokale Funktionen einfügen</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_object_collection_array_and_with_initializers"> <source>Place open brace on new line for object, collection, array, and with initializers</source> <target state="translated">Öffnende geschweifte Klammer für Objekt-, Sammlungs-, Array- und with-Initialisierer in neue Zeile einfügen</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_properties_indexers_and_events"> <source>Place open brace on new line for properties, indexers, and events</source> <target state="translated">Fügt eine öffnende geschweifte Klammer für Eigenschaften, Indexer und Ereignisse in einer neuen Zeile ein.</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_property_indexer_and_event_accessors"> <source>Place open brace on new line for property, indexer, and event accessors</source> <target state="translated">Fügt eine öffnende geschweifte Klammer für eine Eigenschaft, den Indexer und Ereignisaccessor in einer neuen Zeile ein.</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_types"> <source>Place open brace on new line for types</source> <target state="translated">Öffnende geschweifte Klammer für Typen in neuer Zeile platzieren</target> <note /> </trans-unit> <trans-unit id="Place_query_expression_clauses_on_new_line"> <source>Place query expression clauses on new line</source> <target state="translated">Klauseln von Abfrageausdrücken in neuer Zeile platzieren</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_delegate_call"> <source>Prefer conditional delegate call</source> <target state="translated">Bedingten Delegataufruf bevorzugen</target> <note /> </trans-unit> <trans-unit id="Prefer_deconstructed_variable_declaration"> <source>Prefer deconstructed variable declaration</source> <target state="translated">Dekonstruierte Variablendeklaration vorziehen</target> <note /> </trans-unit> <trans-unit id="Prefer_explicit_type"> <source>Prefer explicit type</source> <target state="translated">Expliziten Typ bevorzugen</target> <note /> </trans-unit> <trans-unit id="Prefer_index_operator"> <source>Prefer index operator</source> <target state="translated">Indexoperator bevorzugen</target> <note /> </trans-unit> <trans-unit id="Prefer_inlined_variable_declaration"> <source>Prefer inlined variable declaration</source> <target state="translated">Inlinevariablendeklaration vorziehen</target> <note /> </trans-unit> <trans-unit id="Prefer_local_function_over_anonymous_function"> <source>Prefer local function over anonymous function</source> <target state="translated">Lokale Funktion gegenüber anonymer Funktion bevorzugen</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching"> <source>Prefer pattern matching</source> <target state="translated">Musterabgleich bevorzugen</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_as_with_null_check"> <source>Prefer pattern matching over 'as' with 'null' check</source> <target state="translated">Bei der NULL-Überprüfung Musterabgleich gegenüber "as" bevorzugen</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_is_with_cast_check"> <source>Prefer pattern matching over 'is' with 'cast' check</source> <target state="translated">Bei der cast-Überprüfung Musterabgleich gegenüber "is" bevorzugen</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_mixed_type_check"> <source>Prefer pattern matching over mixed type check</source> <target state="translated">Musterabgleich gegenüber der Überprüfung gemischter Typen bevorzugen</target> <note /> </trans-unit> <trans-unit id="Prefer_range_operator"> <source>Prefer range operator</source> <target state="translated">Bereichsoperator bevorzugen</target> <note /> </trans-unit> <trans-unit id="Prefer_simple_default_expression"> <source>Prefer simple 'default' expression</source> <target state="translated">Einfachen "default"-Ausdruck bevorzugen</target> <note /> </trans-unit> <trans-unit id="Prefer_simple_using_statement"> <source>Prefer simple 'using' statement</source> <target state="translated">Einfache using-Anweisung bevorzugen</target> <note /> </trans-unit> <trans-unit id="Prefer_static_local_functions"> <source>Prefer static local functions</source> <target state="translated">Statische lokale Funktionen bevorzugen</target> <note /> </trans-unit> <trans-unit id="Prefer_switch_expression"> <source>Prefer switch expression</source> <target state="translated">Switch-Ausdruck bevorzugen</target> <note /> </trans-unit> <trans-unit id="Prefer_throw_expression"> <source>Prefer throw-expression</source> <target state="translated">throw-Ausdruck bevorzugen</target> <note /> </trans-unit> <trans-unit id="Prefer_var"> <source>Prefer 'var'</source> <target state="translated">"var" bevorzugen</target> <note /> </trans-unit> <trans-unit id="Preferred_using_directive_placement"> <source>Preferred 'using' directive placement</source> <target state="translated">Bevorzugte Platzierung der using-Anweisung</target> <note /> </trans-unit> <trans-unit id="Press_TAB_to_insert"> <source> (Press TAB to insert)</source> <target state="translated"> (Zum Einfügen TAB-TASTE drücken)</target> <note /> </trans-unit> <trans-unit id="Resolve_0"> <source>Resolve: '{0}'</source> <target state="translated">Auflösen: {0}</target> <note /> </trans-unit> <trans-unit id="Resolve_module_0_of_1"> <source>Resolve module: '{0}' of '{1}'</source> <target state="translated">Modul auflösen: {0} von {1}</target> <note /> </trans-unit> <trans-unit id="Set_spacing_for_operators"> <source>Set spacing for operators</source> <target state="translated">Abstände für Operatoren festlegen</target> <note /> </trans-unit> <trans-unit id="Smart_Indenting"> <source>Smart Indenting</source> <target state="translated">Intelligenter Einzug</target> <note /> </trans-unit> <trans-unit id="Split_string"> <source>Split string</source> <target state="translated">Zeichenfolge teilen</target> <note /> </trans-unit> <trans-unit id="Unused_local"> <source>Unused local</source> <target state="translated">Nicht verwendete lokale Variable</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">Ausdruckskörper für Accessoren verwenden</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">Ausdruckskörper für Konstruktoren verwenden</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">Ausdruckskörper für Indexer verwenden</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_lambdas"> <source>Use expression body for lambdas</source> <target state="translated">Ausdruckskörper für Lambdaausdrücke verwenden</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">Ausdruckstext für lokale Funktionen verwenden</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">Ausdruckskörper für Methoden verwenden</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">Ausdruckskörper für Operatoren verwenden</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">Ausdruckskörper für Eigenschaften verwenden</target> <note /> </trans-unit> <trans-unit id="WARN_Version_mismatch_Expected_0_Got_1"> <source>WARN: Version mismatch. Expected: '{0}', Got: '{1}'</source> <target state="translated">WARNUNG: Versionskonflikt. Erwartet: "{0}", erhalten: "{1}"</target> <note /> </trans-unit> <trans-unit id="When_on_single_line"> <source>When on single line</source> <target state="translated">In einzelner Zeile</target> <note /> </trans-unit> <trans-unit id="When_possible"> <source>When possible</source> <target state="translated">Wenn möglich</target> <note /> </trans-unit> <trans-unit id="When_variable_type_is_apparent"> <source>When variable type is apparent</source> <target state="translated">Wenn der Variablentyp offensichtlich ist</target> <note /> </trans-unit> <trans-unit id="_0_items_in_cache"> <source>'{0}' items in cache</source> <target state="translated">{0} Elemente im Cache</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,223
Rework our netstandard1.3 test references
The `netstandard1.3` test references were being provided by our MS.CA.Test.Resources.Proprietary package. The contents of this package get included in the output directory of every single unit test DLL that we build (which contributes to build output size). The references themselves though were only used in a very small number of tests. This change upgrades to a version of MS.CA.Test.Resources.Proprietary that has the `netstandard1.3` references removed and adds the `netstandard1.3` references to only the projects that needs them
jaredpar
"2021-09-07T20:35:04Z"
"2021-09-07T23:50:57Z"
0240973369997c88a2c2f1aaa22c14182ac17e9f
5dbd783367d7f6b105726b84558cc1809aa198ce
Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our MS.CA.Test.Resources.Proprietary package. The contents of this package get included in the output directory of every single unit test DLL that we build (which contributes to build output size). The references themselves though were only used in a very small number of tests. This change upgrades to a version of MS.CA.Test.Resources.Proprietary that has the `netstandard1.3` references removed and adds the `netstandard1.3` references to only the projects that needs them
./eng/Versions.props
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project> <!-- Roslyn version --> <PropertyGroup> <MajorVersion>4</MajorVersion> <MinorVersion>0</MinorVersion> <PatchVersion>0</PatchVersion> <PreReleaseVersionLabel>5</PreReleaseVersionLabel> <VersionPrefix>$(MajorVersion).$(MinorVersion).$(PatchVersion)</VersionPrefix> <!-- By default the assembly version in official builds is "$(MajorVersion).$(MinorVersion).0.0". Keep the setting conditional. The toolset sets the assembly version to 42.42.42.42 if not set explicitly. --> <AssemblyVersion Condition="'$(OfficialBuild)' == 'true' or '$(DotNetUseShippingVersions)' == 'true'">$(MajorVersion).$(MinorVersion).0.0</AssemblyVersion> <!-- Arcade overrides our VersionPrefix when MajorVersion and MinorVersion are specified. Clear them so that we can keep the PatchVersion until we are using an SDK that includes https://github.com/dotnet/arcade/pull/3601 --> <MajorVersion> </MajorVersion> <MinorVersion> </MinorVersion> <MicrosoftNetCompilersToolsetVersion>4.0.0-4.21420.19</MicrosoftNetCompilersToolsetVersion> </PropertyGroup> <PropertyGroup> <!-- Versions used by several individual references below --> <RoslynDiagnosticsNugetPackageVersion>3.3.3-beta1.21105.3</RoslynDiagnosticsNugetPackageVersion> <MicrosoftCodeAnalysisNetAnalyzersVersion>6.0.0-rc1.21366.2</MicrosoftCodeAnalysisNetAnalyzersVersion> <MicrosoftCodeAnalysisTestingVersion>1.1.0-beta1.21322.2</MicrosoftCodeAnalysisTestingVersion> <!-- CodeStyleAnalyzerVersion should we updated together with version of dotnet-format in dotnet-tools.json --> <CodeStyleAnalyzerVersion>4.0.0-3.final</CodeStyleAnalyzerVersion> <VisualStudioEditorPackagesVersion>16.10.230</VisualStudioEditorPackagesVersion> <VisualStudioEditorNewPackagesVersion>17.0.83-preview</VisualStudioEditorNewPackagesVersion> <ILAsmPackageVersion>5.0.0-alpha1.19409.1</ILAsmPackageVersion> <ILDAsmPackageVersion>5.0.0-preview.1.20112.8</ILDAsmPackageVersion> <MicrosoftVisualStudioLanguageServerProtocolPackagesVersion>17.0.3094-g82ddffa096</MicrosoftVisualStudioLanguageServerProtocolPackagesVersion> <MicrosoftVisualStudioShellPackagesVersion>17.0.0-previews-1-31421-229</MicrosoftVisualStudioShellPackagesVersion> <MicrosoftBuildPackagesVersion>16.5.0</MicrosoftBuildPackagesVersion> <!-- The version of Roslyn we build Source Generators against that are built in this repository. This must be lower than MicrosoftNetCompilersToolsetVersion, but not higher than our minimum dogfoodable Visual Studio version, or else the generators we build would load on the command line but not load in IDEs. --> <SourceGeneratorMicrosoftCodeAnalysisVersion>3.8.0</SourceGeneratorMicrosoftCodeAnalysisVersion> </PropertyGroup> <!-- Dependency versions --> <PropertyGroup> <BasicUndoVersion>0.9.3</BasicUndoVersion> <BasicReferenceAssembliesNetStandard20Version>1.2.1</BasicReferenceAssembliesNetStandard20Version> <BasicReferenceAssembliesNet50Version>1.2.1</BasicReferenceAssembliesNet50Version> <BasicReferenceAssembliesNet60Version>1.2.2</BasicReferenceAssembliesNet60Version> <BenchmarkDotNetVersion>0.13.0</BenchmarkDotNetVersion> <BenchmarkDotNetDiagnosticsWindowsVersion>0.13.0</BenchmarkDotNetDiagnosticsWindowsVersion> <DiffPlexVersion>1.4.4</DiffPlexVersion> <FakeSignVersion>0.9.2</FakeSignVersion> <HumanizerCoreVersion>2.2.0</HumanizerCoreVersion> <ICSharpCodeDecompilerVersion>6.1.0.5902</ICSharpCodeDecompilerVersion> <MicrosoftBuildVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildVersion> <MicrosoftBuildFrameworkVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildFrameworkVersion> <MicrosoftBuildLocatorVersion>1.2.6</MicrosoftBuildLocatorVersion> <MicrosoftBuildRuntimeVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildRuntimeVersion> <MicrosoftBuildTasksCoreVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildTasksCoreVersion> <NuGetVisualStudioContractsVersion>6.0.0-preview.0.15</NuGetVisualStudioContractsVersion> <MicrosoftVisualStudioRpcContractsVersion>16.10.23</MicrosoftVisualStudioRpcContractsVersion> <!-- Since the Microsoft.CodeAnalysis.Analyzers package is a public dependency of our NuGet packages we will keep it untied to the RoslynDiagnosticsNugetPackageVersion we use for other analyzers to ensure it stays on a release version. --> <MicrosoftCodeAnalysisAnalyzersVersion>3.3.2</MicrosoftCodeAnalysisAnalyzersVersion> <MicrosoftCodeAnalysisBuildTasksVersion>2.0.0-rc2-61102-09</MicrosoftCodeAnalysisBuildTasksVersion> <MicrosoftCodeAnalysisCSharpAnalyzerTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisCSharpAnalyzerTestingXUnitVersion> <MicrosoftCodeAnalysisCSharpCodeFixTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisCSharpCodeFixTestingXUnitVersion> <MicrosoftCodeAnalysisCSharpCodeRefactoringTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisCSharpCodeRefactoringTestingXUnitVersion> <MicrosoftCodeAnalysisCSharpCodeStyleVersion>$(CodeStyleAnalyzerVersion)</MicrosoftCodeAnalysisCSharpCodeStyleVersion> <MicrosoftCodeAnalysisElfieVersion>1.0.0-rc14</MicrosoftCodeAnalysisElfieVersion> <MicrosoftCodeAnalysisTestResourcesProprietaryVersion>2.0.41</MicrosoftCodeAnalysisTestResourcesProprietaryVersion> <MicrosoftCodeAnalysisVisualBasicAnalyzerTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisVisualBasicAnalyzerTestingXUnitVersion> <MicrosoftCodeAnalysisVisualBasicCodeFixTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisVisualBasicCodeFixTestingXUnitVersion> <MicrosoftCodeAnalysisVisualBasicCodeRefactoringTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisVisualBasicCodeRefactoringTestingXUnitVersion> <MicrosoftCodeAnalysisVisualBasicCodeStyleVersion>$(CodeStyleAnalyzerVersion)</MicrosoftCodeAnalysisVisualBasicCodeStyleVersion> <MicrosoftCodeAnalysisAnalyzerUtilitiesVersion>3.3.0</MicrosoftCodeAnalysisAnalyzerUtilitiesVersion> <MicrosoftCodeAnalysisPerformanceSensitiveAnalyzersVersion>$(RoslynDiagnosticsNugetPackageVersion)</MicrosoftCodeAnalysisPerformanceSensitiveAnalyzersVersion> <MicrosoftCSharpVersion>4.3.0</MicrosoftCSharpVersion> <MicrosoftDevDivOptimizationDataPowerShellVersion>1.0.339</MicrosoftDevDivOptimizationDataPowerShellVersion> <MicrosoftDiagnosticsRuntimeVersion>0.8.31-beta</MicrosoftDiagnosticsRuntimeVersion> <MicrosoftDiagnosticsTracingTraceEventVersion>1.0.35</MicrosoftDiagnosticsTracingTraceEventVersion> <MicrosoftDiaSymReaderVersion>1.3.0</MicrosoftDiaSymReaderVersion> <MicrosoftDiaSymReaderConverterVersion>1.1.0-beta2-20115-01</MicrosoftDiaSymReaderConverterVersion> <MicrosoftDiaSymReaderConverterXmlVersion>1.1.0-beta2-20115-01</MicrosoftDiaSymReaderConverterXmlVersion> <MicrosoftDiaSymReaderNativeVersion>16.9.0-beta1.21055.5</MicrosoftDiaSymReaderNativeVersion> <MicrosoftDiaSymReaderPortablePdbVersion>1.5.0</MicrosoftDiaSymReaderPortablePdbVersion> <MicrosoftExtensionsLoggingVersion>5.0.0</MicrosoftExtensionsLoggingVersion> <MicrosoftExtensionsLoggingConsoleVersion>5.0.0</MicrosoftExtensionsLoggingConsoleVersion> <MicrosoftIdentityModelClientsActiveDirectoryVersion>3.13.8</MicrosoftIdentityModelClientsActiveDirectoryVersion> <MicrosoftInternalPerformanceCodeMarkersDesignTimeVersion>15.8.27812-alpha</MicrosoftInternalPerformanceCodeMarkersDesignTimeVersion> <MicrosoftInternalVisualStudioInteropVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftInternalVisualStudioInteropVersion> <MicrosoftMetadataVisualizerVersion>1.0.0-beta3.21075.2</MicrosoftMetadataVisualizerVersion> <MicrosoftNETBuildExtensionsVersion>2.2.101</MicrosoftNETBuildExtensionsVersion> <MicrosoftNETCorePlatformsVersion>2.1.2</MicrosoftNETCorePlatformsVersion> <MicrosoftNETCoreAppRefVersion>5.0.0</MicrosoftNETCoreAppRefVersion> <MicrosoftNETFrameworkReferenceAssembliesnet461Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet461Version> <MicrosoftNETFrameworkReferenceAssembliesnet451Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet451Version> <MicrosoftNETFrameworkReferenceAssembliesnet40Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet40Version> <MicrosoftNETFrameworkReferenceAssembliesnet20Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet20Version> <jnm2ReferenceAssembliesnet35Version>1.0.1</jnm2ReferenceAssembliesnet35Version> <MicrosoftNETCoreTestHostVersion>1.1.0</MicrosoftNETCoreTestHostVersion> <MicrosoftNetFX20Version>1.0.3</MicrosoftNetFX20Version> <MicrosoftNETFrameworkReferenceAssembliesVersion>1.0.0</MicrosoftNETFrameworkReferenceAssembliesVersion> <MicrosoftNetSdkVersion>2.0.0-alpha-20170405-2</MicrosoftNetSdkVersion> <MicrosoftNuGetBuildTasksVersion>0.1.0</MicrosoftNuGetBuildTasksVersion> <MicrosoftPortableTargetsVersion>0.1.2-dev</MicrosoftPortableTargetsVersion> <MicrosoftServiceHubClientVersion>2.8.2019</MicrosoftServiceHubClientVersion> <MicrosoftServiceHubFrameworkVersion>2.8.2019</MicrosoftServiceHubFrameworkVersion> <MicrosoftVisualBasicVersion>10.1.0</MicrosoftVisualBasicVersion> <MicrosoftVisualStudioCacheVersion>17.0.13-alpha</MicrosoftVisualStudioCacheVersion> <MicrosoftVisualStudioCallHierarchyPackageDefinitionsVersion>15.8.27812-alpha</MicrosoftVisualStudioCallHierarchyPackageDefinitionsVersion> <MicrosoftVisualStudioCodeAnalysisSdkUIVersion>15.8.27812-alpha</MicrosoftVisualStudioCodeAnalysisSdkUIVersion> <MicrosoftVisualStudioComponentModelHostVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioComponentModelHostVersion> <MicrosoftVisualStudioCompositionVersion>16.9.20</MicrosoftVisualStudioCompositionVersion> <MicrosoftVisualStudioCoreUtilityVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioCoreUtilityVersion> <MicrosoftVisualStudioDebuggerUIInterfacesVersion>17.2.0-beta.21371.1</MicrosoftVisualStudioDebuggerUIInterfacesVersion> <MicrosoftVisualStudioDebuggerContractsVersion>17.2.0-beta.21371.1</MicrosoftVisualStudioDebuggerContractsVersion> <MicrosoftVisualStudioDebuggerEngineimplementationVersion>17.0.1042805-preview</MicrosoftVisualStudioDebuggerEngineimplementationVersion> <MicrosoftVisualStudioDebuggerMetadataimplementationVersion>17.0.1042805-preview</MicrosoftVisualStudioDebuggerMetadataimplementationVersion> <MicrosoftVisualStudioDesignerInterfacesVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioDesignerInterfacesVersion> <MicrosoftVisualStudioDiagnosticsMeasurementVersion>17.0.0-preview-1-30928-1112</MicrosoftVisualStudioDiagnosticsMeasurementVersion> <MicrosoftVisualStudioDiagnosticsPerformanceProviderVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioDiagnosticsPerformanceProviderVersion> <MicrosoftVisualStudioSDKEmbedInteropTypesVersion>15.0.36</MicrosoftVisualStudioSDKEmbedInteropTypesVersion> <MicrosoftVisualStudioEditorVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioEditorVersion> <MicrosoftVisualStudioGraphModelVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioGraphModelVersion> <MicrosoftVisualStudioImageCatalogVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioImageCatalogVersion> <MicrosoftVisualStudioImagingVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioImagingVersion> <MicrosoftVisualStudioImagingInterop140DesignTimeVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioImagingInterop140DesignTimeVersion> <MicrosoftVisualStudioInteropVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioInteropVersion> <MicrosoftVisualStudioLanguageVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioLanguageVersion> <MicrosoftVisualStudioLanguageCallHierarchyVersion>15.8.27812-alpha</MicrosoftVisualStudioLanguageCallHierarchyVersion> <MicrosoftVisualStudioLanguageIntellisenseVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioLanguageIntellisenseVersion> <MicrosoftVisualStudioLanguageNavigateToInterfacesVersion>17.0.25-g975cd8c52c</MicrosoftVisualStudioLanguageNavigateToInterfacesVersion> <MicrosoftVisualStudioLanguageServerProtocolVersion>$(MicrosoftVisualStudioLanguageServerProtocolPackagesVersion)</MicrosoftVisualStudioLanguageServerProtocolVersion> <MicrosoftVisualStudioLanguageServerProtocolExtensionsVersion>$(MicrosoftVisualStudioLanguageServerProtocolPackagesVersion)</MicrosoftVisualStudioLanguageServerProtocolExtensionsVersion> <MicrosoftVisualStudioLanguageServerProtocolInternalVersion>$(MicrosoftVisualStudioLanguageServerProtocolPackagesVersion)</MicrosoftVisualStudioLanguageServerProtocolInternalVersion> <MicrosoftVisualStudioLanguageServerClientVersion>$(MicrosoftVisualStudioLanguageServerProtocolPackagesVersion)</MicrosoftVisualStudioLanguageServerClientVersion> <MicrosoftVisualStudioLanguageStandardClassificationVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioLanguageStandardClassificationVersion> <MicrosoftVisualStudioLiveShareVersion>2.18.6</MicrosoftVisualStudioLiveShareVersion> <MicrosoftVisualStudioLiveShareLanguageServicesVersion>3.0.6</MicrosoftVisualStudioLiveShareLanguageServicesVersion> <MicrosoftVisualStudioLiveShareLanguageServicesGuestVersion>3.0.6</MicrosoftVisualStudioLiveShareLanguageServicesGuestVersion> <MicrosoftVisualStudioLiveShareWebEditorsVersion>3.0.8</MicrosoftVisualStudioLiveShareWebEditorsVersion> <MicrosoftVisualStudioPlatformVSEditorVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioPlatformVSEditorVersion> <MicrosoftVisualStudioProgressionCodeSchemaVersion>15.8.27812-alpha</MicrosoftVisualStudioProgressionCodeSchemaVersion> <MicrosoftVisualStudioProgressionCommonVersion>15.8.27812-alpha</MicrosoftVisualStudioProgressionCommonVersion> <MicrosoftVisualStudioProgressionInterfacesVersion>15.8.27812-alpha</MicrosoftVisualStudioProgressionInterfacesVersion> <MicrosoftVisualStudioProjectSystemVersion>17.0.77-pre-g62a6cb5699</MicrosoftVisualStudioProjectSystemVersion> <MicrosoftVisualStudioProjectSystemManagedVersion>2.3.6152103</MicrosoftVisualStudioProjectSystemManagedVersion> <MicrosoftVisualStudioRemoteControlVersion>16.3.32</MicrosoftVisualStudioRemoteControlVersion> <MicrosoftVisualStudioSDKAnalyzersVersion>16.10.1</MicrosoftVisualStudioSDKAnalyzersVersion> <MicrosoftVisualStudioSetupConfigurationInteropVersion>1.16.30</MicrosoftVisualStudioSetupConfigurationInteropVersion> <MicrosoftVisualStudioShell150Version>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioShell150Version> <MicrosoftVisualStudioShellFrameworkVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioShellFrameworkVersion> <MicrosoftVisualStudioShellDesignVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioShellDesignVersion> <MicrosoftVisualStudioTelemetryVersion>16.3.176</MicrosoftVisualStudioTelemetryVersion> <MicrosoftVisualStudioTemplateWizardInterfaceVersion>8.0.0.0-alpha</MicrosoftVisualStudioTemplateWizardInterfaceVersion> <MicrosoftVisualStudioTextDataVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextDataVersion> <MicrosoftVisualStudioTextInternalVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextInternalVersion> <MicrosoftVisualStudioTextLogicVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextLogicVersion> <MicrosoftVisualStudioTextUIVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextUIVersion> <MicrosoftVisualStudioTextUIWpfVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextUIWpfVersion> <MicrosoftVisualStudioTextUICocoaVersion>$(VisualStudioEditorPackagesVersion)</MicrosoftVisualStudioTextUICocoaVersion> <MicrosoftVisualStudioThreadingAnalyzersVersion>17.0.17-alpha</MicrosoftVisualStudioThreadingAnalyzersVersion> <MicrosoftVisualStudioThreadingVersion>17.0.17-alpha</MicrosoftVisualStudioThreadingVersion> <MicrosoftVisualStudioUtilitiesVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioUtilitiesVersion> <MicrosoftVisualStudioValidationVersion>17.0.16-alpha</MicrosoftVisualStudioValidationVersion> <MicrosoftVisualStudioInteractiveWindowVersion>4.0.0-beta.21267.2</MicrosoftVisualStudioInteractiveWindowVersion> <MicrosoftVisualStudioVsInteractiveWindowVersion>4.0.0-beta.21267.2</MicrosoftVisualStudioVsInteractiveWindowVersion> <MicrosoftVisualStudioWorkspaceVSIntegrationVersion>16.3.43</MicrosoftVisualStudioWorkspaceVSIntegrationVersion> <MicrosoftWin32PrimitivesVersion>4.3.0</MicrosoftWin32PrimitivesVersion> <MicrosoftWin32RegistryVersion>5.0.0</MicrosoftWin32RegistryVersion> <MSBuildStructuredLoggerVersion>2.1.500</MSBuildStructuredLoggerVersion> <MDbgVersion>0.1.0</MDbgVersion> <MonoOptionsVersion>6.6.0.161</MonoOptionsVersion> <MoqVersion>4.10.1</MoqVersion> <NerdbankStreamsVersion>2.7.74</NerdbankStreamsVersion> <NuGetVisualStudioVersion>6.0.0-preview.0.15</NuGetVisualStudioVersion> <NuGetSolutionRestoreManagerInteropVersion>4.8.0</NuGetSolutionRestoreManagerInteropVersion> <MicrosoftDiaSymReaderPdb2PdbVersion>1.1.0-beta1-62506-02</MicrosoftDiaSymReaderPdb2PdbVersion> <RestSharpVersion>105.2.3</RestSharpVersion> <RichCodeNavEnvVarDumpVersion>0.1.1643-alpha</RichCodeNavEnvVarDumpVersion> <RoslynBuildUtilVersion>0.9.8-beta</RoslynBuildUtilVersion> <RoslynDependenciesOptimizationDataVersion>3.0.0-beta2-19053-01</RoslynDependenciesOptimizationDataVersion> <RoslynDiagnosticsAnalyzersVersion>$(RoslynDiagnosticsNugetPackageVersion)</RoslynDiagnosticsAnalyzersVersion> <RoslynToolsVSIXExpInstallerVersion>1.1.0-beta3.21418.3</RoslynToolsVSIXExpInstallerVersion> <RoslynMicrosoftVisualStudioExtensionManagerVersion>0.0.4</RoslynMicrosoftVisualStudioExtensionManagerVersion> <SourceBrowserVersion>1.0.21</SourceBrowserVersion> <SystemBuffersVersion>4.5.1</SystemBuffersVersion> <SystemCompositionVersion>1.0.31</SystemCompositionVersion> <SystemCodeDomVersion>4.7.0</SystemCodeDomVersion> <SystemCommandLineVersion>2.0.0-beta1.20574.7</SystemCommandLineVersion> <SystemCommandLineExperimentalVersion>0.3.0-alpha.19577.1</SystemCommandLineExperimentalVersion> <SystemComponentModelCompositionVersion>4.5.0</SystemComponentModelCompositionVersion> <SystemDrawingCommonVersion>4.5.0</SystemDrawingCommonVersion> <SystemIOFileSystemVersion>4.3.0</SystemIOFileSystemVersion> <SystemIOFileSystemPrimitivesVersion>4.3.0</SystemIOFileSystemPrimitivesVersion> <SystemIOPipesAccessControlVersion>4.5.1</SystemIOPipesAccessControlVersion> <SystemIOPipelinesVersion>5.0.1</SystemIOPipelinesVersion> <SystemManagementVersion>5.0.0-preview.8.20407.11</SystemManagementVersion> <SystemMemoryVersion>4.5.4</SystemMemoryVersion> <SystemResourcesExtensionsVersion>4.7.1</SystemResourcesExtensionsVersion> <SystemRuntimeCompilerServicesUnsafeVersion>5.0.0</SystemRuntimeCompilerServicesUnsafeVersion> <SystemRuntimeLoaderVersion>4.3.0</SystemRuntimeLoaderVersion> <SystemSecurityPrincipalVersion>4.3.0</SystemSecurityPrincipalVersion> <SystemTextEncodingCodePagesVersion>4.5.1</SystemTextEncodingCodePagesVersion> <SystemTextEncodingExtensionsVersion>4.3.0</SystemTextEncodingExtensionsVersion> <!-- Note: When updating SystemTextJsonVersion ensure that the version is no higher than what is used by MSBuild. --> <SystemTextJsonVersion>4.7.0</SystemTextJsonVersion> <SystemThreadingTasksDataflowVersion>5.0.0</SystemThreadingTasksDataflowVersion> <!-- We need System.ValueTuple assembly version at least 4.0.3.0 on net47 to make F5 work against Dev15 - see https://github.com/dotnet/roslyn/issues/29705 --> <SystemValueTupleVersion>4.5.0</SystemValueTupleVersion> <SystemThreadingTasksExtensionsVersion>4.5.4</SystemThreadingTasksExtensionsVersion> <SQLitePCLRawbundle_greenVersion>2.0.4</SQLitePCLRawbundle_greenVersion> <UIAComWrapperVersion>1.1.0.14</UIAComWrapperVersion> <MicroBuildPluginsSwixBuildVersion>1.1.33</MicroBuildPluginsSwixBuildVersion> <MicrosoftVSSDKBuildToolsVersion>17.0.1056-Dev17PIAs-g9dffd635</MicrosoftVSSDKBuildToolsVersion> <MicrosoftVSSDKVSDConfigToolVersion>16.0.2032702</MicrosoftVSSDKVSDConfigToolVersion> <VsWebsiteInteropVersion>8.0.50727</VsWebsiteInteropVersion> <vswhereVersion>2.4.1</vswhereVersion> <XamarinMacVersion>1.0.0</XamarinMacVersion> <xunitVersion>2.4.1-pre.build.4059</xunitVersion> <xunitanalyzersVersion>0.10.0</xunitanalyzersVersion> <xunitassertVersion>$(xunitVersion)</xunitassertVersion> <XunitCombinatorialVersion>1.3.2</XunitCombinatorialVersion> <XUnitXmlTestLoggerVersion>2.1.26</XUnitXmlTestLoggerVersion> <xunitextensibilitycoreVersion>$(xunitVersion)</xunitextensibilitycoreVersion> <xunitrunnerconsoleVersion>2.4.1-pre.build.4059</xunitrunnerconsoleVersion> <xunitrunnerwpfVersion>1.0.51</xunitrunnerwpfVersion> <xunitrunnervisualstudioVersion>$(xunitVersion)</xunitrunnervisualstudioVersion> <xunitextensibilityexecutionVersion>$(xunitVersion)</xunitextensibilityexecutionVersion> <runtimeWinX64MicrosoftNETCoreILAsmPackageVersion>$(ILAsmPackageVersion)</runtimeWinX64MicrosoftNETCoreILAsmPackageVersion> <runtimeLinuxX64MicrosoftNETCoreILAsmPackageVersion>$(ILAsmPackageVersion)</runtimeLinuxX64MicrosoftNETCoreILAsmPackageVersion> <runtimeOSXX64MicrosoftNETCoreILAsmPackageVersion>$(ILAsmPackageVersion)</runtimeOSXX64MicrosoftNETCoreILAsmPackageVersion> <runtimeWinX64MicrosoftNETCoreILDAsmPackageVersion>$(ILDAsmPackageVersion)</runtimeWinX64MicrosoftNETCoreILDAsmPackageVersion> <runtimeLinuxX64MicrosoftNETCoreILDAsmPackageVersion>$(ILDAsmPackageVersion)</runtimeLinuxX64MicrosoftNETCoreILDAsmPackageVersion> <runtimeOSXX64MicrosoftNETCoreILDAsmPackageVersion>$(ILDAsmPackageVersion)</runtimeOSXX64MicrosoftNETCoreILDAsmPackageVersion> <!-- NOTE: The following dependencies have been identified as particularly problematic to update. If you bump their versions, you must push your changes to a dev branch in dotnet/roslyn and create a test insertion in Visual Studio to validate. --> <NewtonsoftJsonVersion>12.0.2</NewtonsoftJsonVersion> <StreamJsonRpcVersion>2.8.21</StreamJsonRpcVersion> <!-- When updating the S.C.I or S.R.M version please let the MSBuild team know in advance so they can update to the same version. Version changes require a VS test insertion for validation. --> <SystemCollectionsImmutableVersion>5.0.0</SystemCollectionsImmutableVersion> <SystemReflectionMetadataVersion>5.0.0</SystemReflectionMetadataVersion> <MicrosoftBclAsyncInterfacesVersion>5.0.0</MicrosoftBclAsyncInterfacesVersion> </PropertyGroup> <PropertyGroup> <UsingToolPdbConverter>true</UsingToolPdbConverter> <UsingToolSymbolUploader>true</UsingToolSymbolUploader> <UsingToolNuGetRepack>true</UsingToolNuGetRepack> <UsingToolVSSDK>true</UsingToolVSSDK> <UsingToolNetFrameworkReferenceAssemblies>true</UsingToolNetFrameworkReferenceAssemblies> <UsingToolIbcOptimization>true</UsingToolIbcOptimization> <UsingToolVisualStudioIbcTraining>true</UsingToolVisualStudioIbcTraining> <UsingToolXliff>true</UsingToolXliff> <UsingToolXUnit>true</UsingToolXUnit> <DiscoverEditorConfigFiles>true</DiscoverEditorConfigFiles> <!-- When using a bootstrap builder we don't want to use the Microsoft.Net.Compilers.Toolset package but rather explicitly override it. --> <UsingToolMicrosoftNetCompilers Condition="'$(BootstrapBuildPath)' == ''">true</UsingToolMicrosoftNetCompilers> <UseVSTestRunner>true</UseVSTestRunner> </PropertyGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project> <!-- Roslyn version --> <PropertyGroup> <MajorVersion>4</MajorVersion> <MinorVersion>0</MinorVersion> <PatchVersion>0</PatchVersion> <PreReleaseVersionLabel>5</PreReleaseVersionLabel> <VersionPrefix>$(MajorVersion).$(MinorVersion).$(PatchVersion)</VersionPrefix> <!-- By default the assembly version in official builds is "$(MajorVersion).$(MinorVersion).0.0". Keep the setting conditional. The toolset sets the assembly version to 42.42.42.42 if not set explicitly. --> <AssemblyVersion Condition="'$(OfficialBuild)' == 'true' or '$(DotNetUseShippingVersions)' == 'true'">$(MajorVersion).$(MinorVersion).0.0</AssemblyVersion> <!-- Arcade overrides our VersionPrefix when MajorVersion and MinorVersion are specified. Clear them so that we can keep the PatchVersion until we are using an SDK that includes https://github.com/dotnet/arcade/pull/3601 --> <MajorVersion> </MajorVersion> <MinorVersion> </MinorVersion> <MicrosoftNetCompilersToolsetVersion>4.0.0-4.21420.19</MicrosoftNetCompilersToolsetVersion> </PropertyGroup> <PropertyGroup> <!-- Versions used by several individual references below --> <RoslynDiagnosticsNugetPackageVersion>3.3.3-beta1.21105.3</RoslynDiagnosticsNugetPackageVersion> <MicrosoftCodeAnalysisNetAnalyzersVersion>6.0.0-rc1.21366.2</MicrosoftCodeAnalysisNetAnalyzersVersion> <MicrosoftCodeAnalysisTestingVersion>1.1.0-beta1.21322.2</MicrosoftCodeAnalysisTestingVersion> <!-- CodeStyleAnalyzerVersion should we updated together with version of dotnet-format in dotnet-tools.json --> <CodeStyleAnalyzerVersion>4.0.0-3.final</CodeStyleAnalyzerVersion> <VisualStudioEditorPackagesVersion>16.10.230</VisualStudioEditorPackagesVersion> <VisualStudioEditorNewPackagesVersion>17.0.83-preview</VisualStudioEditorNewPackagesVersion> <ILAsmPackageVersion>5.0.0-alpha1.19409.1</ILAsmPackageVersion> <ILDAsmPackageVersion>5.0.0-preview.1.20112.8</ILDAsmPackageVersion> <MicrosoftVisualStudioLanguageServerProtocolPackagesVersion>17.0.3094-g82ddffa096</MicrosoftVisualStudioLanguageServerProtocolPackagesVersion> <MicrosoftVisualStudioShellPackagesVersion>17.0.0-previews-1-31421-229</MicrosoftVisualStudioShellPackagesVersion> <MicrosoftBuildPackagesVersion>16.5.0</MicrosoftBuildPackagesVersion> <!-- The version of Roslyn we build Source Generators against that are built in this repository. This must be lower than MicrosoftNetCompilersToolsetVersion, but not higher than our minimum dogfoodable Visual Studio version, or else the generators we build would load on the command line but not load in IDEs. --> <SourceGeneratorMicrosoftCodeAnalysisVersion>3.8.0</SourceGeneratorMicrosoftCodeAnalysisVersion> </PropertyGroup> <!-- Dependency versions --> <PropertyGroup> <BasicUndoVersion>0.9.3</BasicUndoVersion> <BasicReferenceAssembliesNetStandard20Version>1.2.4</BasicReferenceAssembliesNetStandard20Version> <BasicReferenceAssembliesNet50Version>1.2.4</BasicReferenceAssembliesNet50Version> <BasicReferenceAssembliesNet60Version>1.2.4</BasicReferenceAssembliesNet60Version> <BasicReferenceAssembliesNetStandard13Version>1.2.4</BasicReferenceAssembliesNetStandard13Version> <BenchmarkDotNetVersion>0.13.0</BenchmarkDotNetVersion> <BenchmarkDotNetDiagnosticsWindowsVersion>0.13.0</BenchmarkDotNetDiagnosticsWindowsVersion> <DiffPlexVersion>1.4.4</DiffPlexVersion> <FakeSignVersion>0.9.2</FakeSignVersion> <HumanizerCoreVersion>2.2.0</HumanizerCoreVersion> <ICSharpCodeDecompilerVersion>6.1.0.5902</ICSharpCodeDecompilerVersion> <MicrosoftBuildVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildVersion> <MicrosoftBuildFrameworkVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildFrameworkVersion> <MicrosoftBuildLocatorVersion>1.2.6</MicrosoftBuildLocatorVersion> <MicrosoftBuildRuntimeVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildRuntimeVersion> <MicrosoftBuildTasksCoreVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildTasksCoreVersion> <NuGetVisualStudioContractsVersion>6.0.0-preview.0.15</NuGetVisualStudioContractsVersion> <MicrosoftVisualStudioRpcContractsVersion>16.10.23</MicrosoftVisualStudioRpcContractsVersion> <!-- Since the Microsoft.CodeAnalysis.Analyzers package is a public dependency of our NuGet packages we will keep it untied to the RoslynDiagnosticsNugetPackageVersion we use for other analyzers to ensure it stays on a release version. --> <MicrosoftCodeAnalysisAnalyzersVersion>3.3.2</MicrosoftCodeAnalysisAnalyzersVersion> <MicrosoftCodeAnalysisBuildTasksVersion>2.0.0-rc2-61102-09</MicrosoftCodeAnalysisBuildTasksVersion> <MicrosoftCodeAnalysisCSharpAnalyzerTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisCSharpAnalyzerTestingXUnitVersion> <MicrosoftCodeAnalysisCSharpCodeFixTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisCSharpCodeFixTestingXUnitVersion> <MicrosoftCodeAnalysisCSharpCodeRefactoringTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisCSharpCodeRefactoringTestingXUnitVersion> <MicrosoftCodeAnalysisCSharpCodeStyleVersion>$(CodeStyleAnalyzerVersion)</MicrosoftCodeAnalysisCSharpCodeStyleVersion> <MicrosoftCodeAnalysisElfieVersion>1.0.0-rc14</MicrosoftCodeAnalysisElfieVersion> <MicrosoftCodeAnalysisTestResourcesProprietaryVersion>2.0.44</MicrosoftCodeAnalysisTestResourcesProprietaryVersion> <MicrosoftCodeAnalysisVisualBasicAnalyzerTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisVisualBasicAnalyzerTestingXUnitVersion> <MicrosoftCodeAnalysisVisualBasicCodeFixTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisVisualBasicCodeFixTestingXUnitVersion> <MicrosoftCodeAnalysisVisualBasicCodeRefactoringTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisVisualBasicCodeRefactoringTestingXUnitVersion> <MicrosoftCodeAnalysisVisualBasicCodeStyleVersion>$(CodeStyleAnalyzerVersion)</MicrosoftCodeAnalysisVisualBasicCodeStyleVersion> <MicrosoftCodeAnalysisAnalyzerUtilitiesVersion>3.3.0</MicrosoftCodeAnalysisAnalyzerUtilitiesVersion> <MicrosoftCodeAnalysisPerformanceSensitiveAnalyzersVersion>$(RoslynDiagnosticsNugetPackageVersion)</MicrosoftCodeAnalysisPerformanceSensitiveAnalyzersVersion> <MicrosoftCSharpVersion>4.3.0</MicrosoftCSharpVersion> <MicrosoftDevDivOptimizationDataPowerShellVersion>1.0.339</MicrosoftDevDivOptimizationDataPowerShellVersion> <MicrosoftDiagnosticsRuntimeVersion>0.8.31-beta</MicrosoftDiagnosticsRuntimeVersion> <MicrosoftDiagnosticsTracingTraceEventVersion>1.0.35</MicrosoftDiagnosticsTracingTraceEventVersion> <MicrosoftDiaSymReaderVersion>1.3.0</MicrosoftDiaSymReaderVersion> <MicrosoftDiaSymReaderConverterVersion>1.1.0-beta2-20115-01</MicrosoftDiaSymReaderConverterVersion> <MicrosoftDiaSymReaderConverterXmlVersion>1.1.0-beta2-20115-01</MicrosoftDiaSymReaderConverterXmlVersion> <MicrosoftDiaSymReaderNativeVersion>16.9.0-beta1.21055.5</MicrosoftDiaSymReaderNativeVersion> <MicrosoftDiaSymReaderPortablePdbVersion>1.5.0</MicrosoftDiaSymReaderPortablePdbVersion> <MicrosoftExtensionsLoggingVersion>5.0.0</MicrosoftExtensionsLoggingVersion> <MicrosoftExtensionsLoggingConsoleVersion>5.0.0</MicrosoftExtensionsLoggingConsoleVersion> <MicrosoftIdentityModelClientsActiveDirectoryVersion>3.13.8</MicrosoftIdentityModelClientsActiveDirectoryVersion> <MicrosoftInternalPerformanceCodeMarkersDesignTimeVersion>15.8.27812-alpha</MicrosoftInternalPerformanceCodeMarkersDesignTimeVersion> <MicrosoftInternalVisualStudioInteropVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftInternalVisualStudioInteropVersion> <MicrosoftMetadataVisualizerVersion>1.0.0-beta3.21075.2</MicrosoftMetadataVisualizerVersion> <MicrosoftNETBuildExtensionsVersion>2.2.101</MicrosoftNETBuildExtensionsVersion> <MicrosoftNETCorePlatformsVersion>2.1.2</MicrosoftNETCorePlatformsVersion> <MicrosoftNETCoreAppRefVersion>5.0.0</MicrosoftNETCoreAppRefVersion> <MicrosoftNETFrameworkReferenceAssembliesnet461Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet461Version> <MicrosoftNETFrameworkReferenceAssembliesnet451Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet451Version> <MicrosoftNETFrameworkReferenceAssembliesnet40Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet40Version> <MicrosoftNETFrameworkReferenceAssembliesnet20Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet20Version> <jnm2ReferenceAssembliesnet35Version>1.0.1</jnm2ReferenceAssembliesnet35Version> <MicrosoftNETCoreTestHostVersion>1.1.0</MicrosoftNETCoreTestHostVersion> <MicrosoftNetFX20Version>1.0.3</MicrosoftNetFX20Version> <MicrosoftNETFrameworkReferenceAssembliesVersion>1.0.0</MicrosoftNETFrameworkReferenceAssembliesVersion> <MicrosoftNetSdkVersion>2.0.0-alpha-20170405-2</MicrosoftNetSdkVersion> <MicrosoftNuGetBuildTasksVersion>0.1.0</MicrosoftNuGetBuildTasksVersion> <MicrosoftPortableTargetsVersion>0.1.2-dev</MicrosoftPortableTargetsVersion> <MicrosoftServiceHubClientVersion>2.8.2019</MicrosoftServiceHubClientVersion> <MicrosoftServiceHubFrameworkVersion>2.8.2019</MicrosoftServiceHubFrameworkVersion> <MicrosoftVisualBasicVersion>10.1.0</MicrosoftVisualBasicVersion> <MicrosoftVisualStudioCacheVersion>17.0.13-alpha</MicrosoftVisualStudioCacheVersion> <MicrosoftVisualStudioCallHierarchyPackageDefinitionsVersion>15.8.27812-alpha</MicrosoftVisualStudioCallHierarchyPackageDefinitionsVersion> <MicrosoftVisualStudioCodeAnalysisSdkUIVersion>15.8.27812-alpha</MicrosoftVisualStudioCodeAnalysisSdkUIVersion> <MicrosoftVisualStudioComponentModelHostVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioComponentModelHostVersion> <MicrosoftVisualStudioCompositionVersion>16.9.20</MicrosoftVisualStudioCompositionVersion> <MicrosoftVisualStudioCoreUtilityVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioCoreUtilityVersion> <MicrosoftVisualStudioDebuggerUIInterfacesVersion>17.2.0-beta.21371.1</MicrosoftVisualStudioDebuggerUIInterfacesVersion> <MicrosoftVisualStudioDebuggerContractsVersion>17.2.0-beta.21371.1</MicrosoftVisualStudioDebuggerContractsVersion> <MicrosoftVisualStudioDebuggerEngineimplementationVersion>17.0.1042805-preview</MicrosoftVisualStudioDebuggerEngineimplementationVersion> <MicrosoftVisualStudioDebuggerMetadataimplementationVersion>17.0.1042805-preview</MicrosoftVisualStudioDebuggerMetadataimplementationVersion> <MicrosoftVisualStudioDesignerInterfacesVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioDesignerInterfacesVersion> <MicrosoftVisualStudioDiagnosticsMeasurementVersion>17.0.0-preview-1-30928-1112</MicrosoftVisualStudioDiagnosticsMeasurementVersion> <MicrosoftVisualStudioDiagnosticsPerformanceProviderVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioDiagnosticsPerformanceProviderVersion> <MicrosoftVisualStudioSDKEmbedInteropTypesVersion>15.0.36</MicrosoftVisualStudioSDKEmbedInteropTypesVersion> <MicrosoftVisualStudioEditorVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioEditorVersion> <MicrosoftVisualStudioGraphModelVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioGraphModelVersion> <MicrosoftVisualStudioImageCatalogVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioImageCatalogVersion> <MicrosoftVisualStudioImagingVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioImagingVersion> <MicrosoftVisualStudioImagingInterop140DesignTimeVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioImagingInterop140DesignTimeVersion> <MicrosoftVisualStudioInteropVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioInteropVersion> <MicrosoftVisualStudioLanguageVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioLanguageVersion> <MicrosoftVisualStudioLanguageCallHierarchyVersion>15.8.27812-alpha</MicrosoftVisualStudioLanguageCallHierarchyVersion> <MicrosoftVisualStudioLanguageIntellisenseVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioLanguageIntellisenseVersion> <MicrosoftVisualStudioLanguageNavigateToInterfacesVersion>17.0.25-g975cd8c52c</MicrosoftVisualStudioLanguageNavigateToInterfacesVersion> <MicrosoftVisualStudioLanguageServerProtocolVersion>$(MicrosoftVisualStudioLanguageServerProtocolPackagesVersion)</MicrosoftVisualStudioLanguageServerProtocolVersion> <MicrosoftVisualStudioLanguageServerProtocolExtensionsVersion>$(MicrosoftVisualStudioLanguageServerProtocolPackagesVersion)</MicrosoftVisualStudioLanguageServerProtocolExtensionsVersion> <MicrosoftVisualStudioLanguageServerProtocolInternalVersion>$(MicrosoftVisualStudioLanguageServerProtocolPackagesVersion)</MicrosoftVisualStudioLanguageServerProtocolInternalVersion> <MicrosoftVisualStudioLanguageServerClientVersion>$(MicrosoftVisualStudioLanguageServerProtocolPackagesVersion)</MicrosoftVisualStudioLanguageServerClientVersion> <MicrosoftVisualStudioLanguageStandardClassificationVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioLanguageStandardClassificationVersion> <MicrosoftVisualStudioLiveShareVersion>2.18.6</MicrosoftVisualStudioLiveShareVersion> <MicrosoftVisualStudioLiveShareLanguageServicesVersion>3.0.6</MicrosoftVisualStudioLiveShareLanguageServicesVersion> <MicrosoftVisualStudioLiveShareLanguageServicesGuestVersion>3.0.6</MicrosoftVisualStudioLiveShareLanguageServicesGuestVersion> <MicrosoftVisualStudioLiveShareWebEditorsVersion>3.0.8</MicrosoftVisualStudioLiveShareWebEditorsVersion> <MicrosoftVisualStudioPlatformVSEditorVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioPlatformVSEditorVersion> <MicrosoftVisualStudioProgressionCodeSchemaVersion>15.8.27812-alpha</MicrosoftVisualStudioProgressionCodeSchemaVersion> <MicrosoftVisualStudioProgressionCommonVersion>15.8.27812-alpha</MicrosoftVisualStudioProgressionCommonVersion> <MicrosoftVisualStudioProgressionInterfacesVersion>15.8.27812-alpha</MicrosoftVisualStudioProgressionInterfacesVersion> <MicrosoftVisualStudioProjectSystemVersion>17.0.77-pre-g62a6cb5699</MicrosoftVisualStudioProjectSystemVersion> <MicrosoftVisualStudioProjectSystemManagedVersion>2.3.6152103</MicrosoftVisualStudioProjectSystemManagedVersion> <MicrosoftVisualStudioRemoteControlVersion>16.3.32</MicrosoftVisualStudioRemoteControlVersion> <MicrosoftVisualStudioSDKAnalyzersVersion>16.10.1</MicrosoftVisualStudioSDKAnalyzersVersion> <MicrosoftVisualStudioSetupConfigurationInteropVersion>1.16.30</MicrosoftVisualStudioSetupConfigurationInteropVersion> <MicrosoftVisualStudioShell150Version>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioShell150Version> <MicrosoftVisualStudioShellFrameworkVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioShellFrameworkVersion> <MicrosoftVisualStudioShellDesignVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioShellDesignVersion> <MicrosoftVisualStudioTelemetryVersion>16.3.176</MicrosoftVisualStudioTelemetryVersion> <MicrosoftVisualStudioTemplateWizardInterfaceVersion>8.0.0.0-alpha</MicrosoftVisualStudioTemplateWizardInterfaceVersion> <MicrosoftVisualStudioTextDataVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextDataVersion> <MicrosoftVisualStudioTextInternalVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextInternalVersion> <MicrosoftVisualStudioTextLogicVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextLogicVersion> <MicrosoftVisualStudioTextUIVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextUIVersion> <MicrosoftVisualStudioTextUIWpfVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextUIWpfVersion> <MicrosoftVisualStudioTextUICocoaVersion>$(VisualStudioEditorPackagesVersion)</MicrosoftVisualStudioTextUICocoaVersion> <MicrosoftVisualStudioThreadingAnalyzersVersion>17.0.17-alpha</MicrosoftVisualStudioThreadingAnalyzersVersion> <MicrosoftVisualStudioThreadingVersion>17.0.17-alpha</MicrosoftVisualStudioThreadingVersion> <MicrosoftVisualStudioUtilitiesVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioUtilitiesVersion> <MicrosoftVisualStudioValidationVersion>17.0.16-alpha</MicrosoftVisualStudioValidationVersion> <MicrosoftVisualStudioInteractiveWindowVersion>4.0.0-beta.21267.2</MicrosoftVisualStudioInteractiveWindowVersion> <MicrosoftVisualStudioVsInteractiveWindowVersion>4.0.0-beta.21267.2</MicrosoftVisualStudioVsInteractiveWindowVersion> <MicrosoftVisualStudioWorkspaceVSIntegrationVersion>16.3.43</MicrosoftVisualStudioWorkspaceVSIntegrationVersion> <MicrosoftWin32PrimitivesVersion>4.3.0</MicrosoftWin32PrimitivesVersion> <MicrosoftWin32RegistryVersion>5.0.0</MicrosoftWin32RegistryVersion> <MSBuildStructuredLoggerVersion>2.1.500</MSBuildStructuredLoggerVersion> <MDbgVersion>0.1.0</MDbgVersion> <MonoOptionsVersion>6.6.0.161</MonoOptionsVersion> <MoqVersion>4.10.1</MoqVersion> <NerdbankStreamsVersion>2.7.74</NerdbankStreamsVersion> <NuGetVisualStudioVersion>6.0.0-preview.0.15</NuGetVisualStudioVersion> <NuGetSolutionRestoreManagerInteropVersion>4.8.0</NuGetSolutionRestoreManagerInteropVersion> <MicrosoftDiaSymReaderPdb2PdbVersion>1.1.0-beta1-62506-02</MicrosoftDiaSymReaderPdb2PdbVersion> <RestSharpVersion>105.2.3</RestSharpVersion> <RichCodeNavEnvVarDumpVersion>0.1.1643-alpha</RichCodeNavEnvVarDumpVersion> <RoslynBuildUtilVersion>0.9.8-beta</RoslynBuildUtilVersion> <RoslynDependenciesOptimizationDataVersion>3.0.0-beta2-19053-01</RoslynDependenciesOptimizationDataVersion> <RoslynDiagnosticsAnalyzersVersion>$(RoslynDiagnosticsNugetPackageVersion)</RoslynDiagnosticsAnalyzersVersion> <RoslynToolsVSIXExpInstallerVersion>1.1.0-beta3.21418.3</RoslynToolsVSIXExpInstallerVersion> <RoslynMicrosoftVisualStudioExtensionManagerVersion>0.0.4</RoslynMicrosoftVisualStudioExtensionManagerVersion> <SourceBrowserVersion>1.0.21</SourceBrowserVersion> <SystemBuffersVersion>4.5.1</SystemBuffersVersion> <SystemCompositionVersion>1.0.31</SystemCompositionVersion> <SystemCodeDomVersion>4.7.0</SystemCodeDomVersion> <SystemCommandLineVersion>2.0.0-beta1.20574.7</SystemCommandLineVersion> <SystemCommandLineExperimentalVersion>0.3.0-alpha.19577.1</SystemCommandLineExperimentalVersion> <SystemComponentModelCompositionVersion>4.5.0</SystemComponentModelCompositionVersion> <SystemDrawingCommonVersion>4.5.0</SystemDrawingCommonVersion> <SystemIOFileSystemVersion>4.3.0</SystemIOFileSystemVersion> <SystemIOFileSystemPrimitivesVersion>4.3.0</SystemIOFileSystemPrimitivesVersion> <SystemIOPipesAccessControlVersion>4.5.1</SystemIOPipesAccessControlVersion> <SystemIOPipelinesVersion>5.0.1</SystemIOPipelinesVersion> <SystemManagementVersion>5.0.0-preview.8.20407.11</SystemManagementVersion> <SystemMemoryVersion>4.5.4</SystemMemoryVersion> <SystemResourcesExtensionsVersion>4.7.1</SystemResourcesExtensionsVersion> <SystemRuntimeCompilerServicesUnsafeVersion>5.0.0</SystemRuntimeCompilerServicesUnsafeVersion> <SystemRuntimeLoaderVersion>4.3.0</SystemRuntimeLoaderVersion> <SystemSecurityPrincipalVersion>4.3.0</SystemSecurityPrincipalVersion> <SystemTextEncodingCodePagesVersion>4.5.1</SystemTextEncodingCodePagesVersion> <SystemTextEncodingExtensionsVersion>4.3.0</SystemTextEncodingExtensionsVersion> <!-- Note: When updating SystemTextJsonVersion ensure that the version is no higher than what is used by MSBuild. --> <SystemTextJsonVersion>4.7.0</SystemTextJsonVersion> <SystemThreadingTasksDataflowVersion>5.0.0</SystemThreadingTasksDataflowVersion> <!-- We need System.ValueTuple assembly version at least 4.0.3.0 on net47 to make F5 work against Dev15 - see https://github.com/dotnet/roslyn/issues/29705 --> <SystemValueTupleVersion>4.5.0</SystemValueTupleVersion> <SystemThreadingTasksExtensionsVersion>4.5.4</SystemThreadingTasksExtensionsVersion> <SQLitePCLRawbundle_greenVersion>2.0.4</SQLitePCLRawbundle_greenVersion> <UIAComWrapperVersion>1.1.0.14</UIAComWrapperVersion> <MicroBuildPluginsSwixBuildVersion>1.1.33</MicroBuildPluginsSwixBuildVersion> <MicrosoftVSSDKBuildToolsVersion>17.0.1056-Dev17PIAs-g9dffd635</MicrosoftVSSDKBuildToolsVersion> <MicrosoftVSSDKVSDConfigToolVersion>16.0.2032702</MicrosoftVSSDKVSDConfigToolVersion> <VsWebsiteInteropVersion>8.0.50727</VsWebsiteInteropVersion> <vswhereVersion>2.4.1</vswhereVersion> <XamarinMacVersion>1.0.0</XamarinMacVersion> <xunitVersion>2.4.1-pre.build.4059</xunitVersion> <xunitanalyzersVersion>0.10.0</xunitanalyzersVersion> <xunitassertVersion>$(xunitVersion)</xunitassertVersion> <XunitCombinatorialVersion>1.3.2</XunitCombinatorialVersion> <XUnitXmlTestLoggerVersion>2.1.26</XUnitXmlTestLoggerVersion> <xunitextensibilitycoreVersion>$(xunitVersion)</xunitextensibilitycoreVersion> <xunitrunnerconsoleVersion>2.4.1-pre.build.4059</xunitrunnerconsoleVersion> <xunitrunnerwpfVersion>1.0.51</xunitrunnerwpfVersion> <xunitrunnervisualstudioVersion>$(xunitVersion)</xunitrunnervisualstudioVersion> <xunitextensibilityexecutionVersion>$(xunitVersion)</xunitextensibilityexecutionVersion> <runtimeWinX64MicrosoftNETCoreILAsmPackageVersion>$(ILAsmPackageVersion)</runtimeWinX64MicrosoftNETCoreILAsmPackageVersion> <runtimeLinuxX64MicrosoftNETCoreILAsmPackageVersion>$(ILAsmPackageVersion)</runtimeLinuxX64MicrosoftNETCoreILAsmPackageVersion> <runtimeOSXX64MicrosoftNETCoreILAsmPackageVersion>$(ILAsmPackageVersion)</runtimeOSXX64MicrosoftNETCoreILAsmPackageVersion> <runtimeWinX64MicrosoftNETCoreILDAsmPackageVersion>$(ILDAsmPackageVersion)</runtimeWinX64MicrosoftNETCoreILDAsmPackageVersion> <runtimeLinuxX64MicrosoftNETCoreILDAsmPackageVersion>$(ILDAsmPackageVersion)</runtimeLinuxX64MicrosoftNETCoreILDAsmPackageVersion> <runtimeOSXX64MicrosoftNETCoreILDAsmPackageVersion>$(ILDAsmPackageVersion)</runtimeOSXX64MicrosoftNETCoreILDAsmPackageVersion> <!-- NOTE: The following dependencies have been identified as particularly problematic to update. If you bump their versions, you must push your changes to a dev branch in dotnet/roslyn and create a test insertion in Visual Studio to validate. --> <NewtonsoftJsonVersion>12.0.2</NewtonsoftJsonVersion> <StreamJsonRpcVersion>2.8.21</StreamJsonRpcVersion> <!-- When updating the S.C.I or S.R.M version please let the MSBuild team know in advance so they can update to the same version. Version changes require a VS test insertion for validation. --> <SystemCollectionsImmutableVersion>5.0.0</SystemCollectionsImmutableVersion> <SystemReflectionMetadataVersion>5.0.0</SystemReflectionMetadataVersion> <MicrosoftBclAsyncInterfacesVersion>5.0.0</MicrosoftBclAsyncInterfacesVersion> </PropertyGroup> <PropertyGroup> <UsingToolPdbConverter>true</UsingToolPdbConverter> <UsingToolSymbolUploader>true</UsingToolSymbolUploader> <UsingToolNuGetRepack>true</UsingToolNuGetRepack> <UsingToolVSSDK>true</UsingToolVSSDK> <UsingToolNetFrameworkReferenceAssemblies>true</UsingToolNetFrameworkReferenceAssemblies> <UsingToolIbcOptimization>true</UsingToolIbcOptimization> <UsingToolVisualStudioIbcTraining>true</UsingToolVisualStudioIbcTraining> <UsingToolXliff>true</UsingToolXliff> <UsingToolXUnit>true</UsingToolXUnit> <DiscoverEditorConfigFiles>true</DiscoverEditorConfigFiles> <!-- When using a bootstrap builder we don't want to use the Microsoft.Net.Compilers.Toolset package but rather explicitly override it. --> <UsingToolMicrosoftNetCompilers Condition="'$(BootstrapBuildPath)' == ''">true</UsingToolMicrosoftNetCompilers> <UseVSTestRunner>true</UseVSTestRunner> </PropertyGroup> </Project>
1
dotnet/roslyn
56,223
Rework our netstandard1.3 test references
The `netstandard1.3` test references were being provided by our MS.CA.Test.Resources.Proprietary package. The contents of this package get included in the output directory of every single unit test DLL that we build (which contributes to build output size). The references themselves though were only used in a very small number of tests. This change upgrades to a version of MS.CA.Test.Resources.Proprietary that has the `netstandard1.3` references removed and adds the `netstandard1.3` references to only the projects that needs them
jaredpar
"2021-09-07T20:35:04Z"
"2021-09-07T23:50:57Z"
0240973369997c88a2c2f1aaa22c14182ac17e9f
5dbd783367d7f6b105726b84558cc1809aa198ce
Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our MS.CA.Test.Resources.Proprietary package. The contents of this package get included in the output directory of every single unit test DLL that we build (which contributes to build output size). The references themselves though were only used in a very small number of tests. This change upgrades to a version of MS.CA.Test.Resources.Proprietary that has the `netstandard1.3` references removed and adds the `netstandard1.3` references to only the projects that needs them
./src/Compilers/CSharp/Test/CommandLine/CommandLineTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using System.Globalization; using System.IO; using System.IO.MemoryMappedFiles; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Resources.Proprietary; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.DiaSymReader; using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Utilities; using Xunit; using static Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers; using static Roslyn.Test.Utilities.SharedResourceHelpers; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests { public class CommandLineTests : CommandLineTestBase { #if NETCOREAPP private static readonly string s_CSharpCompilerExecutable; private static readonly string s_DotnetCscRun; #else private static readonly string s_CSharpCompilerExecutable = Path.Combine( Path.GetDirectoryName(typeof(CommandLineTests).GetTypeInfo().Assembly.Location), Path.Combine("dependency", "csc.exe")); private static readonly string s_DotnetCscRun = ExecutionConditionUtil.IsMono ? "mono" : string.Empty; #endif private static readonly string s_CSharpScriptExecutable; private static readonly string s_compilerVersion = CommonCompiler.GetProductVersion(typeof(CommandLineTests)); static CommandLineTests() { #if NETCOREAPP var cscDllPath = Path.Combine( Path.GetDirectoryName(typeof(CommandLineTests).GetTypeInfo().Assembly.Location), Path.Combine("dependency", "csc.dll")); var dotnetExe = DotNetCoreSdk.ExePath; var netStandardDllPath = AppDomain.CurrentDomain.GetAssemblies() .FirstOrDefault(assembly => !assembly.IsDynamic && assembly.Location.EndsWith("netstandard.dll")).Location; var netStandardDllDir = Path.GetDirectoryName(netStandardDllPath); // Since we are using references based on the UnitTest's runtime, we need to use // its runtime config when executing out program. var runtimeConfigPath = Path.ChangeExtension(Assembly.GetExecutingAssembly().Location, "runtimeconfig.json"); s_CSharpCompilerExecutable = $@"""{dotnetExe}"" ""{cscDllPath}"" /r:""{netStandardDllPath}"" /r:""{netStandardDllDir}/System.Private.CoreLib.dll"" /r:""{netStandardDllDir}/System.Console.dll"" /r:""{netStandardDllDir}/System.Runtime.dll"""; s_DotnetCscRun = $@"""{dotnetExe}"" exec --runtimeconfig ""{runtimeConfigPath}"""; s_CSharpScriptExecutable = s_CSharpCompilerExecutable.Replace("csc.dll", Path.Combine("csi", "csi.dll")); #else s_CSharpScriptExecutable = s_CSharpCompilerExecutable.Replace("csc.exe", Path.Combine("csi", "csi.exe")); #endif } private class TestCommandLineParser : CSharpCommandLineParser { private readonly Dictionary<string, string> _responseFiles; private readonly Dictionary<string, string[]> _recursivePatterns; private readonly Dictionary<string, string[]> _patterns; public TestCommandLineParser( Dictionary<string, string> responseFiles = null, Dictionary<string, string[]> patterns = null, Dictionary<string, string[]> recursivePatterns = null, bool isInteractive = false) : base(isInteractive) { _responseFiles = responseFiles; _recursivePatterns = recursivePatterns; _patterns = patterns; } internal override IEnumerable<string> EnumerateFiles(string directory, string fileNamePattern, SearchOption searchOption) { var key = directory + "|" + fileNamePattern; if (searchOption == SearchOption.TopDirectoryOnly) { return _patterns[key]; } else { return _recursivePatterns[key]; } } internal override TextReader CreateTextFileReader(string fullPath) { return new StringReader(_responseFiles[fullPath]); } } private CSharpCommandLineArguments ScriptParse(IEnumerable<string> args, string baseDirectory) { return CSharpCommandLineParser.Script.Parse(args, baseDirectory, SdkDirectory); } private CSharpCommandLineArguments FullParse(string commandLine, string baseDirectory, string sdkDirectory = null, string additionalReferenceDirectories = null) { sdkDirectory = sdkDirectory ?? SdkDirectory; var args = CommandLineParser.SplitCommandLineIntoArguments(commandLine, removeHashComments: true); return CSharpCommandLineParser.Default.Parse(args, baseDirectory, sdkDirectory, additionalReferenceDirectories); } [ConditionalFact(typeof(WindowsDesktopOnly))] [WorkItem(34101, "https://github.com/dotnet/roslyn/issues/34101")] public void SuppressedWarnAsErrorsStillEmit() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" #pragma warning disable 1591 public class P { public static void Main() {} }"); const string docName = "doc.xml"; var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/errorlog:errorlog", $"/doc:{docName}", "/warnaserror", src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); string exePath = Path.Combine(dir.Path, "temp.exe"); Assert.True(File.Exists(exePath)); var result = ProcessUtilities.Run(exePath, arguments: ""); Assert.Equal(0, result.ExitCode); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] public void XmlMemoryMapped() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText("class C {}"); const string docName = "doc.xml"; var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", $"/doc:{docName}", src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); var xmlPath = Path.Combine(dir.Path, docName); using (var fileStream = new FileStream(xmlPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var mmf = MemoryMappedFile.CreateFromFile(fileStream, "xmlMap", 0, MemoryMappedFileAccess.Read, HandleInheritability.None, leaveOpen: true)) { exitCode = cmd.Run(outWriter); Assert.StartsWith($"error CS0016: Could not write to output file '{xmlPath}' -- ", outWriter.ToString()); Assert.Equal(1, exitCode); } } [Fact] public void SimpleAnalyzerConfig() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.cs0169.severity = none"); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path }); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); Assert.Null(cmd.AnalyzerOptions); } [Fact] public void AnalyzerConfigWithOptions() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var additionalFile = dir.CreateFile("file.txt"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.cs0169.severity = none dotnet_diagnostic.Warning01.severity = none my_option = my_val [*.txt] dotnet_diagnostic.cs0169.severity = none my_option2 = my_val2"); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/analyzerconfig:" + analyzerConfig.Path, "/analyzer:" + Assembly.GetExecutingAssembly().Location, "/nowarn:8032", "/additionalfile:" + additionalFile.Path, src.Path }); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal("", outWriter.ToString()); Assert.Equal(0, exitCode); var comp = cmd.Compilation; var tree = comp.SyntaxTrees.Single(); var compilerTreeOptions = comp.Options.SyntaxTreeOptionsProvider; Assert.True(compilerTreeOptions.TryGetDiagnosticValue(tree, "cs0169", CancellationToken.None, out var severity)); Assert.Equal(ReportDiagnostic.Suppress, severity); Assert.True(compilerTreeOptions.TryGetDiagnosticValue(tree, "warning01", CancellationToken.None, out severity)); Assert.Equal(ReportDiagnostic.Suppress, severity); var analyzerOptions = cmd.AnalyzerOptions.AnalyzerConfigOptionsProvider; var options = analyzerOptions.GetOptions(tree); Assert.NotNull(options); Assert.True(options.TryGetValue("my_option", out string val)); Assert.Equal("my_val", val); Assert.False(options.TryGetValue("my_option2", out _)); Assert.False(options.TryGetValue("dotnet_diagnostic.cs0169.severity", out _)); options = analyzerOptions.GetOptions(cmd.AnalyzerOptions.AdditionalFiles.Single()); Assert.NotNull(options); Assert.True(options.TryGetValue("my_option2", out val)); Assert.Equal("my_val2", val); Assert.False(options.TryGetValue("my_option", out _)); Assert.False(options.TryGetValue("dotnet_diagnostic.cs0169.severity", out _)); } [Fact] public void AnalyzerConfigBadSeverity() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.cs0169.severity = garbage"); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path }); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal( $@"warning InvalidSeverityInAnalyzerConfig: The diagnostic 'cs0169' was given an invalid severity 'garbage' in the analyzer config file at '{analyzerConfig.Path}'. test.cs(4,9): warning CS0169: The field 'C._f' is never used ", outWriter.ToString()); Assert.Null(cmd.AnalyzerOptions); } [Fact] public void AnalyzerConfigsInSameDir() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var configText = @" [*.cs] dotnet_diagnostic.cs0169.severity = suppress"; var analyzerConfig1 = dir.CreateFile("analyzerconfig1").WriteAllText(configText); var analyzerConfig2 = dir.CreateFile("analyzerconfig2").WriteAllText(configText); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig1.Path, "/analyzerconfig:" + analyzerConfig2.Path, src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal( $"error CS8700: Multiple analyzer config files cannot be in the same directory ('{dir.Path}').", outWriter.ToString().TrimEnd()); } // This test should only run when the machine's default encoding is shift-JIS [ConditionalFact(typeof(WindowsDesktopOnly), typeof(HasShiftJisDefaultEncoding), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void CompileShiftJisOnShiftJis() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("sjis.cs").WriteAllBytes(TestResources.General.ShiftJisSource); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", src.Path }); Assert.Null(cmd.Arguments.Encoding); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); var result = ProcessUtilities.Run(Path.Combine(dir.Path, "sjis.exe"), arguments: "", workingDirectory: dir.Path); Assert.Equal(0, result.ExitCode); Assert.Equal("星野 八郎太", File.ReadAllText(Path.Combine(dir.Path, "output.txt"), Encoding.GetEncoding(932))); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void RunWithShiftJisFile() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("sjis.cs").WriteAllBytes(TestResources.General.ShiftJisSource); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/codepage:932", src.Path }); Assert.Equal(932, cmd.Arguments.Encoding?.WindowsCodePage); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); var result = ProcessUtilities.Run(Path.Combine(dir.Path, "sjis.exe"), arguments: "", workingDirectory: dir.Path); Assert.Equal(0, result.ExitCode); Assert.Equal("星野 八郎太", File.ReadAllText(Path.Combine(dir.Path, "output.txt"), Encoding.GetEncoding(932))); } [WorkItem(946954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/946954")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void CompilerBinariesAreAnyCPU() { Assert.Equal(ProcessorArchitecture.MSIL, AssemblyName.GetAssemblyName(s_CSharpCompilerExecutable).ProcessorArchitecture); } [Fact] public void ResponseFiles1() { string rsp = Temp.CreateFile().WriteAllText(@" /r:System.dll /nostdlib # this is ignored System.Console.WriteLine(""*?""); # this is error a.cs ").Path; var cmd = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { "b.cs" }); cmd.Arguments.Errors.Verify( // error CS2001: Source file 'System.Console.WriteLine(*?);' could not be found Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments("System.Console.WriteLine(*?);")); AssertEx.Equal(new[] { "System.dll" }, cmd.Arguments.MetadataReferences.Select(r => r.Reference)); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "a.cs"), Path.Combine(WorkingDirectory, "b.cs") }, cmd.Arguments.SourceFiles.Select(file => file.Path)); CleanupAllGeneratedFiles(rsp); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] public void ResponseFiles_RelativePaths() { var parentDir = Temp.CreateDirectory(); var baseDir = parentDir.CreateDirectory("temp"); var dirX = baseDir.CreateDirectory("x"); var dirAB = baseDir.CreateDirectory("a b"); var dirSubDir = baseDir.CreateDirectory("subdir"); var dirGoo = parentDir.CreateDirectory("goo"); var dirBar = parentDir.CreateDirectory("bar"); string basePath = baseDir.Path; Func<string, string> prependBasePath = fileName => Path.Combine(basePath, fileName); var parser = new TestCommandLineParser(responseFiles: new Dictionary<string, string>() { { prependBasePath(@"a.rsp"), @" ""@subdir\b.rsp"" /r:..\v4.0.30319\System.dll /r:.\System.Data.dll a.cs @""..\c.rsp"" @\d.rsp /libpaths:..\goo;../bar;""a b"" " }, { Path.Combine(dirSubDir.Path, @"b.rsp"), @" b.cs " }, { prependBasePath(@"..\c.rsp"), @" c.cs /lib:x " }, { Path.Combine(Path.GetPathRoot(basePath), @"d.rsp"), @" # comment d.cs " } }, isInteractive: false); var args = parser.Parse(new[] { "first.cs", "second.cs", "@a.rsp", "last.cs" }, basePath, SdkDirectory); args.Errors.Verify(); Assert.False(args.IsScriptRunner); string[] resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); string[] references = args.MetadataReferences.Select(r => r.Reference).ToArray(); AssertEx.Equal(new[] { "first.cs", "second.cs", "b.cs", "a.cs", "c.cs", "d.cs", "last.cs" }.Select(prependBasePath), resolvedSourceFiles); AssertEx.Equal(new[] { typeof(object).Assembly.Location, @"..\v4.0.30319\System.dll", @".\System.Data.dll" }, references); AssertEx.Equal(new[] { RuntimeEnvironment.GetRuntimeDirectory() }.Concat(new[] { @"x", @"..\goo", @"../bar", @"a b" }.Select(prependBasePath)), args.ReferencePaths.ToArray()); Assert.Equal(basePath, args.BaseDirectory); } #nullable enable [ConditionalFact(typeof(WindowsOnly))] public void NullBaseDirectoryNotAddedToKeyFileSearchPaths() { var parser = CSharpCommandLineParser.Default.Parse(new[] { "c:/test.cs" }, baseDirectory: null, SdkDirectory); AssertEx.Equal(ImmutableArray.Create<string>(), parser.KeyFileSearchPaths); Assert.Null(parser.OutputDirectory); parser.Errors.Verify( // error CS8762: Output directory could not be determined Diagnostic(ErrorCode.ERR_NoOutputDirectory).WithLocation(1, 1) ); } [ConditionalFact(typeof(WindowsOnly))] public void NullBaseDirectoryWithAdditionalFiles() { var parser = CSharpCommandLineParser.Default.Parse(new[] { "/additionalfile:web.config", "c:/test.cs" }, baseDirectory: null, SdkDirectory); AssertEx.Equal(ImmutableArray.Create<string>(), parser.KeyFileSearchPaths); Assert.Null(parser.OutputDirectory); parser.Errors.Verify( // error CS2021: File name 'web.config' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("web.config").WithLocation(1, 1), // error CS8762: Output directory could not be determined Diagnostic(ErrorCode.ERR_NoOutputDirectory).WithLocation(1, 1) ); } [ConditionalFact(typeof(WindowsOnly))] public void NullBaseDirectoryWithAdditionalFiles_Wildcard() { var parser = CSharpCommandLineParser.Default.Parse(new[] { "/additionalfile:*", "c:/test.cs" }, baseDirectory: null, SdkDirectory); AssertEx.Equal(ImmutableArray.Create<string>(), parser.KeyFileSearchPaths); Assert.Null(parser.OutputDirectory); parser.Errors.Verify( // error CS2001: Source file '*' could not be found. Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments("*").WithLocation(1, 1), // error CS8762: Output directory could not be determined Diagnostic(ErrorCode.ERR_NoOutputDirectory).WithLocation(1, 1) ); } #nullable disable [Fact, WorkItem(29252, "https://github.com/dotnet/roslyn/issues/29252")] public void NoSdkPath() { var parentDir = Temp.CreateDirectory(); var parser = CSharpCommandLineParser.Default.Parse(new[] { "file.cs", $"-out:{parentDir.Path}", "/noSdkPath" }, parentDir.Path, null); AssertEx.Equal(ImmutableArray<string>.Empty, parser.ReferencePaths); } [Fact, WorkItem(29252, "https://github.com/dotnet/roslyn/issues/29252")] public void NoSdkPathReferenceSystemDll() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/nosdkpath", "/r:System.dll", "a.cs" }); var exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS0006: Metadata file 'System.dll' could not be found", outWriter.ToString().Trim()); } [ConditionalFact(typeof(WindowsOnly))] public void SourceFiles_Patterns() { var parser = new TestCommandLineParser( patterns: new Dictionary<string, string[]>() { { @"C:\temp|*.cs", new[] { "a.cs", "b.cs", "c.cs" } } }, recursivePatterns: new Dictionary<string, string[]>() { { @"C:\temp\a|*.cs", new[] { @"a\x.cs", @"a\b\b.cs", @"a\c.cs" } }, }); var args = parser.Parse(new[] { @"*.cs", @"/recurse:a\*.cs" }, @"C:\temp", SdkDirectory); args.Errors.Verify(); string[] resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); AssertEx.Equal(new[] { @"C:\temp\a.cs", @"C:\temp\b.cs", @"C:\temp\c.cs", @"C:\temp\a\x.cs", @"C:\temp\a\b\b.cs", @"C:\temp\a\c.cs" }, resolvedSourceFiles); } [Fact] public void ParseQuotedMainType() { // Verify the main switch are unquoted when used because of the issue with // MSBuild quoting some usages and not others. A quote character is not valid in either // these names. CSharpCommandLineArguments args; var folder = Temp.CreateDirectory(); CreateFile(folder, "a.cs"); args = DefaultParse(new[] { "/main:Test", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/main:\"Test\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/main:\"Test.Class1\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test.Class1", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/m:Test", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/m:\"Test\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/m:\"Test.Class1\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test.Class1", args.CompilationOptions.MainTypeName); // Use of Cyrillic namespace args = DefaultParse(new[] { "/m:\"решения.Class1\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("решения.Class1", args.CompilationOptions.MainTypeName); } [Fact] [WorkItem(21508, "https://github.com/dotnet/roslyn/issues/21508")] public void ArgumentStartWithDashAndContainingSlash() { CSharpCommandLineArguments args; var folder = Temp.CreateDirectory(); args = DefaultParse(new[] { "-debug+/debug:portable" }, folder.Path); args.Errors.Verify( // error CS2007: Unrecognized option: '-debug+/debug:portable' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("-debug+/debug:portable").WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1) ); } [WorkItem(546009, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546009")] [WorkItem(545991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545991")] [ConditionalFact(typeof(WindowsOnly))] public void SourceFiles_Patterns2() { var folder = Temp.CreateDirectory(); CreateFile(folder, "a.cs"); CreateFile(folder, "b.vb"); CreateFile(folder, "c.cpp"); var folderA = folder.CreateDirectory("A"); CreateFile(folderA, "A_a.cs"); CreateFile(folderA, "A_b.cs"); CreateFile(folderA, "A_c.vb"); var folderB = folder.CreateDirectory("B"); CreateFile(folderB, "B_a.cs"); CreateFile(folderB, "B_b.vb"); CreateFile(folderB, "B_c.cpx"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse:.", "/out:abc.dll" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse:. ", "/out:abc.dll" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse: . ", "/out:abc.dll" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse:././.", "/out:abc.dll" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim()); CSharpCommandLineArguments args; string[] resolvedSourceFiles; args = DefaultParse(new[] { @"/recurse:*.cp*", @"/recurse:a\*.c*", @"/out:a.dll" }, folder.Path); args.Errors.Verify(); resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); AssertEx.Equal(new[] { folder.Path + @"\c.cpp", folder.Path + @"\B\B_c.cpx", folder.Path + @"\a\A_a.cs", folder.Path + @"\a\A_b.cs", }, resolvedSourceFiles); args = DefaultParse(new[] { @"/recurse:.\\\\\\*.cs", @"/out:a.dll" }, folder.Path); args.Errors.Verify(); resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); Assert.Equal(4, resolvedSourceFiles.Length); args = DefaultParse(new[] { @"/recurse:.////*.cs", @"/out:a.dll" }, folder.Path); args.Errors.Verify(); resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); Assert.Equal(4, resolvedSourceFiles.Length); } [ConditionalFact(typeof(WindowsOnly))] public void SourceFile_BadPath() { var args = DefaultParse(new[] { @"e:c:\test\test.cs", "/t:library" }, WorkingDirectory); Assert.Equal(3, args.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, args.Errors[0].Code); Assert.Equal((int)ErrorCode.WRN_NoSources, args.Errors[1].Code); Assert.Equal((int)ErrorCode.ERR_OutputNeedsName, args.Errors[2].Code); } private void CreateFile(TempDirectory folder, string file) { var f = folder.CreateFile(file); f.WriteAllText(""); } [Fact, WorkItem(546023, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546023")] public void Win32ResourceArguments() { string[] args = new string[] { @"/win32manifest:..\here\there\everywhere\nonexistent" }; var parsedArgs = DefaultParse(args, WorkingDirectory); var compilation = CreateCompilation(new SyntaxTree[0]); IEnumerable<DiagnosticInfo> errors; CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Manifest, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32icon:\bogus" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenIcon, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32Res:\bogus" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Res, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32Res:goo.win32data:bar.win32data2" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Res, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32icon:goo.win32data:bar.win32data2" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenIcon, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32manifest:goo.win32data:bar.win32data2" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Manifest, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); } [Fact] public void Win32ResConflicts() { var parsedArgs = DefaultParse(new[] { "/win32res:goo", "/win32icon:goob", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_CantHaveWin32ResAndIcon, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "/win32res:goo", "/win32manifest:goob", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_CantHaveWin32ResAndManifest, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "/win32res:", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_NoFileSpec, parsedArgs.Errors.First().Code); Assert.Equal(1, parsedArgs.Errors.First().Arguments.Count); parsedArgs = DefaultParse(new[] { "/win32Icon: ", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_NoFileSpec, parsedArgs.Errors.First().Code); Assert.Equal(1, parsedArgs.Errors.First().Arguments.Count); parsedArgs = DefaultParse(new[] { "/win32Manifest:", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_NoFileSpec, parsedArgs.Errors.First().Code); Assert.Equal(1, parsedArgs.Errors.First().Arguments.Count); parsedArgs = DefaultParse(new[] { "/win32Manifest:goo", "/noWin32Manifest", "a.cs" }, WorkingDirectory); Assert.Equal(0, parsedArgs.Errors.Length); Assert.True(parsedArgs.NoWin32Manifest); Assert.Null(parsedArgs.Win32Manifest); } [Fact] public void Win32ResInvalid() { var parsedArgs = DefaultParse(new[] { "/win32res", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/win32res")); parsedArgs = DefaultParse(new[] { "/win32res+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/win32res+")); parsedArgs = DefaultParse(new[] { "/win32icon", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/win32icon")); parsedArgs = DefaultParse(new[] { "/win32icon+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/win32icon+")); parsedArgs = DefaultParse(new[] { "/win32manifest", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/win32manifest")); parsedArgs = DefaultParse(new[] { "/win32manifest+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/win32manifest+")); } [Fact] public void Win32IconContainsGarbage() { string tmpFileName = Temp.CreateFile().WriteAllBytes(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }).Path; var parsedArgs = DefaultParse(new[] { "/win32icon:" + tmpFileName, "a.cs" }, WorkingDirectory); var compilation = CreateCompilation(new SyntaxTree[0]); IEnumerable<DiagnosticInfo> errors; CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_ErrorBuildingWin32Resources, errors.First().Code); Assert.Equal(1, errors.First().Arguments.Count()); CleanupAllGeneratedFiles(tmpFileName); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void Win32ResQuotes() { string[] responseFile = new string[] { @" /win32res:d:\\""abc def""\a""b c""d\a.res", }; CSharpCommandLineArguments args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\"); Assert.Equal(@"d:\abc def\ab cd\a.res", args.Win32ResourceFile); responseFile = new string[] { @" /win32icon:d:\\""abc def""\a""b c""d\a.ico", }; args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\"); Assert.Equal(@"d:\abc def\ab cd\a.ico", args.Win32Icon); responseFile = new string[] { @" /win32manifest:d:\\""abc def""\a""b c""d\a.manifest", }; args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\"); Assert.Equal(@"d:\abc def\ab cd\a.manifest", args.Win32Manifest); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseResources() { var diags = new List<Diagnostic>(); ResourceDescription desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,someName", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("someName", desc.ResourceName); desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\s""ome Fil""e.goo.bar,someName", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"some File.goo.bar", desc.FileName); Assert.Equal("someName", desc.ResourceName); desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,""some Name"",public", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("some Name", desc.ResourceName); Assert.True(desc.IsPublic); // Use file name in place of missing resource name. desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); Assert.False(desc.IsPublic); // Quoted accessibility is fine. desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,""private""", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); Assert.False(desc.IsPublic); // Leading commas are not ignored... desc = CSharpCommandLineParser.ParseResourceDescription("", @",,\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option '\somepath\someFile.goo.bar'; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(@"\somepath\someFile.goo.bar")); diags.Clear(); Assert.Null(desc); // ...even if there's whitespace between them. desc = CSharpCommandLineParser.ParseResourceDescription("", @", ,\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option '\somepath\someFile.goo.bar'; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(@"\somepath\someFile.goo.bar")); diags.Clear(); Assert.Null(desc); // Trailing commas are ignored... desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false); diags.Verify(); diags.Clear(); Assert.Equal("someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); Assert.False(desc.IsPublic); // ...even if there's whitespace between them. desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,private, ,", WorkingDirectory, diags, embedded: false); diags.Verify(); diags.Clear(); Assert.Equal("someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); Assert.False(desc.IsPublic); desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,someName,publi", WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments("publi")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", @"D:rive\relative\path,someName,public", WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"D:rive\relative\path")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", @"inva\l*d?path,someName,public", WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"inva\l*d?path")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", (string)null, WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", "", WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", " ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", " , ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path, ", WorkingDirectory, diags, embedded: false); diags.Verify(); diags.Clear(); Assert.Equal("path", desc.FileName); Assert.Equal("path", desc.ResourceName); Assert.True(desc.IsPublic); desc = CSharpCommandLineParser.ParseResourceDescription("", " ,name", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", " , , ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option ' '; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" ")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path, , ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option ' '; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" ")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", " ,name, ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option ' '; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" ")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", " , ,private", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path,name,", WorkingDirectory, diags, embedded: false); diags.Verify( // CONSIDER: Dev10 actually prints "Invalid option '|'" (note the pipe) // error CS1906: Invalid option ''; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments("")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path,name,,", WorkingDirectory, diags, embedded: false); diags.Verify( // CONSIDER: Dev10 actually prints "Invalid option '|'" (note the pipe) // error CS1906: Invalid option ''; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments("")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path,name, ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option ''; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" ")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path, ,private", WorkingDirectory, diags, embedded: false); diags.Verify(); diags.Clear(); Assert.Equal("path", desc.FileName); Assert.Equal("path", desc.ResourceName); Assert.False(desc.IsPublic); desc = CSharpCommandLineParser.ParseResourceDescription("", " ,name,private", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); var longE = new String('e', 1024); desc = CSharpCommandLineParser.ParseResourceDescription("", String.Format("path,{0},private", longE), WorkingDirectory, diags, embedded: false); diags.Verify(); // Now checked during emit. diags.Clear(); Assert.Equal("path", desc.FileName); Assert.Equal(longE, desc.ResourceName); Assert.False(desc.IsPublic); var longI = new String('i', 260); desc = CSharpCommandLineParser.ParseResourceDescription("", String.Format("{0},e,private", longI), WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2021: File name 'iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii").WithLocation(1, 1)); } [Fact] public void ManagedResourceOptions() { CSharpCommandLineArguments parsedArgs; ResourceDescription resourceDescription; parsedArgs = DefaultParse(new[] { "/resource:a", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); resourceDescription = parsedArgs.ManifestResources.Single(); Assert.Null(resourceDescription.FileName); // since embedded Assert.Equal("a", resourceDescription.ResourceName); parsedArgs = DefaultParse(new[] { "/res:b", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); resourceDescription = parsedArgs.ManifestResources.Single(); Assert.Null(resourceDescription.FileName); // since embedded Assert.Equal("b", resourceDescription.ResourceName); parsedArgs = DefaultParse(new[] { "/linkresource:c", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); resourceDescription = parsedArgs.ManifestResources.Single(); Assert.Equal("c", resourceDescription.FileName); Assert.Equal("c", resourceDescription.ResourceName); parsedArgs = DefaultParse(new[] { "/linkres:d", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); resourceDescription = parsedArgs.ManifestResources.Single(); Assert.Equal("d", resourceDescription.FileName); Assert.Equal("d", resourceDescription.ResourceName); } [Fact] public void ManagedResourceOptions_SimpleErrors() { var parsedArgs = DefaultParse(new[] { "/resource:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/resource:")); parsedArgs = DefaultParse(new[] { "/resource: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/resource:")); parsedArgs = DefaultParse(new[] { "/res", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/res")); parsedArgs = DefaultParse(new[] { "/RES+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/RES+")); parsedArgs = DefaultParse(new[] { "/res-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/res-:")); parsedArgs = DefaultParse(new[] { "/linkresource:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/linkresource:")); parsedArgs = DefaultParse(new[] { "/linkresource: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/linkresource:")); parsedArgs = DefaultParse(new[] { "/linkres", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/linkres")); parsedArgs = DefaultParse(new[] { "/linkRES+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/linkRES+")); parsedArgs = DefaultParse(new[] { "/linkres-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/linkres-:")); } [Fact] public void Link_SimpleTests() { var parsedArgs = DefaultParse(new[] { "/link:a", "/link:b,,,,c", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "a", "b", "c" }, parsedArgs.MetadataReferences. Where((res) => res.Properties.EmbedInteropTypes). Select((res) => res.Reference)); parsedArgs = DefaultParse(new[] { "/Link: ,,, b ,,", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { " b " }, parsedArgs.MetadataReferences. Where((res) => res.Properties.EmbedInteropTypes). Select((res) => res.Reference)); parsedArgs = DefaultParse(new[] { "/l:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/l:")); parsedArgs = DefaultParse(new[] { "/L", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/L")); parsedArgs = DefaultParse(new[] { "/l+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/l+")); parsedArgs = DefaultParse(new[] { "/link-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/link-:")); } [ConditionalFact(typeof(WindowsOnly))] public void Recurse_SimpleTests() { var dir = Temp.CreateDirectory(); var file1 = dir.CreateFile("a.cs"); var file2 = dir.CreateFile("b.cs"); var file3 = dir.CreateFile("c.txt"); var file4 = dir.CreateDirectory("d1").CreateFile("d.txt"); var file5 = dir.CreateDirectory("d2").CreateFile("e.cs"); file1.WriteAllText(""); file2.WriteAllText(""); file3.WriteAllText(""); file4.WriteAllText(""); file5.WriteAllText(""); var parsedArgs = DefaultParse(new[] { "/recurse:" + dir.ToString() + "\\*.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "{DIR}\\a.cs", "{DIR}\\b.cs", "{DIR}\\d2\\e.cs" }, parsedArgs.SourceFiles.Select((file) => file.Path.Replace(dir.ToString(), "{DIR}"))); parsedArgs = DefaultParse(new[] { "*.cs" }, dir.ToString()); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "{DIR}\\a.cs", "{DIR}\\b.cs" }, parsedArgs.SourceFiles.Select((file) => file.Path.Replace(dir.ToString(), "{DIR}"))); parsedArgs = DefaultParse(new[] { "/reCURSE:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/reCURSE:")); parsedArgs = DefaultParse(new[] { "/RECURSE: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/RECURSE:")); parsedArgs = DefaultParse(new[] { "/recurse", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/recurse")); parsedArgs = DefaultParse(new[] { "/recurse+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/recurse+")); parsedArgs = DefaultParse(new[] { "/recurse-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/recurse-:")); CleanupAllGeneratedFiles(file1.Path); CleanupAllGeneratedFiles(file2.Path); CleanupAllGeneratedFiles(file3.Path); CleanupAllGeneratedFiles(file4.Path); CleanupAllGeneratedFiles(file5.Path); } [Fact] public void Reference_SimpleTests() { var parsedArgs = DefaultParse(new[] { "/nostdlib", "/r:a", "/REFERENCE:b,,,,c", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "a", "b", "c" }, parsedArgs.MetadataReferences. Where((res) => !res.Properties.EmbedInteropTypes). Select((res) => res.Reference)); parsedArgs = DefaultParse(new[] { "/Reference: ,,, b ,,", "/nostdlib", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { " b " }, parsedArgs.MetadataReferences. Where((res) => !res.Properties.EmbedInteropTypes). Select((res) => res.Reference)); parsedArgs = DefaultParse(new[] { "/Reference:a=b,,,", "/nostdlib", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.MetadataReferences.Single().Properties.Aliases.Single()); Assert.Equal("b", parsedArgs.MetadataReferences.Single().Reference); parsedArgs = DefaultParse(new[] { "/r:a=b,,,c", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_OneAliasPerReference).WithArguments("b,,,c")); parsedArgs = DefaultParse(new[] { "/r:1=b", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadExternIdentifier).WithArguments("1")); parsedArgs = DefaultParse(new[] { "/r:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/r:")); parsedArgs = DefaultParse(new[] { "/R", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/R")); parsedArgs = DefaultParse(new[] { "/reference+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/reference+")); parsedArgs = DefaultParse(new[] { "/reference-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/reference-:")); } [Fact] public void Target_SimpleTests() { var parsedArgs = DefaultParse(new[] { "/target:exe", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.ConsoleApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/t:module", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:library", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.DynamicallyLinkedLibrary, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/TARGET:winexe", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.WindowsApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:appcontainerexe", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.WindowsRuntimeApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:winmdobj", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.WindowsRuntimeMetadata, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:winexe", "/T:exe", "/target:module", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/t", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/t")); parsedArgs = DefaultParse(new[] { "/target:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_InvalidTarget)); parsedArgs = DefaultParse(new[] { "/target:xyz", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_InvalidTarget)); parsedArgs = DefaultParse(new[] { "/T+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/T+")); parsedArgs = DefaultParse(new[] { "/TARGET-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/TARGET-:")); } [Fact] public void Target_SimpleTestsNoSource() { var parsedArgs = DefaultParse(new[] { "/target:exe" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.ConsoleApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/t:module" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:library" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.DynamicallyLinkedLibrary, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/TARGET:winexe" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.WindowsApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:appcontainerexe" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.WindowsRuntimeApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:winmdobj" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.WindowsRuntimeMetadata, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:winexe", "/T:exe", "/target:module" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/t" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/t' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/t").WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/target:" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2019: Invalid target type for /target: must specify 'exe', 'winexe', 'library', or 'module' Diagnostic(ErrorCode.FTL_InvalidTarget).WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/target:xyz" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2019: Invalid target type for /target: must specify 'exe', 'winexe', 'library', or 'module' Diagnostic(ErrorCode.FTL_InvalidTarget).WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/T+" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/T+' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/T+").WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/TARGET-:" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/TARGET-:' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/TARGET-:").WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); } [Fact] public void ModuleManifest() { CSharpCommandLineArguments args = DefaultParse(new[] { "/win32manifest:blah", "/target:module", "a.cs" }, WorkingDirectory); args.Errors.Verify( // warning CS1927: Ignoring /win32manifest for module because it only applies to assemblies Diagnostic(ErrorCode.WRN_CantHaveManifestForModule)); // Illegal, but not clobbered. Assert.Equal("blah", args.Win32Manifest); } [Fact] public void ArgumentParsing() { var sdkDirectory = SdkDirectory; var parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "a + b" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "a + b; c" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/help" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayHelp); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/version" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayVersion); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/langversion:?" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayLangVersions); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "//langversion:?" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS2001: Source file '//langversion:?' could not be found. Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments("//langversion:?").WithLocation(1, 1) ); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/version", "c.csx" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayVersion); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/version:something" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayVersion); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/?" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayHelp); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "c.csx /langversion:6" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/langversion:-1", "c.csx", }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS1617: Invalid option '-1' for /langversion. Use '/langversion:?' to list supported values. Diagnostic(ErrorCode.ERR_BadCompatMode).WithArguments("-1").WithLocation(1, 1)); Assert.False(parsedArgs.DisplayHelp); Assert.Equal(1, parsedArgs.SourceFiles.Length); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "c.csx /r:s=d /r:d.dll" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "@roslyn_test_non_existing_file" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS2011: Error opening response file 'D:\R0\Main\Binaries\Debug\dd' Diagnostic(ErrorCode.ERR_OpenResponseFile).WithArguments(Path.Combine(WorkingDirectory, @"roslyn_test_non_existing_file"))); Assert.False(parsedArgs.DisplayHelp); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "c /define:DEBUG" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "\\" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/r:d.dll", "c.csx" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/define:goo", "c.csx" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/define:goo' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/define:goo")); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "\"/r d.dll\"" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/r: d.dll", "a.cs" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); } [Theory] [InlineData("iso-1", LanguageVersion.CSharp1)] [InlineData("iso-2", LanguageVersion.CSharp2)] [InlineData("1", LanguageVersion.CSharp1)] [InlineData("1.0", LanguageVersion.CSharp1)] [InlineData("2", LanguageVersion.CSharp2)] [InlineData("2.0", LanguageVersion.CSharp2)] [InlineData("3", LanguageVersion.CSharp3)] [InlineData("3.0", LanguageVersion.CSharp3)] [InlineData("4", LanguageVersion.CSharp4)] [InlineData("4.0", LanguageVersion.CSharp4)] [InlineData("5", LanguageVersion.CSharp5)] [InlineData("5.0", LanguageVersion.CSharp5)] [InlineData("6", LanguageVersion.CSharp6)] [InlineData("6.0", LanguageVersion.CSharp6)] [InlineData("7", LanguageVersion.CSharp7)] [InlineData("7.0", LanguageVersion.CSharp7)] [InlineData("7.1", LanguageVersion.CSharp7_1)] [InlineData("7.2", LanguageVersion.CSharp7_2)] [InlineData("7.3", LanguageVersion.CSharp7_3)] [InlineData("8", LanguageVersion.CSharp8)] [InlineData("8.0", LanguageVersion.CSharp8)] [InlineData("9", LanguageVersion.CSharp9)] [InlineData("9.0", LanguageVersion.CSharp9)] [InlineData("preview", LanguageVersion.Preview)] public void LangVersion_CanParseCorrectVersions(string value, LanguageVersion expectedVersion) { var parsedArgs = DefaultParse(new[] { $"/langversion:{value}", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(expectedVersion, parsedArgs.ParseOptions.LanguageVersion); Assert.Equal(expectedVersion, parsedArgs.ParseOptions.SpecifiedLanguageVersion); var scriptParsedArgs = ScriptParse(new[] { $"/langversion:{value}" }, WorkingDirectory); scriptParsedArgs.Errors.Verify(); Assert.Equal(expectedVersion, scriptParsedArgs.ParseOptions.LanguageVersion); Assert.Equal(expectedVersion, scriptParsedArgs.ParseOptions.SpecifiedLanguageVersion); } [Theory] [InlineData("6", "7", LanguageVersion.CSharp7)] [InlineData("7", "6", LanguageVersion.CSharp6)] [InlineData("7", "1", LanguageVersion.CSharp1)] [InlineData("6", "iso-1", LanguageVersion.CSharp1)] [InlineData("6", "iso-2", LanguageVersion.CSharp2)] [InlineData("6", "default", LanguageVersion.Default)] [InlineData("7", "default", LanguageVersion.Default)] [InlineData("iso-2", "6", LanguageVersion.CSharp6)] public void LangVersion_LatterVersionOverridesFormerOne(string formerValue, string latterValue, LanguageVersion expectedVersion) { var parsedArgs = DefaultParse(new[] { $"/langversion:{formerValue}", $"/langversion:{latterValue}", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(expectedVersion, parsedArgs.ParseOptions.SpecifiedLanguageVersion); } [Fact] public void LangVersion_DefaultMapsCorrectly() { LanguageVersion defaultEffectiveVersion = LanguageVersion.Default.MapSpecifiedToEffectiveVersion(); Assert.NotEqual(LanguageVersion.Default, defaultEffectiveVersion); var parsedArgs = DefaultParse(new[] { "/langversion:default", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(LanguageVersion.Default, parsedArgs.ParseOptions.SpecifiedLanguageVersion); Assert.Equal(defaultEffectiveVersion, parsedArgs.ParseOptions.LanguageVersion); } [Fact] public void LangVersion_LatestMapsCorrectly() { LanguageVersion latestEffectiveVersion = LanguageVersion.Latest.MapSpecifiedToEffectiveVersion(); Assert.NotEqual(LanguageVersion.Latest, latestEffectiveVersion); var parsedArgs = DefaultParse(new[] { "/langversion:latest", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(LanguageVersion.Latest, parsedArgs.ParseOptions.SpecifiedLanguageVersion); Assert.Equal(latestEffectiveVersion, parsedArgs.ParseOptions.LanguageVersion); } [Fact] public void LangVersion_NoValueSpecified() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(LanguageVersion.Default, parsedArgs.ParseOptions.SpecifiedLanguageVersion); } [Theory] [InlineData("iso-3")] [InlineData("iso1")] [InlineData("8.1")] [InlineData("10.1")] [InlineData("11")] [InlineData("1000")] public void LangVersion_BadVersion(string value) { DefaultParse(new[] { $"/langversion:{value}", "a.cs" }, WorkingDirectory).Errors.Verify( // error CS1617: Invalid option 'XXX' for /langversion. Use '/langversion:?' to list supported values. Diagnostic(ErrorCode.ERR_BadCompatMode).WithArguments(value).WithLocation(1, 1) ); } [Theory] [InlineData("0")] [InlineData("05")] [InlineData("07")] [InlineData("07.1")] [InlineData("08")] [InlineData("09")] public void LangVersion_LeadingZeroes(string value) { DefaultParse(new[] { $"/langversion:{value}", "a.cs" }, WorkingDirectory).Errors.Verify( // error CS8303: Specified language version 'XXX' cannot have leading zeroes Diagnostic(ErrorCode.ERR_LanguageVersionCannotHaveLeadingZeroes).WithArguments(value).WithLocation(1, 1)); } [Theory] [InlineData("/langversion")] [InlineData("/langversion:")] [InlineData("/LANGversion:")] public void LangVersion_NoVersion(string option) { DefaultParse(new[] { option, "a.cs" }, WorkingDirectory).Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/langversion:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/langversion:").WithLocation(1, 1)); } [Fact] public void LangVersion_LangVersions() { var args = DefaultParse(new[] { "/langversion:?" }, WorkingDirectory); args.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1) ); Assert.True(args.DisplayLangVersions); } [Fact] public void LanguageVersionAdded_Canary() { // When a new version is added, this test will break. This list must be checked: // - update the "UpgradeProject" codefixer // - update all the tests that call this canary // - update MaxSupportedLangVersion (a relevant test should break when new version is introduced) // - email release management to add to the release notes (see old example: https://github.com/dotnet/core/pull/1454) AssertEx.SetEqual(new[] { "default", "1", "2", "3", "4", "5", "6", "7.0", "7.1", "7.2", "7.3", "8.0", "9.0", "10.0", "latest", "latestmajor", "preview" }, Enum.GetValues(typeof(LanguageVersion)).Cast<LanguageVersion>().Select(v => v.ToDisplayString())); // For minor versions and new major versions, the format should be "x.y", such as "7.1" } [Fact] public void LanguageVersion_GetErrorCode() { var versions = Enum.GetValues(typeof(LanguageVersion)) .Cast<LanguageVersion>() .Except(new[] { LanguageVersion.Default, LanguageVersion.Latest, LanguageVersion.LatestMajor, LanguageVersion.Preview }) .Select(v => v.GetErrorCode()); var errorCodes = new[] { ErrorCode.ERR_FeatureNotAvailableInVersion1, ErrorCode.ERR_FeatureNotAvailableInVersion2, ErrorCode.ERR_FeatureNotAvailableInVersion3, ErrorCode.ERR_FeatureNotAvailableInVersion4, ErrorCode.ERR_FeatureNotAvailableInVersion5, ErrorCode.ERR_FeatureNotAvailableInVersion6, ErrorCode.ERR_FeatureNotAvailableInVersion7, ErrorCode.ERR_FeatureNotAvailableInVersion7_1, ErrorCode.ERR_FeatureNotAvailableInVersion7_2, ErrorCode.ERR_FeatureNotAvailableInVersion7_3, ErrorCode.ERR_FeatureNotAvailableInVersion8, ErrorCode.ERR_FeatureNotAvailableInVersion9, ErrorCode.ERR_FeatureNotAvailableInVersion10, }; AssertEx.SetEqual(versions, errorCodes); // The canary check is a reminder that this test needs to be updated when a language version is added LanguageVersionAdded_Canary(); } [Theory, InlineData(LanguageVersion.CSharp1, LanguageVersion.CSharp1), InlineData(LanguageVersion.CSharp2, LanguageVersion.CSharp2), InlineData(LanguageVersion.CSharp3, LanguageVersion.CSharp3), InlineData(LanguageVersion.CSharp4, LanguageVersion.CSharp4), InlineData(LanguageVersion.CSharp5, LanguageVersion.CSharp5), InlineData(LanguageVersion.CSharp6, LanguageVersion.CSharp6), InlineData(LanguageVersion.CSharp7, LanguageVersion.CSharp7), InlineData(LanguageVersion.CSharp7_1, LanguageVersion.CSharp7_1), InlineData(LanguageVersion.CSharp7_2, LanguageVersion.CSharp7_2), InlineData(LanguageVersion.CSharp7_3, LanguageVersion.CSharp7_3), InlineData(LanguageVersion.CSharp8, LanguageVersion.CSharp8), InlineData(LanguageVersion.CSharp9, LanguageVersion.CSharp9), InlineData(LanguageVersion.CSharp10, LanguageVersion.CSharp10), InlineData(LanguageVersion.CSharp10, LanguageVersion.LatestMajor), InlineData(LanguageVersion.CSharp10, LanguageVersion.Latest), InlineData(LanguageVersion.CSharp10, LanguageVersion.Default), InlineData(LanguageVersion.Preview, LanguageVersion.Preview), ] public void LanguageVersion_MapSpecifiedToEffectiveVersion(LanguageVersion expectedMappedVersion, LanguageVersion input) { Assert.Equal(expectedMappedVersion, input.MapSpecifiedToEffectiveVersion()); Assert.True(expectedMappedVersion.IsValid()); // The canary check is a reminder that this test needs to be updated when a language version is added LanguageVersionAdded_Canary(); } [Theory, InlineData("iso-1", true, LanguageVersion.CSharp1), InlineData("ISO-1", true, LanguageVersion.CSharp1), InlineData("iso-2", true, LanguageVersion.CSharp2), InlineData("1", true, LanguageVersion.CSharp1), InlineData("1.0", true, LanguageVersion.CSharp1), InlineData("2", true, LanguageVersion.CSharp2), InlineData("2.0", true, LanguageVersion.CSharp2), InlineData("3", true, LanguageVersion.CSharp3), InlineData("3.0", true, LanguageVersion.CSharp3), InlineData("4", true, LanguageVersion.CSharp4), InlineData("4.0", true, LanguageVersion.CSharp4), InlineData("5", true, LanguageVersion.CSharp5), InlineData("5.0", true, LanguageVersion.CSharp5), InlineData("05", false, LanguageVersion.Default), InlineData("6", true, LanguageVersion.CSharp6), InlineData("6.0", true, LanguageVersion.CSharp6), InlineData("7", true, LanguageVersion.CSharp7), InlineData("7.0", true, LanguageVersion.CSharp7), InlineData("07", false, LanguageVersion.Default), InlineData("7.1", true, LanguageVersion.CSharp7_1), InlineData("7.2", true, LanguageVersion.CSharp7_2), InlineData("7.3", true, LanguageVersion.CSharp7_3), InlineData("8", true, LanguageVersion.CSharp8), InlineData("8.0", true, LanguageVersion.CSharp8), InlineData("9", true, LanguageVersion.CSharp9), InlineData("9.0", true, LanguageVersion.CSharp9), InlineData("10", true, LanguageVersion.CSharp10), InlineData("10.0", true, LanguageVersion.CSharp10), InlineData("08", false, LanguageVersion.Default), InlineData("07.1", false, LanguageVersion.Default), InlineData("default", true, LanguageVersion.Default), InlineData("latest", true, LanguageVersion.Latest), InlineData("latestmajor", true, LanguageVersion.LatestMajor), InlineData("preview", true, LanguageVersion.Preview), InlineData("latestpreview", false, LanguageVersion.Default), InlineData(null, true, LanguageVersion.Default), InlineData("bad", false, LanguageVersion.Default)] public void LanguageVersion_TryParseDisplayString(string input, bool success, LanguageVersion expected) { Assert.Equal(success, LanguageVersionFacts.TryParse(input, out var version)); Assert.Equal(expected, version); // The canary check is a reminder that this test needs to be updated when a language version is added LanguageVersionAdded_Canary(); } [Fact] public void LanguageVersion_TryParseTurkishDisplayString() { var originalCulture = Thread.CurrentThread.CurrentCulture; Thread.CurrentThread.CurrentCulture = new CultureInfo("tr-TR", useUserOverride: false); Assert.True(LanguageVersionFacts.TryParse("ISO-1", out var version)); Assert.Equal(LanguageVersion.CSharp1, version); Thread.CurrentThread.CurrentCulture = originalCulture; } [Fact] public void LangVersion_ListLangVersions() { var dir = Temp.CreateDirectory(); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/langversion:?" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var expected = Enum.GetValues(typeof(LanguageVersion)).Cast<LanguageVersion>() .Select(v => v.ToDisplayString()); var actual = outWriter.ToString(); var acceptableSurroundingChar = new[] { '\r', '\n', '(', ')', ' ' }; foreach (var version in expected) { if (version == "latest") continue; var foundIndex = actual.IndexOf(version); Assert.True(foundIndex > 0, $"Missing version '{version}'"); Assert.True(Array.IndexOf(acceptableSurroundingChar, actual[foundIndex - 1]) >= 0); Assert.True(Array.IndexOf(acceptableSurroundingChar, actual[foundIndex + version.Length]) >= 0); } } [Fact] [WorkItem(546961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546961")] public void Define() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); Assert.Equal(0, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count()); Assert.False(parsedArgs.Errors.Any()); parsedArgs = DefaultParse(new[] { "/d:GOO", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count()); Assert.Contains("GOO", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.False(parsedArgs.Errors.Any()); parsedArgs = DefaultParse(new[] { "/d:GOO;BAR,ZIP", "a.cs" }, WorkingDirectory); Assert.Equal(3, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count()); Assert.Contains("GOO", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.Contains("BAR", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.Contains("ZIP", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.False(parsedArgs.Errors.Any()); parsedArgs = DefaultParse(new[] { "/d:GOO;4X", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count()); Assert.Contains("GOO", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.WRN_DefineIdentifierRequired, parsedArgs.Errors.First().Code); Assert.Equal("4X", parsedArgs.Errors.First().Arguments[0]); IEnumerable<Diagnostic> diagnostics; // The docs say /d:def1[;def2] string compliant = "def1;def2;def3"; var expected = new[] { "def1", "def2", "def3" }; var parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(compliant, out diagnostics); diagnostics.Verify(); Assert.Equal<string>(expected, parsed); // Bug 17360: Dev11 allows for a terminating semicolon var dev11Compliant = "def1;def2;def3;"; parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(dev11Compliant, out diagnostics); diagnostics.Verify(); Assert.Equal<string>(expected, parsed); // And comma dev11Compliant = "def1,def2,def3,"; parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(dev11Compliant, out diagnostics); diagnostics.Verify(); Assert.Equal<string>(expected, parsed); // This breaks everything var nonCompliant = "def1;;def2;"; parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(nonCompliant, out diagnostics); diagnostics.Verify( // warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("")); Assert.Equal(new[] { "def1", "def2" }, parsed); // Bug 17360 parsedArgs = DefaultParse(new[] { "/d:public1;public2;", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); } [Fact] public void Debug() { var platformPdbKind = PathUtilities.IsUnixLikePlatform ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb; var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.False(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.False(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.True(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.True(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug+", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.False(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:full", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:FULL", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:portable", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(DebugInformationFormat.PortablePdb, parsedArgs.EmitOptions.DebugInformationFormat); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/debug:embedded", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(DebugInformationFormat.Embedded, parsedArgs.EmitOptions.DebugInformationFormat); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/debug:PDBONLY", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:full", "/debug:pdbonly", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug:full", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug-", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug-", "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:embedded", "/debug-", "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(DebugInformationFormat.Embedded, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:embedded", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.Equal(DebugInformationFormat.Embedded, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "debug")); parsedArgs = DefaultParse(new[] { "/debug:+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadDebugType).WithArguments("+")); parsedArgs = DefaultParse(new[] { "/debug:invalid", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadDebugType).WithArguments("invalid")); parsedArgs = DefaultParse(new[] { "/debug-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/debug-:")); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void Pdb() { var parsedArgs = DefaultParse(new[] { "/pdb:something", "a.cs" }, WorkingDirectory); Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.PdbPath); Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.GetPdbFilePath("a.dll")); Assert.False(parsedArgs.EmitPdbFile); parsedArgs = DefaultParse(new[] { "/pdb:something", "/debug:embedded", "a.cs" }, WorkingDirectory); Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.PdbPath); Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.GetPdbFilePath("a.dll")); Assert.False(parsedArgs.EmitPdbFile); parsedArgs = DefaultParse(new[] { "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.PdbPath); Assert.True(parsedArgs.EmitPdbFile); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/pdb")); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/pdb:", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/pdb:")); parsedArgs = DefaultParse(new[] { "/pdb:something", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // temp: path changed //parsedArgs = DefaultParse(new[] { "/debug", "/pdb:.x", "a.cs" }, baseDirectory); //parsedArgs.Errors.Verify( // // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x")); parsedArgs = DefaultParse(new[] { @"/pdb:""""", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for '/pdb:""' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments(@"/pdb:""""").WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/pdb:C:\\", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("C:\\")); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/pdb:C:\MyFolder\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\MyFolder\MyPdb.pdb", parsedArgs.PdbPath); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/pdb:c:\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"c:\MyPdb.pdb", parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { @"/pdb:\MyFolder\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(Path.GetPathRoot(WorkingDirectory), @"MyFolder\MyPdb.pdb"), parsedArgs.PdbPath); // Should handle quotes parsedArgs = DefaultParse(new[] { @"/pdb:""C:\My Folder\MyPdb.pdb""", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\My Folder\MyPdb.pdb", parsedArgs.PdbPath); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/pdb:MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(FileUtilities.ResolveRelativePath("MyPdb.pdb", WorkingDirectory), parsedArgs.PdbPath); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/pdb:..\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // Temp: Path info changed // Assert.Equal(FileUtilities.ResolveRelativePath("MyPdb.pdb", "..\\", baseDirectory), parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { @"/pdb:\\b", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b")); Assert.Null(parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { @"/pdb:\\b\OkFileName.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b\OkFileName.pdb")); Assert.Null(parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { @"/pdb:\\server\share\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"\\server\share\MyPdb.pdb", parsedArgs.PdbPath); // invalid name: parsedArgs = DefaultParse(new[] { "/pdb:a.b\0b", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b")); Assert.Null(parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { "/pdb:a\uD800b.pdb", "/debug", "a.cs" }, WorkingDirectory); //parsedArgs.Errors.Verify( // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a\uD800b.pdb")); Assert.Null(parsedArgs.PdbPath); // Dev11 reports CS0016: Could not write to output file 'd:\Temp\q\a<>.z' parsedArgs = DefaultParse(new[] { @"/pdb:""a<>.pdb""", "a.vb" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'a<>.pdb' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.pdb")); Assert.Null(parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { "/pdb:.x", "/debug", "a.cs" }, WorkingDirectory); //parsedArgs.Errors.Verify( // // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x")); Assert.Null(parsedArgs.PdbPath); } [Fact] public void SourceLink() { var parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:portable", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "sl.json"), parsedArgs.SourceLink); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:embedded", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "sl.json"), parsedArgs.SourceLink); parsedArgs = DefaultParse(new[] { @"/sourcelink:""s l.json""", "/debug:embedded", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "s l.json"), parsedArgs.SourceLink); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:full", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:pdbonly", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SourceLinkRequiresPdb)); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SourceLinkRequiresPdb)); } [Fact] public void SourceLink_EndToEnd_EmbeddedPortable() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText(@"class C { public static void Main() {} }"); var sl = dir.CreateFile("sl.json"); sl.WriteAllText(@"{ ""documents"" : {} }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/debug:embedded", "/sourcelink:sl.json", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var peStream = File.OpenRead(Path.Combine(dir.Path, "a.exe")); using (var peReader = new PEReader(peStream)) { var entry = peReader.ReadDebugDirectory().Single(e => e.Type == DebugDirectoryEntryType.EmbeddedPortablePdb); using (var mdProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(entry)) { var blob = mdProvider.GetMetadataReader().GetSourceLinkBlob(); AssertEx.Equal(File.ReadAllBytes(sl.Path), blob); } } // Clean up temp files CleanupAllGeneratedFiles(src.Path); } [Fact] public void SourceLink_EndToEnd_Portable() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText(@"class C { public static void Main() {} }"); var sl = dir.CreateFile("sl.json"); sl.WriteAllText(@"{ ""documents"" : {} }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/debug:portable", "/sourcelink:sl.json", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var pdbStream = File.OpenRead(Path.Combine(dir.Path, "a.pdb")); using (var mdProvider = MetadataReaderProvider.FromPortablePdbStream(pdbStream)) { var blob = mdProvider.GetMetadataReader().GetSourceLinkBlob(); AssertEx.Equal(File.ReadAllBytes(sl.Path), blob); } // Clean up temp files CleanupAllGeneratedFiles(src.Path); } [Fact] public void SourceLink_EndToEnd_Windows() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText(@"class C { public static void Main() {} }"); var sl = dir.CreateFile("sl.json"); byte[] slContent = Encoding.UTF8.GetBytes(@"{ ""documents"" : {} }"); sl.WriteAllBytes(slContent); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/debug:full", "/sourcelink:sl.json", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var pdbStream = File.OpenRead(Path.Combine(dir.Path, "a.pdb")); var actualData = PdbValidation.GetSourceLinkData(pdbStream); AssertEx.Equal(slContent, actualData); // Clean up temp files CleanupAllGeneratedFiles(src.Path); } [Fact] public void Embed() { var parsedArgs = DefaultParse(new[] { "a.cs " }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Empty(parsedArgs.EmbeddedFiles); parsedArgs = DefaultParse(new[] { "/embed", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(parsedArgs.SourceFiles, parsedArgs.EmbeddedFiles); AssertEx.Equal( new[] { "a.cs", "b.cs", "c.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed:a.cs", "/embed:b.cs", "/debug:embedded", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal( new[] { "a.cs", "b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed:a.cs;b.cs", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal( new[] { "a.cs", "b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed:a.cs,b.cs", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal( new[] { "a.cs", "b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { @"/embed:""a,b.cs""", "/debug:portable", "a,b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal( new[] { "a,b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed:a.txt", "/embed", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); ; AssertEx.Equal( new[] { "a.txt", "a.cs", "b.cs", "c.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb)); parsedArgs = DefaultParse(new[] { "/embed:a.txt", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb)); parsedArgs = DefaultParse(new[] { "/embed", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb)); parsedArgs = DefaultParse(new[] { "/embed:a.txt", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb)); parsedArgs = DefaultParse(new[] { "/embed", "/debug:full", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/embed", "/debug:pdbonly", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/embed", "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); } [Theory] [InlineData("/debug:portable", "/embed", new[] { "embed.cs", "embed2.cs", "embed.xyz" })] [InlineData("/debug:portable", "/embed:embed.cs", new[] { "embed.cs", "embed.xyz" })] [InlineData("/debug:portable", "/embed:embed2.cs", new[] { "embed2.cs" })] [InlineData("/debug:portable", "/embed:embed.xyz", new[] { "embed.xyz" })] [InlineData("/debug:embedded", "/embed", new[] { "embed.cs", "embed2.cs", "embed.xyz" })] [InlineData("/debug:embedded", "/embed:embed.cs", new[] { "embed.cs", "embed.xyz" })] [InlineData("/debug:embedded", "/embed:embed2.cs", new[] { "embed2.cs" })] [InlineData("/debug:embedded", "/embed:embed.xyz", new[] { "embed.xyz" })] public void Embed_EndToEnd_Portable(string debugSwitch, string embedSwitch, string[] expectedEmbedded) { // embed.cs: large enough to compress, has #line directives const string embed_cs = @"/////////////////////////////////////////////////////////////////////////////// class Program { static void Main() { #line 1 ""embed.xyz"" System.Console.WriteLine(""Hello, World""); #line 3 System.Console.WriteLine(""Goodbye, World""); } } ///////////////////////////////////////////////////////////////////////////////"; // embed2.cs: small enough to not compress, no sequence points const string embed2_cs = @"class C { }"; // target of #line const string embed_xyz = @"print Hello, World print Goodbye, World"; Assert.True(embed_cs.Length >= EmbeddedText.CompressionThreshold); Assert.True(embed2_cs.Length < EmbeddedText.CompressionThreshold); var dir = Temp.CreateDirectory(); var src = dir.CreateFile("embed.cs"); var src2 = dir.CreateFile("embed2.cs"); var txt = dir.CreateFile("embed.xyz"); src.WriteAllText(embed_cs); src2.WriteAllText(embed2_cs); txt.WriteAllText(embed_xyz); var expectedEmbeddedMap = new Dictionary<string, string>(); if (expectedEmbedded.Contains("embed.cs")) { expectedEmbeddedMap.Add(src.Path, embed_cs); } if (expectedEmbedded.Contains("embed2.cs")) { expectedEmbeddedMap.Add(src2.Path, embed2_cs); } if (expectedEmbedded.Contains("embed.xyz")) { expectedEmbeddedMap.Add(txt.Path, embed_xyz); } var output = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", debugSwitch, embedSwitch, "embed.cs", "embed2.cs" }); int exitCode = csc.Run(output); Assert.Equal("", output.ToString().Trim()); Assert.Equal(0, exitCode); switch (debugSwitch) { case "/debug:embedded": ValidateEmbeddedSources_Portable(expectedEmbeddedMap, dir, isEmbeddedPdb: true); break; case "/debug:portable": ValidateEmbeddedSources_Portable(expectedEmbeddedMap, dir, isEmbeddedPdb: false); break; case "/debug:full": ValidateEmbeddedSources_Windows(expectedEmbeddedMap, dir); break; } Assert.Empty(expectedEmbeddedMap); CleanupAllGeneratedFiles(src.Path); } private static void ValidateEmbeddedSources_Portable(Dictionary<string, string> expectedEmbeddedMap, TempDirectory dir, bool isEmbeddedPdb) { using (var peReader = new PEReader(File.OpenRead(Path.Combine(dir.Path, "embed.exe")))) { var entry = peReader.ReadDebugDirectory().SingleOrDefault(e => e.Type == DebugDirectoryEntryType.EmbeddedPortablePdb); Assert.Equal(isEmbeddedPdb, entry.DataSize > 0); using (var mdProvider = isEmbeddedPdb ? peReader.ReadEmbeddedPortablePdbDebugDirectoryData(entry) : MetadataReaderProvider.FromPortablePdbStream(File.OpenRead(Path.Combine(dir.Path, "embed.pdb")))) { var mdReader = mdProvider.GetMetadataReader(); foreach (var handle in mdReader.Documents) { var doc = mdReader.GetDocument(handle); var docPath = mdReader.GetString(doc.Name); SourceText embeddedSource = mdReader.GetEmbeddedSource(handle); if (embeddedSource == null) { continue; } Assert.Equal(expectedEmbeddedMap[docPath], embeddedSource.ToString()); Assert.True(expectedEmbeddedMap.Remove(docPath)); } } } } private static void ValidateEmbeddedSources_Windows(Dictionary<string, string> expectedEmbeddedMap, TempDirectory dir) { ISymUnmanagedReader5 symReader = null; try { symReader = SymReaderFactory.CreateReader(File.OpenRead(Path.Combine(dir.Path, "embed.pdb"))); foreach (var doc in symReader.GetDocuments()) { var docPath = doc.GetName(); var sourceBlob = doc.GetEmbeddedSource(); if (sourceBlob.Array == null) { continue; } var sourceStr = Encoding.UTF8.GetString(sourceBlob.Array, sourceBlob.Offset, sourceBlob.Count); Assert.Equal(expectedEmbeddedMap[docPath], sourceStr); Assert.True(expectedEmbeddedMap.Remove(docPath)); } } catch { symReader?.Dispose(); } } private static void ValidateWrittenSources(Dictionary<string, Dictionary<string, string>> expectedFilesMap, Encoding encoding = null) { foreach ((var dirPath, var fileMap) in expectedFilesMap.ToArray()) { foreach (var file in Directory.GetFiles(dirPath)) { var name = Path.GetFileName(file); var content = File.ReadAllText(file, encoding ?? Encoding.UTF8); Assert.Equal(fileMap[name], content); Assert.True(fileMap.Remove(name)); } Assert.Empty(fileMap); Assert.True(expectedFilesMap.Remove(dirPath)); } Assert.Empty(expectedFilesMap); } [Fact] public void Optimize() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(new CSharpCompilationOptions(OutputKind.ConsoleApplication).OptimizationLevel, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize+", "/optimize-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize:+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/optimize:+")); parsedArgs = DefaultParse(new[] { "/optimize:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/optimize:")); parsedArgs = DefaultParse(new[] { "/optimize-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/optimize-:")); parsedArgs = DefaultParse(new[] { "/o-", "a.cs" }, WorkingDirectory); Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new string[] { "/o", "a.cs" }, WorkingDirectory); Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new string[] { "/o+", "a.cs" }, WorkingDirectory); Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new string[] { "/o+", "/optimize-", "a.cs" }, WorkingDirectory); Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new string[] { "/o:+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/o:+")); parsedArgs = DefaultParse(new string[] { "/o:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/o:")); parsedArgs = DefaultParse(new string[] { "/o-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/o-:")); } [Fact] public void Deterministic() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.Deterministic); parsedArgs = DefaultParse(new[] { "/deterministic+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.Deterministic); parsedArgs = DefaultParse(new[] { "/deterministic", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.Deterministic); parsedArgs = DefaultParse(new[] { "/deterministic-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.Deterministic); } [Fact] public void ParseReferences() { var parsedArgs = DefaultParse(new string[] { "/r:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.MetadataReferences.Length); parsedArgs = DefaultParse(new string[] { "/r:goo.dll;", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.MetadataReferences.Length); Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties); Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[1].Properties); parsedArgs = DefaultParse(new string[] { @"/l:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.MetadataReferences.Length); Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties); Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataReferenceProperties.Assembly.WithEmbedInteropTypes(true), parsedArgs.MetadataReferences[1].Properties); parsedArgs = DefaultParse(new string[] { @"/addmodule:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.MetadataReferences.Length); Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties); Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataReferenceProperties.Module, parsedArgs.MetadataReferences[1].Properties); parsedArgs = DefaultParse(new string[] { @"/r:a=goo.dll", "/l:b=bar.dll", "/addmodule:c=mod.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(4, parsedArgs.MetadataReferences.Length); Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties); Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataReferenceProperties.Assembly.WithAliases(new[] { "a" }), parsedArgs.MetadataReferences[1].Properties); Assert.Equal("bar.dll", parsedArgs.MetadataReferences[2].Reference); Assert.Equal(MetadataReferenceProperties.Assembly.WithAliases(new[] { "b" }).WithEmbedInteropTypes(true), parsedArgs.MetadataReferences[2].Properties); Assert.Equal("c=mod.dll", parsedArgs.MetadataReferences[3].Reference); Assert.Equal(MetadataReferenceProperties.Module, parsedArgs.MetadataReferences[3].Properties); // TODO: multiple files, quotes, etc. } [Fact] public void ParseAnalyzers() { var parsedArgs = DefaultParse(new string[] { @"/a:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(1, parsedArgs.AnalyzerReferences.Length); Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath); parsedArgs = DefaultParse(new string[] { @"/analyzer:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(1, parsedArgs.AnalyzerReferences.Length); Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath); parsedArgs = DefaultParse(new string[] { "/analyzer:\"goo.dll\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(1, parsedArgs.AnalyzerReferences.Length); Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath); parsedArgs = DefaultParse(new string[] { @"/a:goo.dll;bar.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.AnalyzerReferences.Length); Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath); Assert.Equal("bar.dll", parsedArgs.AnalyzerReferences[1].FilePath); parsedArgs = DefaultParse(new string[] { @"/a:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/a:")); parsedArgs = DefaultParse(new string[] { "/a", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/a")); } [Fact] public void Analyzers_Missing() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/a:missing.dll", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS0006: Metadata file 'missing.dll' could not be found", outWriter.ToString().Trim()); // Clean up temp files CleanupAllGeneratedFiles(file.Path); } [Fact] public void Analyzers_Empty() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + typeof(object).Assembly.Location, "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.DoesNotContain("warning", outWriter.ToString()); CleanupAllGeneratedFiles(file.Path); } private TempFile CreateRuleSetFile(string source) { var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.ruleset"); file.WriteAllText(source); return file; } [Fact] public void RuleSetSwitchPositive() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> <Rule Id=""CA1013"" Action=""Warning"" /> <Rule Id=""CA1014"" Action=""None"" /> </Rules> </RuleSet> "; var file = CreateRuleSetFile(source); var parsedArgs = DefaultParse(new string[] { @"/ruleset:" + file.Path, "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(expected: file.Path, actual: parsedArgs.RuleSetPath); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1012")); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions["CA1012"] == ReportDiagnostic.Error); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1013")); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions["CA1013"] == ReportDiagnostic.Warn); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1014")); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions["CA1014"] == ReportDiagnostic.Suppress); Assert.True(parsedArgs.CompilationOptions.GeneralDiagnosticOption == ReportDiagnostic.Warn); } [Fact] public void RuleSetSwitchQuoted() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> <Rule Id=""CA1013"" Action=""Warning"" /> <Rule Id=""CA1014"" Action=""None"" /> </Rules> </RuleSet> "; var file = CreateRuleSetFile(source); var parsedArgs = DefaultParse(new string[] { @"/ruleset:" + "\"" + file.Path + "\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(expected: file.Path, actual: parsedArgs.RuleSetPath); } [Fact] public void RuleSetSwitchParseErrors() { var parsedArgs = DefaultParse(new string[] { @"/ruleset", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "ruleset")); Assert.Null(parsedArgs.RuleSetPath); parsedArgs = DefaultParse(new string[] { @"/ruleset:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "ruleset")); Assert.Null(parsedArgs.RuleSetPath); parsedArgs = DefaultParse(new string[] { @"/ruleset:blah", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_CantReadRulesetFile).WithArguments(Path.Combine(TempRoot.Root, "blah"), "File not found.")); Assert.Equal(expected: Path.Combine(TempRoot.Root, "blah"), actual: parsedArgs.RuleSetPath); parsedArgs = DefaultParse(new string[] { @"/ruleset:blah;blah.ruleset", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_CantReadRulesetFile).WithArguments(Path.Combine(TempRoot.Root, "blah;blah.ruleset"), "File not found.")); Assert.Equal(expected: Path.Combine(TempRoot.Root, "blah;blah.ruleset"), actual: parsedArgs.RuleSetPath); var file = CreateRuleSetFile("Random text"); parsedArgs = DefaultParse(new string[] { @"/ruleset:" + file.Path, "a.cs" }, WorkingDirectory); //parsedArgs.Errors.Verify( // Diagnostic(ErrorCode.ERR_CantReadRulesetFile).WithArguments(file.Path, "Data at the root level is invalid. Line 1, position 1.")); Assert.Equal(expected: file.Path, actual: parsedArgs.RuleSetPath); var err = parsedArgs.Errors.Single(); Assert.Equal((int)ErrorCode.ERR_CantReadRulesetFile, err.Code); Assert.Equal(2, err.Arguments.Count); Assert.Equal(file.Path, (string)err.Arguments[0]); var currentUICultureName = Thread.CurrentThread.CurrentUICulture.Name; if (currentUICultureName.Length == 0 || currentUICultureName.StartsWith("en", StringComparison.OrdinalIgnoreCase)) { Assert.Equal("Data at the root level is invalid. Line 1, position 1.", (string)err.Arguments[1]); } } [WorkItem(892467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/892467")] [Fact] public void Analyzers_Found() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation. var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); // Diagnostic thrown Assert.True(outWriter.ToString().Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared")); // Diagnostic cannot be instantiated Assert.True(outWriter.ToString().Contains("warning CS8032")); CleanupAllGeneratedFiles(file.Path); } [Fact] public void Analyzers_WithRuleSet() { string source = @" class C { int x; } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); string rulesetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Warning01"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSetFile = CreateRuleSetFile(rulesetSource); var outWriter = new StringWriter(CultureInfo.InvariantCulture); // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation. var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/ruleset:" + ruleSetFile.Path }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); // Diagnostic thrown as error. Assert.True(outWriter.ToString().Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared")); // Clean up temp files CleanupAllGeneratedFiles(file.Path); } [WorkItem(912906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912906")] [Fact] public void Analyzers_CommandLineOverridesRuleset1() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); string rulesetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> </RuleSet> "; var ruleSetFile = CreateRuleSetFile(rulesetSource); var outWriter = new StringWriter(CultureInfo.InvariantCulture); // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation. var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/ruleset:" + ruleSetFile.Path, "/warnaserror+", "/nowarn:8032" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); // Diagnostic thrown as error: command line always overrides ruleset. Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/warnaserror+", "/ruleset:" + ruleSetFile.Path, "/nowarn:8032" }); exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); // Diagnostic thrown as error: command line always overrides ruleset. Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", outWriter.ToString(), StringComparison.Ordinal); // Clean up temp files CleanupAllGeneratedFiles(file.Path); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_GeneralCommandLineOptionOverridesGeneralRuleSetOption() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_GeneralWarnAsErrorPromotesWarningFromRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Error); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_GeneralWarnAsErrorDoesNotPromoteInfoFromRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Info"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Info); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_SpecificWarnAsErrorPromotesInfoFromRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Info"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Default); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Error); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_GeneralWarnAsErrorMinusResetsRules() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "/warnaserror-", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Default); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Warn); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_SpecificWarnAsErrorMinusResetsRules() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "/warnaserror-:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Warn); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_SpecificWarnAsErrorMinusDefaultsRuleNotInRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+:Test002", "/warnaserror-:Test002", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Default); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Warn); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test002"], expected: ReportDiagnostic.Default); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void NoWarn_SpecificNoWarnOverridesRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/nowarn:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: 1, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void NoWarn_SpecificNoWarnOverridesGeneralWarnAsError() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "/nowarn:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Error, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: 1, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void NoWarn_SpecificNoWarnOverridesSpecificWarnAsError() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/nowarn:Test001", "/warnaserror+:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: 1, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]); } [Fact] [WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void NoWarn_Nullable() { var dir = Temp.CreateDirectory(); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/nowarn:nullable", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 2, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); foreach (string warning in ErrorFacts.NullableWarnings) { Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]); } Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]); } [Fact] [WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void NoWarn_Nullable_Capitalization() { var dir = Temp.CreateDirectory(); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/nowarn:NullABLE", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 2, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); foreach (string warning in ErrorFacts.NullableWarnings) { Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]); } Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]); } [Fact] [WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void NoWarn_Nullable_MultipleArguments() { var dir = Temp.CreateDirectory(); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/nowarn:nullable,Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 3, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); foreach (string warning in ErrorFacts.NullableWarnings) { Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]); } Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]); } [Fact] [WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void WarnAsError_Nullable() { var dir = Temp.CreateDirectory(); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/warnaserror:nullable", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 2, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); foreach (string warning in ErrorFacts.NullableWarnings) { Assert.Equal(expected: ReportDiagnostic.Error, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]); } Assert.Equal(expected: ReportDiagnostic.Error, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]); Assert.Equal(expected: ReportDiagnostic.Error, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]); } [WorkItem(912906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912906")] [Fact] public void Analyzers_CommandLineOverridesRuleset2() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); string rulesetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Warning01"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSetFile = CreateRuleSetFile(rulesetSource); var outWriter = new StringWriter(CultureInfo.InvariantCulture); // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation. var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/ruleset:" + ruleSetFile.Path, "/warn:0" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); // Diagnostic suppressed: commandline always overrides ruleset. Assert.DoesNotContain("Warning01", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/warn:0", "/ruleset:" + ruleSetFile.Path }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); // Diagnostic suppressed: commandline always overrides ruleset. Assert.DoesNotContain("Warning01", outWriter.ToString(), StringComparison.Ordinal); // Clean up temp files CleanupAllGeneratedFiles(file.Path); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void DiagnosticFormatting() { string source = @" using System; class C { public static void Main() { Goo(0); #line 10 ""c:\temp\a\1.cs"" Goo(1); #line 20 ""C:\a\..\b.cs"" Goo(2); #line 30 ""C:\a\../B.cs"" Goo(3); #line 40 ""../b.cs"" Goo(4); #line 50 ""..\b.cs"" Goo(5); #line 60 ""C:\X.cs"" Goo(6); #line 70 ""C:\x.cs"" Goo(7); #line 90 "" "" Goo(9); #line 100 ""C:\*.cs"" Goo(10); #line 110 """" Goo(11); #line hidden Goo(12); #line default Goo(13); #line 140 ""***"" Goo(14); } } "; var dir = Temp.CreateDirectory(); dir.CreateFile("a.cs").WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); // with /fullpaths off string expected = @" a.cs(8,13): error CS0103: The name 'Goo' does not exist in the current context c:\temp\a\1.cs(10,13): error CS0103: The name 'Goo' does not exist in the current context C:\b.cs(20,13): error CS0103: The name 'Goo' does not exist in the current context C:\B.cs(30,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(40,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(50,13): error CS0103: The name 'Goo' does not exist in the current context C:\X.cs(60,13): error CS0103: The name 'Goo' does not exist in the current context C:\x.cs(70,13): error CS0103: The name 'Goo' does not exist in the current context (90,7): error CS0103: The name 'Goo' does not exist in the current context C:\*.cs(100,7): error CS0103: The name 'Goo' does not exist in the current context (110,7): error CS0103: The name 'Goo' does not exist in the current context (112,13): error CS0103: The name 'Goo' does not exist in the current context a.cs(32,13): error CS0103: The name 'Goo' does not exist in the current context ***(140,13): error CS0103: The name 'Goo' does not exist in the current context"; AssertEx.Equal( expected.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries), outWriter.ToString().Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries), itemSeparator: "\r\n"); // with /fullpaths on outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/fullpaths", "a.cs" }); exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); expected = @" " + Path.Combine(dir.Path, @"a.cs") + @"(8,13): error CS0103: The name 'Goo' does not exist in the current context c:\temp\a\1.cs(10,13): error CS0103: The name 'Goo' does not exist in the current context C:\b.cs(20,13): error CS0103: The name 'Goo' does not exist in the current context C:\B.cs(30,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(40,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(50,13): error CS0103: The name 'Goo' does not exist in the current context C:\X.cs(60,13): error CS0103: The name 'Goo' does not exist in the current context C:\x.cs(70,13): error CS0103: The name 'Goo' does not exist in the current context (90,7): error CS0103: The name 'Goo' does not exist in the current context C:\*.cs(100,7): error CS0103: The name 'Goo' does not exist in the current context (110,7): error CS0103: The name 'Goo' does not exist in the current context (112,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.Combine(dir.Path, @"a.cs") + @"(32,13): error CS0103: The name 'Goo' does not exist in the current context ***(140,13): error CS0103: The name 'Goo' does not exist in the current context"; AssertEx.Equal( expected.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries), outWriter.ToString().Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries), itemSeparator: "\r\n"); } [WorkItem(540891, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540891")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseOut() { const string baseDirectory = @"C:\abc\def\baz"; var parsedArgs = DefaultParse(new[] { @"/out:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '' contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("")); parsedArgs = DefaultParse(new[] { @"/out:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for '/out:' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/out:")); parsedArgs = DefaultParse(new[] { @"/refout:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for '/refout:' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/refout:")); parsedArgs = DefaultParse(new[] { @"/refout:ref.dll", "/refonly", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS8301: Do not use refout when using refonly. Diagnostic(ErrorCode.ERR_NoRefOutWhenRefOnly).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { @"/refout:ref.dll", "/link:b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/refonly", "/link:b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/refonly:incorrect", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/refonly:incorrect' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/refonly:incorrect").WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/refout:ref.dll", "/target:module", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS8302: Cannot compile net modules when using /refout or /refonly. Diagnostic(ErrorCode.ERR_NoNetModuleOutputWhenRefOutOrRefOnly).WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/refonly", "/target:module", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS8302: Cannot compile net modules when using /refout or /refonly. Diagnostic(ErrorCode.ERR_NoNetModuleOutputWhenRefOutOrRefOnly).WithLocation(1, 1) ); // Dev11 reports CS2007: Unrecognized option: '/out' parsedArgs = DefaultParse(new[] { @"/out", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for '/out' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/out")); parsedArgs = DefaultParse(new[] { @"/out+", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/out+")); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/out:C:\MyFolder\MyBinary.dll", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("MyBinary", parsedArgs.CompilationName); Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName); Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(@"C:\MyFolder", parsedArgs.OutputDirectory); Assert.Equal(@"C:\MyFolder\MyBinary.dll", parsedArgs.GetOutputFilePath(parsedArgs.OutputFileName)); // Should handle quotes parsedArgs = DefaultParse(new[] { @"/out:""C:\My Folder\MyBinary.dll""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"MyBinary", parsedArgs.CompilationName); Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName); Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(@"C:\My Folder", parsedArgs.OutputDirectory); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/out:MyBinary.dll", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("MyBinary", parsedArgs.CompilationName); Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName); Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); Assert.Equal(Path.Combine(baseDirectory, "MyBinary.dll"), parsedArgs.GetOutputFilePath(parsedArgs.OutputFileName)); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/out:..\MyBinary.dll", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("MyBinary", parsedArgs.CompilationName); Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName); Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(@"C:\abc\def", parsedArgs.OutputDirectory); // not specified: exe parsedArgs = DefaultParse(new[] { @"a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // not specified: dll parsedArgs = DefaultParse(new[] { @"/target:library", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.CompilationName); Assert.Equal("a.dll", parsedArgs.OutputFileName); Assert.Equal("a.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // not specified: module parsedArgs = DefaultParse(new[] { @"/target:module", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.CompilationName); Assert.Equal("a.netmodule", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // not specified: appcontainerexe parsedArgs = DefaultParse(new[] { @"/target:appcontainerexe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // not specified: winmdobj parsedArgs = DefaultParse(new[] { @"/target:winmdobj", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.CompilationName); Assert.Equal("a.winmdobj", parsedArgs.OutputFileName); Assert.Equal("a.winmdobj", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // drive-relative path: char currentDrive = Directory.GetCurrentDirectory()[0]; parsedArgs = DefaultParse(new[] { currentDrive + @":a.cs", "b.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'D:a.cs' is contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + ":a.cs")); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // UNC parsedArgs = DefaultParse(new[] { @"/out:\\b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/out:\\server\share\file.exe", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"\\server\share", parsedArgs.OutputDirectory); Assert.Equal("file.exe", parsedArgs.OutputFileName); Assert.Equal("file", parsedArgs.CompilationName); Assert.Equal("file.exe", parsedArgs.CompilationOptions.ModuleName); // invalid name: parsedArgs = DefaultParse(new[] { "/out:a.b\0b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); // Temporary skip following scenarios because of the error message changed (path) //parsedArgs = DefaultParse(new[] { "/out:a\uD800b.dll", "a.cs" }, baseDirectory); //parsedArgs.Errors.Verify( // // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a\uD800b.dll")); // Dev11 reports CS0016: Could not write to output file 'd:\Temp\q\a<>.z' parsedArgs = DefaultParse(new[] { @"/out:""a<>.dll""", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'a<>.dll' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.dll")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/out:.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.exe' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".exe") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:exe", @"/out:.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.exe' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".exe") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:library", @"/out:.dll", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.dll' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".dll") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:module", @"/out:.netmodule", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.netmodule' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".netmodule") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { ".cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:exe", ".cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:library", ".cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.dll' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".dll") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:module", ".cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(".netmodule", parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Equal(".netmodule", parsedArgs.CompilationOptions.ModuleName); } [WorkItem(546012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546012")] [WorkItem(546007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546007")] [Fact] public void ParseOut2() { var parsedArgs = DefaultParse(new[] { "/out:.x", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { "/out:.x", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); } [Fact] public void ParseInstrumentTestNames() { var parsedArgs = DefaultParse(SpecializedCollections.EmptyEnumerable<string>(), WorkingDirectory); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { @"/instrument", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { @"/instrument:""""", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { @"/instrument:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { "/instrument:", "Test.Flag.Name", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { "/instrument:InvalidOption", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_InvalidInstrumentationKind).WithArguments("InvalidOption")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { "/instrument:None", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_InvalidInstrumentationKind).WithArguments("None")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage,InvalidOption", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_InvalidInstrumentationKind).WithArguments("InvalidOption")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { @"/instrument:""TestCoverage""", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { @"/instrument:""TESTCOVERAGE""", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage,TestCoverage", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage", "/instrument:TestCoverage", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseDoc() { const string baseDirectory = @"C:\abc\def\baz"; var parsedArgs = DefaultParse(new[] { @"/doc:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/doc:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/doc:")); Assert.Null(parsedArgs.DocumentationPath); parsedArgs = DefaultParse(new[] { @"/doc:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/doc:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/doc:")); Assert.Null(parsedArgs.DocumentationPath); // NOTE: no colon in error message '/doc' parsedArgs = DefaultParse(new[] { @"/doc", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/doc' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/doc")); Assert.Null(parsedArgs.DocumentationPath); parsedArgs = DefaultParse(new[] { @"/doc+", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/doc+")); Assert.Null(parsedArgs.DocumentationPath); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/doc:C:\MyFolder\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\MyFolder\MyBinary.xml", parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // Should handle quotes parsedArgs = DefaultParse(new[] { @"/doc:""C:\My Folder\MyBinary.xml""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\My Folder\MyBinary.xml", parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/doc:MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "MyBinary.xml"), parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/doc:..\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\MyBinary.xml", parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // drive-relative path: char currentDrive = Directory.GetCurrentDirectory()[0]; parsedArgs = DefaultParse(new[] { "/doc:" + currentDrive + @":a.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'D:a.xml' is contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + ":a.xml")); Assert.Null(parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect // UNC parsedArgs = DefaultParse(new[] { @"/doc:\\b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b")); Assert.Null(parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect parsedArgs = DefaultParse(new[] { @"/doc:\\server\share\file.xml", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"\\server\share\file.xml", parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // invalid name: parsedArgs = DefaultParse(new[] { "/doc:a.b\0b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b")); Assert.Null(parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect // Temp // parsedArgs = DefaultParse(new[] { "/doc:a\uD800b.xml", "a.cs" }, baseDirectory); // parsedArgs.Errors.Verify( // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a\uD800b.xml")); // Assert.Null(parsedArgs.DocumentationPath); // Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect parsedArgs = DefaultParse(new[] { @"/doc:""a<>.xml""", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'a<>.xml' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.xml")); Assert.Null(parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseErrorLog() { const string baseDirectory = @"C:\abc\def\baz"; var parsedArgs = DefaultParse(new[] { @"/errorlog:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<(error log option format>' for '/errorlog:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(CSharpCommandLineParser.ErrorLogOptionFormat, "/errorlog:")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); parsedArgs = DefaultParse(new[] { @"/errorlog:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<(error log option format>' for '/errorlog:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(CSharpCommandLineParser.ErrorLogOptionFormat, "/errorlog:")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); parsedArgs = DefaultParse(new[] { @"/errorlog", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<(error log option format>' for '/errorlog' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(CSharpCommandLineParser.ErrorLogOptionFormat, "/errorlog")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/errorlog:C:\MyFolder\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\MyFolder\MyBinary.xml", parsedArgs.ErrorLogOptions.Path); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Escaped quote in the middle is an error parsedArgs = DefaultParse(new[] { @"/errorlog:C:\""My Folder""\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"C:""My Folder\MyBinary.xml").WithLocation(1, 1)); // Should handle quotes parsedArgs = DefaultParse(new[] { @"/errorlog:""C:\My Folder\MyBinary.xml""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\My Folder\MyBinary.xml", parsedArgs.ErrorLogOptions.Path); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/errorlog:MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "MyBinary.xml"), parsedArgs.ErrorLogOptions.Path); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/errorlog:..\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\MyBinary.xml", parsedArgs.ErrorLogOptions.Path); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // drive-relative path: char currentDrive = Directory.GetCurrentDirectory()[0]; parsedArgs = DefaultParse(new[] { "/errorlog:" + currentDrive + @":a.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'D:a.xml' is contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + ":a.xml")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // UNC parsedArgs = DefaultParse(new[] { @"/errorlog:\\b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); parsedArgs = DefaultParse(new[] { @"/errorlog:\\server\share\file.xml", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"\\server\share\file.xml", parsedArgs.ErrorLogOptions.Path); // invalid name: parsedArgs = DefaultParse(new[] { "/errorlog:a.b\0b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); parsedArgs = DefaultParse(new[] { @"/errorlog:""a<>.xml""", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'a<>.xml' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.xml")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Parses SARIF version. parsedArgs = DefaultParse(new[] { @"/errorlog:C:\MyFolder\MyBinary.xml,version=2", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\MyFolder\MyBinary.xml", parsedArgs.ErrorLogOptions.Path); Assert.Equal(SarifVersion.Sarif2, parsedArgs.ErrorLogOptions.SarifVersion); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Invalid SARIF version. string[] invalidSarifVersions = new string[] { @"C:\MyFolder\MyBinary.xml,version=1.0.0", @"C:\MyFolder\MyBinary.xml,version=2.1.0", @"C:\MyFolder\MyBinary.xml,version=42" }; foreach (string invalidSarifVersion in invalidSarifVersions) { parsedArgs = DefaultParse(new[] { $"/errorlog:{invalidSarifVersion}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2046: Command-line syntax error: 'C:\MyFolder\MyBinary.xml,version=42' is not a valid value for the '/errorlog:' option. The value must be of the form '<file>[,version={1|1.0|2|2.1}]'. Diagnostic(ErrorCode.ERR_BadSwitchValue).WithArguments(invalidSarifVersion, "/errorlog:", CSharpCommandLineParser.ErrorLogOptionFormat)); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); } // Invalid errorlog qualifier. const string InvalidErrorLogQualifier = @"C:\MyFolder\MyBinary.xml,invalid=42"; parsedArgs = DefaultParse(new[] { $"/errorlog:{InvalidErrorLogQualifier}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2046: Command-line syntax error: 'C:\MyFolder\MyBinary.xml,invalid=42' is not a valid value for the '/errorlog:' option. The value must be of the form '<file>[,version={1|1.0|2|2.1}]'. Diagnostic(ErrorCode.ERR_BadSwitchValue).WithArguments(InvalidErrorLogQualifier, "/errorlog:", CSharpCommandLineParser.ErrorLogOptionFormat)); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Too many errorlog qualifiers. const string TooManyErrorLogQualifiers = @"C:\MyFolder\MyBinary.xml,version=2,version=2"; parsedArgs = DefaultParse(new[] { $"/errorlog:{TooManyErrorLogQualifiers}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2046: Command-line syntax error: 'C:\MyFolder\MyBinary.xml,version=2,version=2' is not a valid value for the '/errorlog:' option. The value must be of the form '<file>[,version={1|1.0|2|2.1}]'. Diagnostic(ErrorCode.ERR_BadSwitchValue).WithArguments(TooManyErrorLogQualifiers, "/errorlog:", CSharpCommandLineParser.ErrorLogOptionFormat)); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); } [ConditionalFact(typeof(WindowsOnly))] public void AppConfigParse() { const string baseDirectory = @"C:\abc\def\baz"; var parsedArgs = DefaultParse(new[] { @"/appconfig:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing ':<text>' for '/appconfig:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(":<text>", "/appconfig:")); Assert.Null(parsedArgs.AppConfigPath); parsedArgs = DefaultParse(new[] { "/appconfig:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing ':<text>' for '/appconfig:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(":<text>", "/appconfig:")); Assert.Null(parsedArgs.AppConfigPath); parsedArgs = DefaultParse(new[] { "/appconfig", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing ':<text>' for '/appconfig' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(":<text>", "/appconfig")); Assert.Null(parsedArgs.AppConfigPath); parsedArgs = DefaultParse(new[] { "/appconfig:a.exe.config", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\a.exe.config", parsedArgs.AppConfigPath); // If ParseDoc succeeds, all other possible AppConfig paths should succeed as well -- they both call ParseGenericFilePath } [Fact] public void AppConfigBasic() { var srcFile = Temp.CreateFile().WriteAllText(@"class A { static void Main(string[] args) { } }"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var appConfigFile = Temp.CreateFile().WriteAllText( @"<?xml version=""1.0"" encoding=""utf-8"" ?> <configuration> <runtime> <assemblyBinding xmlns=""urn:schemas-microsoft-com:asm.v1""> <supportPortability PKT=""7cec85d7bea7798e"" enable=""false""/> </assemblyBinding> </runtime> </configuration>"); var silverlight = Temp.CreateFile().WriteAllBytes(ProprietaryTestResources.silverlight_v5_0_5_0.System_v5_0_5_0_silverlight).Path; var net4_0dll = Temp.CreateFile().WriteAllBytes(ResourcesNet451.System).Path; // Test linking two appconfig dlls with simple src var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = CreateCSharpCompiler(null, srcDirectory, new[] { "/nologo", "/r:" + silverlight, "/r:" + net4_0dll, "/appconfig:" + appConfigFile.Path, srcFile.Path }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(srcFile.Path); CleanupAllGeneratedFiles(appConfigFile.Path); } [ConditionalFact(typeof(WindowsOnly))] public void AppConfigBasicFail() { var srcFile = Temp.CreateFile().WriteAllText(@"class A { static void Main(string[] args) { } }"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); string root = Path.GetPathRoot(srcDirectory); // Make sure we pick a drive that exists and is plugged in to avoid 'Drive not ready' var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = CreateCSharpCompiler(null, srcDirectory, new[] { "/nologo", "/preferreduilang:en", $@"/appconfig:{root}DoesNotExist\NOwhere\bonobo.exe.config" , srcFile.Path }).Run(outWriter); Assert.NotEqual(0, exitCode); Assert.Equal($@"error CS7093: Cannot read config file '{root}DoesNotExist\NOwhere\bonobo.exe.config' -- 'Could not find a part of the path '{root}DoesNotExist\NOwhere\bonobo.exe.config'.'", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(srcFile.Path); } [ConditionalFact(typeof(WindowsOnly))] public void ParseDocAndOut() { const string baseDirectory = @"C:\abc\def\baz"; // Can specify separate directories for binary and XML output. var parsedArgs = DefaultParse(new[] { @"/doc:a\b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\a\b.xml", parsedArgs.DocumentationPath); Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory); Assert.Equal("d.exe", parsedArgs.OutputFileName); // XML does not fall back on output directory. parsedArgs = DefaultParse(new[] { @"/doc:b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\b.xml", parsedArgs.DocumentationPath); Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory); Assert.Equal("d.exe", parsedArgs.OutputFileName); } [ConditionalFact(typeof(WindowsOnly))] public void ParseErrorLogAndOut() { const string baseDirectory = @"C:\abc\def\baz"; // Can specify separate directories for binary and error log output. var parsedArgs = DefaultParse(new[] { @"/errorlog:a\b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\a\b.xml", parsedArgs.ErrorLogOptions.Path); Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory); Assert.Equal("d.exe", parsedArgs.OutputFileName); // XML does not fall back on output directory. parsedArgs = DefaultParse(new[] { @"/errorlog:b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\b.xml", parsedArgs.ErrorLogOptions.Path); Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory); Assert.Equal("d.exe", parsedArgs.OutputFileName); } [Fact] public void ModuleAssemblyName() { var parsedArgs = DefaultParse(new[] { @"/target:module", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("goo", parsedArgs.CompilationName); Assert.Equal("a.netmodule", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:library", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS0734: The /moduleassemblyname option may only be specified when building a target type of 'module' Diagnostic(ErrorCode.ERR_AssemblyNameOnNonModule)); parsedArgs = DefaultParse(new[] { @"/target:exe", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS0734: The /moduleassemblyname option may only be specified when building a target type of 'module' Diagnostic(ErrorCode.ERR_AssemblyNameOnNonModule)); parsedArgs = DefaultParse(new[] { @"/target:winexe", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS0734: The /moduleassemblyname option may only be specified when building a target type of 'module' Diagnostic(ErrorCode.ERR_AssemblyNameOnNonModule)); } [Fact] public void ModuleName() { var parsedArgs = DefaultParse(new[] { @"/target:module", "/modulename:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("goo", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:library", "/modulename:bar", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("bar", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:exe", "/modulename:CommonLanguageRuntimeLibrary", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("CommonLanguageRuntimeLibrary", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:winexe", "/modulename:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("goo", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:exe", "/modulename:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'modulename' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "modulename").WithLocation(1, 1) ); } [Fact] public void ModuleName001() { var dir = Temp.CreateDirectory(); var file1 = dir.CreateFile("a.cs"); file1.WriteAllText(@" class c1 { public static void Main(){} } "); var exeName = "aa.exe"; var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/modulename:hocusPocus ", "/out:" + exeName + " ", file1.Path }); int exitCode = csc.Run(outWriter); if (exitCode != 0) { Console.WriteLine(outWriter.ToString()); Assert.Equal(0, exitCode); } Assert.Equal(1, Directory.EnumerateFiles(dir.Path, exeName).Count()); using (var metadata = ModuleMetadata.CreateFromImage(File.ReadAllBytes(Path.Combine(dir.Path, "aa.exe")))) { var peReader = metadata.Module.GetMetadataReader(); Assert.True(peReader.IsAssembly); Assert.Equal("aa", peReader.GetString(peReader.GetAssemblyDefinition().Name)); Assert.Equal("hocusPocus", peReader.GetString(peReader.GetModuleDefinition().Name)); } if (System.IO.File.Exists(exeName)) { System.IO.File.Delete(exeName); } CleanupAllGeneratedFiles(file1.Path); } [Fact] public void ParsePlatform() { var parsedArgs = DefaultParse(new[] { @"/platform:x64", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.Equal(Platform.X64, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { @"/platform:X86", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.Equal(Platform.X86, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { @"/platform:itanum", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadPlatformType, parsedArgs.Errors.First().Code); Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform:itanium", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Platform.Itanium, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform:anycpu", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform:anycpu32bitpreferred", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Platform.AnyCpu32BitPreferred, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform:arm", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Platform.Arm, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<string>' for 'platform' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<string>", "/platform")); Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform); //anycpu is default parsedArgs = DefaultParse(new[] { "/platform:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<string>' for 'platform' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<string>", "/platform:")); Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform); //anycpu is default } [WorkItem(546016, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546016")] [WorkItem(545997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545997")] [WorkItem(546019, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546019")] [WorkItem(546029, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546029")] [Fact] public void ParseBaseAddress() { var parsedArgs = DefaultParse(new[] { @"/baseaddress:x64", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadBaseNumber, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:0x8000000000011111", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.Equal(0x8000000000011111ul, parsedArgs.EmitOptions.BaseAddress); parsedArgs = DefaultParse(new[] { @"/platform:x86", @"/baseaddress:0x8000000000011111", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadBaseNumber, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { @"/baseaddress:", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_SwitchNeedsNumber, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { @"/baseaddress:-23", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadBaseNumber, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:01777777777777777777777", "a.cs" }, WorkingDirectory); Assert.Equal(ulong.MaxValue, parsedArgs.EmitOptions.BaseAddress); parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:0x0000000100000000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:0xffff8000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "test.cs", "/platform:x86", "/baseaddress:0xffffffff" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFFFFFF")); parsedArgs = DefaultParse(new[] { "test.cs", "/platform:x86", "/baseaddress:0xffff8000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF8000")); parsedArgs = DefaultParse(new[] { "test.cs", "/baseaddress:0xffff8000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF8000")); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x86", "/baseaddress:0xffff7fff" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x64", "/baseaddress:0xffff8000" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x64", "/baseaddress:0x100000000" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "test.cs", "/baseaddress:0xFFFF0000FFFF0000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF0000FFFF0000")); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x64", "/baseaddress:0x10000000000000000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0x10000000000000000")); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/baseaddress:0xFFFF0000FFFF0000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF0000FFFF0000")); } [Fact] public void ParseFileAlignment() { var parsedArgs = DefaultParse(new[] { @"/filealign:x64", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2024: Invalid file section alignment number 'x64' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("x64")); parsedArgs = DefaultParse(new[] { @"/filealign:0x200", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(0x200, parsedArgs.EmitOptions.FileAlignment); parsedArgs = DefaultParse(new[] { @"/filealign:512", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(512, parsedArgs.EmitOptions.FileAlignment); parsedArgs = DefaultParse(new[] { @"/filealign:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for 'filealign' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("filealign")); parsedArgs = DefaultParse(new[] { @"/filealign:-23", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2024: Invalid file section alignment number '-23' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("-23")); parsedArgs = DefaultParse(new[] { @"/filealign:020000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(8192, parsedArgs.EmitOptions.FileAlignment); parsedArgs = DefaultParse(new[] { @"/filealign:0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2024: Invalid file section alignment number '0' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("0")); parsedArgs = DefaultParse(new[] { @"/filealign:123", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2024: Invalid file section alignment number '123' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("123")); } [ConditionalFact(typeof(WindowsOnly))] public void SdkPathAndLibEnvVariable() { var dir = Temp.CreateDirectory(); var lib1 = dir.CreateDirectory("lib1"); var lib2 = dir.CreateDirectory("lib2"); var lib3 = dir.CreateDirectory("lib3"); var sdkDirectory = SdkDirectory; var parsedArgs = DefaultParse(new[] { @"/lib:lib1", @"/libpath:lib2", @"/libpaths:lib3", "a.cs" }, dir.Path, sdkDirectory: sdkDirectory); AssertEx.Equal(new[] { sdkDirectory, lib1.Path, lib2.Path, lib3.Path }, parsedArgs.ReferencePaths); } [ConditionalFact(typeof(WindowsOnly))] public void SdkPathAndLibEnvVariable_Errors() { var parsedArgs = DefaultParse(new[] { @"/lib:c:lib2", @"/lib:o:\sdk1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS1668: Invalid search path 'c:lib2' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"c:lib2", "/LIB option", "path is too long or invalid"), // warning CS1668: Invalid search path 'o:\sdk1' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"o:\sdk1", "/LIB option", "directory does not exist")); parsedArgs = DefaultParse(new[] { @"/lib:c:\Windows,o:\Windows;e:;", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS1668: Invalid search path 'o:\Windows' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"o:\Windows", "/LIB option", "directory does not exist"), // warning CS1668: Invalid search path 'e:' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"e:", "/LIB option", "path is too long or invalid")); parsedArgs = DefaultParse(new[] { @"/lib:c:\Windows,.\Windows;e;", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS1668: Invalid search path '.\Windows' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@".\Windows", "/LIB option", "directory does not exist"), // warning CS1668: Invalid search path 'e' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"e", "/LIB option", "directory does not exist")); parsedArgs = DefaultParse(new[] { @"/lib:c:\Windows,o:\Windows;e:; ; ; ; ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS1668: Invalid search path 'o:\Windows' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"o:\Windows", "/LIB option", "directory does not exist"), // warning CS1668: Invalid search path 'e:' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("e:", "/LIB option", "path is too long or invalid"), // warning CS1668: Invalid search path ' ' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(" ", "/LIB option", "path is too long or invalid"), // warning CS1668: Invalid search path ' ' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(" ", "/LIB option", "path is too long or invalid"), // warning CS1668: Invalid search path ' ' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(" ", "/LIB option", "path is too long or invalid")); parsedArgs = DefaultParse(new[] { @"/lib", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<path list>", "lib")); parsedArgs = DefaultParse(new[] { @"/lib:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<path list>", "lib")); parsedArgs = DefaultParse(new[] { @"/lib+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/lib+")); parsedArgs = DefaultParse(new[] { @"/lib: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<path list>", "lib")); } [Fact, WorkItem(546005, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546005")] public void SdkPathAndLibEnvVariable_Relative_csc() { var tempFolder = Temp.CreateDirectory(); var baseDirectory = tempFolder.ToString(); var subFolder = tempFolder.CreateDirectory("temp"); var subDirectory = subFolder.ToString(); var src = Temp.CreateFile("a.cs"); src.WriteAllText("public class C{}"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, subDirectory, new[] { "/nologo", "/t:library", "/out:abc.xyz", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDirectory, new[] { "/nologo", "/lib:temp", "/r:abc.xyz", "/t:library", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(src.Path); } [Fact] public void UnableWriteOutput() { var tempFolder = Temp.CreateDirectory(); var baseDirectory = tempFolder.ToString(); var subFolder = tempFolder.CreateDirectory("temp"); var src = Temp.CreateFile("a.cs"); src.WriteAllText("public class C{}"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/out:" + subFolder.ToString(), src.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.True(outWriter.ToString().Trim().StartsWith("error CS2012: Cannot open '" + subFolder.ToString() + "' for writing -- '", StringComparison.Ordinal)); // Cannot create a file when that file already exists. CleanupAllGeneratedFiles(src.Path); } [Fact] public void ParseHighEntropyVA() { var parsedArgs = DefaultParse(new[] { @"/highentropyva", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.True(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); parsedArgs = DefaultParse(new[] { @"/highentropyva+", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.True(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); parsedArgs = DefaultParse(new[] { @"/highentropyva-", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.False(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); parsedArgs = DefaultParse(new[] { @"/highentropyva:-", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal(EmitOptions.Default.HighEntropyVirtualAddressSpace, parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); parsedArgs = DefaultParse(new[] { @"/highentropyva:", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal(EmitOptions.Default.HighEntropyVirtualAddressSpace, parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); //last one wins parsedArgs = DefaultParse(new[] { @"/highenTROPyva+", @"/HIGHentropyva-", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.False(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); } [Fact] public void Checked() { var parsedArgs = DefaultParse(new[] { @"/checked+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.CheckOverflow); parsedArgs = DefaultParse(new[] { @"/checked-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.CheckOverflow); parsedArgs = DefaultParse(new[] { @"/checked", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.CheckOverflow); parsedArgs = DefaultParse(new[] { @"/checked-", @"/checked", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.CheckOverflow); parsedArgs = DefaultParse(new[] { @"/checked:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/checked:")); } [Fact] public void Nullable() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enabled' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.0", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:yes", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'yes' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("yes").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:enable", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enable' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.0", "8.0").WithLocation(1, 1)); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:disable", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:yes", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'yes' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("yes").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:eNable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:disablE", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Safeonly", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'Safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("Safeonly").WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:safeonly", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:safeonly", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1), // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1), // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:safeonly", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1), // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:yeS", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'yeS' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("yeS").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enable' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enabled' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:enable", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enabled' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:disable", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { "a.cs", "/langversion:8" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { "a.cs", "/langversion:7.3" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:""safeonly""", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:\""enable\""", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option '"enable"' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("\"enable\"").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:\\disable\\", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option '\\disable\\' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("\\\\disable\\\\").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:\\""enable\\""", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option '\enable\' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("\\enable\\").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonlywarnings", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonlywarnings' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonlywarnings").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:SafeonlyWarnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'SafeonlyWarnings' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("SafeonlyWarnings").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:safeonlyWarnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonlyWarnings' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonlyWarnings").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:warnings", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Warnings' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Warnings", "7.0", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Annotations' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Warnings", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:annotations", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Annotations' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Annotations", "7.0", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Annotations' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Annotations", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); } [Fact] public void Usings() { CSharpCommandLineArguments parsedArgs; var sdkDirectory = SdkDirectory; parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:Goo.Bar" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "Goo.Bar" }, parsedArgs.CompilationOptions.Usings.AsEnumerable()); parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:Goo.Bar;Baz", "/using:System.Core;System" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "Goo.Bar", "Baz", "System.Core", "System" }, parsedArgs.CompilationOptions.Usings.AsEnumerable()); parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:Goo;;Bar" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "Goo", "Bar" }, parsedArgs.CompilationOptions.Usings.AsEnumerable()); parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<namespace>' for '/u:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<namespace>", "/u:")); } [Fact] public void WarningsErrors() { var parsedArgs = DefaultParse(new string[] { "/nowarn", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for 'nowarn' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("nowarn")); parsedArgs = DefaultParse(new string[] { "/nowarn:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for 'nowarn' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("nowarn")); // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied via /nowarn or /warnaserror. // We no longer generate a warning in such cases. parsedArgs = DefaultParse(new string[] { "/nowarn:-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/nowarn:abc", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warnaserror:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for 'warnaserror' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warnaserror")); parsedArgs = DefaultParse(new string[] { "/warnaserror:-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warnaserror:70000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warnaserror:abc", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warnaserror+:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/warnaserror+:' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warnaserror+")); parsedArgs = DefaultParse(new string[] { "/warnaserror-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/warnaserror-:' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warnaserror-")); parsedArgs = DefaultParse(new string[] { "/w", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/w' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("w")); parsedArgs = DefaultParse(new string[] { "/w:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/w:' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("w")); parsedArgs = DefaultParse(new string[] { "/warn:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/warn:' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warn")); parsedArgs = DefaultParse(new string[] { "/w:-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS1900: Warning level must be zero or greater Diagnostic(ErrorCode.ERR_BadWarningLevel).WithArguments("w")); parsedArgs = DefaultParse(new string[] { "/w:5", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warn:-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS1900: Warning level must be zero or greater Diagnostic(ErrorCode.ERR_BadWarningLevel).WithArguments("warn")); parsedArgs = DefaultParse(new string[] { "/warn:5", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied via /nowarn or /warnaserror. // We no longer generate a warning in such cases. parsedArgs = DefaultParse(new string[] { "/warnaserror:1,2,3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/nowarn:1,2,3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/nowarn:1;2;;3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); } private static void AssertSpecificDiagnostics(int[] expectedCodes, ReportDiagnostic[] expectedOptions, CSharpCommandLineArguments args) { var actualOrdered = args.CompilationOptions.SpecificDiagnosticOptions.OrderBy(entry => entry.Key); AssertEx.Equal( expectedCodes.Select(i => MessageProvider.Instance.GetIdForErrorCode(i)), actualOrdered.Select(entry => entry.Key)); AssertEx.Equal(expectedOptions, actualOrdered.Select(entry => entry.Value)); } [Fact] public void WarningsParse() { var parsedArgs = DefaultParse(new string[] { "/warnaserror", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Error, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); Assert.Equal(0, parsedArgs.CompilationOptions.SpecificDiagnosticOptions.Count); parsedArgs = DefaultParse(new string[] { "/warnaserror:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror:+1062,+1066,+1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Error, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror+:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror-:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Default, ReportDiagnostic.Default, ReportDiagnostic.Default }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror+:1062,1066,1734", "/warnaserror-:1762,1974", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics( new[] { 1062, 1066, 1734, 1762, 1974 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Default, ReportDiagnostic.Default }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror+:1062,1066,1734", "/warnaserror-:1062,1974", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); Assert.Equal(4, parsedArgs.CompilationOptions.SpecificDiagnosticOptions.Count); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1974 }, new[] { ReportDiagnostic.Default, ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Default }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror-:1062,1066,1734", "/warnaserror+:1062,1974", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1974 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Default, ReportDiagnostic.Default, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/w:1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(1, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs); parsedArgs = DefaultParse(new string[] { "/warn:1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(1, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs); parsedArgs = DefaultParse(new string[] { "/warn:1", "/warnaserror+:1062,1974", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(1, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1974 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/nowarn:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress }, parsedArgs); parsedArgs = DefaultParse(new string[] { @"/nowarn:""1062 1066 1734""", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/nowarn:1062,1066,1734", "/warnaserror:1066,1762", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1762 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror:1066,1762", "/nowarn:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1762 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Error }, parsedArgs); } [Fact] public void AllowUnsafe() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/unsafe", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "/unsafe+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "/UNSAFE-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "/unsafe-", "/unsafe+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); // default parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "/unsafe:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/unsafe:")); parsedArgs = DefaultParse(new[] { "/unsafe:+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/unsafe:+")); parsedArgs = DefaultParse(new[] { "/unsafe-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/unsafe-:")); } [Fact] public void DelaySign() { CSharpCommandLineArguments parsedArgs; parsedArgs = DefaultParse(new[] { "/delaysign", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.NotNull(parsedArgs.CompilationOptions.DelaySign); Assert.True((bool)parsedArgs.CompilationOptions.DelaySign); parsedArgs = DefaultParse(new[] { "/delaysign+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.NotNull(parsedArgs.CompilationOptions.DelaySign); Assert.True((bool)parsedArgs.CompilationOptions.DelaySign); parsedArgs = DefaultParse(new[] { "/DELAYsign-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.NotNull(parsedArgs.CompilationOptions.DelaySign); Assert.False((bool)parsedArgs.CompilationOptions.DelaySign); parsedArgs = DefaultParse(new[] { "/delaysign:-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/delaysign:-' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/delaysign:-")); Assert.Null(parsedArgs.CompilationOptions.DelaySign); } [Fact] public void PublicSign() { var parsedArgs = DefaultParse(new[] { "/publicsign", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.PublicSign); parsedArgs = DefaultParse(new[] { "/publicsign+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.PublicSign); parsedArgs = DefaultParse(new[] { "/PUBLICsign-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.PublicSign); parsedArgs = DefaultParse(new[] { "/publicsign:-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/publicsign:-' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/publicsign:-").WithLocation(1, 1)); Assert.False(parsedArgs.CompilationOptions.PublicSign); } [WorkItem(8360, "https://github.com/dotnet/roslyn/issues/8360")] [Fact] public void PublicSign_KeyFileRelativePath() { var parsedArgs = DefaultParse(new[] { "/publicsign", "/keyfile:test.snk", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "test.snk"), parsedArgs.CompilationOptions.CryptoKeyFile); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void PublicSignWithEmptyKeyPath() { DefaultParse(new[] { "/publicsign", "/keyfile:", "a.cs" }, WorkingDirectory).Errors.Verify( // error CS2005: Missing file specification for 'keyfile' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile").WithLocation(1, 1)); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void PublicSignWithEmptyKeyPath2() { DefaultParse(new[] { "/publicsign", "/keyfile:\"\"", "a.cs" }, WorkingDirectory).Errors.Verify( // error CS2005: Missing file specification for 'keyfile' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile").WithLocation(1, 1)); } [WorkItem(546301, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546301")] [Fact] public void SubsystemVersionTests() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/subsystemversion:4.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SubsystemVersion.Create(4, 0), parsedArgs.EmitOptions.SubsystemVersion); // wrongly supported subsystem version. CompilationOptions data will be faithful to the user input. // It is normalized at the time of emit. parsedArgs = DefaultParse(new[] { "/subsystemversion:0.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // no error in Dev11 Assert.Equal(SubsystemVersion.Create(0, 0), parsedArgs.EmitOptions.SubsystemVersion); parsedArgs = DefaultParse(new[] { "/subsystemversion:0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // no error in Dev11 Assert.Equal(SubsystemVersion.Create(0, 0), parsedArgs.EmitOptions.SubsystemVersion); parsedArgs = DefaultParse(new[] { "/subsystemversion:3.99", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // no error in Dev11 Assert.Equal(SubsystemVersion.Create(3, 99), parsedArgs.EmitOptions.SubsystemVersion); parsedArgs = DefaultParse(new[] { "/subsystemversion:4.0", "/SUBsystemversion:5.333", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SubsystemVersion.Create(5, 333), parsedArgs.EmitOptions.SubsystemVersion); parsedArgs = DefaultParse(new[] { "/subsystemversion:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "subsystemversion")); parsedArgs = DefaultParse(new[] { "/subsystemversion", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "subsystemversion")); parsedArgs = DefaultParse(new[] { "/subsystemversion-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/subsystemversion-")); parsedArgs = DefaultParse(new[] { "/subsystemversion: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "subsystemversion")); parsedArgs = DefaultParse(new[] { "/subsystemversion: 4.1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments(" 4.1")); parsedArgs = DefaultParse(new[] { "/subsystemversion:4 .0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4 .0")); parsedArgs = DefaultParse(new[] { "/subsystemversion:4. 0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4. 0")); parsedArgs = DefaultParse(new[] { "/subsystemversion:.", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments(".")); parsedArgs = DefaultParse(new[] { "/subsystemversion:4.", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4.")); parsedArgs = DefaultParse(new[] { "/subsystemversion:.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments(".0")); parsedArgs = DefaultParse(new[] { "/subsystemversion:4.2 ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/subsystemversion:4.65536", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4.65536")); parsedArgs = DefaultParse(new[] { "/subsystemversion:65536.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("65536.0")); parsedArgs = DefaultParse(new[] { "/subsystemversion:-4.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("-4.0")); // TODO: incompatibilities: versions lower than '6.2' and 'arm', 'winmdobj', 'appcontainer' } [Fact] public void MainType() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/m:A.B.C", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("A.B.C", parsedArgs.CompilationOptions.MainTypeName); parsedArgs = DefaultParse(new[] { "/m: ", "a.cs" }, WorkingDirectory); // Mimicking Dev11 parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "m")); Assert.Null(parsedArgs.CompilationOptions.MainTypeName); // overriding the value parsedArgs = DefaultParse(new[] { "/m:A.B.C", "/MAIN:X.Y.Z", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("X.Y.Z", parsedArgs.CompilationOptions.MainTypeName); // error parsedArgs = DefaultParse(new[] { "/maiN:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "main")); parsedArgs = DefaultParse(new[] { "/MAIN+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/MAIN+")); parsedArgs = DefaultParse(new[] { "/M", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "m")); // incompatible values /main && /target parsedArgs = DefaultParse(new[] { "/main:a", "/t:library", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoMainOnDLL)); parsedArgs = DefaultParse(new[] { "/main:a", "/t:module", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoMainOnDLL)); } [Fact] public void Codepage() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/CodePage:1200", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("Unicode", parsedArgs.Encoding.EncodingName); parsedArgs = DefaultParse(new[] { "/CodePage:1200", "/codePAGE:65001", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("Unicode (UTF-8)", parsedArgs.Encoding.EncodingName); // error parsedArgs = DefaultParse(new[] { "/codepage:0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("0")); parsedArgs = DefaultParse(new[] { "/codepage:abc", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("abc")); parsedArgs = DefaultParse(new[] { "/codepage:-5", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("-5")); parsedArgs = DefaultParse(new[] { "/codepage: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("")); parsedArgs = DefaultParse(new[] { "/codepage:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("")); parsedArgs = DefaultParse(new[] { "/codepage", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "codepage")); parsedArgs = DefaultParse(new[] { "/codepage+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/codepage+")); } [Fact, WorkItem(24735, "https://github.com/dotnet/roslyn/issues/24735")] public void ChecksumAlgorithm() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sHa1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SourceHashAlgorithm.Sha1, parsedArgs.ChecksumAlgorithm); Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sha256", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SourceHashAlgorithm.Sha256, parsedArgs.ChecksumAlgorithm); Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm); parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SourceHashAlgorithm.Sha256, parsedArgs.ChecksumAlgorithm); Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm); // error parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:256", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadChecksumAlgorithm).WithArguments("256")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sha-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadChecksumAlgorithm).WithArguments("sha-1")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sha", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadChecksumAlgorithm).WithArguments("sha")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "checksumalgorithm")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "checksumalgorithm")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "checksumalgorithm")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/checksumAlgorithm+")); } [Fact] public void AddModule() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/noconfig", "/nostdlib", "/addmodule:abc.netmodule", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(1, parsedArgs.MetadataReferences.Length); Assert.Equal("abc.netmodule", parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[0].Properties.Kind); parsedArgs = DefaultParse(new[] { "/noconfig", "/nostdlib", "/aDDmodule:c:\\abc;c:\\abc;d:\\xyz", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(3, parsedArgs.MetadataReferences.Length); Assert.Equal("c:\\abc", parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[0].Properties.Kind); Assert.Equal("c:\\abc", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[1].Properties.Kind); Assert.Equal("d:\\xyz", parsedArgs.MetadataReferences[2].Reference); Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[2].Properties.Kind); // error parsedArgs = DefaultParse(new[] { "/ADDMODULE", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/addmodule:")); parsedArgs = DefaultParse(new[] { "/ADDMODULE+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/ADDMODULE+")); parsedArgs = DefaultParse(new[] { "/ADDMODULE:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/ADDMODULE:")); } [Fact, WorkItem(530751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530751")] public void CS7061fromCS0647_ModuleWithCompilationRelaxations() { string source1 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" using System.Runtime.CompilerServices; [assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)] public class Mod { }").Path; string source2 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" using System.Runtime.CompilerServices; [assembly: CompilationRelaxations(4)] public class Mod { }").Path; string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" using System.Runtime.CompilerServices; [assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)] class Test { static void Main() {} }").Path; var baseDir = Path.GetDirectoryName(source); // === Scenario 1 === var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source1 }).Run(outWriter); Assert.Equal(0, exitCode); var modfile = source1.Substring(0, source1.Length - 2) + "netmodule"; outWriter = new StringWriter(CultureInfo.InvariantCulture); var parsedArgs = DefaultParse(new[] { "/nologo", "/addmodule:" + modfile, source }, WorkingDirectory); parsedArgs.Errors.Verify(); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/addmodule:" + modfile, source }).Run(outWriter); Assert.Empty(outWriter.ToString()); // === Scenario 2 === outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source2 }).Run(outWriter); Assert.Equal(0, exitCode); modfile = source2.Substring(0, source2.Length - 2) + "netmodule"; outWriter = new StringWriter(CultureInfo.InvariantCulture); parsedArgs = DefaultParse(new[] { "/nologo", "/addmodule:" + modfile, source }, WorkingDirectory); parsedArgs.Errors.Verify(); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/addmodule:" + modfile, source }).Run(outWriter); Assert.Equal(1, exitCode); // Dev11: CS0647 (Emit) Assert.Contains("error CS7061: Duplicate 'CompilationRelaxationsAttribute' attribute in", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source1); CleanupAllGeneratedFiles(source2); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(530780, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530780")] public void AddModuleWithExtensionMethod() { string source1 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"public static class Extensions { public static bool EB(this bool b) { return b; } }").Path; string source2 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class C { static void Main() {} }").Path; var baseDir = Path.GetDirectoryName(source2); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source1 }).Run(outWriter); Assert.Equal(0, exitCode); var modfile = source1.Substring(0, source1.Length - 2) + "netmodule"; outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/addmodule:" + modfile, source2 }).Run(outWriter); Assert.Equal(0, exitCode); CleanupAllGeneratedFiles(source1); CleanupAllGeneratedFiles(source2); } [Fact, WorkItem(546297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546297")] public void OLDCS0013FTL_MetadataEmitFailureSameModAndRes() { string source1 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class Mod { }").Path; string source2 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class C { static void Main() {} }").Path; var baseDir = Path.GetDirectoryName(source2); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source1 }).Run(outWriter); Assert.Equal(0, exitCode); var modfile = source1.Substring(0, source1.Length - 2) + "netmodule"; outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/addmodule:" + modfile, "/linkres:" + modfile, source2 }).Run(outWriter); Assert.Equal(1, exitCode); // Native gives CS0013 at emit stage Assert.Equal("error CS7041: Each linked resource and module must have a unique filename. Filename '" + Path.GetFileName(modfile) + "' is specified more than once in this assembly", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source1); CleanupAllGeneratedFiles(source2); } [Fact] public void Utf8Output() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/utf8output", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True((bool)parsedArgs.Utf8Output); parsedArgs = DefaultParse(new[] { "/utf8output", "/utf8output", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True((bool)parsedArgs.Utf8Output); parsedArgs = DefaultParse(new[] { "/utf8output:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/utf8output:")); } [Fact] public void CscCompile_WithSourceCodeRedirectedViaStandardInput_ProducesRunnableProgram() { string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C echo ^ class A ^ {{ ^ public static void Main() =^^^> ^ System.Console.WriteLine(""Hello World!""); ^ }} | {s_CSharpCompilerExecutable} /nologo /t:exe -" .Replace(Environment.NewLine, string.Empty), workingDirectory: tempDir) : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo \ class A \ {{ \ public static void Main\(\) =\> \ System.Console.WriteLine\(\\\""Hello World\!\\\""\)\; \ }} | {s_CSharpCompilerExecutable} /nologo /t:exe -""", workingDirectory: tempDir, // we are testing shell's piped/redirected stdin behavior explicitly // instead of using Process.StandardInput.Write(), so we set // redirectStandardInput to true, which implies that isatty of child // process is false and thereby Console.IsInputRedirected will return // true in csc code. redirectStandardInput: true); Assert.False(result.ContainsErrors, $"Compilation error(s) occurred: {result.Output} {result.Errors}"); string output = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.RunAndGetOutput("cmd.exe", $@"/C ""{s_DotnetCscRun} -.exe""", expectedRetCode: 0, startFolder: tempDir) : ProcessUtilities.RunAndGetOutput("sh", $@"-c ""{s_DotnetCscRun} -.exe""", expectedRetCode: 0, startFolder: tempDir); Assert.Equal("Hello World!", output.Trim()); } [Fact] public void CscCompile_WithSourceCodeRedirectedViaStandardInput_ProducesLibrary() { var name = Guid.NewGuid().ToString() + ".dll"; string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C echo ^ class A ^ {{ ^ public A Get() =^^^> default; ^ }} | {s_CSharpCompilerExecutable} /nologo /t:library /out:{name} -" .Replace(Environment.NewLine, string.Empty), workingDirectory: tempDir) : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo \ class A \ {{ \ public A Get\(\) =\> default\; \ }} | {s_CSharpCompilerExecutable} /nologo /t:library /out:{name} -""", workingDirectory: tempDir, // we are testing shell's piped/redirected stdin behavior explicitly // instead of using Process.StandardInput.Write(), so we set // redirectStandardInput to true, which implies that isatty of child // process is false and thereby Console.IsInputRedirected will return // true in csc code. redirectStandardInput: true); Assert.False(result.ContainsErrors, $"Compilation error(s) occurred: {result.Output} {result.Errors}"); var assemblyName = AssemblyName.GetAssemblyName(Path.Combine(tempDir, name)); Assert.Equal(name.Replace(".dll", ", Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), assemblyName.ToString()); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/55727")] public void CsiScript_WithSourceCodeRedirectedViaStandardInput_ExecutesNonInteractively() { string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C echo Console.WriteLine(""Hello World!"") | {s_CSharpScriptExecutable} -") : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo Console.WriteLine\(\\\""Hello World\!\\\""\) | {s_CSharpScriptExecutable} -""", workingDirectory: tempDir, // we are testing shell's piped/redirected stdin behavior explicitly // instead of using Process.StandardInput.Write(), so we set // redirectStandardInput to true, which implies that isatty of child // process is false and thereby Console.IsInputRedirected will return // true in csc code. redirectStandardInput: true); Assert.False(result.ContainsErrors, $"Compilation error(s) occurred: {result.Output} {result.Errors}"); Assert.Equal("Hello World!", result.Output.Trim()); } [Fact] public void CscCompile_WithRedirectedInputIndicatorAndStandardInputNotRedirected_ReportsCS8782() { if (Console.IsInputRedirected) { // [applicable to both Windows and Unix] // if our parent (xunit) process itself has input redirected, we cannot test this // error case because our child process will inherit it and we cannot achieve what // we are aiming for: isatty(0):true and thereby Console.IsInputerRedirected:false in // child. running this case will make StreamReader to hang (waiting for input, that // we do not propagate: parent.In->child.In). // // note: in Unix we can "close" fd0 by appending `0>&-` in the `sh -c` command below, // but that will also not impact the result of isatty(), and in turn causes a different // compiler error. return; } string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C ""{s_CSharpCompilerExecutable} /nologo /t:exe -""", workingDirectory: tempDir) : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""{s_CSharpCompilerExecutable} /nologo /t:exe -""", workingDirectory: tempDir); Assert.True(result.ContainsErrors); Assert.Contains(((int)ErrorCode.ERR_StdInOptionProvidedButConsoleInputIsNotRedirected).ToString(), result.Output); } [Fact] public void CscCompile_WithMultipleStdInOperators_WarnsCS2002() { string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C echo ^ class A ^ {{ ^ public static void Main() =^^^> ^ System.Console.WriteLine(""Hello World!""); ^ }} | {s_CSharpCompilerExecutable} /nologo - /t:exe -" .Replace(Environment.NewLine, string.Empty)) : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo \ class A \ {{ \ public static void Main\(\) =\> \ System.Console.WriteLine\(\\\""Hello World\!\\\""\)\; \ }} | {s_CSharpCompilerExecutable} /nologo - /t:exe -""", workingDirectory: tempDir, // we are testing shell's piped/redirected stdin behavior explicitly // instead of using Process.StandardInput.Write(), so we set // redirectStandardInput to true, which implies that isatty of child // process is false and thereby Console.IsInputRedirected will return // true in csc code. redirectStandardInput: true); Assert.Contains(((int)ErrorCode.WRN_FileAlreadyIncluded).ToString(), result.Output); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void CscUtf8Output_WithRedirecting_Off() { var srcFile = Temp.CreateFile().WriteAllText("\u265A").Path; var tempOut = Temp.CreateFile(); var output = ProcessUtilities.RunAndGetOutput("cmd", "/C \"" + s_CSharpCompilerExecutable + "\" /nologo /preferreduilang:en /t:library " + srcFile + " > " + tempOut.Path, expectedRetCode: 1); Assert.Equal("", output.Trim()); Assert.Equal("SRC.CS(1,1): error CS1056: Unexpected character '?'", tempOut.ReadAllText().Trim().Replace(srcFile, "SRC.CS")); CleanupAllGeneratedFiles(srcFile); CleanupAllGeneratedFiles(tempOut.Path); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void CscUtf8Output_WithRedirecting_On() { var srcFile = Temp.CreateFile().WriteAllText("\u265A").Path; var tempOut = Temp.CreateFile(); var output = ProcessUtilities.RunAndGetOutput("cmd", "/C \"" + s_CSharpCompilerExecutable + "\" /utf8output /nologo /preferreduilang:en /t:library " + srcFile + " > " + tempOut.Path, expectedRetCode: 1); Assert.Equal("", output.Trim()); Assert.Equal("SRC.CS(1,1): error CS1056: Unexpected character '♚'", tempOut.ReadAllText().Trim().Replace(srcFile, "SRC.CS")); CleanupAllGeneratedFiles(srcFile); CleanupAllGeneratedFiles(tempOut.Path); } [WorkItem(546653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546653")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void NoSourcesWithModule() { var folder = Temp.CreateDirectory(); var aCs = folder.CreateFile("a.cs"); aCs.WriteAllText("public class C {}"); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/nologo /t:module /out:a.netmodule \"{aCs}\"", startFolder: folder.ToString()); Assert.Equal("", output.Trim()); output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /t:library /out:b.dll /addmodule:a.netmodule ", startFolder: folder.ToString()); Assert.Equal("", output.Trim()); output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /preferreduilang:en /t:module /out:b.dll /addmodule:a.netmodule ", startFolder: folder.ToString()); Assert.Equal("warning CS2008: No source files specified.", output.Trim()); CleanupAllGeneratedFiles(aCs.Path); } [WorkItem(546653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546653")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void NoSourcesWithResource() { var folder = Temp.CreateDirectory(); var aCs = folder.CreateFile("a.cs"); aCs.WriteAllText("public class C {}"); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /t:library /out:b.dll /resource:a.cs", startFolder: folder.ToString()); Assert.Equal("", output.Trim()); CleanupAllGeneratedFiles(aCs.Path); } [WorkItem(546653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546653")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void NoSourcesWithLinkResource() { var folder = Temp.CreateDirectory(); var aCs = folder.CreateFile("a.cs"); aCs.WriteAllText("public class C {}"); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /t:library /out:b.dll /linkresource:a.cs", startFolder: folder.ToString()); Assert.Equal("", output.Trim()); CleanupAllGeneratedFiles(aCs.Path); } [Fact] public void KeyContainerAndKeyFile() { // KEYCONTAINER CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/keycontainer:RIPAdamYauch", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("RIPAdamYauch", parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keycontainer", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'keycontainer' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "keycontainer")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keycontainer-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/keycontainer-' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/keycontainer-")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keycontainer:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'keycontainer' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "keycontainer")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keycontainer: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "keycontainer")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); // KEYFILE parsedArgs = DefaultParse(new[] { @"/keyfile:\somepath\s""ome Fil""e.goo.bar", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); //EDMAURER let's not set the option in the event that there was an error. //Assert.Equal(@"\somepath\some File.goo.bar", parsedArgs.CompilationOptions.CryptoKeyFile); parsedArgs = DefaultParse(new[] { "/keyFile", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for 'keyfile' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile); parsedArgs = DefaultParse(new[] { "/keyFile: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile); parsedArgs = DefaultParse(new[] { "/keyfile-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/keyfile-' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/keyfile-")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile); // DEFAULTS parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); // KEYFILE | KEYCONTAINER conflicts parsedArgs = DefaultParse(new[] { "/keyFile:a", "/keyContainer:b", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.CompilationOptions.CryptoKeyFile); Assert.Equal("b", parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keyContainer:b", "/keyFile:a", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.CompilationOptions.CryptoKeyFile); Assert.Equal("b", parsedArgs.CompilationOptions.CryptoKeyContainer); } [Fact, WorkItem(554551, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554551")] public void CS1698WRN_AssumedMatchThis() { // compile with: /target:library /keyfile:mykey.snk var text1 = @"[assembly:System.Reflection.AssemblyVersion(""2"")] public class CS1698_a {} "; // compile with: /target:library /reference:CS1698_a.dll /keyfile:mykey.snk var text2 = @"public class CS1698_b : CS1698_a {} "; //compile with: /target:library /out:cs1698_a.dll /reference:cs1698_b.dll /keyfile:mykey.snk var text = @"[assembly:System.Reflection.AssemblyVersion(""3"")] public class CS1698_c : CS1698_b {} public class CS1698_a {} "; var folder = Temp.CreateDirectory(); var cs1698a = folder.CreateFile("CS1698a.cs"); cs1698a.WriteAllText(text1); var cs1698b = folder.CreateFile("CS1698b.cs"); cs1698b.WriteAllText(text2); var cs1698 = folder.CreateFile("CS1698.cs"); cs1698.WriteAllText(text); var snkFile = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey); var kfile = "/keyfile:" + snkFile.Path; CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/t:library", kfile, "CS1698a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/t:library", kfile, "/r:" + cs1698a.Path, "CS1698b.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/t:library", kfile, "/r:" + cs1698b.Path, "/out:" + cs1698a.Path, "CS1698.cs" }, WorkingDirectory); // Roslyn no longer generates a warning for this...since this was only a warning, we're not really // saving anyone...does not provide high value to implement... // warning CS1698: Circular assembly reference 'CS1698a, Version=2.0.0.0, Culture=neutral,PublicKeyToken = 9e9d6755e7bb4c10' // does not match the output assembly name 'CS1698a, Version = 3.0.0.0, Culture = neutral, PublicKeyToken = 9e9d6755e7bb4c10'. // Try adding a reference to 'CS1698a, Version = 2.0.0.0, Culture = neutral, PublicKeyToken = 9e9d6755e7bb4c10' or changing the output assembly name to match. parsedArgs.Errors.Verify(); CleanupAllGeneratedFiles(snkFile.Path); CleanupAllGeneratedFiles(cs1698a.Path); CleanupAllGeneratedFiles(cs1698b.Path); CleanupAllGeneratedFiles(cs1698.Path); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/dotnet/roslyn/issues/30926")] public void BinaryFileErrorTest() { var binaryPath = Temp.CreateFile().WriteAllBytes(ResourcesNet451.mscorlib).Path; var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", binaryPath }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal( "error CS2015: '" + binaryPath + "' is a binary file instead of a text file", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(binaryPath); } #if !NETCOREAPP [WorkItem(530221, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530221")] [WorkItem(5660, "https://github.com/dotnet/roslyn/issues/5660")] [ConditionalFact(typeof(WindowsOnly), typeof(IsEnglishLocal))] public void Bug15538() { // Several Jenkins VMs are still running with local systems permissions. This suite won't run properly // in that environment. Removing this check is being tracked by issue #79. using (var identity = System.Security.Principal.WindowsIdentity.GetCurrent()) { if (identity.IsSystem) { return; } // The icacls command fails on our Helix machines and it appears to be related to the use of the $ in // the username. // https://github.com/dotnet/roslyn/issues/28836 if (StringComparer.OrdinalIgnoreCase.Equals(Environment.UserDomainName, "WORKGROUP")) { return; } } var folder = Temp.CreateDirectory(); var source = folder.CreateFile("src.vb").WriteAllText("").Path; var _ref = folder.CreateFile("ref.dll").WriteAllText("").Path; try { var output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " + _ref + " /inheritance:r /Q"); Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim()); output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " + _ref + @" /deny %USERDOMAIN%\%USERNAME%:(r,WDAC) /Q"); Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim()); output = ProcessUtilities.RunAndGetOutput("cmd", "/C \"" + s_CSharpCompilerExecutable + "\" /nologo /preferreduilang:en /r:" + _ref + " /t:library " + source, expectedRetCode: 1); Assert.Equal("error CS0009: Metadata file '" + _ref + "' could not be opened -- Access to the path '" + _ref + "' is denied.", output.Trim()); } finally { var output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " + _ref + " /reset /Q"); Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim()); File.Delete(_ref); } CleanupAllGeneratedFiles(source); } #endif [WorkItem(545832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545832")] [Fact] public void ResponseFilesWithEmptyAliasReference() { string source = Temp.CreateFile("a.cs").WriteAllText(@" // <Area> ExternAlias - command line alias</Area> // <Title> // negative test cases: empty file name ("""") // </Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=error>CS1680:.*myAlias=</Expects> // <Code> class myClass { static int Main() { return 1; } } // </Code> ").Path; string rsp = Temp.CreateFile().WriteAllText(@" /nologo /r:myAlias="""" ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS1680: Invalid reference alias option: 'myAlias=' -- missing filename", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [Fact] public void ResponseFileOrdering() { var rspFilePath1 = Temp.CreateFile().WriteAllText(@" /b /c ").Path; assertOrder( new[] { "/a", "/b", "/c", "/d" }, new[] { "/a", @$"@""{rspFilePath1}""", "/d" }); var rspFilePath2 = Temp.CreateFile().WriteAllText(@" /c /d ").Path; rspFilePath1 = Temp.CreateFile().WriteAllText(@$" /b @""{rspFilePath2}"" ").Path; assertOrder( new[] { "/a", "/b", "/c", "/d", "/e" }, new[] { "/a", @$"@""{rspFilePath1}""", "/e" }); rspFilePath1 = Temp.CreateFile().WriteAllText(@$" /b ").Path; rspFilePath2 = Temp.CreateFile().WriteAllText(@" # this will be ignored /c /d ").Path; assertOrder( new[] { "/a", "/b", "/c", "/d", "/e" }, new[] { "/a", @$"@""{rspFilePath1}""", $@"@""{rspFilePath2}""", "/e" }); void assertOrder(string[] expected, string[] args) { var flattenedArgs = ArrayBuilder<string>.GetInstance(); var diagnostics = new List<Diagnostic>(); CSharpCommandLineParser.Default.FlattenArgs( args, diagnostics, flattenedArgs, scriptArgsOpt: null, baseDirectory: Path.DirectorySeparatorChar == '\\' ? @"c:\" : "/"); Assert.Empty(diagnostics); Assert.Equal(expected, flattenedArgs); flattenedArgs.Free(); } } [WorkItem(545832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545832")] [Fact] public void ResponseFilesWithEmptyAliasReference2() { string source = Temp.CreateFile("a.cs").WriteAllText(@" // <Area> ExternAlias - command line alias</Area> // <Title> // negative test cases: empty file name ("""") // </Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=error>CS1680:.*myAlias=</Expects> // <Code> class myClass { static int Main() { return 1; } } // </Code> ").Path; string rsp = Temp.CreateFile().WriteAllText(@" /nologo /r:myAlias="" "" ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS1680: Invalid reference alias option: 'myAlias=' -- missing filename", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(1784, "https://github.com/dotnet/roslyn/issues/1784")] [Fact] public void QuotedDefineInRespFile() { string source = Temp.CreateFile("a.cs").WriteAllText(@" #if NN class myClass { #endif static int Main() #if DD { return 1; #endif #if AA } #endif #if BB } #endif ").Path; string rsp = Temp.CreateFile().WriteAllText(@" /d:""DD"" /d:""AA;BB"" /d:""N""N ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(1784, "https://github.com/dotnet/roslyn/issues/1784")] [Fact] public void QuotedDefineInRespFileErr() { string source = Temp.CreateFile("a.cs").WriteAllText(@" #if NN class myClass { #endif static int Main() #if DD { return 1; #endif #if AA } #endif #if BB } #endif ").Path; string rsp = Temp.CreateFile().WriteAllText(@" /d:""DD"""" /d:""AA;BB"" /d:""N"" ""N ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [Fact] public void ResponseFileSplitting() { string[] responseFile; responseFile = new string[] { @"a.cs b.cs ""c.cs e.cs""", @"hello world # this is a comment" }; IEnumerable<string> args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { "a.cs", "b.cs", @"c.cs e.cs", "hello", "world" }, args); // Check comment handling; comment character only counts at beginning of argument responseFile = new string[] { @" # ignore this", @" # ignore that ""hello""", @" a.cs #3.cs", @" b#.cs c#d.cs #e.cs", @" ""#f.cs""", @" ""#g.cs #h.cs""" }; args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { "a.cs", "b#.cs", "c#d.cs", "#f.cs", "#g.cs #h.cs" }, args); // Check backslash escaping responseFile = new string[] { @"a\b\c d\\e\\f\\ \\\g\\\h\\\i \\\\ \\\\\k\\\\\", }; args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { @"a\b\c", @"d\\e\\f\\", @"\\\g\\\h\\\i", @"\\\\", @"\\\\\k\\\\\" }, args); // More backslash escaping and quoting responseFile = new string[] { @"a\""a b\\""b c\\\""c d\\\\""d e\\\\\""e f"" g""", }; args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { @"a\""a", @"b\\""b c\\\""c d\\\\""d", @"e\\\\\""e", @"f"" g""" }, args); // Quoting inside argument is valid. responseFile = new string[] { @" /o:""goo.cs"" /o:""abc def""\baz ""/o:baz bar""bing", }; args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { @"/o:""goo.cs""", @"/o:""abc def""\baz", @"""/o:baz bar""bing" }, args); } [ConditionalFact(typeof(WindowsOnly))] private void SourceFileQuoting() { string[] responseFile = new string[] { @"d:\\""abc def""\baz.cs ab""c d""e.cs", }; CSharpCommandLineArguments args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\"); AssertEx.Equal(new[] { @"d:\abc def\baz.cs", @"c:\abc de.cs" }, args.SourceFiles.Select(file => file.Path)); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName1() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from first input (file, not class) name, since DLL. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:library" }, expectedOutputName: "p.dll"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName2() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from command-line option. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:library", "/out:r.dll" }, expectedOutputName: "r.dll"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName3() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe" }, expectedOutputName: "q.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName4() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from command-line option. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe", "/out:r.exe" }, expectedOutputName: "r.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName5() { string source1 = @" class A { static void Main() { } } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint - affected by /main, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe", "/main:A" }, expectedOutputName: "p.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName6() { string source1 = @" class A { static void Main() { } } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint - affected by /main, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe", "/main:B" }, expectedOutputName: "q.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName7() { string source1 = @" partial class A { static partial void Main() { } } "; string source2 = @" partial class A { static partial void Main(); } "; // Name comes from name of file containing entrypoint, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe" }, expectedOutputName: "p.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName8() { string source1 = @" partial class A { static partial void Main(); } "; string source2 = @" partial class A { static partial void Main() { } } "; // Name comes from name of file containing entrypoint, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe" }, expectedOutputName: "q.exe"); } [Fact] public void OutputFileName9() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from first input (file, not class) name, since winmdobj. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:winmdobj" }, expectedOutputName: "p.winmdobj"); } [Fact] public void OutputFileName10() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint, since appcontainerexe. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:appcontainerexe" }, expectedOutputName: "q.exe"); } [Fact] public void OutputFileName_Switch() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe", "/out:r.exe" }, expectedOutputName: "r.exe"); } [Fact] public void OutputFileName_NoEntryPoint() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/target:exe", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.NotEqual(0, exitCode); Assert.Equal("error CS5001: Program does not contain a static 'Main' method suitable for an entry point", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(file.Path); } [Fact, WorkItem(1093063, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1093063")] public void VerifyDiagnosticSeverityNotLocalized() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/target:exe", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.NotEqual(0, exitCode); // If "error" was localized, below assert will fail on PLOC builds. The output would be something like: "!pTCvB!vbc : !FLxft!error 表! CS5001:" Assert.Contains("error CS5001:", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(file.Path); } [Fact] public void NoLogo_1() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/target:library", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal(@"", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(file.Path); } [Fact] public void NoLogo_2() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var patched = Regex.Replace(outWriter.ToString().Trim(), "version \\d+\\.\\d+\\.\\d+(-[\\w\\d]+)*", "version A.B.C-d"); patched = ReplaceCommitHash(patched); Assert.Equal(@" Microsoft (R) Visual C# Compiler version A.B.C-d (HASH) Copyright (C) Microsoft Corporation. All rights reserved.".Trim(), patched); CleanupAllGeneratedFiles(file.Path); } [Theory, InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (<developer build>)", "Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)"), InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (ABCDEF01)", "Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)"), InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (abcdef90)", "Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)"), InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (12345678)", "Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)")] public void TestReplaceCommitHash(string orig, string expected) { Assert.Equal(expected, ReplaceCommitHash(orig)); } private static string ReplaceCommitHash(string s) { // open paren, followed by either <developer build> or 8 hex, followed by close paren return Regex.Replace(s, "(\\((<developer build>|[a-fA-F0-9]{8})\\))", "(HASH)"); } [Fact] public void ExtractShortCommitHash() { Assert.Null(CommonCompiler.ExtractShortCommitHash(null)); Assert.Equal("", CommonCompiler.ExtractShortCommitHash("")); Assert.Equal("<", CommonCompiler.ExtractShortCommitHash("<")); Assert.Equal("<developer build>", CommonCompiler.ExtractShortCommitHash("<developer build>")); Assert.Equal("1", CommonCompiler.ExtractShortCommitHash("1")); Assert.Equal("1234567", CommonCompiler.ExtractShortCommitHash("1234567")); Assert.Equal("12345678", CommonCompiler.ExtractShortCommitHash("12345678")); Assert.Equal("12345678", CommonCompiler.ExtractShortCommitHash("123456789")); } private void CheckOutputFileName(string source1, string source2, string inputName1, string inputName2, string[] commandLineArguments, string expectedOutputName) { var dir = Temp.CreateDirectory(); var file1 = dir.CreateFile(inputName1); file1.WriteAllText(source1); var file2 = dir.CreateFile(inputName2); file2.WriteAllText(source2); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, commandLineArguments.Concat(new[] { inputName1, inputName2 }).ToArray()); int exitCode = csc.Run(outWriter); if (exitCode != 0) { Console.WriteLine(outWriter.ToString()); Assert.Equal(0, exitCode); } Assert.Equal(1, Directory.EnumerateFiles(dir.Path, "*" + PathUtilities.GetExtension(expectedOutputName)).Count()); Assert.Equal(1, Directory.EnumerateFiles(dir.Path, expectedOutputName).Count()); using (var metadata = ModuleMetadata.CreateFromImage(File.ReadAllBytes(Path.Combine(dir.Path, expectedOutputName)))) { var peReader = metadata.Module.GetMetadataReader(); Assert.True(peReader.IsAssembly); Assert.Equal(PathUtilities.RemoveExtension(expectedOutputName), peReader.GetString(peReader.GetAssemblyDefinition().Name)); Assert.Equal(expectedOutputName, peReader.GetString(peReader.GetModuleDefinition().Name)); } if (System.IO.File.Exists(expectedOutputName)) { System.IO.File.Delete(expectedOutputName); } CleanupAllGeneratedFiles(file1.Path); CleanupAllGeneratedFiles(file2.Path); } [Fact] public void MissingReference() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/r:missing.dll", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS0006: Metadata file 'missing.dll' could not be found", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545025")] [ConditionalFact(typeof(WindowsOnly))] public void CompilationWithWarnAsError_01() { string source = @" public class C { public static void Main() { } }"; // Baseline without warning options (expect success) int exitCode = GetExitCode(source, "a.cs", new String[] { }); Assert.Equal(0, exitCode); // The case with /warnaserror (expect to be success, since there will be no warning) exitCode = GetExitCode(source, "b.cs", new[] { "/warnaserror" }); Assert.Equal(0, exitCode); // The case with /warnaserror and /nowarn:1 (expect success) // Note that even though the command line option has a warning, it is not going to become an error // in order to avoid the halt of compilation. exitCode = GetExitCode(source, "c.cs", new[] { "/warnaserror", "/nowarn:1" }); Assert.Equal(0, exitCode); } [WorkItem(545025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545025")] [ConditionalFact(typeof(WindowsOnly))] public void CompilationWithWarnAsError_02() { string source = @" public class C { public static void Main() { int x; // CS0168 } }"; // Baseline without warning options (expect success) int exitCode = GetExitCode(source, "a.cs", new String[] { }); Assert.Equal(0, exitCode); // The case with /warnaserror (expect failure) exitCode = GetExitCode(source, "b.cs", new[] { "/warnaserror" }); Assert.NotEqual(0, exitCode); // The case with /warnaserror:168 (expect failure) exitCode = GetExitCode(source, "c.cs", new[] { "/warnaserror:168" }); Assert.NotEqual(0, exitCode); // The case with /warnaserror:219 (expect success) exitCode = GetExitCode(source, "c.cs", new[] { "/warnaserror:219" }); Assert.Equal(0, exitCode); // The case with /warnaserror and /nowarn:168 (expect success) exitCode = GetExitCode(source, "d.cs", new[] { "/warnaserror", "/nowarn:168" }); Assert.Equal(0, exitCode); } private int GetExitCode(string source, string fileName, string[] commandLineArguments) { var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, commandLineArguments.Concat(new[] { fileName }).ToArray()); int exitCode = csc.Run(outWriter); return exitCode; } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [ConditionalFact(typeof(WindowsOnly))] public void CompilationWithNonExistingOutPath() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:sub\\a.exe" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS2012: Cannot open '" + dir.Path + "\\sub\\a.exe' for writing", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [Fact] public void CompilationWithWrongOutPath_01() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:sub\\" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); var message = outWriter.ToString(); Assert.Contains("error CS2021: File name", message, StringComparison.Ordinal); Assert.Contains("sub", message, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [Fact] public void CompilationWithWrongOutPath_02() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:sub\\ " }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); var message = outWriter.ToString(); Assert.Contains("error CS2021: File name", message, StringComparison.Ordinal); Assert.Contains("sub", message, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [ConditionalFact(typeof(WindowsDesktopOnly))] public void CompilationWithWrongOutPath_03() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:aaa:\\a.exe" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains(@"error CS2021: File name 'aaa:\a.exe' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [Fact] public void CompilationWithWrongOutPath_04() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out: " }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS2005: Missing file specification for '/out:' option", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [Fact] public void EmittedSubsystemVersion() { var compilation = CSharpCompilation.Create("a.dll", references: new[] { MscorlibRef }, options: TestOptions.ReleaseDll); var peHeaders = new PEHeaders(compilation.EmitToStream(options: new EmitOptions(subsystemVersion: SubsystemVersion.Create(5, 1)))); Assert.Equal(5, peHeaders.PEHeader.MajorSubsystemVersion); Assert.Equal(1, peHeaders.PEHeader.MinorSubsystemVersion); } [Fact] public void CreateCompilationWithKeyFile() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "a.cs", "/keyfile:key.snk", }); var comp = cmd.CreateCompilation(TextWriter.Null, new TouchedFileLogger(), NullErrorLogger.Instance); Assert.IsType<DesktopStrongNameProvider>(comp.Options.StrongNameProvider); } [Fact] public void CreateCompilationWithKeyContainer() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "a.cs", "/keycontainer:bbb", }); var comp = cmd.CreateCompilation(TextWriter.Null, new TouchedFileLogger(), NullErrorLogger.Instance); Assert.Equal(typeof(DesktopStrongNameProvider), comp.Options.StrongNameProvider.GetType()); } [Fact] public void CreateCompilationFallbackCommand() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "a.cs", "/keyFile:key.snk", "/features:UseLegacyStrongNameProvider" }); var comp = cmd.CreateCompilation(TextWriter.Null, new TouchedFileLogger(), NullErrorLogger.Instance); Assert.Equal(typeof(DesktopStrongNameProvider), comp.Options.StrongNameProvider.GetType()); } [Fact] public void CreateCompilation_MainAndTargetIncompatibilities() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var compilation = CSharpCompilation.Create("a.dll", options: TestOptions.ReleaseDll); var options = compilation.Options; Assert.Equal(0, options.Errors.Length); options = options.WithMainTypeName("a"); options.Errors.Verify( // error CS2017: Cannot specify /main if building a module or library Diagnostic(ErrorCode.ERR_NoMainOnDLL) ); var comp = CSharpCompilation.Create("a.dll", options: options); comp.GetDiagnostics().Verify( // error CS2017: Cannot specify /main if building a module or library Diagnostic(ErrorCode.ERR_NoMainOnDLL) ); options = options.WithOutputKind(OutputKind.WindowsApplication); options.Errors.Verify(); comp = CSharpCompilation.Create("a.dll", options: options); comp.GetDiagnostics().Verify( // error CS1555: Could not find 'a' specified for Main method Diagnostic(ErrorCode.ERR_MainClassNotFound).WithArguments("a") ); options = options.WithOutputKind(OutputKind.NetModule); options.Errors.Verify( // error CS2017: Cannot specify /main if building a module or library Diagnostic(ErrorCode.ERR_NoMainOnDLL) ); comp = CSharpCompilation.Create("a.dll", options: options); comp.GetDiagnostics().Verify( // error CS2017: Cannot specify /main if building a module or library Diagnostic(ErrorCode.ERR_NoMainOnDLL) ); options = options.WithMainTypeName(null); options.Errors.Verify(); comp = CSharpCompilation.Create("a.dll", options: options); comp.GetDiagnostics().Verify(); CleanupAllGeneratedFiles(file.Path); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30328")] public void SpecifyProperCodePage() { byte[] source = { 0x63, // c 0x6c, // l 0x61, // a 0x73, // s 0x73, // s 0x20, // 0xd0, 0x96, // Utf-8 Cyrillic character 0x7b, // { 0x7d, // } }; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllBytes(source); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/nologo /t:library \"{file}\"", startFolder: dir.Path); Assert.Equal("", output); // Autodetected UTF8, NO ERROR output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/nologo /preferreduilang:en /t:library /codepage:20127 \"{file}\"", expectedRetCode: 1, startFolder: dir.Path); // 20127: US-ASCII // 0xd0, 0x96 ==> ERROR Assert.Equal(@" a.cs(1,7): error CS1001: Identifier expected a.cs(1,7): error CS1514: { expected a.cs(1,7): error CS1513: } expected a.cs(1,7): error CS8803: Top-level statements must precede namespace and type declarations. a.cs(1,7): error CS1525: Invalid expression term '??' a.cs(1,9): error CS1525: Invalid expression term '{' a.cs(1,9): error CS1002: ; expected ".Trim(), Regex.Replace(output, "^.*a.cs", "a.cs", RegexOptions.Multiline).Trim()); CleanupAllGeneratedFiles(file.Path); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultWin32ResForExe() { var source = @" class C { static void Main() { } } "; CheckManifestString(source, OutputKind.ConsoleApplication, explicitManifest: null, expectedManifest: @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""490""> <Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource>"); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultManifestForDll() { var source = @" class C { } "; CheckManifestString(source, OutputKind.DynamicallyLinkedLibrary, explicitManifest: null, expectedManifest: null); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultManifestForWinExe() { var source = @" class C { static void Main() { } } "; CheckManifestString(source, OutputKind.WindowsApplication, explicitManifest: null, expectedManifest: @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""490""> <Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource>"); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultManifestForAppContainerExe() { var source = @" class C { static void Main() { } } "; CheckManifestString(source, OutputKind.WindowsRuntimeApplication, explicitManifest: null, expectedManifest: @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""490""> <Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource>"); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultManifestForWinMD() { var source = @" class C { } "; CheckManifestString(source, OutputKind.WindowsRuntimeMetadata, explicitManifest: null, expectedManifest: null); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultWin32ResForModule() { var source = @" class C { } "; CheckManifestString(source, OutputKind.NetModule, explicitManifest: null, expectedManifest: null); } [ConditionalFact(typeof(WindowsOnly))] public void ExplicitWin32ResForExe() { var source = @" class C { static void Main() { } } "; var explicitManifest = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""Test.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>"; var explicitManifestStream = new MemoryStream(Encoding.UTF8.GetBytes(explicitManifest)); var expectedManifest = @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""476""> <Contents><![CDATA[" + explicitManifest + @"]]></Contents> </ManifestResource>"; CheckManifestString(source, OutputKind.ConsoleApplication, explicitManifest, expectedManifest); } // DLLs don't get the default manifest, but they do respect explicitly set manifests. [ConditionalFact(typeof(WindowsOnly))] public void ExplicitWin32ResForDll() { var source = @" class C { static void Main() { } } "; var explicitManifest = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""Test.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>"; var expectedManifest = @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""476""> <Contents><![CDATA[" + explicitManifest + @"]]></Contents> </ManifestResource>"; CheckManifestString(source, OutputKind.DynamicallyLinkedLibrary, explicitManifest, expectedManifest); } // Modules don't have manifests, even if one is explicitly specified. [ConditionalFact(typeof(WindowsOnly))] public void ExplicitWin32ResForModule() { var source = @" class C { } "; var explicitManifest = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""Test.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>"; CheckManifestString(source, OutputKind.NetModule, explicitManifest, expectedManifest: null); } [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr LoadLibraryEx(string lpFileName, IntPtr hFile, uint dwFlags); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool FreeLibrary([In] IntPtr hFile); private void CheckManifestString(string source, OutputKind outputKind, string explicitManifest, string expectedManifest) { var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("Test.cs").WriteAllText(source); string outputFileName; string target; switch (outputKind) { case OutputKind.ConsoleApplication: outputFileName = "Test.exe"; target = "exe"; break; case OutputKind.WindowsApplication: outputFileName = "Test.exe"; target = "winexe"; break; case OutputKind.DynamicallyLinkedLibrary: outputFileName = "Test.dll"; target = "library"; break; case OutputKind.NetModule: outputFileName = "Test.netmodule"; target = "module"; break; case OutputKind.WindowsRuntimeMetadata: outputFileName = "Test.winmdobj"; target = "winmdobj"; break; case OutputKind.WindowsRuntimeApplication: outputFileName = "Test.exe"; target = "appcontainerexe"; break; default: throw TestExceptionUtilities.UnexpectedValue(outputKind); } MockCSharpCompiler csc; if (explicitManifest == null) { csc = CreateCSharpCompiler(null, dir.Path, new[] { string.Format("/target:{0}", target), string.Format("/out:{0}", outputFileName), Path.GetFileName(sourceFile.Path), }); } else { var manifestFile = dir.CreateFile("Test.config").WriteAllText(explicitManifest); csc = CreateCSharpCompiler(null, dir.Path, new[] { string.Format("/target:{0}", target), string.Format("/out:{0}", outputFileName), string.Format("/win32manifest:{0}", Path.GetFileName(manifestFile.Path)), Path.GetFileName(sourceFile.Path), }); } int actualExitCode = csc.Run(new StringWriter(CultureInfo.InvariantCulture)); Assert.Equal(0, actualExitCode); //Open as data IntPtr lib = LoadLibraryEx(Path.Combine(dir.Path, outputFileName), IntPtr.Zero, 0x00000002); if (lib == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error()); const string resourceType = "#24"; var resourceId = outputKind == OutputKind.DynamicallyLinkedLibrary ? "#2" : "#1"; uint manifestSize; if (expectedManifest == null) { Assert.Throws<Win32Exception>(() => Win32Res.GetResource(lib, resourceId, resourceType, out manifestSize)); } else { IntPtr manifestResourcePointer = Win32Res.GetResource(lib, resourceId, resourceType, out manifestSize); string actualManifest = Win32Res.ManifestResourceToXml(manifestResourcePointer, manifestSize); Assert.Equal(expectedManifest, actualManifest); } FreeLibrary(lib); } [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")] [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ResponseFilesWithNoconfig_01() { string source = Temp.CreateFile("a.cs").WriteAllText(@" public class C { public static void Main() { int x; // CS0168 } }").Path; string rsp = Temp.CreateFile().WriteAllText(@" /warnaserror ").Path; // Checks the base case without /noconfig (expect to see error) var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /noconfig (expect to see warning, instead of error) outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/noconfig", "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /NOCONFIG (expect to see warning, instead of error) outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/NOCONFIG", "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with -noconfig (expect to see warning, instead of error) outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "-noconfig", "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")] [ConditionalFact(typeof(WindowsOnly))] public void ResponseFilesWithNoconfig_02() { string source = Temp.CreateFile("a.cs").WriteAllText(@" public class C { public static void Main() { } }").Path; string rsp = Temp.CreateFile().WriteAllText(@" /noconfig ").Path; // Checks the case with /noconfig inside the response file (expect to see warning) var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /noconfig inside the response file as along with /nowarn (expect to see warning) // to verify that this warning is not suppressed by the /nowarn option (See MSDN). outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en", "/nowarn:2023" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")] [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ResponseFilesWithNoconfig_03() { string source = Temp.CreateFile("a.cs").WriteAllText(@" public class C { public static void Main() { } }").Path; string rsp = Temp.CreateFile().WriteAllText(@" /NOCONFIG ").Path; // Checks the case with /noconfig inside the response file (expect to see warning) var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /NOCONFIG inside the response file as along with /nowarn (expect to see warning) // to verify that this warning is not suppressed by the /nowarn option (See MSDN). outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en", "/nowarn:2023" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")] [ConditionalFact(typeof(WindowsOnly))] public void ResponseFilesWithNoconfig_04() { string source = Temp.CreateFile("a.cs").WriteAllText(@" public class C { public static void Main() { } }").Path; string rsp = Temp.CreateFile().WriteAllText(@" -noconfig ").Path; // Checks the case with /noconfig inside the response file (expect to see warning) var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with -noconfig inside the response file as along with /nowarn (expect to see warning) // to verify that this warning is not suppressed by the /nowarn option (See MSDN). outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en", "/nowarn:2023" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [Fact, WorkItem(530024, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530024")] public void NoStdLib() { var src = Temp.CreateFile("a.cs"); src.WriteAllText("public class C{}"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/t:library", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/nostdlib", "/t:library", src.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("{FILE}(1,14): error CS0518: Predefined type 'System.Object' is not defined or imported", outWriter.ToString().Replace(Path.GetFileName(src.Path), "{FILE}").Trim()); // Bug#15021: breaking change - empty source no error with /nostdlib src.WriteAllText("namespace System { }"); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nostdlib", "/t:library", "/runtimemetadataversion:v4.0.30319", "/langversion:8", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(src.Path); } private string GetDefaultResponseFilePath() { var cscRsp = global::TestResources.ResourceLoader.GetResourceBlob("csc.rsp"); return Temp.CreateFile().WriteAllBytes(cscRsp).Path; } [Fact, WorkItem(530359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530359")] public void NoStdLib02() { #region "source" var source = @" // <Title>A collection initializer can be declared with a user-defined IEnumerable that is declared in a user-defined System.Collections</Title> using System.Collections; class O<T> where T : new() { public T list = new T(); } class C { static StructCollection sc = new StructCollection { 1 }; public static int Main() { ClassCollection cc = new ClassCollection { 2 }; var o1 = new O<ClassCollection> { list = { 5 } }; var o2 = new O<StructCollection> { list = sc }; return 0; } } struct StructCollection : IEnumerable { public int added; #region IEnumerable Members public void Add(int t) { added = t; } #endregion } class ClassCollection : IEnumerable { public int added; #region IEnumerable Members public void Add(int t) { added = t; } #endregion } namespace System.Collections { public interface IEnumerable { void Add(int t); } } "; #endregion #region "mslib" var mslib = @" 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 Exception(string s){} } 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 { } public class Activator { public static T CreateInstance<T>(){return default(T);} } namespace Collections { public interface IEnumerator { } } namespace Runtime { namespace InteropServices { public class OutAttribute { } } namespace CompilerServices { public class RuntimeHelpers { } } } namespace Reflection { public class DefaultMemberAttribute { } } } "; #endregion var src = Temp.CreateFile("NoStdLib02.cs"); src.WriteAllText(source + mslib); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/noconfig", "/nostdlib", "/runtimemetadataversion:v4.0.30319", "/nowarn:8625", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nostdlib", "/runtimemetadataversion:v4.0.30319", "/nowarn:8625", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); string OriginalSource = src.Path; src = Temp.CreateFile("NoStdLib02b.cs"); src.WriteAllText(mslib); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(GetDefaultResponseFilePath(), WorkingDirectory, new[] { "/nologo", "/noconfig", "/nostdlib", "/t:library", "/runtimemetadataversion:v4.0.30319", "/nowarn:8625", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(OriginalSource); CleanupAllGeneratedFiles(src.Path); } [Fact, WorkItem(546018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546018"), WorkItem(546020, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546020"), WorkItem(546024, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546024"), WorkItem(546049, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546049")] public void InvalidDefineSwitch() { var src = Temp.CreateFile("a.cs"); src.WriteAllText("public class C{}"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", src.ToString(), "/define" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2006: Command-line syntax error: Missing '<text>' for '/define' option", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), @"/define:""""" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define: " }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2006: Command-line syntax error: Missing '<text>' for '/define:' option", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2006: Command-line syntax error: Missing '<text>' for '/define:' option", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:,,," }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:,blah,Blah" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:a;;b@" }).Run(outWriter); Assert.Equal(0, exitCode); var errorLines = outWriter.ToString().Trim().Split(new string[] { Environment.NewLine }, StringSplitOptions.None); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", errorLines[0]); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; 'b@' is not a valid identifier", errorLines[1]); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:a,b@;" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; 'b@' is not a valid identifier", outWriter.ToString().Trim()); //Bug 531612 - Native would normally not give the 2nd warning outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), @"/define:OE_WIN32=-1:LANG_HOST_EN=-1:LANG_OE_EN=-1:LANG_PRJ_EN=-1:HOST_COM20SDKEVERETT=-1:EXEMODE=-1:OE_NT5=-1:Win32=-1", @"/d:TRACE=TRUE,DEBUG=TRUE" }).Run(outWriter); Assert.Equal(0, exitCode); errorLines = outWriter.ToString().Trim().Split(new string[] { Environment.NewLine }, StringSplitOptions.None); Assert.Equal(@"warning CS2029: Invalid name for a preprocessing symbol; 'OE_WIN32=-1:LANG_HOST_EN=-1:LANG_OE_EN=-1:LANG_PRJ_EN=-1:HOST_COM20SDKEVERETT=-1:EXEMODE=-1:OE_NT5=-1:Win32=-1' is not a valid identifier", errorLines[0]); Assert.Equal(@"warning CS2029: Invalid name for a preprocessing symbol; 'TRACE=TRUE' is not a valid identifier", errorLines[1]); CleanupAllGeneratedFiles(src.Path); } [WorkItem(733242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/733242")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void Bug733242() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText( @" /// <summary>ABC...XYZ</summary> class C {} "); var xml = dir.CreateFile("a.xml"); xml.WriteAllText("EMPTY"); using (var xmlFileHandle = File.Open(xml.ToString(), FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite)) { var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /t:library /doc:\"{1}\" \"{0}\"", src.ToString(), xml.ToString()), startFolder: dir.ToString()); Assert.Equal("", output.Trim()); Assert.True(File.Exists(Path.Combine(dir.ToString(), "a.xml"))); using (var reader = new StreamReader(xmlFileHandle)) { var content = reader.ReadToEnd(); Assert.Equal( @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""T:C""> <summary>ABC...XYZ</summary> </member> </members> </doc>".Trim(), content.Trim()); } } CleanupAllGeneratedFiles(src.Path); CleanupAllGeneratedFiles(xml.Path); } [WorkItem(768605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768605")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void Bug768605() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText( @" /// <summary>ABC</summary> class C {} /// <summary>XYZ</summary> class E {} "); var xml = dir.CreateFile("a.xml"); xml.WriteAllText("EMPTY"); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /t:library /doc:\"{1}\" \"{0}\"", src.ToString(), xml.ToString()), startFolder: dir.ToString()); Assert.Equal("", output.Trim()); using (var reader = new StreamReader(xml.ToString())) { var content = reader.ReadToEnd(); Assert.Equal( @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""T:C""> <summary>ABC</summary> </member> <member name=""T:E""> <summary>XYZ</summary> </member> </members> </doc>".Trim(), content.Trim()); } src.WriteAllText( @" /// <summary>ABC</summary> class C {} "); output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /t:library /doc:\"{1}\" \"{0}\"", src.ToString(), xml.ToString()), startFolder: dir.ToString()); Assert.Equal("", output.Trim()); using (var reader = new StreamReader(xml.ToString())) { var content = reader.ReadToEnd(); Assert.Equal( @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""T:C""> <summary>ABC</summary> </member> </members> </doc>".Trim(), content.Trim()); } CleanupAllGeneratedFiles(src.Path); CleanupAllGeneratedFiles(xml.Path); } [Fact] public void ParseFullpaths() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.PrintFullPaths); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths" }, WorkingDirectory); Assert.True(parsedArgs.PrintFullPaths); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths:" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths: " }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths+" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths+:" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code); } [Fact] public void CheckFullpaths() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" public class C { public static void Main() { string x; } }").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); // Checks the base case without /fullpaths (expect to see relative path name) // c:\temp> csc.exe c:\temp\a.cs // a.cs(6,16): warning CS0168: The variable 'x' is declared but never used var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, baseDir, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(fileName + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); // Checks the base case without /fullpaths when the file is located in the sub-folder (expect to see relative path name) // c:\temp> csc.exe c:\temp\example\a.cs // example\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, Directory.GetParent(baseDir).FullName, new[] { source, "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(fileName + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); Assert.DoesNotContain(source, outWriter.ToString(), StringComparison.Ordinal); // Checks the base case without /fullpaths when the file is not located under the base directory (expect to see the full path name) // c:\temp> csc.exe c:\test\a.cs // c:\test\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, Temp.CreateDirectory().Path, new[] { source, "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(source + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /fullpaths (expect to see the full paths) // c:\temp> csc.exe c:\temp\a.cs /fullpaths // c:\temp\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, baseDir, new[] { source, "/fullpaths", "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(source + @"(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); // Checks the base case without /fullpaths when the file is located in the sub-folder (expect to see the full path name) // c:\temp> csc.exe c:\temp\example\a.cs /fullpaths // c:\temp\example\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, Directory.GetParent(baseDir).FullName, new[] { source, "/preferreduilang:en", "/fullpaths" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(source + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); // Checks the base case without /fullpaths when the file is not located under the base directory (expect to see the full path name) // c:\temp> csc.exe c:\test\a.cs /fullpaths // c:\test\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, Temp.CreateDirectory().Path, new[] { source, "/preferreduilang:en", "/fullpaths" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(source + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(source)), Path.GetFileName(source))); } [Fact] public void DefaultResponseFile() { var sdkDirectory = SdkDirectory; MockCSharpCompiler csc = new MockCSharpCompiler( GetDefaultResponseFilePath(), RuntimeUtilities.CreateBuildPaths(WorkingDirectory, sdkDirectory), new string[0]); AssertEx.Equal(csc.Arguments.MetadataReferences.Select(r => r.Reference), new string[] { MscorlibFullPath, "Accessibility.dll", "Microsoft.CSharp.dll", "System.Configuration.dll", "System.Configuration.Install.dll", "System.Core.dll", "System.Data.dll", "System.Data.DataSetExtensions.dll", "System.Data.Linq.dll", "System.Data.OracleClient.dll", "System.Deployment.dll", "System.Design.dll", "System.DirectoryServices.dll", "System.dll", "System.Drawing.Design.dll", "System.Drawing.dll", "System.EnterpriseServices.dll", "System.Management.dll", "System.Messaging.dll", "System.Runtime.Remoting.dll", "System.Runtime.Serialization.dll", "System.Runtime.Serialization.Formatters.Soap.dll", "System.Security.dll", "System.ServiceModel.dll", "System.ServiceModel.Web.dll", "System.ServiceProcess.dll", "System.Transactions.dll", "System.Web.dll", "System.Web.Extensions.Design.dll", "System.Web.Extensions.dll", "System.Web.Mobile.dll", "System.Web.RegularExpressions.dll", "System.Web.Services.dll", "System.Windows.Forms.dll", "System.Workflow.Activities.dll", "System.Workflow.ComponentModel.dll", "System.Workflow.Runtime.dll", "System.Xml.dll", "System.Xml.Linq.dll", }, StringComparer.OrdinalIgnoreCase); } [Fact] public void DefaultResponseFileNoConfig() { MockCSharpCompiler csc = CreateCSharpCompiler(GetDefaultResponseFilePath(), WorkingDirectory, new[] { "/noconfig" }); Assert.Equal(csc.Arguments.MetadataReferences.Select(r => r.Reference), new string[] { MscorlibFullPath, }, StringComparer.OrdinalIgnoreCase); } [Fact, WorkItem(545954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545954")] public void TestFilterParseDiagnostics() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" #pragma warning disable 440 using global = A; // CS0440 class A { static void Main() { #pragma warning suppress 440 } }").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal(Path.GetFileName(source) + "(7,17): warning CS1634: Expected 'disable' or 'restore'", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/nowarn:1634", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", Path.Combine(baseDir, "nonexistent.cs"), source.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2001: Source file '" + Path.Combine(baseDir, "nonexistent.cs") + "' could not be found.", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(546058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546058")] public void TestNoWarnParseDiagnostics() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" class Test { static void Main() { //Generates warning CS1522: Empty switch block switch (1) { } //Generates warning CS0642: Possible mistaken empty statement while (false) ; { } } } ").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nowarn:1522,642", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(41610, "https://github.com/dotnet/roslyn/issues/41610")] public void TestWarnAsError_CS8632() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" public class C { public string? field; public static void Main() { } } ").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/warn:3", "/warnaserror:nullable", source.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal( $@"{fileName}(4,18): error CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(546076, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546076")] public void TestWarnAsError_CS1522() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" public class Test { // CS0169 (level 3) private int x; // CS0109 (level 4) public new void Method() { } public static int Main() { int i = 5; // CS1522 (level 1) switch (i) { } return 0; // CS0162 (level 2) i = 6; } } ").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/warn:3", "/warnaserror", source.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal( $@"{fileName}(12,20): error CS1522: Empty switch block {fileName}(15,9): error CS0162: Unreachable code detected {fileName}(5,17): error CS0169: The field 'Test.x' is never used", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [Fact(), WorkItem(546025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546025")] public void TestWin32ResWithBadResFile_CS1583ERR_BadWin32Res_01() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class Test { static void Main() {} }").Path; string badres = Temp.CreateFile().WriteAllBytes(TestResources.DiagnosticTests.badresfile).Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/win32res:" + badres, source }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS1583: Error reading Win32 resources -- Image is too small.", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(badres); } [Fact(), WorkItem(217718, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=217718")] public void TestWin32ResWithBadResFile_CS1583ERR_BadWin32Res_02() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class Test { static void Main() {} }").Path; string badres = Temp.CreateFile().WriteAllBytes(new byte[] { 0, 0 }).Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/win32res:" + badres, source }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS1583: Error reading Win32 resources -- Unrecognized resource file format.", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(badres); } [Fact, WorkItem(546114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546114")] public void TestFilterCommandLineDiagnostics() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" class A { static void Main() { } }").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/target:library", "/out:goo.dll", "/nowarn:2008" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); System.IO.File.Delete(System.IO.Path.Combine(baseDir, "goo.dll")); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(546452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546452")] public void CS1691WRN_BadWarningNumber_Bug15905() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" class Program { #pragma warning disable 1998 public static void Main() { } #pragma warning restore 1998 } ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // Repro case 1 int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/warnaserror", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); // Repro case 2 exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nowarn:1998", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void ExistingPdb() { var dir = Temp.CreateDirectory(); var source1 = dir.CreateFile("program1.cs").WriteAllText(@" class " + new string('a', 10000) + @" { public static void Main() { } }"); var source2 = dir.CreateFile("program2.cs").WriteAllText(@" class Program2 { public static void Main() { } }"); var source3 = dir.CreateFile("program3.cs").WriteAllText(@" class Program3 { public static void Main() { } }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int oldSize = 16 * 1024; var exe = dir.CreateFile("Program.exe"); using (var stream = File.OpenWrite(exe.Path)) { byte[] buffer = new byte[oldSize]; stream.Write(buffer, 0, buffer.Length); } var pdb = dir.CreateFile("Program.pdb"); using (var stream = File.OpenWrite(pdb.Path)) { byte[] buffer = new byte[oldSize]; stream.Write(buffer, 0, buffer.Length); } int exitCode1 = CreateCSharpCompiler(null, dir.Path, new[] { "/debug:full", "/out:Program.exe", source1.Path }).Run(outWriter); Assert.NotEqual(0, exitCode1); ValidateZeroes(exe.Path, oldSize); ValidateZeroes(pdb.Path, oldSize); int exitCode2 = CreateCSharpCompiler(null, dir.Path, new[] { "/debug:full", "/out:Program.exe", source2.Path }).Run(outWriter); Assert.Equal(0, exitCode2); using (var peFile = File.OpenRead(exe.Path)) { PdbValidation.ValidateDebugDirectory(peFile, null, pdb.Path, hashAlgorithm: default, hasEmbeddedPdb: false, isDeterministic: false); } Assert.True(new FileInfo(exe.Path).Length < oldSize); Assert.True(new FileInfo(pdb.Path).Length < oldSize); int exitCode3 = CreateCSharpCompiler(null, dir.Path, new[] { "/debug:full", "/out:Program.exe", source3.Path }).Run(outWriter); Assert.Equal(0, exitCode3); using (var peFile = File.OpenRead(exe.Path)) { PdbValidation.ValidateDebugDirectory(peFile, null, pdb.Path, hashAlgorithm: default, hasEmbeddedPdb: false, isDeterministic: false); } } private static void ValidateZeroes(string path, int count) { using (var stream = File.OpenRead(path)) { byte[] buffer = new byte[count]; stream.Read(buffer, 0, buffer.Length); for (int i = 0; i < buffer.Length; i++) { if (buffer[i] != 0) { Assert.True(false); } } } } /// <summary> /// When the output file is open with <see cref="FileShare.Read"/> | <see cref="FileShare.Delete"/> /// the compiler should delete the file to unblock build while allowing the reader to continue /// reading the previous snapshot of the file content. /// /// On Windows we can read the original data directly from the stream without creating a memory map. /// </summary> [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void FileShareDeleteCompatibility_Windows() { var dir = Temp.CreateDirectory(); var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }"); var libDll = dir.CreateFile("Lib.dll").WriteAllText("DLL"); var libPdb = dir.CreateFile("Lib.pdb").WriteAllText("PDB"); var fsDll = new FileStream(libDll.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var fsPdb = new FileStream(libPdb.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/debug:full", libSrc.Path }).Run(outWriter); if (exitCode != 0) { AssertEx.AssertEqualToleratingWhitespaceDifferences("", outWriter.ToString()); } Assert.Equal(0, exitCode); AssertEx.Equal(new byte[] { 0x4D, 0x5A }, ReadBytes(libDll.Path, 2)); AssertEx.Equal(new[] { (byte)'D', (byte)'L', (byte)'L' }, ReadBytes(fsDll, 3)); AssertEx.Equal(new byte[] { 0x4D, 0x69 }, ReadBytes(libPdb.Path, 2)); AssertEx.Equal(new[] { (byte)'P', (byte)'D', (byte)'B' }, ReadBytes(fsPdb, 3)); fsDll.Dispose(); fsPdb.Dispose(); AssertEx.Equal(new[] { "Lib.cs", "Lib.dll", "Lib.pdb" }, Directory.GetFiles(dir.Path).Select(p => Path.GetFileName(p)).Order()); } /// <summary> /// On Linux/Mac <see cref="FileShare.Delete"/> on its own doesn't do anything. /// We need to create the actual memory map. This works on Windows as well. /// </summary> [WorkItem(8896, "https://github.com/dotnet/roslyn/issues/8896")] [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void FileShareDeleteCompatibility_Xplat() { var bytes = TestResources.MetadataTests.InterfaceAndClass.CSClasses01; var mvid = ReadMvid(new MemoryStream(bytes)); var dir = Temp.CreateDirectory(); var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }"); var libDll = dir.CreateFile("Lib.dll").WriteAllBytes(bytes); var libPdb = dir.CreateFile("Lib.pdb").WriteAllBytes(bytes); var fsDll = new FileStream(libDll.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var fsPdb = new FileStream(libPdb.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var peDll = new PEReader(fsDll); var pePdb = new PEReader(fsPdb); // creates memory map view: var imageDll = peDll.GetEntireImage(); var imagePdb = pePdb.GetEntireImage(); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/target:library /debug:portable \"{libSrc.Path}\"", startFolder: dir.ToString()); AssertEx.AssertEqualToleratingWhitespaceDifferences($@" Microsoft (R) Visual C# Compiler version {s_compilerVersion} Copyright (C) Microsoft Corporation. All rights reserved.", output); // reading original content from the memory map: Assert.Equal(mvid, ReadMvid(new MemoryStream(imageDll.GetContent().ToArray()))); Assert.Equal(mvid, ReadMvid(new MemoryStream(imagePdb.GetContent().ToArray()))); // reading original content directly from the streams: fsDll.Position = 0; fsPdb.Position = 0; Assert.Equal(mvid, ReadMvid(fsDll)); Assert.Equal(mvid, ReadMvid(fsPdb)); // reading new content from the file: using (var fsNewDll = File.OpenRead(libDll.Path)) { Assert.NotEqual(mvid, ReadMvid(fsNewDll)); } // Portable PDB metadata signature: AssertEx.Equal(new[] { (byte)'B', (byte)'S', (byte)'J', (byte)'B' }, ReadBytes(libPdb.Path, 4)); // dispose PEReaders (they dispose the underlying file streams) peDll.Dispose(); pePdb.Dispose(); AssertEx.Equal(new[] { "Lib.cs", "Lib.dll", "Lib.pdb" }, Directory.GetFiles(dir.Path).Select(p => Path.GetFileName(p)).Order()); // files can be deleted now: File.Delete(libSrc.Path); File.Delete(libDll.Path); File.Delete(libPdb.Path); // directory can be deleted (should be empty): Directory.Delete(dir.Path, recursive: false); } private static Guid ReadMvid(Stream stream) { using (var peReader = new PEReader(stream, PEStreamOptions.LeaveOpen)) { var mdReader = peReader.GetMetadataReader(); return mdReader.GetGuid(mdReader.GetModuleDefinition().Mvid); } } // Seems like File.SetAttributes(libDll.Path, FileAttributes.ReadOnly) doesn't restrict access to the file on Mac (Linux passes). [ConditionalFact(typeof(WindowsOnly)), WorkItem(8939, "https://github.com/dotnet/roslyn/issues/8939")] public void FileShareDeleteCompatibility_ReadOnlyFiles() { var dir = Temp.CreateDirectory(); var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }"); var libDll = dir.CreateFile("Lib.dll").WriteAllText("DLL"); File.SetAttributes(libDll.Path, FileAttributes.ReadOnly); var fsDll = new FileStream(libDll.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/preferreduilang:en", libSrc.Path }).Run(outWriter); Assert.Contains($"error CS2012: Cannot open '{libDll.Path}' for writing", outWriter.ToString()); AssertEx.Equal(new[] { (byte)'D', (byte)'L', (byte)'L' }, ReadBytes(libDll.Path, 3)); AssertEx.Equal(new[] { (byte)'D', (byte)'L', (byte)'L' }, ReadBytes(fsDll, 3)); fsDll.Dispose(); AssertEx.Equal(new[] { "Lib.cs", "Lib.dll" }, Directory.GetFiles(dir.Path).Select(p => Path.GetFileName(p)).Order()); } [Fact] public void FileShareDeleteCompatibility_ExistingDirectory() { var dir = Temp.CreateDirectory(); var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }"); var libDll = dir.CreateDirectory("Lib.dll"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/preferreduilang:en", libSrc.Path }).Run(outWriter); Assert.Contains($"error CS2012: Cannot open '{libDll.Path}' for writing", outWriter.ToString()); } private byte[] ReadBytes(Stream stream, int count) { var buffer = new byte[count]; stream.Read(buffer, 0, count); return buffer; } private byte[] ReadBytes(string path, int count) { using (var stream = File.OpenRead(path)) { return ReadBytes(stream, count); } } [Fact] public void IOFailure_DisposeOutputFile() { var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path); var exePath = Path.Combine(Path.GetDirectoryName(srcPath), "test.exe"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", $"/out:{exePath}", srcPath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == exePath) { return new TestStream(backingStream: new MemoryStream(), dispose: () => { throw new IOException("Fake IOException"); }); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Contains($"error CS0016: Could not write to output file '{exePath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString()); } [Fact] public void IOFailure_DisposePdbFile() { var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path); var exePath = Path.Combine(Path.GetDirectoryName(srcPath), "test.exe"); var pdbPath = Path.ChangeExtension(exePath, "pdb"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/debug", $"/out:{exePath}", srcPath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == pdbPath) { return new TestStream(backingStream: new MemoryStream(), dispose: () => { throw new IOException("Fake IOException"); }); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Contains($"error CS0016: Could not write to output file '{pdbPath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString()); } [Fact] public void IOFailure_DisposeXmlFile() { var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path); var xmlPath = Path.Combine(Path.GetDirectoryName(srcPath), "test.xml"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", $"/doc:{xmlPath}", srcPath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == xmlPath) { return new TestStream(backingStream: new MemoryStream(), dispose: () => { throw new IOException("Fake IOException"); }); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Equal($"error CS0016: Could not write to output file '{xmlPath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString()); } [Theory] [InlineData("portable")] [InlineData("full")] public void IOFailure_DisposeSourceLinkFile(string format) { var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path); var sourceLinkPath = Path.Combine(Path.GetDirectoryName(srcPath), "test.json"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/debug:" + format, $"/sourcelink:{sourceLinkPath}", srcPath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == sourceLinkPath) { return new TestStream(backingStream: new MemoryStream(Encoding.UTF8.GetBytes(@" { ""documents"": { ""f:/build/*"" : ""https://raw.githubusercontent.com/my-org/my-project/1111111111111111111111111111111111111111/*"" } } ")), dispose: () => { throw new IOException("Fake IOException"); }); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Equal($"error CS0016: Could not write to output file '{sourceLinkPath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString()); } [Fact] public void IOFailure_OpenOutputFile() { string sourcePath = MakeTrivialExe(); string exePath = Path.Combine(Path.GetDirectoryName(sourcePath), "test.exe"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", $"/out:{exePath}", sourcePath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == exePath) { throw new IOException(); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Contains($"error CS2012: Cannot open '{exePath}' for writing", outWriter.ToString()); System.IO.File.Delete(sourcePath); System.IO.File.Delete(exePath); CleanupAllGeneratedFiles(sourcePath); } [Fact] public void IOFailure_OpenPdbFileNotCalled() { string sourcePath = MakeTrivialExe(); string exePath = Path.Combine(Path.GetDirectoryName(sourcePath), "test.exe"); string pdbPath = Path.ChangeExtension(exePath, ".pdb"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/debug-", $"/out:{exePath}", sourcePath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == pdbPath) { throw new IOException(); } return File.Open(file, (FileMode)mode, (FileAccess)access, (FileShare)share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(0, csc.Run(outWriter)); System.IO.File.Delete(sourcePath); System.IO.File.Delete(exePath); System.IO.File.Delete(pdbPath); CleanupAllGeneratedFiles(sourcePath); } [Fact] public void IOFailure_OpenXmlFinal() { string sourcePath = MakeTrivialExe(); string xmlPath = Path.Combine(WorkingDirectory, "Test.xml"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/doc:" + xmlPath, sourcePath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == xmlPath) { throw new IOException(); } else { return File.Open(file, (FileMode)mode, (FileAccess)access, (FileShare)share); } }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = csc.Run(outWriter); var expectedOutput = string.Format("error CS0016: Could not write to output file '{0}' -- 'I/O error occurred.'", xmlPath); Assert.Equal(expectedOutput, outWriter.ToString().Trim()); Assert.NotEqual(0, exitCode); System.IO.File.Delete(xmlPath); System.IO.File.Delete(sourcePath); CleanupAllGeneratedFiles(sourcePath); } private string MakeTrivialExe(string directory = null) { return Temp.CreateFile(directory: directory, prefix: "", extension: ".cs").WriteAllText(@" class Program { public static void Main() { } } ").Path; } [Fact, WorkItem(546452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546452")] public void CS1691WRN_BadWarningNumber_AllErrorCodes() { const int jump = 200; for (int i = 0; i < 8000; i += (8000 / jump)) { int startErrorCode = (int)i * jump; int endErrorCode = startErrorCode + jump; string source = ComputeSourceText(startErrorCode, endErrorCode); // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied in a #pragma directive // (or via /nowarn /warnaserror flags on the command line). // Going forward, we won't generate any warning in such cases. This will make // maintenance of backwards compatibility easier (we no longer need to worry // about breaking existing projects / command lines if we deprecate / remove // an old warning code). Test(source, startErrorCode, endErrorCode); } } private static string ComputeSourceText(int startErrorCode, int endErrorCode) { string pragmaDisableWarnings = String.Empty; for (int errorCode = startErrorCode; errorCode < endErrorCode; errorCode++) { string pragmaDisableStr = @"#pragma warning disable " + errorCode.ToString() + @" "; pragmaDisableWarnings += pragmaDisableStr; } return pragmaDisableWarnings + @" public class C { public static void Main() { } }"; } private void Test(string source, int startErrorCode, int endErrorCode) { string sourcePath = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(source).Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", sourcePath }).Run(outWriter); Assert.Equal(0, exitCode); var cscOutput = outWriter.ToString().Trim(); for (int errorCode = startErrorCode; errorCode < endErrorCode; errorCode++) { Assert.True(cscOutput == string.Empty, "Failed at error code: " + errorCode); } CleanupAllGeneratedFiles(sourcePath); } [Fact] public void WriteXml() { var source = @" /// <summary> /// A subtype of <see cref=""object""/>. /// </summary> public class C { } "; var sourcePath = Temp.CreateFile(directory: WorkingDirectory, extension: ".cs").WriteAllText(source).Path; string xmlPath = Path.Combine(WorkingDirectory, "Test.xml"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/target:library", "/out:Test.dll", "/doc:" + xmlPath, sourcePath }); var writer = new StringWriter(CultureInfo.InvariantCulture); var exitCode = csc.Run(writer); if (exitCode != 0) { Console.WriteLine(writer.ToString()); Assert.Equal(0, exitCode); } var bytes = File.ReadAllBytes(xmlPath); var actual = new string(Encoding.UTF8.GetChars(bytes)); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> A subtype of <see cref=""T:System.Object""/>. </summary> </member> </members> </doc> "; Assert.Equal(expected.Trim(), actual.Trim()); System.IO.File.Delete(xmlPath); System.IO.File.Delete(sourcePath); CleanupAllGeneratedFiles(sourcePath); CleanupAllGeneratedFiles(xmlPath); } [WorkItem(546468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546468")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void CS2002WRN_FileAlreadyIncluded() { const string cs2002 = @"warning CS2002: Source file '{0}' specified multiple times"; TempDirectory tempParentDir = Temp.CreateDirectory(); TempDirectory tempDir = tempParentDir.CreateDirectory("tmpDir"); TempFile tempFile = tempDir.CreateFile("a.cs").WriteAllText(@"public class A { }"); // Simple case var commandLineArgs = new[] { "a.cs", "a.cs" }; // warning CS2002: Source file 'a.cs' specified multiple times string aWrnString = String.Format(cs2002, "a.cs"); TestCS2002(commandLineArgs, tempDir.Path, 0, aWrnString); // Multiple duplicates commandLineArgs = new[] { "a.cs", "a.cs", "a.cs" }; // warning CS2002: Source file 'a.cs' specified multiple times var warnings = new[] { aWrnString }; TestCS2002(commandLineArgs, tempDir.Path, 0, warnings); // Case-insensitive commandLineArgs = new[] { "a.cs", "A.cs" }; // warning CS2002: Source file 'A.cs' specified multiple times string AWrnString = String.Format(cs2002, "A.cs"); TestCS2002(commandLineArgs, tempDir.Path, 0, AWrnString); // Different extensions tempDir.CreateFile("a.csx"); commandLineArgs = new[] { "a.cs", "a.csx" }; // No errors or warnings TestCS2002(commandLineArgs, tempDir.Path, 0, String.Empty); // Absolute vs Relative commandLineArgs = new[] { @"tmpDir\a.cs", tempFile.Path }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times string tmpDiraString = String.Format(cs2002, @"tmpDir\a.cs"); TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); // Both relative commandLineArgs = new[] { @"tmpDir\..\tmpDir\a.cs", @"tmpDir\a.cs" }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); // With wild cards commandLineArgs = new[] { tempFile.Path, @"tmpDir\*.cs" }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); // "/recurse" scenarios commandLineArgs = new[] { @"/recurse:a.cs", @"tmpDir\a.cs" }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); commandLineArgs = new[] { @"/recurse:a.cs", @"/recurse:tmpDir\..\tmpDir\*.cs" }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); // Invalid file/path characters const string cs1504 = @"error CS1504: Source file '{0}' could not be opened -- {1}"; commandLineArgs = new[] { "/preferreduilang:en", tempFile.Path, "tmpDir\a.cs" }; // error CS1504: Source file '{0}' could not be opened: Illegal characters in path. var formattedcs1504Str = String.Format(cs1504, PathUtilities.CombineAbsoluteAndRelativePaths(tempParentDir.Path, "tmpDir\a.cs"), "Illegal characters in path."); TestCS2002(commandLineArgs, tempParentDir.Path, 1, formattedcs1504Str); commandLineArgs = new[] { tempFile.Path, @"tmpDi\r*a?.cs" }; var parseDiags = new[] { // error CS2021: File name 'tmpDi\r*a?.cs' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"tmpDi\r*a?.cs"), // error CS2001: Source file 'tmpDi\r*a?.cs' could not be found. Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments(@"tmpDi\r*a?.cs")}; TestCS2002(commandLineArgs, tempParentDir.Path, 1, (string[])null, parseDiags); char currentDrive = Directory.GetCurrentDirectory()[0]; commandLineArgs = new[] { tempFile.Path, currentDrive + @":a.cs" }; parseDiags = new[] { // error CS2021: File name 'e:a.cs' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + @":a.cs")}; TestCS2002(commandLineArgs, tempParentDir.Path, 1, (string[])null, parseDiags); commandLineArgs = new[] { "/preferreduilang:en", tempFile.Path, @":a.cs" }; // error CS1504: Source file '{0}' could not be opened: {1} var formattedcs1504 = String.Format(cs1504, PathUtilities.CombineAbsoluteAndRelativePaths(tempParentDir.Path, @":a.cs"), @"The given path's format is not supported."); TestCS2002(commandLineArgs, tempParentDir.Path, 1, formattedcs1504); CleanupAllGeneratedFiles(tempFile.Path); System.IO.Directory.Delete(tempParentDir.Path, true); } private void TestCS2002(string[] commandLineArgs, string baseDirectory, int expectedExitCode, string compileDiagnostic, params DiagnosticDescription[] parseDiagnostics) { TestCS2002(commandLineArgs, baseDirectory, expectedExitCode, new[] { compileDiagnostic }, parseDiagnostics); } private void TestCS2002(string[] commandLineArgs, string baseDirectory, int expectedExitCode, string[] compileDiagnostics, params DiagnosticDescription[] parseDiagnostics) { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var allCommandLineArgs = new[] { "/nologo", "/preferreduilang:en", "/t:library" }.Concat(commandLineArgs).ToArray(); // Verify command line parser diagnostics. DefaultParse(allCommandLineArgs, baseDirectory).Errors.Verify(parseDiagnostics); // Verify compile. int exitCode = CreateCSharpCompiler(null, baseDirectory, allCommandLineArgs).Run(outWriter); Assert.Equal(expectedExitCode, exitCode); if (parseDiagnostics.IsEmpty()) { // Verify compile diagnostics. string outString = String.Empty; for (int i = 0; i < compileDiagnostics.Length; i++) { if (i != 0) { outString += @" "; } outString += compileDiagnostics[i]; } Assert.Equal(outString, outWriter.ToString().Trim()); } else { Assert.Null(compileDiagnostics); } } [Fact] public void ErrorLineEnd() { var tree = SyntaxFactory.ParseSyntaxTree("class C public { }", path: "goo"); var comp = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/errorendlocation" }); var loc = new SourceLocation(tree.GetCompilationUnitRoot().FindToken(6)); var diag = new CSDiagnostic(new DiagnosticInfo(MessageProvider.Instance, (int)ErrorCode.ERR_MetadataNameTooLong), loc); var text = comp.DiagnosticFormatter.Format(diag); string stringStart = "goo(1,7,1,8)"; Assert.Equal(stringStart, text.Substring(0, stringStart.Length)); } [Fact] public void ReportAnalyzer() { var parsedArgs1 = DefaultParse(new[] { "a.cs", "/reportanalyzer" }, WorkingDirectory); Assert.True(parsedArgs1.ReportAnalyzer); var parsedArgs2 = DefaultParse(new[] { "a.cs", "" }, WorkingDirectory); Assert.False(parsedArgs2.ReportAnalyzer); } [Fact] public void ReportAnalyzerOutput() { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, srcDirectory, new[] { "/reportanalyzer", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, srcFile.Path }); var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); Assert.Contains(CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader, output, StringComparison.Ordinal); Assert.Contains("WarningDiagnosticAnalyzer (Warning01)", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] [WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")] public void SkipAnalyzersParse() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/SKIPANALYZERS+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers-", "/skipanalyzers+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers", "/skipanalyzers-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.SkipAnalyzers); } [Theory, CombinatorialData] [WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")] public void SkipAnalyzersSemantics(bool skipAnalyzers) { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var skipAnalyzersFlag = "/skipanalyzers" + (skipAnalyzers ? "+" : "-"); var csc = CreateCSharpCompiler(null, srcDirectory, new[] { skipAnalyzersFlag, "/reportanalyzer", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, srcFile.Path }); var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); if (skipAnalyzers) { Assert.DoesNotContain(CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader, output, StringComparison.Ordinal); Assert.DoesNotContain(new WarningDiagnosticAnalyzer().ToString(), output, StringComparison.Ordinal); } else { Assert.Contains(CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader, output, StringComparison.Ordinal); Assert.Contains(new WarningDiagnosticAnalyzer().ToString(), output, StringComparison.Ordinal); } CleanupAllGeneratedFiles(srcFile.Path); } [Fact] [WorkItem(24835, "https://github.com/dotnet/roslyn/issues/24835")] public void TestCompilationSuccessIfOnlySuppressedDiagnostics() { var srcFile = Temp.CreateFile().WriteAllText(@" #pragma warning disable Warning01 class C { } "); var errorLog = Temp.CreateFile(); var csc = CreateCSharpCompiler( null, workingDirectory: Path.GetDirectoryName(srcFile.Path), args: new[] { "/errorlog:" + errorLog.Path, "/warnaserror+", "/nologo", "/t:library", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new WarningDiagnosticAnalyzer())); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = csc.Run(outWriter); // Previously, the compiler would return error code 1 without printing any diagnostics Assert.Empty(outWriter.ToString()); Assert.Equal(0, exitCode); CleanupAllGeneratedFiles(srcFile.Path); CleanupAllGeneratedFiles(errorLog.Path); } [Fact] [WorkItem(1759, "https://github.com/dotnet/roslyn/issues/1759")] public void AnalyzerDiagnosticThrowsInGetMessage() { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/t:library", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerThatThrowsInGetMessage())); var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); // Verify that the diagnostic reported by AnalyzerThatThrowsInGetMessage is reported, though it doesn't have the message. Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.Id, output, StringComparison.Ordinal); // Verify that the analyzer exception diagnostic for the exception throw in AnalyzerThatThrowsInGetMessage is also reported. Assert.Contains(AnalyzerExecutor.AnalyzerExceptionDiagnosticId, output, StringComparison.Ordinal); Assert.Contains(nameof(NotImplementedException), output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] [WorkItem(3707, "https://github.com/dotnet/roslyn/issues/3707")] public void AnalyzerExceptionDiagnosticCanBeConfigured() { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/t:library", $"/warnaserror:{AnalyzerExecutor.AnalyzerExceptionDiagnosticId}", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerThatThrowsInGetMessage())); var exitCode = csc.Run(outWriter); Assert.NotEqual(0, exitCode); var output = outWriter.ToString(); // Verify that the analyzer exception diagnostic for the exception throw in AnalyzerThatThrowsInGetMessage is also reported. Assert.Contains(AnalyzerExecutor.AnalyzerExceptionDiagnosticId, output, StringComparison.Ordinal); Assert.Contains(nameof(NotImplementedException), output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] [WorkItem(4589, "https://github.com/dotnet/roslyn/issues/4589")] public void AnalyzerReportsMisformattedDiagnostic() { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/t:library", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerReportingMisformattedDiagnostic())); var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); // Verify that the diagnostic reported by AnalyzerReportingMisformattedDiagnostic is reported with the message format string, instead of the formatted message. Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.Id, output, StringComparison.Ordinal); Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.MessageFormat.ToString(CultureInfo.InvariantCulture), output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] public void ErrorPathsFromLineDirectives() { string sampleProgram = @" #line 10 "".."" //relative path using System* "; var syntaxTree = SyntaxFactory.ParseSyntaxTree(sampleProgram, path: "filename.cs"); var comp = CreateCSharpCompiler(null, WorkingDirectory, new string[] { }); var text = comp.DiagnosticFormatter.Format(syntaxTree.GetDiagnostics().First()); //Pull off the last segment of the current directory. var expectedPath = Path.GetDirectoryName(WorkingDirectory); //the end of the diagnostic's "file" portion should be signaled with the '(' of the line/col info. Assert.Equal('(', text[expectedPath.Length]); sampleProgram = @" #line 10 "".>"" //invalid path character using System* "; syntaxTree = SyntaxFactory.ParseSyntaxTree(sampleProgram, path: "filename.cs"); text = comp.DiagnosticFormatter.Format(syntaxTree.GetDiagnostics().First()); Assert.True(text.StartsWith(".>", StringComparison.Ordinal)); sampleProgram = @" #line 10 ""http://goo.bar/baz.aspx"" //URI using System* "; syntaxTree = SyntaxFactory.ParseSyntaxTree(sampleProgram, path: "filename.cs"); text = comp.DiagnosticFormatter.Format(syntaxTree.GetDiagnostics().First()); Assert.True(text.StartsWith("http://goo.bar/baz.aspx", StringComparison.Ordinal)); } [WorkItem(1119609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119609")] [Fact] public void PreferredUILang() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("CS2006", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("CS2006", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:zz" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("CS2038", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:en-zz" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("CS2038", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:en-US" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.DoesNotContain("CS2038", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:de" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.DoesNotContain("CS2038", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:de-AT" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.DoesNotContain("CS2038", outWriter.ToString(), StringComparison.Ordinal); } [WorkItem(531263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531263")] [Fact] public void EmptyFileName() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "" }).Run(outWriter); Assert.NotEqual(0, exitCode); // error CS2021: File name '' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Assert.Contains("CS2021", outWriter.ToString(), StringComparison.Ordinal); } [WorkItem(747219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/747219")] [Fact] public void NoInfoDiagnostics() { string filePath = Temp.CreateFile().WriteAllText(@" using System.Diagnostics; // Unused. ").Path; var cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/target:library", filePath }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(filePath); } [Fact] public void RuntimeMetadataVersion() { var parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_SwitchNeedsString, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion:" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_SwitchNeedsString, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion: " }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_SwitchNeedsString, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion:v4.0.30319" }, WorkingDirectory); Assert.Equal(0, parsedArgs.Errors.Length); Assert.Equal("v4.0.30319", parsedArgs.EmitOptions.RuntimeMetadataVersion); parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion:-_+@%#*^" }, WorkingDirectory); Assert.Equal(0, parsedArgs.Errors.Length); Assert.Equal("-_+@%#*^", parsedArgs.EmitOptions.RuntimeMetadataVersion); var comp = CreateEmptyCompilation(string.Empty); Assert.Equal("v4.0.30319", ModuleMetadata.CreateFromImage(comp.EmitToArray(new EmitOptions(runtimeMetadataVersion: "v4.0.30319"))).Module.MetadataVersion); comp = CreateEmptyCompilation(string.Empty); Assert.Equal("_+@%#*^", ModuleMetadata.CreateFromImage(comp.EmitToArray(new EmitOptions(runtimeMetadataVersion: "_+@%#*^"))).Module.MetadataVersion); } [WorkItem(715339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715339")] [ConditionalFact(typeof(WindowsOnly))] public void WRN_InvalidSearchPathDir() { var baseDir = Temp.CreateDirectory(); var sourceFile = baseDir.CreateFile("Source.cs"); var invalidPath = "::"; var nonExistentPath = "DoesNotExist"; // lib switch DefaultParse(new[] { "/lib:" + invalidPath, sourceFile.Path }, WorkingDirectory).Errors.Verify( // warning CS1668: Invalid search path '::' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("::", "/LIB option", "path is too long or invalid")); DefaultParse(new[] { "/lib:" + nonExistentPath, sourceFile.Path }, WorkingDirectory).Errors.Verify( // warning CS1668: Invalid search path 'DoesNotExist' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("DoesNotExist", "/LIB option", "directory does not exist")); // LIB environment variable DefaultParse(new[] { sourceFile.Path }, WorkingDirectory, additionalReferenceDirectories: invalidPath).Errors.Verify( // warning CS1668: Invalid search path '::' specified in 'LIB environment variable' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("::", "LIB environment variable", "path is too long or invalid")); DefaultParse(new[] { sourceFile.Path }, WorkingDirectory, additionalReferenceDirectories: nonExistentPath).Errors.Verify( // warning CS1668: Invalid search path 'DoesNotExist' specified in 'LIB environment variable' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("DoesNotExist", "LIB environment variable", "directory does not exist")); CleanupAllGeneratedFiles(sourceFile.Path); } [WorkItem(650083, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/650083")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/55730")] public void ReservedDeviceNameAsFileName() { var parsedArgs = DefaultParse(new[] { "com9.cs", "/t:library " }, WorkingDirectory); Assert.Equal(0, parsedArgs.Errors.Length); parsedArgs = DefaultParse(new[] { "a.cs", "/t:library ", "/appconfig:.\\aux.config" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/out:com1.dll " }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/doc:..\\lpt2.xml: " }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/debug+", "/pdb:.\\prn.pdb" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "@con.rsp" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_OpenResponseFile, parsedArgs.Errors.First().Code); } [Fact] public void ReservedDeviceNameAsFileName2() { string filePath = Temp.CreateFile().WriteAllText(@"class C {}").Path; // make sure reserved device names don't var cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/r:com2.dll", "/target:library", "/preferreduilang:en", filePath }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS0006: Metadata file 'com2.dll' could not be found", outWriter.ToString(), StringComparison.Ordinal); cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/link:..\\lpt8.dll", "/target:library", "/preferreduilang:en", filePath }); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = cmd.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS0006: Metadata file '..\\lpt8.dll' could not be found", outWriter.ToString(), StringComparison.Ordinal); cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/lib:aux", "/preferreduilang:en", filePath }); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = cmd.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("warning CS1668: Invalid search path 'aux' specified in '/LIB option' -- 'directory does not exist'", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(filePath); } [Fact] public void ParseFeatures() { var args = DefaultParse(new[] { "/features:Test", "a.vb" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal("Test", args.ParseOptions.Features.Single().Key); args = DefaultParse(new[] { "/features:Test", "a.vb", "/Features:Experiment" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.ParseOptions.Features.Count); Assert.True(args.ParseOptions.Features.ContainsKey("Test")); Assert.True(args.ParseOptions.Features.ContainsKey("Experiment")); args = DefaultParse(new[] { "/features:Test=false,Key=value", "a.vb" }, WorkingDirectory); args.Errors.Verify(); Assert.True(args.ParseOptions.Features.SetEquals(new Dictionary<string, string> { { "Test", "false" }, { "Key", "value" } })); args = DefaultParse(new[] { "/features:Test,", "a.vb" }, WorkingDirectory); args.Errors.Verify(); Assert.True(args.ParseOptions.Features.SetEquals(new Dictionary<string, string> { { "Test", "true" } })); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseAdditionalFile() { var args = DefaultParse(new[] { "/additionalfile:web.config", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles.Single().Path); args = DefaultParse(new[] { "/additionalfile:web.config", "a.cs", "/additionalfile:app.manifest" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { "/additionalfile:web.config", "a.cs", "/additionalfile:web.config" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { "/additionalfile:..\\web.config", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "..\\web.config"), args.AdditionalFiles.Single().Path); var baseDir = Temp.CreateDirectory(); baseDir.CreateFile("web1.config"); baseDir.CreateFile("web2.config"); baseDir.CreateFile("web3.config"); args = DefaultParse(new[] { "/additionalfile:web*.config", "a.cs" }, baseDir.Path); args.Errors.Verify(); Assert.Equal(3, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(baseDir.Path, "web1.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(baseDir.Path, "web2.config"), args.AdditionalFiles[1].Path); Assert.Equal(Path.Combine(baseDir.Path, "web3.config"), args.AdditionalFiles[2].Path); args = DefaultParse(new[] { "/additionalfile:web.config;app.manifest", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { "/additionalfile:web.config,app.manifest", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { "/additionalfile:web.config,app.manifest", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { @"/additionalfile:""web.config,app.manifest""", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(1, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config,app.manifest"), args.AdditionalFiles[0].Path); args = DefaultParse(new[] { "/additionalfile:web.config:app.manifest", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(1, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config:app.manifest"), args.AdditionalFiles[0].Path); args = DefaultParse(new[] { "/additionalfile", "a.cs" }, WorkingDirectory); args.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "additionalfile")); Assert.Equal(0, args.AdditionalFiles.Length); args = DefaultParse(new[] { "/additionalfile:", "a.cs" }, WorkingDirectory); args.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "additionalfile")); Assert.Equal(0, args.AdditionalFiles.Length); } [Fact] public void ParseEditorConfig() { var args = DefaultParse(new[] { "/analyzerconfig:.editorconfig", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths.Single()); args = DefaultParse(new[] { "/analyzerconfig:.editorconfig", "a.cs", "/analyzerconfig:subdir\\.editorconfig" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AnalyzerConfigPaths.Length); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[0]); Assert.Equal(Path.Combine(WorkingDirectory, "subdir\\.editorconfig"), args.AnalyzerConfigPaths[1]); args = DefaultParse(new[] { "/analyzerconfig:.editorconfig", "a.cs", "/analyzerconfig:.editorconfig" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AnalyzerConfigPaths.Length); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[0]); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[1]); args = DefaultParse(new[] { "/analyzerconfig:..\\.editorconfig", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "..\\.editorconfig"), args.AnalyzerConfigPaths.Single()); args = DefaultParse(new[] { "/analyzerconfig:.editorconfig;subdir\\.editorconfig", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AnalyzerConfigPaths.Length); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[0]); Assert.Equal(Path.Combine(WorkingDirectory, "subdir\\.editorconfig"), args.AnalyzerConfigPaths[1]); args = DefaultParse(new[] { "/analyzerconfig", "a.cs" }, WorkingDirectory); args.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<file list>' for 'analyzerconfig' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "analyzerconfig").WithLocation(1, 1)); Assert.Equal(0, args.AnalyzerConfigPaths.Length); args = DefaultParse(new[] { "/analyzerconfig:", "a.cs" }, WorkingDirectory); args.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<file list>' for 'analyzerconfig' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "analyzerconfig").WithLocation(1, 1)); Assert.Equal(0, args.AnalyzerConfigPaths.Length); } [Fact] public void NullablePublicOnly() { string source = @"namespace System.Runtime.CompilerServices { public sealed class NullableAttribute : Attribute { } // missing constructor } public class Program { private object? F = null; }"; string errorMessage = "error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'"; string filePath = Temp.CreateFile().WriteAllText(source).Path; int exitCode; string output; // No /feature (exitCode, output) = compileAndRun(featureOpt: null); Assert.Equal(1, exitCode); Assert.Contains(errorMessage, output, StringComparison.Ordinal); // /features:nullablePublicOnly (exitCode, output) = compileAndRun("/features:nullablePublicOnly"); Assert.Equal(0, exitCode); Assert.DoesNotContain(errorMessage, output, StringComparison.Ordinal); // /features:nullablePublicOnly=true (exitCode, output) = compileAndRun("/features:nullablePublicOnly=true"); Assert.Equal(0, exitCode); Assert.DoesNotContain(errorMessage, output, StringComparison.Ordinal); // /features:nullablePublicOnly=false (the value is ignored) (exitCode, output) = compileAndRun("/features:nullablePublicOnly=false"); Assert.Equal(0, exitCode); Assert.DoesNotContain(errorMessage, output, StringComparison.Ordinal); CleanupAllGeneratedFiles(filePath); (int, string) compileAndRun(string featureOpt) { var args = new[] { "/target:library", "/preferreduilang:en", "/langversion:8", "/nullable+", filePath }; if (featureOpt != null) args = args.Concat(featureOpt).ToArray(); var compiler = CreateCSharpCompiler(null, WorkingDirectory, args); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = compiler.Run(outWriter); return (exitCode, outWriter.ToString()); }; } // See also NullableContextTests.NullableAnalysisFlags_01(). [Fact] public void NullableAnalysisFlags() { string source = @"class Program { #nullable enable static object F1() => null; #nullable disable static object F2() => null; }"; string filePath = Temp.CreateFile().WriteAllText(source).Path; string fileName = Path.GetFileName(filePath); string[] expectedWarningsAll = new[] { fileName + "(4,27): warning CS8603: Possible null reference return." }; string[] expectedWarningsNone = Array.Empty<string>(); AssertEx.Equal(expectedWarningsAll, compileAndRun(featureOpt: null)); AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis")); AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=always")); AssertEx.Equal(expectedWarningsNone, compileAndRun("/features:run-nullable-analysis=never")); AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=ALWAYS")); // unrecognized value (incorrect case) ignored AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=NEVER")); // unrecognized value (incorrect case) ignored AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=true")); // unrecognized value ignored AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=false")); // unrecognized value ignored AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=unknown")); // unrecognized value ignored CleanupAllGeneratedFiles(filePath); string[] compileAndRun(string featureOpt) { var args = new[] { "/target:library", "/preferreduilang:en", "/nologo", filePath }; if (featureOpt != null) args = args.Concat(featureOpt).ToArray(); var compiler = CreateCSharpCompiler(null, WorkingDirectory, args); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = compiler.Run(outWriter); return outWriter.ToString().Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); }; } [Fact] public void Compiler_Uses_DriverCache() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); int sourceCallbackCount = 0; var generator = new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount++; }); }); // with no cache, we'll see the callback execute multiple times RunWithNoCache(); Assert.Equal(1, sourceCallbackCount); RunWithNoCache(); Assert.Equal(2, sourceCallbackCount); RunWithNoCache(); Assert.Equal(3, sourceCallbackCount); // now re-run with a cache GeneratorDriverCache cache = new GeneratorDriverCache(); sourceCallbackCount = 0; RunWithCache(); Assert.Equal(1, sourceCallbackCount); RunWithCache(); Assert.Equal(1, sourceCallbackCount); RunWithCache(); Assert.Equal(1, sourceCallbackCount); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); void RunWithNoCache() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview" }, generators: new[] { generator.AsSourceGenerator() }, analyzers: null); void RunWithCache() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); } [Fact] public void Compiler_Doesnt_Use_Cache_From_Other_Compilation() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); int sourceCallbackCount = 0; var generator = new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount++; }); }); // now re-run with a cache GeneratorDriverCache cache = new GeneratorDriverCache(); sourceCallbackCount = 0; RunWithCache("1.dll"); Assert.Equal(1, sourceCallbackCount); RunWithCache("1.dll"); Assert.Equal(1, sourceCallbackCount); // now emulate a new compilation, and check we were invoked, but only once RunWithCache("2.dll"); Assert.Equal(2, sourceCallbackCount); RunWithCache("2.dll"); Assert.Equal(2, sourceCallbackCount); // now re-run our first compilation RunWithCache("1.dll"); Assert.Equal(2, sourceCallbackCount); // a new one RunWithCache("3.dll"); Assert.Equal(3, sourceCallbackCount); // and another old one RunWithCache("2.dll"); Assert.Equal(3, sourceCallbackCount); RunWithCache("1.dll"); Assert.Equal(3, sourceCallbackCount); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); void RunWithCache(string outputPath) => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/out:" + outputPath }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); } [Fact] public void Compiler_Can_Disable_DriverCache() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); int sourceCallbackCount = 0; var generator = new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount++; }); }); // run with the cache GeneratorDriverCache cache = new GeneratorDriverCache(); sourceCallbackCount = 0; RunWithCache(); Assert.Equal(1, sourceCallbackCount); RunWithCache(); Assert.Equal(1, sourceCallbackCount); RunWithCache(); Assert.Equal(1, sourceCallbackCount); // now re-run with the cache disabled sourceCallbackCount = 0; RunWithCacheDisabled(); Assert.Equal(1, sourceCallbackCount); RunWithCacheDisabled(); Assert.Equal(2, sourceCallbackCount); RunWithCacheDisabled(); Assert.Equal(3, sourceCallbackCount); // now clear the cache as well as disabling, and verify we don't put any entries into it either cache = new GeneratorDriverCache(); sourceCallbackCount = 0; RunWithCacheDisabled(); Assert.Equal(1, sourceCallbackCount); Assert.Equal(0, cache.CacheSize); RunWithCacheDisabled(); Assert.Equal(2, sourceCallbackCount); Assert.Equal(0, cache.CacheSize); RunWithCacheDisabled(); Assert.Equal(3, sourceCallbackCount); Assert.Equal(0, cache.CacheSize); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); void RunWithCache() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); void RunWithCacheDisabled() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/features:disable-generator-cache" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); } [Fact] public void Adding_Or_Removing_A_Generator_Invalidates_Cache() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); int sourceCallbackCount = 0; int sourceCallbackCount2 = 0; var generator = new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount++; }); }); var generator2 = new PipelineCallbackGenerator2((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount2++; }); }); // run with the cache GeneratorDriverCache cache = new GeneratorDriverCache(); RunWithOneGenerator(); Assert.Equal(1, sourceCallbackCount); Assert.Equal(0, sourceCallbackCount2); RunWithOneGenerator(); Assert.Equal(1, sourceCallbackCount); Assert.Equal(0, sourceCallbackCount2); RunWithTwoGenerators(); Assert.Equal(2, sourceCallbackCount); Assert.Equal(1, sourceCallbackCount2); RunWithTwoGenerators(); Assert.Equal(2, sourceCallbackCount); Assert.Equal(1, sourceCallbackCount2); // this seems counterintuitive, but when the only thing to change is the generator, we end up back at the state of the project when // we just ran a single generator. Thus we already have an entry in the cache we can use (the one created by the original call to // RunWithOneGenerator above) meaning we can use the previously cached results and not run. RunWithOneGenerator(); Assert.Equal(2, sourceCallbackCount); Assert.Equal(1, sourceCallbackCount2); void RunWithOneGenerator() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); void RunWithTwoGenerators() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview" }, generators: new[] { generator.AsSourceGenerator(), generator2.AsSourceGenerator() }, driverCache: cache, analyzers: null); } private static int OccurrenceCount(string source, string word) { var n = 0; var index = source.IndexOf(word, StringComparison.Ordinal); while (index >= 0) { ++n; index = source.IndexOf(word, index + word.Length, StringComparison.Ordinal); } return n; } private string VerifyOutput(TempDirectory sourceDir, TempFile sourceFile, bool includeCurrentAssemblyAsAnalyzerReference = true, string[] additionalFlags = null, int expectedInfoCount = 0, int expectedWarningCount = 0, int expectedErrorCount = 0, int? expectedExitCode = null, bool errorlog = false, IEnumerable<ISourceGenerator> generators = null, GeneratorDriverCache driverCache = null, params DiagnosticAnalyzer[] analyzers) { var args = new[] { "/nologo", "/preferreduilang:en", "/t:library", sourceFile.Path }; if (includeCurrentAssemblyAsAnalyzerReference) { args = args.Append("/a:" + Assembly.GetExecutingAssembly().Location); } if (errorlog) { args = args.Append("/errorlog:errorlog"); } if (additionalFlags != null) { args = args.Append(additionalFlags); } var csc = CreateCSharpCompiler(null, sourceDir.Path, args, analyzers: analyzers.ToImmutableArrayOrEmpty(), generators: generators.ToImmutableArrayOrEmpty(), driverCache: driverCache); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = csc.Run(outWriter); var output = outWriter.ToString(); expectedExitCode ??= expectedErrorCount > 0 ? 1 : 0; Assert.True( expectedExitCode == exitCode, string.Format("Expected exit code to be '{0}' was '{1}'.{2} Output:{3}{4}", expectedExitCode, exitCode, Environment.NewLine, Environment.NewLine, output)); Assert.DoesNotContain("hidden", output, StringComparison.Ordinal); if (expectedInfoCount == 0) { Assert.DoesNotContain("info", output, StringComparison.Ordinal); } else { // Info diagnostics are only logged with /errorlog. Assert.True(errorlog); Assert.Equal(expectedInfoCount, OccurrenceCount(output, "info")); } if (expectedWarningCount == 0) { Assert.DoesNotContain("warning", output, StringComparison.Ordinal); } else { Assert.Equal(expectedWarningCount, OccurrenceCount(output, "warning")); } if (expectedErrorCount == 0) { Assert.DoesNotContain("error", output, StringComparison.Ordinal); } else { Assert.Equal(expectedErrorCount, OccurrenceCount(output, "error")); } return output; } [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [Fact] public void NoWarnAndWarnAsError_AnalyzerDriverWarnings() { // This assembly has an abstract MockAbstractDiagnosticAnalyzer type which should cause // compiler warning CS8032 to be produced when compilations created in this test try to load it. string source = @"using System;"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS8032 can be suppressed via /warn:0. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that compiler warning CS8032 can be individually suppressed via /nowarn:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:CS8032" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that compiler warning CS8032 can be promoted to an error via /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS8032 can be individually promoted to an error via /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:8032" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [Fact] public void NoWarnAndWarnAsError_HiddenDiagnostic() { // This assembly has a HiddenDiagnosticAnalyzer type which should produce custom hidden // diagnostics for #region directives present in the compilations created in this test. var source = @"using System; #region Region #endregion"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that /nowarn: has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warnaserror+ has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:8032" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that /warnaserror- has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warnaserror: promotes custom hidden diagnostic Hidden01 to an error. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Hidden01" }, expectedWarningCount: 1, expectedErrorCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal); // TEST: Verify that /warnaserror-: has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Hidden01", "/nowarn:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Hidden01", "/warnaserror:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/nowarn:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Hidden01", "/warnaserror-:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror:Hidden01" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that /warn:0 has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Hidden01", "/warn:0" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Hidden01", "/warnaserror-:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/warnaserror+:Hidden01" }, expectedWarningCount: 1, expectedErrorCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror+:Hidden01" }, expectedWarningCount: 1, expectedErrorCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/warnaserror+:Hidden01", "/nowarn:8032" }, expectedErrorCount: 1); Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Hidden01", "/warnaserror+", "/nowarn:8032" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Hidden01", "/warnaserror-" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/warnaserror-:Hidden01", "/nowarn:8032" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/warnaserror-" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror-:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [WorkItem(42166, "https://github.com/dotnet/roslyn/issues/42166")] [CombinatorialData, Theory] public void NoWarnAndWarnAsError_InfoDiagnostic(bool errorlog) { // NOTE: Info diagnostics are only logged on command line when /errorlog is specified. See https://github.com/dotnet/roslyn/issues/42166 for details. // This assembly has an InfoDiagnosticAnalyzer type which should produce custom info // diagnostics for the #pragma warning restore directives present in the compilations created in this test. var source = @"using System; #pragma warning restore"; var name = "a.cs"; string output; output = GetOutput(name, source, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 suppresses custom info diagnostic Info01. output = GetOutput(name, source, additionalFlags: new[] { "/warn:0" }, errorlog: errorlog); // TEST: Verify that custom info diagnostic Info01 can be individually suppressed via /nowarn:. output = GetOutput(name, source, additionalFlags: new[] { "/nowarn:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that custom info diagnostic Info01 can never be promoted to an error via /warnaserror+. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that custom info diagnostic Info01 is still reported as an info when /warnaserror- is used. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that custom info diagnostic Info01 can be individually promoted to an error via /warnaserror:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror:Info01" }, expectedWarningCount: 1, expectedErrorCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that custom info diagnostic Info01 is still reported as an info when passed to /warnaserror-:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify /nowarn overrides /warnaserror. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror:Info01", "/nowarn:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn overrides /warnaserror. output = GetOutput(name, source, additionalFlags: new[] { "/nowarn:Info01", "/warnaserror:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn overrides /warnaserror-. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/nowarn:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn overrides /warnaserror-. output = GetOutput(name, source, additionalFlags: new[] { "/nowarn:Info01", "/warnaserror-:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 has no impact on custom info diagnostic Info01. output = GetOutput(name, source, additionalFlags: new[] { "/warn:0", "/warnaserror:Info01" }, errorlog: errorlog); // TEST: Verify that /warn:0 has no impact on custom info diagnostic Info01. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror:Info01", "/warn:0" }); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+:Info01", "/warnaserror-:Info01" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/warnaserror+:Info01" }, expectedWarningCount: 1, expectedErrorCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-", "/warnaserror+:Info01" }, expectedWarningCount: 1, expectedErrorCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/warnaserror+", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+:Info01", "/warnaserror+", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+", "/warnaserror+:Info01", "/nowarn:8032" }, expectedErrorCount: 1, errorlog: errorlog); Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+:Info01", "/warnaserror-" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+", "/warnaserror-:Info01", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/warnaserror-" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-", "/warnaserror-:Info01" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); } private string GetOutput( string name, string source, bool includeCurrentAssemblyAsAnalyzerReference = true, string[] additionalFlags = null, int expectedInfoCount = 0, int expectedWarningCount = 0, int expectedErrorCount = 0, bool errorlog = false) { var dir = Temp.CreateDirectory(); var file = dir.CreateFile(name); file.WriteAllText(source); var output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference, additionalFlags, expectedInfoCount, expectedWarningCount, expectedErrorCount, null, errorlog); CleanupAllGeneratedFiles(file.Path); return output; } [WorkItem(11368, "https://github.com/dotnet/roslyn/issues/11368")] [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [WorkItem(998069, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/998069")] [WorkItem(998724, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/998724")] [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [Fact] public void NoWarnAndWarnAsError_WarningDiagnostic() { // This assembly has a WarningDiagnosticAnalyzer type which should produce custom warning // diagnostics for source types present in the compilations created in this test. string source = @" class C { static void Main() { int i; } } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, expectedWarningCount: 3); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be suppressed via /warn:0. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be individually suppressed via /nowarn:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that diagnostic ids are processed in case-sensitive fashion inside /nowarn:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:cs0168,warning01,700000" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be promoted to errors via /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/nowarn:8032" }, expectedErrorCount: 2); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be promoted to errors via /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:8032" }, expectedErrorCount: 2); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); // TEST: Verify that /warnaserror- keeps compiler warning CS0168 as well as custom warning diagnostic Warning01 as warnings. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that custom warning diagnostic Warning01 can be individually promoted to an error via /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Something,Warning01" }, expectedWarningCount: 2, expectedErrorCount: 1); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS0168 can be individually promoted to an error via /warnaserror+:. // This doesn't work correctly currently - promoting compiler warning CS0168 to an error causes us to no longer report any custom warning diagnostics as errors (Bug 998069). output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:CS0168" }, expectedWarningCount: 2, expectedErrorCount: 1); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that diagnostic ids are processed in case-sensitive fashion inside /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:cs0168,warning01,58000" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that custom warning diagnostic Warning01 as well as compiler warning CS0168 can be promoted to errors via /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:CS0168,Warning01" }, expectedWarningCount: 1, expectedErrorCount: 2); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror+" }); // TEST: Verify that /warn:0 overrides /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warn:0" }); // TEST: Verify that /warn:0 overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warn:0" }); // TEST: Verify that /warn:0 overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror-" }); // TEST: Verify that /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Something,CS0168,Warning01", "/nowarn:0168,Warning01,58000" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000", "/warnaserror:Something,CS0168,Warning01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Something,CS0168,Warning01", "/nowarn:0168,Warning01,58000" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000", "/warnaserror-:Something,CS0168,Warning01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:0168,Warning01,58000,8032" }); // TEST: Verify that /nowarn: overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000,8032", "/warnaserror+" }); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/nowarn:0168,Warning01,58000,8032" }); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000,8032", "/warnaserror-" }); // TEST: Verify that /warn:0 overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Something,CS0168,Warning01", "/warn:0" }); // TEST: Verify that /warn:0 overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror:Something,CS0168,Warning01" }); // TEST: Verify that last /warnaserror[+/-] flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-] flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warnaserror-" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Warning01", "/warnaserror+:Warning01" }, expectedWarningCount: 2, expectedErrorCount: 1); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Warning01", "/warnaserror-:Warning01" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Warning01,CS0168,58000,8032", "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warnaserror-:Warning01,CS0168,58000,8032" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Warning01,58000,8032", "/warnaserror-" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror+:Warning01" }, expectedWarningCount: 2, expectedErrorCount: 1); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Warning01,CS0168,58000", "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warnaserror+:Warning01,CS0168,58000" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Warning01,58000,8032", "/warnaserror-" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror-:Warning01,58000,8032" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [Fact] public void NoWarnAndWarnAsError_ErrorDiagnostic() { // This assembly has an ErrorDiagnosticAnalyzer type which should produce custom error // diagnostics for #pragma warning disable directives present in the compilations created in this test. string source = @"using System; #pragma warning disable"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); // TEST: Verify that custom error diagnostic Error01 can't be suppressed via /warn:0. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" }, expectedErrorCount: 1); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); // TEST: Verify that custom error diagnostic Error01 can be suppressed via /nowarn:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:Error01" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror+:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror+:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Error01", "/nowarn:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/nowarn:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror-" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Error01", "/nowarn:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror-:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that nothing bad happens when using /warnaserror[+/-] when custom error diagnostic Error01 is present. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-" }, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); // TEST: Verify that nothing bad happens if someone passes custom error diagnostic Error01 to /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Error01" }, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Error01" }, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Error01" }, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void ConsistentErrorMessageWhenProvidingNoKeyFile() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim()); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void ConsistentErrorMessageWhenProvidingEmptyKeyFile() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:\"\"", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim()); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void ConsistentErrorMessageWhenProvidingNoKeyFile_PublicSign() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:", "/publicsign", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim()); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void ConsistentErrorMessageWhenProvidingEmptyKeyFile_PublicSign() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:\"\"", "/publicsign", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim()); } [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [Fact] public void NoWarnAndWarnAsError_CompilerErrorDiagnostic() { string source = @"using System; class C { static void Main() { int i = new Exception(); } }"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); // TEST: Verify that compiler error CS0029 can't be suppressed via /warn:0. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warn:0" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); // TEST: Verify that compiler error CS0029 can't be suppressed via /nowarn:. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:29" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:CS0029" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); // TEST: Verify that nothing bad happens when using /warnaserror[+/-] when compiler error CS0029 is present. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror-" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); // TEST: Verify that nothing bad happens if someone passes compiler error CS0029 to /warnaserror[+/-]:. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror:0029" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror+:CS0029" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror-:29" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror-:CS0029" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [Fact] public void WarnAsError_LastOneWins1() { var arguments = DefaultParse(new[] { "/warnaserror-:3001", "/warnaserror" }, null); var options = arguments.CompilationOptions; var comp = CreateCompilation(@"[assembly: System.CLSCompliant(true)] public class C { public void M(ushort i) { } public static void Main(string[] args) {} }", options: options); comp.VerifyDiagnostics( // (4,26): warning CS3001: Argument type 'ushort' is not CLS-compliant // public void M(ushort i) Diagnostic(ErrorCode.WRN_CLS_BadArgType, "i") .WithArguments("ushort") .WithLocation(4, 26) .WithWarningAsError(true)); } [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [Fact] public void WarnAsError_LastOneWins2() { var arguments = DefaultParse(new[] { "/warnaserror", "/warnaserror-:3001" }, null); var options = arguments.CompilationOptions; var comp = CreateCompilation(@"[assembly: System.CLSCompliant(true)] public class C { public void M(ushort i) { } public static void Main(string[] args) {} }", options: options); comp.VerifyDiagnostics( // (4,26): warning CS3001: Argument type 'ushort' is not CLS-compliant // public void M(ushort i) Diagnostic(ErrorCode.WRN_CLS_BadArgType, "i") .WithArguments("ushort") .WithLocation(4, 26) .WithWarningAsError(false)); } [WorkItem(1091972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091972")] [WorkItem(444, "CodePlex")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void Bug1091972() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText( @" /// <summary>ABC...XYZ</summary> class C { static void Main() { var textStreamReader = new System.IO.StreamReader(typeof(C).Assembly.GetManifestResourceStream(""doc.xml"")); System.Console.WriteLine(textStreamReader.ReadToEnd()); } } "); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /doc:doc.xml /out:out.exe /resource:doc.xml \"{0}\"", src.ToString()), startFolder: dir.ToString()); Assert.Equal("", output.Trim()); Assert.True(File.Exists(Path.Combine(dir.ToString(), "doc.xml"))); var expected = @"<?xml version=""1.0""?> <doc> <assembly> <name>out</name> </assembly> <members> <member name=""T:C""> <summary>ABC...XYZ</summary> </member> </members> </doc>".Trim(); using (var reader = new StreamReader(Path.Combine(dir.ToString(), "doc.xml"))) { var content = reader.ReadToEnd(); Assert.Equal(expected, content.Trim()); } output = ProcessUtilities.RunAndGetOutput(Path.Combine(dir.ToString(), "out.exe"), startFolder: dir.ToString()); Assert.Equal(expected, output.Trim()); CleanupAllGeneratedFiles(src.Path); } [ConditionalFact(typeof(WindowsOnly))] public void CommandLineMisc() { CSharpCommandLineArguments args = null; string baseDirectory = @"c:\test"; Func<string, CSharpCommandLineArguments> parse = (x) => FullParse(x, baseDirectory); args = parse(@"/out:""a.exe"""); Assert.Equal(@"a.exe", args.OutputFileName); args = parse(@"/pdb:""a.pdb"""); Assert.Equal(Path.Combine(baseDirectory, @"a.pdb"), args.PdbPath); // The \ here causes " to be treated as a quote, not as an escaping construct args = parse(@"a\""b c""\d.cs"); Assert.Equal( new[] { @"c:\test\a""b", @"c:\test\c\d.cs" }, args.SourceFiles.Select(x => x.Path)); args = parse(@"a\\""b c""\d.cs"); Assert.Equal( new[] { @"c:\test\a\b c\d.cs" }, args.SourceFiles.Select(x => x.Path)); args = parse(@"/nostdlib /r:""a.dll"",""b.dll"" c.cs"); Assert.Equal( new[] { @"a.dll", @"b.dll" }, args.MetadataReferences.Select(x => x.Reference)); args = parse(@"/nostdlib /r:""a-s.dll"",""b-s.dll"" c.cs"); Assert.Equal( new[] { @"a-s.dll", @"b-s.dll" }, args.MetadataReferences.Select(x => x.Reference)); args = parse(@"/nostdlib /r:""a,;s.dll"",""b,;s.dll"" c.cs"); Assert.Equal( new[] { @"a,;s.dll", @"b,;s.dll" }, args.MetadataReferences.Select(x => x.Reference)); } [Fact] public void CommandLine_ScriptRunner1() { var args = ScriptParse(new[] { "--", "script.csx", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "--", "@script.csx", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "@script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "--", "-script.csx", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "-script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "script.csx", "--", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "--", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "script.csx", "a", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "a", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "script.csx", "a", "--", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "a", "--", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "-i", "script.csx", "a", "b", "c" }, baseDirectory: WorkingDirectory); Assert.True(args.InteractiveMode); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "a", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "-i", "--", "script.csx", "a", "b", "c" }, baseDirectory: WorkingDirectory); Assert.True(args.InteractiveMode); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "a", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "-i", "--", "--", "--" }, baseDirectory: WorkingDirectory); Assert.True(args.InteractiveMode); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "--") }, args.SourceFiles.Select(f => f.Path)); Assert.True(args.SourceFiles[0].IsScript); AssertEx.Equal(new[] { "--" }, args.ScriptArguments); // TODO: fails on Linux (https://github.com/dotnet/roslyn/issues/5904) // Result: C:\/script.csx //args = ScriptParse(new[] { "-i", "script.csx", "--", "--" }, baseDirectory: @"C:\"); //Assert.True(args.InteractiveMode); //AssertEx.Equal(new[] { @"C:\script.csx" }, args.SourceFiles.Select(f => f.Path)); //Assert.True(args.SourceFiles[0].IsScript); //AssertEx.Equal(new[] { "--" }, args.ScriptArguments); } [WorkItem(127403, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/127403")] [Fact] public void ParseSeparatedPaths_QuotedComma() { var paths = CSharpCommandLineParser.ParseSeparatedPaths(@"""a, b"""); Assert.Equal( new[] { @"a, b" }, paths); } [Fact] [CompilerTrait(CompilerFeature.Determinism)] public void PathMapParser() { var s = PathUtilities.DirectorySeparatorStr; var parsedArgs = DefaultParse(new[] { "/pathmap:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ImmutableArray.Create<KeyValuePair<string, string>>(), parsedArgs.PathMap); parsedArgs = DefaultParse(new[] { "/pathmap:K1=V1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("K1" + s, "V1" + s), parsedArgs.PathMap[0]); parsedArgs = DefaultParse(new[] { $"/pathmap:abc{s}=/", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("abc" + s, "/"), parsedArgs.PathMap[0]); parsedArgs = DefaultParse(new[] { "/pathmap:K1=V1,K2=V2", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("K1" + s, "V1" + s), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create("K2" + s, "V2" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { "/pathmap:,", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ImmutableArray.Create<KeyValuePair<string, string>>(), parsedArgs.PathMap); parsedArgs = DefaultParse(new[] { "/pathmap:,,", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:,,,", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:k=,=v", "a.cs" }, WorkingDirectory); Assert.Equal(2, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[1].Code); parsedArgs = DefaultParse(new[] { "/pathmap:k=v=bad", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:k=", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:=v", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:\"supporting spaces=is hard\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("supporting spaces" + s, "is hard" + s), parsedArgs.PathMap[0]); parsedArgs = DefaultParse(new[] { "/pathmap:\"K 1=V 1\",\"K 2=V 2\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("K 1" + s, "V 1" + s), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create("K 2" + s, "V 2" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { "/pathmap:\"K 1\"=\"V 1\",\"K 2\"=\"V 2\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("K 1" + s, "V 1" + s), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create("K 2" + s, "V 2" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { "/pathmap:\"a ==,,b\"=\"1,,== 2\",\"x ==,,y\"=\"3 4\",", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("a =,b" + s, "1,= 2" + s), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create("x =,y" + s, "3 4" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { @"/pathmap:C:\temp\=/_1/,C:\temp\a\=/_2/,C:\temp\a\b\=/_3/", "a.cs", @"a\b.cs", @"a\b\c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create(@"C:\temp\a\b\", "/_3/"), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create(@"C:\temp\a\", "/_2/"), parsedArgs.PathMap[1]); Assert.Equal(KeyValuePairUtil.Create(@"C:\temp\", "/_1/"), parsedArgs.PathMap[2]); } [Theory] [InlineData("", new string[0])] [InlineData(",", new[] { "", "" })] [InlineData(",,", new[] { "," })] [InlineData(",,,", new[] { ",", "" })] [InlineData(",,,,", new[] { ",," })] [InlineData("a,", new[] { "a", "" })] [InlineData("a,b", new[] { "a", "b" })] [InlineData(",,a,,,,,b,,", new[] { ",a,,", "b," })] public void SplitWithDoubledSeparatorEscaping(string str, string[] expected) { AssertEx.Equal(expected, CommandLineParser.SplitWithDoubledSeparatorEscaping(str, ',')); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] [CompilerTrait(CompilerFeature.Determinism)] public void PathMapPdbParser() { var dir = Path.Combine(WorkingDirectory, "a"); var parsedArgs = DefaultParse(new[] { $@"/pathmap:{dir}=b:\", "a.cs", @"/pdb:a\data.pdb", "/debug:full" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(dir, @"data.pdb"), parsedArgs.PdbPath); // This value is calculate during Emit phases and should be null even in the face of a pathmap targeting it. Assert.Null(parsedArgs.EmitOptions.PdbFilePath); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] [CompilerTrait(CompilerFeature.Determinism)] public void PathMapPdbEmit() { void AssertPdbEmit(TempDirectory dir, string pdbPath, string pePdbPath, params string[] extraArgs) { var source = @"class Program { static void Main() { } }"; var src = dir.CreateFile("a.cs").WriteAllText(source); var defaultArgs = new[] { "/nologo", "a.cs", "/out:a.exe", "/debug:full", $"/pdb:{pdbPath}" }; var isDeterministic = extraArgs.Contains("/deterministic"); var args = defaultArgs.Concat(extraArgs).ToArray(); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, args); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var exePath = Path.Combine(dir.Path, "a.exe"); Assert.True(File.Exists(exePath)); Assert.True(File.Exists(pdbPath)); using (var peStream = File.OpenRead(exePath)) { PdbValidation.ValidateDebugDirectory(peStream, null, pePdbPath, hashAlgorithm: default, hasEmbeddedPdb: false, isDeterministic); } } // Case with no mappings using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, pdbPath); } // Simple mapping using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, @"q:\a.pdb", $@"/pathmap:{dir.Path}=q:\"); } // Simple mapping deterministic using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, @"q:\a.pdb", $@"/pathmap:{dir.Path}=q:\", "/deterministic"); } // Partial mapping using (var dir = new DisposableDirectory(Temp)) { dir.CreateDirectory("pdb"); var pdbPath = Path.Combine(dir.Path, @"pdb\a.pdb"); AssertPdbEmit(dir, pdbPath, @"q:\pdb\a.pdb", $@"/pathmap:{dir.Path}=q:\"); } // Legacy feature flag using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, @"a.pdb", $@"/features:pdb-path-determinism"); } // Unix path map using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, @"/a.pdb", $@"/pathmap:{dir.Path}=/"); } // Multi-specified path map with mixed slashes using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, "/goo/a.pdb", $"/pathmap:{dir.Path}=/goo,{dir.Path}{PathUtilities.DirectorySeparatorChar}=/bar"); } } [CompilerTrait(CompilerFeature.Determinism)] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void DeterministicPdbsRegardlessOfBitness() { var dir = Temp.CreateDirectory(); var dir32 = dir.CreateDirectory("32"); var dir64 = dir.CreateDirectory("64"); var programExe32 = dir32.CreateFile("Program.exe"); var programPdb32 = dir32.CreateFile("Program.pdb"); var programExe64 = dir64.CreateFile("Program.exe"); var programPdb64 = dir64.CreateFile("Program.pdb"); var sourceFile = dir.CreateFile("Source.cs").WriteAllText(@" using System; using System.Linq; using System.Collections.Generic; namespace N { using I4 = System.Int32; class Program { public static IEnumerable<int> F() { I4 x = 1; yield return 1; yield return x; } public static void Main(string[] args) { dynamic x = 1; const int a = 1; F().ToArray(); Console.WriteLine(x + a); } } }"); var csc32src = $@" using System; using System.Reflection; class Runner {{ static int Main(string[] args) {{ var assembly = Assembly.LoadFrom(@""{s_CSharpCompilerExecutable}""); var program = assembly.GetType(""Microsoft.CodeAnalysis.CSharp.CommandLine.Program""); var main = program.GetMethod(""Main""); return (int)main.Invoke(null, new object[] {{ args }}); }} }} "; var csc32 = CreateCompilationWithMscorlib46(csc32src, options: TestOptions.ReleaseExe.WithPlatform(Platform.X86), assemblyName: "csc32"); var csc32exe = dir.CreateFile("csc32.exe").WriteAllBytes(csc32.EmitToArray()); dir.CopyFile(Path.ChangeExtension(s_CSharpCompilerExecutable, ".exe.config"), "csc32.exe.config"); dir.CopyFile(Path.Combine(Path.GetDirectoryName(s_CSharpCompilerExecutable), "csc.rsp")); var output = ProcessUtilities.RunAndGetOutput(csc32exe.Path, $@"/nologo /debug:full /deterministic /out:Program.exe /pathmap:""{dir32.Path}""=X:\ ""{sourceFile.Path}""", expectedRetCode: 0, startFolder: dir32.Path); Assert.Equal("", output); output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $@"/nologo /debug:full /deterministic /out:Program.exe /pathmap:""{dir64.Path}""=X:\ ""{sourceFile.Path}""", expectedRetCode: 0, startFolder: dir64.Path); Assert.Equal("", output); AssertEx.Equal(programExe32.ReadAllBytes(), programExe64.ReadAllBytes()); AssertEx.Equal(programPdb32.ReadAllBytes(), programPdb64.ReadAllBytes()); } [WorkItem(7588, "https://github.com/dotnet/roslyn/issues/7588")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void Version() { var folderName = Temp.CreateDirectory().ToString(); var argss = new[] { "/version", "a.cs /version /preferreduilang:en", "/version /nologo", "/version /help", }; foreach (var args in argss) { var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, args, startFolder: folderName); Assert.Equal(s_compilerVersion, output.Trim()); } } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void RefOut() { var dir = Temp.CreateDirectory(); var refDir = dir.CreateDirectory("ref"); var src = dir.CreateFile("a.cs"); src.WriteAllText(@" public class C { /// <summary>Main method</summary> public static void Main() { System.Console.Write(""Hello""); } /// <summary>Private method</summary> private static void PrivateMethod() { System.Console.Write(""Private""); } }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/out:a.exe", "/refout:ref/a.dll", "/doc:doc.xml", "/deterministic", "/langversion:7", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var exe = Path.Combine(dir.Path, "a.exe"); Assert.True(File.Exists(exe)); MetadataReaderUtils.VerifyPEMetadata(exe, new[] { "TypeDefinition:<Module>", "TypeDefinition:C" }, new[] { "MethodDefinition:Void C.Main()", "MethodDefinition:Void C.PrivateMethod()", "MethodDefinition:Void C..ctor()" }, new[] { "CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute" } ); var doc = Path.Combine(dir.Path, "doc.xml"); Assert.True(File.Exists(doc)); var content = File.ReadAllText(doc); var expectedDoc = @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""M:C.Main""> <summary>Main method</summary> </member> <member name=""M:C.PrivateMethod""> <summary>Private method</summary> </member> </members> </doc>"; Assert.Equal(expectedDoc, content.Trim()); var output = ProcessUtilities.RunAndGetOutput(exe, startFolder: dir.Path); Assert.Equal("Hello", output.Trim()); var refDll = Path.Combine(refDir.Path, "a.dll"); Assert.True(File.Exists(refDll)); // The types and members that are included needs further refinement. // See issue https://github.com/dotnet/roslyn/issues/17612 MetadataReaderUtils.VerifyPEMetadata(refDll, new[] { "TypeDefinition:<Module>", "TypeDefinition:C" }, new[] { "MethodDefinition:Void C.Main()", "MethodDefinition:Void C..ctor()" }, new[] { "CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute", "ReferenceAssemblyAttribute" } ); // Clean up temp files CleanupAllGeneratedFiles(dir.Path); CleanupAllGeneratedFiles(refDir.Path); } [Fact] public void RefOutWithError() { var dir = Temp.CreateDirectory(); dir.CreateDirectory("ref"); var src = dir.CreateFile("a.cs"); src.WriteAllText(@"class C { public static void Main() { error(); } }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/out:a.dll", "/refout:ref/a.dll", "/deterministic", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); var dll = Path.Combine(dir.Path, "a.dll"); Assert.False(File.Exists(dll)); var refDll = Path.Combine(dir.Path, Path.Combine("ref", "a.dll")); Assert.False(File.Exists(refDll)); Assert.Equal("a.cs(1,39): error CS0103: The name 'error' does not exist in the current context", outWriter.ToString().Trim()); // Clean up temp files CleanupAllGeneratedFiles(dir.Path); } [Fact] public void RefOnly() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText(@" using System; class C { /// <summary>Main method</summary> public static void Main() { error(); // semantic error in method body } private event Action E1 { add { } remove { } } private event Action E2; /// <summary>Private Class Field</summary> private int field; /// <summary>Private Struct</summary> private struct S { /// <summary>Private Struct Field</summary> private int field; } }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/out:a.dll", "/refonly", "/debug", "/deterministic", "/langversion:7", "/doc:doc.xml", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal("", outWriter.ToString()); Assert.Equal(0, exitCode); var refDll = Path.Combine(dir.Path, "a.dll"); Assert.True(File.Exists(refDll)); // The types and members that are included needs further refinement. // See issue https://github.com/dotnet/roslyn/issues/17612 MetadataReaderUtils.VerifyPEMetadata(refDll, new[] { "TypeDefinition:<Module>", "TypeDefinition:C", "TypeDefinition:S" }, new[] { "MethodDefinition:Void C.Main()", "MethodDefinition:Void C..ctor()" }, new[] { "CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute", "ReferenceAssemblyAttribute" } ); var pdb = Path.Combine(dir.Path, "a.pdb"); Assert.False(File.Exists(pdb)); var doc = Path.Combine(dir.Path, "doc.xml"); Assert.True(File.Exists(doc)); var content = File.ReadAllText(doc); var expectedDoc = @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""M:C.Main""> <summary>Main method</summary> </member> <member name=""F:C.field""> <summary>Private Class Field</summary> </member> <member name=""T:C.S""> <summary>Private Struct</summary> </member> <member name=""F:C.S.field""> <summary>Private Struct Field</summary> </member> </members> </doc>"; Assert.Equal(expectedDoc, content.Trim()); // Clean up temp files CleanupAllGeneratedFiles(dir.Path); } [Fact] public void CompilingCodeWithInvalidPreProcessorSymbolsShouldProvideDiagnostics() { var parsedArgs = DefaultParse(new[] { "/define:1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2029: Invalid name for a preprocessing symbol; '1' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("1").WithLocation(1, 1)); } [Fact] public void CompilingCodeWithInvalidLanguageVersionShouldProvideDiagnostics() { var parsedArgs = DefaultParse(new[] { "/langversion:1000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS1617: Invalid option '1000' for /langversion. Use '/langversion:?' to list supported values. Diagnostic(ErrorCode.ERR_BadCompatMode).WithArguments("1000").WithLocation(1, 1)); } [Fact, WorkItem(16913, "https://github.com/dotnet/roslyn/issues/16913")] public void CompilingCodeWithMultipleInvalidPreProcessorSymbolsShouldErrorOut() { var parsedArgs = DefaultParse(new[] { "/define:valid1,2invalid,valid3", "/define:4,5,valid6", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2029: Invalid value for '/define'; '2invalid' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("2invalid"), // warning CS2029: Invalid value for '/define'; '4' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("4"), // warning CS2029: Invalid value for '/define'; '5' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("5")); } [WorkItem(406649, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=406649")] [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void MissingCompilerAssembly() { var dir = Temp.CreateDirectory(); var cscPath = dir.CopyFile(s_CSharpCompilerExecutable).Path; dir.CopyFile(typeof(Compilation).Assembly.Location); // Missing Microsoft.CodeAnalysis.CSharp.dll. var result = ProcessUtilities.Run(cscPath, arguments: "/nologo /t:library unknown.cs", workingDirectory: dir.Path); Assert.Equal(1, result.ExitCode); Assert.Equal( $"Could not load file or assembly '{typeof(CSharpCompilation).Assembly.FullName}' or one of its dependencies. The system cannot find the file specified.", result.Output.Trim()); // Missing System.Collections.Immutable.dll. dir.CopyFile(typeof(CSharpCompilation).Assembly.Location); result = ProcessUtilities.Run(cscPath, arguments: "/nologo /t:library unknown.cs", workingDirectory: dir.Path); Assert.Equal(1, result.ExitCode); Assert.Equal( $"Could not load file or assembly '{typeof(ImmutableArray).Assembly.FullName}' or one of its dependencies. The system cannot find the file specified.", result.Output.Trim()); } #if NET472 [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void LoadinganalyzerNetStandard13() { var analyzerFileName = "AnalyzerNS13.dll"; var srcFileName = "src.cs"; var analyzerDir = Temp.CreateDirectory(); var analyzerFile = analyzerDir.CreateFile(analyzerFileName).WriteAllBytes(DesktopTestHelpers.CreateCSharpAnalyzerNetStandard13(Path.GetFileNameWithoutExtension(analyzerFileName))); var srcFile = analyzerDir.CreateFile(srcFileName).WriteAllText("public class C { }"); var result = ProcessUtilities.Run(s_CSharpCompilerExecutable, arguments: $"/nologo /t:library /analyzer:{analyzerFileName} {srcFileName}", workingDirectory: analyzerDir.Path); var outputWithoutPaths = Regex.Replace(result.Output, " in .*", ""); AssertEx.AssertEqualToleratingWhitespaceDifferences( $@"warning AD0001: Analyzer 'TestAnalyzer' threw an exception of type 'System.NotImplementedException' with message '28'. System.NotImplementedException: 28 at TestAnalyzer.get_SupportedDiagnostics() at Microsoft.CodeAnalysis.Diagnostics.AnalyzerManager.AnalyzerExecutionContext.<>c__DisplayClass20_0.<ComputeDiagnosticDescriptors>b__0(Object _) at Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.ExecuteAndCatchIfThrows_NoLock[TArg](DiagnosticAnalyzer analyzer, Action`1 analyze, TArg argument, Nullable`1 info) -----", outputWithoutPaths); Assert.Equal(0, result.ExitCode); } #endif [WorkItem(406649, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=484417")] [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void MicrosoftDiaSymReaderNativeAltLoadPath() { var dir = Temp.CreateDirectory(); var cscDir = Path.GetDirectoryName(s_CSharpCompilerExecutable); // copy csc and dependencies except for DSRN: foreach (var filePath in Directory.EnumerateFiles(cscDir)) { var fileName = Path.GetFileName(filePath); if (fileName.StartsWith("csc") || fileName.StartsWith("System.") || fileName.StartsWith("Microsoft.") && !fileName.StartsWith("Microsoft.DiaSymReader.Native")) { dir.CopyFile(filePath); } } dir.CreateFile("Source.cs").WriteAllText("class C { void F() { } }"); var cscCopy = Path.Combine(dir.Path, "csc.exe"); var arguments = "/nologo /t:library /debug:full Source.cs"; // env variable not set (deterministic) -- DSRN is required: var result = ProcessUtilities.Run(cscCopy, arguments + " /deterministic", workingDirectory: dir.Path); AssertEx.AssertEqualToleratingWhitespaceDifferences( "error CS0041: Unexpected error writing debug information -- 'Unable to load DLL 'Microsoft.DiaSymReader.Native.amd64.dll': " + "The specified module could not be found. (Exception from HRESULT: 0x8007007E)'", result.Output.Trim()); // env variable not set (non-deterministic) -- globally registered SymReader is picked up: result = ProcessUtilities.Run(cscCopy, arguments, workingDirectory: dir.Path); AssertEx.AssertEqualToleratingWhitespaceDifferences("", result.Output.Trim()); // env variable set: result = ProcessUtilities.Run( cscCopy, arguments + " /deterministic", workingDirectory: dir.Path, additionalEnvironmentVars: new[] { KeyValuePairUtil.Create("MICROSOFT_DIASYMREADER_NATIVE_ALT_LOAD_PATH", cscDir) }); Assert.Equal("", result.Output.Trim()); } [ConditionalFact(typeof(WindowsOnly))] [WorkItem(21935, "https://github.com/dotnet/roslyn/issues/21935")] public void PdbPathNotEmittedWithoutPdb() { var dir = Temp.CreateDirectory(); var source = @"class Program { static void Main() { } }"; var src = dir.CreateFile("a.cs").WriteAllText(source); var args = new[] { "/nologo", "a.cs", "/out:a.exe", "/debug-" }; var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, args); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var exePath = Path.Combine(dir.Path, "a.exe"); Assert.True(File.Exists(exePath)); using (var peStream = File.OpenRead(exePath)) using (var peReader = new PEReader(peStream)) { var debugDirectory = peReader.PEHeaders.PEHeader.DebugTableDirectory; Assert.Equal(0, debugDirectory.Size); Assert.Equal(0, debugDirectory.RelativeVirtualAddress); } } [Fact] public void StrongNameProviderWithCustomTempPath() { var tempDir = Temp.CreateDirectory(); var workingDir = Temp.CreateDirectory(); workingDir.CreateFile("a.cs"); var buildPaths = new BuildPaths(clientDir: "", workingDir: workingDir.Path, sdkDir: null, tempDir: tempDir.Path); var csc = new MockCSharpCompiler(null, buildPaths, args: new[] { "/features:UseLegacyStrongNameProvider", "/nostdlib", "a.cs" }); var comp = csc.CreateCompilation(new StringWriter(), new TouchedFileLogger(), errorLogger: null); Assert.True(!comp.SignUsingBuilder); } public class QuotedArgumentTests : CommandLineTestBase { private static readonly string s_rootPath = ExecutionConditionUtil.IsWindows ? @"c:\" : "/"; private void VerifyQuotedValid<T>(string name, string value, T expected, Func<CSharpCommandLineArguments, T> getValue) { var args = DefaultParse(new[] { $"/{name}:{value}", "a.cs" }, s_rootPath); Assert.Equal(0, args.Errors.Length); Assert.Equal(expected, getValue(args)); args = DefaultParse(new[] { $@"/{name}:""{value}""", "a.cs" }, s_rootPath); Assert.Equal(0, args.Errors.Length); Assert.Equal(expected, getValue(args)); } private void VerifyQuotedInvalid<T>(string name, string value, T expected, Func<CSharpCommandLineArguments, T> getValue) { var args = DefaultParse(new[] { $"/{name}:{value}", "a.cs" }, s_rootPath); Assert.Equal(0, args.Errors.Length); Assert.Equal(expected, getValue(args)); args = DefaultParse(new[] { $@"/{name}:""{value}""", "a.cs" }, s_rootPath); Assert.True(args.Errors.Length > 0); } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void DebugFlag() { var platformPdbKind = PathUtilities.IsUnixLikePlatform ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb; var list = new List<Tuple<string, DebugInformationFormat>>() { Tuple.Create("portable", DebugInformationFormat.PortablePdb), Tuple.Create("full", platformPdbKind), Tuple.Create("pdbonly", platformPdbKind), Tuple.Create("embedded", DebugInformationFormat.Embedded) }; foreach (var tuple in list) { VerifyQuotedValid("debug", tuple.Item1, tuple.Item2, x => x.EmitOptions.DebugInformationFormat); } } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30328")] public void CodePage() { VerifyQuotedValid("codepage", "1252", 1252, x => x.Encoding.CodePage); } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void Target() { var list = new List<Tuple<string, OutputKind>>() { Tuple.Create("exe", OutputKind.ConsoleApplication), Tuple.Create("winexe", OutputKind.WindowsApplication), Tuple.Create("library", OutputKind.DynamicallyLinkedLibrary), Tuple.Create("module", OutputKind.NetModule), Tuple.Create("appcontainerexe", OutputKind.WindowsRuntimeApplication), Tuple.Create("winmdobj", OutputKind.WindowsRuntimeMetadata) }; foreach (var tuple in list) { VerifyQuotedInvalid("target", tuple.Item1, tuple.Item2, x => x.CompilationOptions.OutputKind); } } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void PlatformFlag() { var list = new List<Tuple<string, Platform>>() { Tuple.Create("x86", Platform.X86), Tuple.Create("x64", Platform.X64), Tuple.Create("itanium", Platform.Itanium), Tuple.Create("anycpu", Platform.AnyCpu), Tuple.Create("anycpu32bitpreferred",Platform.AnyCpu32BitPreferred), Tuple.Create("arm", Platform.Arm) }; foreach (var tuple in list) { VerifyQuotedValid("platform", tuple.Item1, tuple.Item2, x => x.CompilationOptions.Platform); } } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void WarnFlag() { VerifyQuotedValid("warn", "1", 1, x => x.CompilationOptions.WarningLevel); } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void LangVersionFlag() { VerifyQuotedValid("langversion", "2", LanguageVersion.CSharp2, x => x.ParseOptions.LanguageVersion); } } [Fact] [WorkItem(23525, "https://github.com/dotnet/roslyn/issues/23525")] public void InvalidPathCharacterInPathMap() { string filePath = Temp.CreateFile().WriteAllText("").Path; var compiler = CreateCSharpCompiler(null, WorkingDirectory, new[] { filePath, "/debug:embedded", "/pathmap:test\\=\"", "/target:library", "/preferreduilang:en" }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = compiler.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS8101: The pathmap option was incorrectly formatted.", outWriter.ToString(), StringComparison.Ordinal); } [WorkItem(23525, "https://github.com/dotnet/roslyn/issues/23525")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void InvalidPathCharacterInPdbPath() { string filePath = Temp.CreateFile().WriteAllText("").Path; var compiler = CreateCSharpCompiler(null, WorkingDirectory, new[] { filePath, "/debug:embedded", "/pdb:test\\?.pdb", "/target:library", "/preferreduilang:en" }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = compiler.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS2021: File name 'test\\?.pdb' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long", outWriter.ToString(), StringComparison.Ordinal); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [ConditionalFact(typeof(IsEnglishLocal))] public void TestSuppression_CompilerParserWarningAsError() { string source = @" class C { long M(int i) { // warning CS0078 : The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity return 0l; } } "; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that parser warning CS0078 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("warning CS0078", output, StringComparison.Ordinal); // Verify that parser warning CS0078 is reported as error for /warnaserror. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("error CS0078", output, StringComparison.Ordinal); // Verify that parser warning CS0078 is suppressed with diagnostic suppressor even with /warnaserror // and info diagnostic is logged with programmatic suppression information. var suppressor = new DiagnosticSuppressorForId("CS0078"); output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, expectedErrorCount: 0, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, analyzers: suppressor); Assert.DoesNotContain($"error CS0078", output, StringComparison.Ordinal); Assert.DoesNotContain($"warning CS0078", output, StringComparison.Ordinal); // Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.WRN_LowercaseEllSuffix, "l"), Location.None).GetMessage(CultureInfo.InvariantCulture), suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [ConditionalFact(typeof(IsEnglishLocal))] public void TestSuppression_CompilerSyntaxWarning() { // warning CS1522: Empty switch block // NOTE: Empty switch block warning is reported by the C# language parser string source = @" class C { void M(int i) { switch (i) { } } }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that compiler warning CS1522 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("warning CS1522", output, StringComparison.Ordinal); // Verify that compiler warning CS1522 is suppressed with diagnostic suppressor // and info diagnostic is logged with programmatic suppression information. var suppressor = new DiagnosticSuppressorForId("CS1522"); // Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.WRN_EmptySwitch), Location.None).GetMessage(CultureInfo.InvariantCulture), suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification); output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: suppressor, errorlog: true); Assert.DoesNotContain($"warning CS1522", output, StringComparison.Ordinal); Assert.Contains($"info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); // Verify that compiler warning CS1522 is reported as error for /warnaserror. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("error CS1522", output, StringComparison.Ordinal); // Verify that compiler warning CS1522 is suppressed with diagnostic suppressor even with /warnaserror // and info diagnostic is logged with programmatic suppression information. output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, expectedErrorCount: 0, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, analyzers: suppressor); Assert.DoesNotContain($"error CS1522", output, StringComparison.Ordinal); Assert.DoesNotContain($"warning CS1522", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [ConditionalFact(typeof(IsEnglishLocal))] public void TestSuppression_CompilerSemanticWarning() { string source = @" class C { // warning CS0169: The field 'C.f' is never used private readonly int f; }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that compiler warning CS0169 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("warning CS0169", output, StringComparison.Ordinal); // Verify that compiler warning CS0169 is suppressed with diagnostic suppressor // and info diagnostic is logged with programmatic suppression information. var suppressor = new DiagnosticSuppressorForId("CS0169"); // Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.WRN_UnreferencedField, "C.f"), Location.None).GetMessage(CultureInfo.InvariantCulture), suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification); output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: suppressor, errorlog: true); Assert.DoesNotContain($"warning CS0169", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); // Verify that compiler warning CS0169 is reported as error for /warnaserror. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("error CS0169", output, StringComparison.Ordinal); // Verify that compiler warning CS0169 is suppressed with diagnostic suppressor even with /warnaserror // and info diagnostic is logged with programmatic suppression information. output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, expectedErrorCount: 0, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, analyzers: suppressor); Assert.DoesNotContain($"error CS0169", output, StringComparison.Ordinal); Assert.DoesNotContain($"warning CS0169", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [Fact] public void TestNoSuppression_CompilerSyntaxError() { // error CS1001: Identifier expected string source = @" class { }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that compiler syntax error CS1001 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("error CS1001", output, StringComparison.Ordinal); // Verify that compiler syntax error CS1001 cannot be suppressed with diagnostic suppressor. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: new DiagnosticSuppressorForId("CS1001")); Assert.Contains("error CS1001", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [Fact] public void TestNoSuppression_CompilerSemanticError() { // error CS0246: The type or namespace name 'UndefinedType' could not be found (are you missing a using directive or an assembly reference?) string source = @" class C { void M(UndefinedType x) { } }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that compiler error CS0246 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("error CS0246", output, StringComparison.Ordinal); // Verify that compiler error CS0246 cannot be suppressed with diagnostic suppressor. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: new DiagnosticSuppressorForId("CS0246")); Assert.Contains("error CS0246", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [ConditionalFact(typeof(IsEnglishLocal))] public void TestSuppression_AnalyzerWarning() { string source = @" class C { }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that analyzer warning is reported. var analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Warning, configurable: true); var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzer); Assert.Contains($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); // Verify that analyzer warning is suppressed with diagnostic suppressor // and info diagnostic is logged with programmatic suppression information. var suppressor = new DiagnosticSuppressorForId(analyzer.Descriptor.Id); // Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, analyzer.Descriptor.MessageFormat, suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification); var analyzerAndSuppressor = new DiagnosticAnalyzer[] { analyzer, suppressor }; output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, analyzers: analyzerAndSuppressor); Assert.DoesNotContain($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); // Verify that analyzer warning is reported as error for /warnaserror. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzer); Assert.Contains($"error {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); // Verify that analyzer warning is suppressed with diagnostic suppressor even with /warnaserror // and info diagnostic is logged with programmatic suppression information. output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, analyzers: analyzerAndSuppressor); Assert.DoesNotContain($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); // Verify that "NotConfigurable" analyzer warning cannot be suppressed with diagnostic suppressor. analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Warning, configurable: false); suppressor = new DiagnosticSuppressorForId(analyzer.Descriptor.Id); analyzerAndSuppressor = new DiagnosticAnalyzer[] { analyzer, suppressor }; output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzerAndSuppressor); Assert.Contains($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [Fact] public void TestNoSuppression_AnalyzerError() { string source = @" class C { }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that analyzer error is reported. var analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Error, configurable: true); var output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzer); Assert.Contains($"error {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); // Verify that analyzer error cannot be suppressed with diagnostic suppressor. var suppressor = new DiagnosticSuppressorForId(analyzer.Descriptor.Id); var analyzerAndSuppressor = new DiagnosticAnalyzer[] { analyzer, suppressor }; output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzerAndSuppressor); Assert.Contains($"error {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(38674, "https://github.com/dotnet/roslyn/issues/38674")] [InlineData(DiagnosticSeverity.Warning, false)] [InlineData(DiagnosticSeverity.Info, true)] [InlineData(DiagnosticSeverity.Info, false)] [InlineData(DiagnosticSeverity.Hidden, false)] [Theory] public void TestCategoryBasedBulkAnalyzerDiagnosticConfiguration(DiagnosticSeverity defaultSeverity, bool errorlog) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity); var diagnosticId = analyzer.Descriptor.Id; var category = analyzer.Descriptor.Category; // Verify category based configuration without any diagnostic ID configuration is respected. var analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error); // Verify category based configuration does not get applied for suppressed diagnostic. TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress, noWarn: true); // Verify category based configuration does not get applied for diagnostic configured in ruleset. var rulesetText = $@"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis""> <Rule Id=""{diagnosticId}"" Action=""Warning"" /> </Rules> </RuleSet>"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn, rulesetText: rulesetText); // Verify category based configuration before diagnostic ID configuration is not respected. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = error dotnet_diagnostic.{diagnosticId}.severity = warning"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify category based configuration after diagnostic ID configuration is not respected. analyzerConfigText = $@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = warning dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify global config based configuration before diagnostic ID configuration is not respected. analyzerConfigText = $@" is_global = true dotnet_analyzer_diagnostic.category-{category}.severity = error dotnet_diagnostic.{diagnosticId}.severity = warning"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify global config based configuration after diagnostic ID configuration is not respected. analyzerConfigText = $@" is_global = true dotnet_diagnostic.{diagnosticId}.severity = warning dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify disabled by default analyzer is not enabled by category based configuration. analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: false, defaultSeverity); analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); // Verify disabled by default analyzer is not enabled by category based configuration in global config analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: false, defaultSeverity); analyzerConfigText = $@" is_global=true dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); if (defaultSeverity == DiagnosticSeverity.Hidden || defaultSeverity == DiagnosticSeverity.Info && !errorlog) { // Verify analyzer with Hidden severity OR Info severity + no /errorlog is not executed. analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: true); TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText: string.Empty, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); // Verify that bulk configuration 'none' entry does not enable this analyzer. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = none"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); // Verify that bulk configuration 'none' entry does not enable this analyzer via global config analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = none"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); } } [WorkItem(38674, "https://github.com/dotnet/roslyn/issues/38674")] [InlineData(DiagnosticSeverity.Warning, false)] [InlineData(DiagnosticSeverity.Info, true)] [InlineData(DiagnosticSeverity.Info, false)] [InlineData(DiagnosticSeverity.Hidden, false)] [Theory] public void TestBulkAnalyzerDiagnosticConfiguration(DiagnosticSeverity defaultSeverity, bool errorlog) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity); var diagnosticId = analyzer.Descriptor.Id; // Verify bulk configuration without any diagnostic ID configuration is respected. var analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error); // Verify bulk configuration does not get applied for suppressed diagnostic. TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress, noWarn: true); // Verify bulk configuration does not get applied for diagnostic configured in ruleset. var rulesetText = $@"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis""> <Rule Id=""{diagnosticId}"" Action=""Warning"" /> </Rules> </RuleSet>"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn, rulesetText: rulesetText); // Verify bulk configuration before diagnostic ID configuration is not respected. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = error dotnet_diagnostic.{diagnosticId}.severity = warning"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify bulk configuration after diagnostic ID configuration is not respected. analyzerConfigText = $@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = warning dotnet_analyzer_diagnostic.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify disabled by default analyzer is not enabled by bulk configuration. analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: false, defaultSeverity); analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); if (defaultSeverity == DiagnosticSeverity.Hidden || defaultSeverity == DiagnosticSeverity.Info && !errorlog) { // Verify analyzer with Hidden severity OR Info severity + no /errorlog is not executed. analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: true); TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText: string.Empty, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); // Verify that bulk configuration 'none' entry does not enable this analyzer. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = none"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); } } [WorkItem(38674, "https://github.com/dotnet/roslyn/issues/38674")] [InlineData(DiagnosticSeverity.Warning, false)] [InlineData(DiagnosticSeverity.Info, true)] [InlineData(DiagnosticSeverity.Info, false)] [InlineData(DiagnosticSeverity.Hidden, false)] [Theory] public void TestMixedCategoryBasedAndBulkAnalyzerDiagnosticConfiguration(DiagnosticSeverity defaultSeverity, bool errorlog) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity); var diagnosticId = analyzer.Descriptor.Id; var category = analyzer.Descriptor.Category; // Verify category based configuration before bulk analyzer diagnostic configuration is respected. var analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = error dotnet_analyzer_diagnostic.severity = warning"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error); // Verify category based configuration after bulk analyzer diagnostic configuration is respected. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = warning dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error); // Verify neither category based nor bulk diagnostic configuration is respected when specific diagnostic ID is configured in analyzer config. analyzerConfigText = $@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = warning dotnet_analyzer_diagnostic.category-{category}.severity = none dotnet_analyzer_diagnostic.severity = suggestion"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify neither category based nor bulk diagnostic configuration is respected when specific diagnostic ID is configured in ruleset. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = none dotnet_analyzer_diagnostic.severity = suggestion"; var rulesetText = $@"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis""> <Rule Id=""{diagnosticId}"" Action=""Warning"" /> </Rules> </RuleSet>"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn, rulesetText); } private void TestBulkAnalyzerConfigurationCore( NamedTypeAnalyzerWithConfigurableEnabledByDefault analyzer, string analyzerConfigText, bool errorlog, ReportDiagnostic expectedDiagnosticSeverity, string rulesetText = null, bool noWarn = false) { var diagnosticId = analyzer.Descriptor.Id; var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(analyzerConfigText); var arguments = new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path }; if (noWarn) { arguments = arguments.Append($"/nowarn:{diagnosticId}"); } if (errorlog) { arguments = arguments.Append($"/errorlog:errorlog"); } if (rulesetText != null) { var rulesetFile = CreateRuleSetFile(rulesetText); arguments = arguments.Append($"/ruleset:{rulesetFile.Path}"); } var cmd = CreateCSharpCompiler(null, dir.Path, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var expectedErrorCode = expectedDiagnosticSeverity == ReportDiagnostic.Error ? 1 : 0; Assert.Equal(expectedErrorCode, exitCode); var prefix = expectedDiagnosticSeverity switch { ReportDiagnostic.Error => "error", ReportDiagnostic.Warn => "warning", ReportDiagnostic.Info => errorlog ? "info" : null, ReportDiagnostic.Hidden => null, ReportDiagnostic.Suppress => null, _ => throw ExceptionUtilities.UnexpectedValue(expectedDiagnosticSeverity) }; if (prefix == null) { Assert.DoesNotContain(diagnosticId, outWriter.ToString()); } else { Assert.Contains($"{prefix} {diagnosticId}: {analyzer.Descriptor.MessageFormat}", outWriter.ToString()); } } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void CompilerWarnAsErrorDoesNotEmit(bool warnAsError) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { int _f; // CS0169: unused field }"); var docName = "temp.xml"; var pdbName = "temp.pdb"; var additionalArgs = new[] { $"/doc:{docName}", $"/pdb:{pdbName}", "/debug" }; if (warnAsError) { additionalArgs = additionalArgs.Append("/warnaserror").AsArray(); } var expectedErrorCount = warnAsError ? 1 : 0; var expectedWarningCount = !warnAsError ? 1 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectedErrorCount, expectedWarningCount: expectedWarningCount); var expectedOutput = warnAsError ? "error CS0169" : "warning CS0169"; Assert.Contains(expectedOutput, output); string binaryPath = Path.Combine(dir.Path, "temp.dll"); Assert.True(File.Exists(binaryPath) == !warnAsError); string pdbPath = Path.Combine(dir.Path, pdbName); Assert.True(File.Exists(pdbPath) == !warnAsError); string xmlDocFilePath = Path.Combine(dir.Path, docName); Assert.True(File.Exists(xmlDocFilePath) == !warnAsError); } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void AnalyzerConfigSeverityEscalationToErrorDoesNotEmit(bool analyzerConfigSetToError) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { int _f; // CS0169: unused field }"); var docName = "temp.xml"; var pdbName = "temp.pdb"; var additionalArgs = new[] { $"/doc:{docName}", $"/pdb:{pdbName}", "/debug" }; if (analyzerConfigSetToError) { var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.cs0169.severity = error"); additionalArgs = additionalArgs.Append("/analyzerconfig:" + analyzerConfig.Path).ToArray(); } var expectedErrorCount = analyzerConfigSetToError ? 1 : 0; var expectedWarningCount = !analyzerConfigSetToError ? 1 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectedErrorCount, expectedWarningCount: expectedWarningCount); var expectedOutput = analyzerConfigSetToError ? "error CS0169" : "warning CS0169"; Assert.Contains(expectedOutput, output); string binaryPath = Path.Combine(dir.Path, "temp.dll"); Assert.True(File.Exists(binaryPath) == !analyzerConfigSetToError); string pdbPath = Path.Combine(dir.Path, pdbName); Assert.True(File.Exists(pdbPath) == !analyzerConfigSetToError); string xmlDocFilePath = Path.Combine(dir.Path, docName); Assert.True(File.Exists(xmlDocFilePath) == !analyzerConfigSetToError); } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void RulesetSeverityEscalationToErrorDoesNotEmit(bool rulesetSetToError) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { int _f; // CS0169: unused field }"); var docName = "temp.xml"; var pdbName = "temp.pdb"; var additionalArgs = new[] { $"/doc:{docName}", $"/pdb:{pdbName}", "/debug" }; if (rulesetSetToError) { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis""> <Rule Id=""CS0169"" Action=""Error"" /> </Rules> </RuleSet> "; var rulesetFile = CreateRuleSetFile(source); additionalArgs = additionalArgs.Append("/ruleset:" + rulesetFile.Path).ToArray(); } var expectedErrorCount = rulesetSetToError ? 1 : 0; var expectedWarningCount = !rulesetSetToError ? 1 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectedErrorCount, expectedWarningCount: expectedWarningCount); var expectedOutput = rulesetSetToError ? "error CS0169" : "warning CS0169"; Assert.Contains(expectedOutput, output); string binaryPath = Path.Combine(dir.Path, "temp.dll"); Assert.True(File.Exists(binaryPath) == !rulesetSetToError); string pdbPath = Path.Combine(dir.Path, pdbName); Assert.True(File.Exists(pdbPath) == !rulesetSetToError); string xmlDocFilePath = Path.Combine(dir.Path, docName); Assert.True(File.Exists(xmlDocFilePath) == !rulesetSetToError); } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void AnalyzerWarnAsErrorDoesNotEmit(bool warnAsError) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText("class C { }"); var additionalArgs = warnAsError ? new[] { "/warnaserror" } : null; var expectedErrorCount = warnAsError ? 1 : 0; var expectedWarningCount = !warnAsError ? 1 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectedErrorCount, expectedWarningCount: expectedWarningCount, analyzers: new[] { new WarningDiagnosticAnalyzer() }); var expectedDiagnosticSeverity = warnAsError ? "error" : "warning"; Assert.Contains($"{expectedDiagnosticSeverity} {WarningDiagnosticAnalyzer.Warning01.Id}", output); string binaryPath = Path.Combine(dir.Path, "temp.dll"); Assert.True(File.Exists(binaryPath) == !warnAsError); } // Currently, configuring no location diagnostics through editorconfig is not supported. [Theory(Skip = "https://github.com/dotnet/roslyn/issues/38042")] [CombinatorialData] public void AnalyzerConfigRespectedForNoLocationDiagnostic(ReportDiagnostic reportDiagnostic, bool isEnabledByDefault, bool noWarn, bool errorlog) { var analyzer = new AnalyzerWithNoLocationDiagnostics(isEnabledByDefault); TestAnalyzerConfigRespectedCore(analyzer, analyzer.Descriptor, reportDiagnostic, noWarn, errorlog); } [WorkItem(37876, "https://github.com/dotnet/roslyn/issues/37876")] [Theory] [CombinatorialData] public void AnalyzerConfigRespectedForDisabledByDefaultDiagnostic(ReportDiagnostic analyzerConfigSeverity, bool isEnabledByDefault, bool noWarn, bool errorlog) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault, defaultSeverity: DiagnosticSeverity.Warning); TestAnalyzerConfigRespectedCore(analyzer, analyzer.Descriptor, analyzerConfigSeverity, noWarn, errorlog); } private void TestAnalyzerConfigRespectedCore(DiagnosticAnalyzer analyzer, DiagnosticDescriptor descriptor, ReportDiagnostic analyzerConfigSeverity, bool noWarn, bool errorlog) { if (analyzerConfigSeverity == ReportDiagnostic.Default) { // "dotnet_diagnostic.ID.severity = default" is not supported. return; } var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText($@" [*.cs] dotnet_diagnostic.{descriptor.Id}.severity = {analyzerConfigSeverity.ToAnalyzerConfigString()}"); var arguments = new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path }; if (noWarn) { arguments = arguments.Append($"/nowarn:{descriptor.Id}"); } if (errorlog) { arguments = arguments.Append($"/errorlog:errorlog"); } var cmd = CreateCSharpCompiler(null, dir.Path, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var expectedErrorCode = !noWarn && analyzerConfigSeverity == ReportDiagnostic.Error ? 1 : 0; Assert.Equal(expectedErrorCode, exitCode); // NOTE: Info diagnostics are only logged on command line when /errorlog is specified. See https://github.com/dotnet/roslyn/issues/42166 for details. if (!noWarn && (analyzerConfigSeverity == ReportDiagnostic.Error || analyzerConfigSeverity == ReportDiagnostic.Warn || (analyzerConfigSeverity == ReportDiagnostic.Info && errorlog))) { var prefix = analyzerConfigSeverity == ReportDiagnostic.Error ? "error" : analyzerConfigSeverity == ReportDiagnostic.Warn ? "warning" : "info"; Assert.Contains($"{prefix} {descriptor.Id}: {descriptor.MessageFormat}", outWriter.ToString()); } else { Assert.DoesNotContain(descriptor.Id.ToString(), outWriter.ToString()); } } [Fact] [WorkItem(3705, "https://github.com/dotnet/roslyn/issues/3705")] public void IsUserConfiguredGeneratedCodeInAnalyzerConfig() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M(C? c) { _ = c.ToString(); // warning CS8602: Dereference of a possibly null reference. } }"); var output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable" }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning CS8602: Dereference of a possibly null reference. Assert.Contains("warning CS8602", output, StringComparison.Ordinal); // generated_code = true var analyzerConfigFile = dir.CreateFile(".editorconfig"); var analyzerConfig = analyzerConfigFile.WriteAllText(@" [*.cs] generated_code = true"); output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable", "/analyzerconfig:" + analyzerConfig.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.DoesNotContain("warning CS8602", output, StringComparison.Ordinal); // warning CS8669: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. Auto-generated code requires an explicit '#nullable' directive in source. Assert.Contains("warning CS8669", output, StringComparison.Ordinal); // generated_code = false analyzerConfig = analyzerConfigFile.WriteAllText(@" [*.cs] generated_code = false"); output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable", "/analyzerconfig:" + analyzerConfig.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning CS8602: Dereference of a possibly null reference. Assert.Contains("warning CS8602", output, StringComparison.Ordinal); // generated_code = auto analyzerConfig = analyzerConfigFile.WriteAllText(@" [*.cs] generated_code = auto"); output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable", "/analyzerconfig:" + analyzerConfig.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning CS8602: Dereference of a possibly null reference. Assert.Contains("warning CS8602", output, StringComparison.Ordinal); } [WorkItem(42166, "https://github.com/dotnet/roslyn/issues/42166")] [CombinatorialData, Theory] public void TestAnalyzerFilteringBasedOnSeverity(DiagnosticSeverity defaultSeverity, bool errorlog) { // This test verifies that analyzer execution is skipped at build time for the following: // 1. Analyzer reporting Hidden diagnostics // 2. Analyzer reporting Info diagnostics, when /errorlog is not specified var analyzerShouldBeSkipped = defaultSeverity == DiagnosticSeverity.Hidden || defaultSeverity == DiagnosticSeverity.Info && !errorlog; // We use an analyzer that throws an exception on every analyzer callback. // So an AD0001 analyzer exception diagnostic is reported if analyzer executed, otherwise not. var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: true); var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); var args = new[] { "/nologo", "/t:library", "/preferreduilang:en", src.Path }; if (errorlog) args = args.Append("/errorlog:errorlog"); var cmd = CreateCSharpCompiler(null, dir.Path, args, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); if (analyzerShouldBeSkipped) { Assert.Empty(output); } else { Assert.Contains("warning AD0001: Analyzer 'Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers+NamedTypeAnalyzerWithConfigurableEnabledByDefault' threw an exception of type 'System.NotImplementedException'", output, StringComparison.Ordinal); } } [WorkItem(47017, "https://github.com/dotnet/roslyn/issues/47017")] [CombinatorialData, Theory] public void TestWarnAsErrorMinusDoesNotEnableDisabledByDefaultAnalyzers(DiagnosticSeverity defaultSeverity, bool isEnabledByDefault) { // This test verifies that '/warnaserror-:DiagnosticId' does not affect if analyzers are executed or skipped.. // Setup the analyzer to always throw an exception on analyzer callbacks for cases where we expect analyzer execution to be skipped: // 1. Disabled by default analyzer, i.e. 'isEnabledByDefault == false'. // 2. Default severity Hidden/Info: We only execute analyzers reporting Warning/Error severity diagnostics on command line builds. var analyzerShouldBeSkipped = !isEnabledByDefault || defaultSeverity == DiagnosticSeverity.Hidden || defaultSeverity == DiagnosticSeverity.Info; var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault, defaultSeverity, throwOnAllNamedTypes: analyzerShouldBeSkipped); var diagnosticId = analyzer.Descriptor.Id; var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); // Verify '/warnaserror-:DiagnosticId' behavior. var args = new[] { "/warnaserror+", $"/warnaserror-:{diagnosticId}", "/nologo", "/t:library", "/preferreduilang:en", src.Path }; var cmd = CreateCSharpCompiler(null, dir.Path, args, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var expectedExitCode = !analyzerShouldBeSkipped && defaultSeverity == DiagnosticSeverity.Error ? 1 : 0; Assert.Equal(expectedExitCode, exitCode); var output = outWriter.ToString(); if (analyzerShouldBeSkipped) { Assert.Empty(output); } else { var prefix = defaultSeverity == DiagnosticSeverity.Warning ? "warning" : "error"; Assert.Contains($"{prefix} {diagnosticId}: {analyzer.Descriptor.MessageFormat}", output); } } [WorkItem(49446, "https://github.com/dotnet/roslyn/issues/49446")] [Theory] // Verify '/warnaserror-:ID' prevents escalation to 'Error' when config file bumps severity to 'Warning' [InlineData(false, DiagnosticSeverity.Info, DiagnosticSeverity.Warning, DiagnosticSeverity.Error)] [InlineData(true, DiagnosticSeverity.Info, DiagnosticSeverity.Warning, DiagnosticSeverity.Warning)] // Verify '/warnaserror-:ID' prevents escalation to 'Error' when default severity is 'Warning' and no config file setting is specified. [InlineData(false, DiagnosticSeverity.Warning, null, DiagnosticSeverity.Error)] [InlineData(true, DiagnosticSeverity.Warning, null, DiagnosticSeverity.Warning)] // Verify '/warnaserror-:ID' prevents escalation to 'Error' when default severity is 'Warning' and config file bumps severity to 'Error' [InlineData(false, DiagnosticSeverity.Warning, DiagnosticSeverity.Error, DiagnosticSeverity.Error)] [InlineData(true, DiagnosticSeverity.Warning, DiagnosticSeverity.Error, DiagnosticSeverity.Warning)] // Verify '/warnaserror-:ID' has no effect when default severity is 'Info' and config file bumps severity to 'Error' [InlineData(false, DiagnosticSeverity.Info, DiagnosticSeverity.Error, DiagnosticSeverity.Error)] [InlineData(true, DiagnosticSeverity.Info, DiagnosticSeverity.Error, DiagnosticSeverity.Error)] public void TestWarnAsErrorMinusDoesNotNullifyEditorConfig( bool warnAsErrorMinus, DiagnosticSeverity defaultSeverity, DiagnosticSeverity? severityInConfigFile, DiagnosticSeverity expectedEffectiveSeverity) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: false); var diagnosticId = analyzer.Descriptor.Id; var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); var additionalFlags = new[] { "/warnaserror+" }; if (severityInConfigFile.HasValue) { var severityString = DiagnosticDescriptor.MapSeverityToReport(severityInConfigFile.Value).ToAnalyzerConfigString(); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText($@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = {severityString}"); additionalFlags = additionalFlags.Append($"/analyzerconfig:{analyzerConfig.Path}").ToArray(); } if (warnAsErrorMinus) { additionalFlags = additionalFlags.Append($"/warnaserror-:{diagnosticId}").ToArray(); } int expectedWarningCount = 0, expectedErrorCount = 0; switch (expectedEffectiveSeverity) { case DiagnosticSeverity.Warning: expectedWarningCount = 1; break; case DiagnosticSeverity.Error: expectedErrorCount = 1; break; default: throw ExceptionUtilities.UnexpectedValue(expectedEffectiveSeverity); } VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, expectedWarningCount: expectedWarningCount, expectedErrorCount: expectedErrorCount, additionalFlags: additionalFlags, analyzers: new[] { analyzer }); } [Fact] public void SourceGenerators_EmbeddedSources() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/debug:embedded", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); ValidateEmbeddedSources_Portable(new Dictionary<string, string> { { Path.Combine(dir.Path, generatorPrefix, $"generatedSource.cs"), generatedSource } }, dir, true); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Theory, CombinatorialData] [WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")] public void TestSourceGeneratorsWithAnalyzers(bool includeCurrentAssemblyAsAnalyzerReference, bool skipAnalyzers) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); // 'skipAnalyzers' should have no impact on source generator execution, but should prevent analyzer execution. var skipAnalyzersFlag = "/skipAnalyzers" + (skipAnalyzers ? "+" : "-"); // Verify analyzers were executed only if both the following conditions were satisfied: // 1. Current assembly was added as an analyzer reference, i.e. "includeCurrentAssemblyAsAnalyzerReference = true" and // 2. We did not explicitly request skipping analyzers, i.e. "skipAnalyzers = false". var expectedAnalyzerExecution = includeCurrentAssemblyAsAnalyzerReference && !skipAnalyzers; // 'WarningDiagnosticAnalyzer' generates a warning for each named type. // We expect two warnings for this test: type "C" defined in source and the source generator defined type. // Additionally, we also have an analyzer that generates "warning CS8032: An instance of analyzer cannot be created" var expectedWarningCount = expectedAnalyzerExecution ? 3 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference, expectedWarningCount: expectedWarningCount, additionalFlags: new[] { "/debug:embedded", "/out:embed.exe", skipAnalyzersFlag }, generators: new[] { generator }); // Verify source generator was executed, regardless of the value of 'skipAnalyzers'. var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); ValidateEmbeddedSources_Portable(new Dictionary<string, string> { { Path.Combine(dir.Path, generatorPrefix, "generatedSource.cs"), generatedSource } }, dir, true); if (expectedAnalyzerExecution) { Assert.Contains("warning Warning01", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); } else { Assert.Empty(output); } // Clean up temp files CleanupAllGeneratedFiles(src.Path); } [Theory] [InlineData("partial class D {}", "file1.cs", "partial class E {}", "file2.cs")] // different files, different names [InlineData("partial class D {}", "file1.cs", "partial class E {}", "file1.cs")] // different files, same names [InlineData("partial class D {}", "file1.cs", "partial class D {}", "file2.cs")] // same files, different names [InlineData("partial class D {}", "file1.cs", "partial class D {}", "file1.cs")] // same files, same names [InlineData("partial class D {}", "file1.cs", "", "file2.cs")] // empty second file public void SourceGenerators_EmbeddedSources_MultipleFiles(string source1, string source1Name, string source2, string source2Name) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generator = new SingleFileTestGenerator(source1, source1Name); var generator2 = new SingleFileTestGenerator2(source2, source2Name); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/debug:embedded", "/out:embed.exe" }, generators: new[] { generator, generator2 }, analyzers: null); var generator1Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); var generator2Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator2); ValidateEmbeddedSources_Portable(new Dictionary<string, string> { { Path.Combine(dir.Path, generator1Prefix, source1Name), source1}, { Path.Combine(dir.Path, generator2Prefix, source2Name), source2}, }, dir, true); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_WriteGeneratedSources() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource } } } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_OverwriteGeneratedSources() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generatedSource1 = "class D { } class E { }"; var generator1 = new SingleFileTestGenerator(generatedSource1, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator1 }, analyzers: null); var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator1); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource1 } } } }); var generatedSource2 = "public class D { }"; var generator2 = new SingleFileTestGenerator(generatedSource2, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator2 }, analyzers: null); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource2 } } } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Theory] [InlineData("partial class D {}", "file1.cs", "partial class E {}", "file2.cs")] // different files, different names [InlineData("partial class D {}", "file1.cs", "partial class E {}", "file1.cs")] // different files, same names [InlineData("partial class D {}", "file1.cs", "partial class D {}", "file2.cs")] // same files, different names [InlineData("partial class D {}", "file1.cs", "partial class D {}", "file1.cs")] // same files, same names [InlineData("partial class D {}", "file1.cs", "", "file2.cs")] // empty second file public void SourceGenerators_WriteGeneratedSources_MultipleFiles(string source1, string source1Name, string source2, string source2Name) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generator = new SingleFileTestGenerator(source1, source1Name); var generator2 = new SingleFileTestGenerator2(source2, source2Name); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator, generator2 }, analyzers: null); var generator1Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); var generator2Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator2); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generator1Prefix), new() { { source1Name, source1 } } }, { Path.Combine(generatedDir.Path, generator2Prefix), new() { { source2Name, source2 } } } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [ConditionalFact(typeof(DesktopClrOnly))] //CoreCLR doesn't support SxS loading [WorkItem(47990, "https://github.com/dotnet/roslyn/issues/47990")] public void SourceGenerators_SxS_AssemblyLoading() { // compile the generators var dir = Temp.CreateDirectory(); var snk = Temp.CreateFile("TestKeyPair_", ".snk", dir.Path).WriteAllBytes(TestResources.General.snKey); var src = dir.CreateFile("generator.cs"); var virtualSnProvider = new DesktopStrongNameProvider(ImmutableArray.Create(dir.Path)); string createGenerator(string version) { var generatorSource = $@" using Microsoft.CodeAnalysis; [assembly:System.Reflection.AssemblyVersion(""{version}"")] [Generator] public class TestGenerator : ISourceGenerator {{ public void Execute(GeneratorExecutionContext context) {{ context.AddSource(""generatedSource.cs"", ""//from version {version}""); }} public void Initialize(GeneratorInitializationContext context) {{ }} }}"; var path = Path.Combine(dir.Path, Guid.NewGuid().ToString() + ".dll"); var comp = CreateEmptyCompilation(source: generatorSource, references: TargetFrameworkUtil.NetStandard20References.Add(MetadataReference.CreateFromAssemblyInternal(typeof(ISourceGenerator).Assembly)), options: TestOptions.DebugDll.WithCryptoKeyFile(Path.GetFileName(snk.Path)).WithStrongNameProvider(virtualSnProvider), assemblyName: "generator"); comp.VerifyDiagnostics(); comp.Emit(path); return path; } var gen1 = createGenerator("1.0.0.0"); var gen2 = createGenerator("2.0.0.0"); var generatedDir = dir.CreateDirectory("generated"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/analyzer:" + gen1, "/analyzer:" + gen2 }.ToArray()); // This is wrong! Both generators are writing the same file out, over the top of each other // See https://github.com/dotnet/roslyn/issues/47990 ValidateWrittenSources(new() { // { Path.Combine(generatedDir.Path, "generator", "TestGenerator"), new() { { "generatedSource.cs", "//from version 1.0.0.0" } } }, { Path.Combine(generatedDir.Path, "generator", "TestGenerator"), new() { { "generatedSource.cs", "//from version 2.0.0.0" } } } }); } [Fact] public void SourceGenerators_DoNotWriteGeneratedSources_When_No_Directory_Supplied() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); ValidateWrittenSources(new() { { generatedDir.Path, new() } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_Error_When_GeneratedDir_NotExist() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDirPath = Path.Combine(dir.Path, "noexist"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); var output = VerifyOutput(dir, src, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDirPath, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); Assert.Contains("CS0016:", output); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_GeneratedDir_Has_Spaces() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated files"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource } } } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void ParseGeneratedFilesOut() { string root = PathUtilities.IsUnixLikePlatform ? "/" : "c:\\"; string baseDirectory = Path.Combine(root, "abc", "def"); var parsedArgs = DefaultParse(new[] { @"/generatedfilesout:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/generatedfilesout:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/generatedfilesout:")); Assert.Null(parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/generatedfilesout:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/generatedfilesout:\"\"")); Assert.Null(parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:outdir", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "outdir"), parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:""outdir""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "outdir"), parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:out dir", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "out dir"), parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:""out dir""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "out dir"), parsedArgs.GeneratedFilesOutputDirectory); var absPath = Path.Combine(root, "outdir"); parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:{absPath}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:""{absPath}""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory); absPath = Path.Combine(root, "generated files"); parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:{absPath}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:""{absPath}""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory); } [Fact] public void SourceGenerators_Error_When_NoDirectoryArgumentGiven() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var output = VerifyOutput(dir, src, expectedErrorCount: 2, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:", "/langversion:preview", "/out:embed.exe" }); Assert.Contains("error CS2006: Command-line syntax error: Missing '<text>' for '/generatedfilesout:' option", output); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_ReportedWrittenFiles_To_TouchedFilesLogger() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, $"/touchedfiles:{dir.Path}/touched", "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); var touchedFiles = Directory.GetFiles(dir.Path, "touched*"); Assert.Equal(2, touchedFiles.Length); string[] writtenText = File.ReadAllLines(Path.Combine(dir.Path, "touched.write")); Assert.Equal(2, writtenText.Length); Assert.EndsWith("EMBED.EXE", writtenText[0], StringComparison.OrdinalIgnoreCase); Assert.EndsWith("GENERATEDSOURCE.CS", writtenText[1], StringComparison.OrdinalIgnoreCase); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44087")] public void SourceGeneratorsAndAnalyzerConfig() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] key = value"); var generator = new SingleFileTestGenerator("public class D {}", "generated.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzerconfig:" + analyzerConfig.Path }, generators: new[] { generator }, analyzers: null); } [Fact] public void SourceGeneratorsCanReadAnalyzerConfig() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var analyzerConfig1 = dir.CreateFile(".globaleditorconfig").WriteAllText(@" is_global = true key1 = value1 [*.cs] key2 = value2 [*.vb] key3 = value3"); var analyzerConfig2 = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] key4 = value4 [*.vb] key5 = value5"); var subDir = dir.CreateDirectory("subDir"); var analyzerConfig3 = subDir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] key6 = value6 [*.vb] key7 = value7"); var generator = new CallbackGenerator((ic) => { }, (gc) => { // can get the global options var globalOptions = gc.AnalyzerConfigOptions.GlobalOptions; Assert.True(globalOptions.TryGetValue("key1", out var keyValue)); Assert.Equal("value1", keyValue); Assert.False(globalOptions.TryGetValue("key2", out _)); Assert.False(globalOptions.TryGetValue("key3", out _)); Assert.False(globalOptions.TryGetValue("key4", out _)); Assert.False(globalOptions.TryGetValue("key5", out _)); Assert.False(globalOptions.TryGetValue("key6", out _)); Assert.False(globalOptions.TryGetValue("key7", out _)); // can get the options for class C var classOptions = gc.AnalyzerConfigOptions.GetOptions(gc.Compilation.SyntaxTrees.First()); Assert.True(classOptions.TryGetValue("key1", out keyValue)); Assert.Equal("value1", keyValue); Assert.False(classOptions.TryGetValue("key2", out _)); Assert.False(classOptions.TryGetValue("key3", out _)); Assert.True(classOptions.TryGetValue("key4", out keyValue)); Assert.Equal("value4", keyValue); Assert.False(classOptions.TryGetValue("key5", out _)); Assert.False(classOptions.TryGetValue("key6", out _)); Assert.False(classOptions.TryGetValue("key7", out _)); }); var args = new[] { "/analyzerconfig:" + analyzerConfig1.Path, "/analyzerconfig:" + analyzerConfig2.Path, "/analyzerconfig:" + analyzerConfig3.Path, "/t:library", src.Path }; var cmd = CreateCSharpCompiler(null, dir.Path, args, generators: ImmutableArray.Create<ISourceGenerator>(generator)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); // test for both the original tree and the generated one var provider = cmd.AnalyzerOptions.AnalyzerConfigOptionsProvider; // get the global options var globalOptions = provider.GlobalOptions; Assert.True(globalOptions.TryGetValue("key1", out var keyValue)); Assert.Equal("value1", keyValue); Assert.False(globalOptions.TryGetValue("key2", out _)); Assert.False(globalOptions.TryGetValue("key3", out _)); Assert.False(globalOptions.TryGetValue("key4", out _)); Assert.False(globalOptions.TryGetValue("key5", out _)); Assert.False(globalOptions.TryGetValue("key6", out _)); Assert.False(globalOptions.TryGetValue("key7", out _)); // get the options for class C var classOptions = provider.GetOptions(cmd.Compilation.SyntaxTrees.First()); Assert.True(classOptions.TryGetValue("key1", out keyValue)); Assert.Equal("value1", keyValue); Assert.False(classOptions.TryGetValue("key2", out _)); Assert.False(classOptions.TryGetValue("key3", out _)); Assert.True(classOptions.TryGetValue("key4", out keyValue)); Assert.Equal("value4", keyValue); Assert.False(classOptions.TryGetValue("key5", out _)); Assert.False(classOptions.TryGetValue("key6", out _)); Assert.False(classOptions.TryGetValue("key7", out _)); // get the options for generated class D var generatedOptions = provider.GetOptions(cmd.Compilation.SyntaxTrees.Last()); Assert.True(generatedOptions.TryGetValue("key1", out keyValue)); Assert.Equal("value1", keyValue); Assert.False(generatedOptions.TryGetValue("key2", out _)); Assert.False(generatedOptions.TryGetValue("key3", out _)); Assert.True(classOptions.TryGetValue("key4", out keyValue)); Assert.Equal("value4", keyValue); Assert.False(generatedOptions.TryGetValue("key5", out _)); Assert.False(generatedOptions.TryGetValue("key6", out _)); Assert.False(generatedOptions.TryGetValue("key7", out _)); } [Theory] [CombinatorialData] public void SourceGeneratorsRunRegardlessOfLanguageVersion(LanguageVersion version) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@"class C {}"); var generator = new CallbackGenerator(i => { }, e => throw null); var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:" + version.ToDisplayString() }, generators: new[] { generator }, expectedWarningCount: 1, expectedErrorCount: 1, expectedExitCode: 0); Assert.Contains("CS8785: Generator 'CallbackGenerator' failed to generate source.", output); } [DiagnosticAnalyzer(LanguageNames.CSharp)] private sealed class FieldAnalyzer : DiagnosticAnalyzer { private static readonly DiagnosticDescriptor _rule = new DiagnosticDescriptor("Id", "Title", "Message", "Category", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(_rule); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeFieldDeclaration, SyntaxKind.FieldDeclaration); } private static void AnalyzeFieldDeclaration(SyntaxNodeAnalysisContext context) { } } [Fact] [WorkItem(44000, "https://github.com/dotnet/roslyn/issues/44000")] public void TupleField_ForceComplete() { var source = @"namespace System { public struct ValueTuple<T1> { public T1 Item1; public ValueTuple(T1 item1) { Item1 = item1; } } }"; var srcFile = Temp.CreateFile().WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler( null, WorkingDirectory, new[] { "/nologo", "/t:library", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new FieldAnalyzer())); // at least one analyzer required var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); Assert.Empty(output); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] public void GlobalAnalyzerConfigsAllowedInSameDir() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var configText = @" is_global = true "; var analyzerConfig1 = dir.CreateFile("analyzerconfig1").WriteAllText(configText); var analyzerConfig2 = dir.CreateFile("analyzerconfig2").WriteAllText(configText); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig1.Path, "/analyzerconfig:" + analyzerConfig2.Path, src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); } [Fact] public void GlobalAnalyzerConfigMultipleSetKeys() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var analyzerConfigFile = dir.CreateFile(".globalconfig"); var analyzerConfig = analyzerConfigFile.WriteAllText(@" is_global = true global_level = 100 option1 = abc"); var analyzerConfigFile2 = dir.CreateFile(".globalconfig2"); var analyzerConfig2 = analyzerConfigFile2.WriteAllText(@" is_global = true global_level = 100 option1 = def"); var output = VerifyOutput(dir, src, additionalFlags: new[] { "/analyzerconfig:" + analyzerConfig.Path + "," + analyzerConfig2.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning MultipleGlobalAnalyzerKeys: Multiple global analyzer config files set the same key 'option1' in section 'Global Section'. It has been unset. Key was set by the following files: ... Assert.Contains("MultipleGlobalAnalyzerKeys:", output, StringComparison.Ordinal); Assert.Contains("'option1'", output, StringComparison.Ordinal); Assert.Contains("'Global Section'", output, StringComparison.Ordinal); analyzerConfig = analyzerConfigFile.WriteAllText(@" is_global = true global_level = 100 [/file.cs] option1 = abc"); analyzerConfig2 = analyzerConfigFile2.WriteAllText(@" is_global = true global_level = 100 [/file.cs] option1 = def"); output = VerifyOutput(dir, src, additionalFlags: new[] { "/analyzerconfig:" + analyzerConfig.Path + "," + analyzerConfig2.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning MultipleGlobalAnalyzerKeys: Multiple global analyzer config files set the same key 'option1' in section 'file.cs'. It has been unset. Key was set by the following files: ... Assert.Contains("MultipleGlobalAnalyzerKeys:", output, StringComparison.Ordinal); Assert.Contains("'option1'", output, StringComparison.Ordinal); Assert.Contains("'/file.cs'", output, StringComparison.Ordinal); } [Fact] public void GlobalAnalyzerConfigWithOptions() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { }"); var additionalFile = dir.CreateFile("file.txt"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] key1 = value1 [*.txt] key2 = value2"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText(@" is_global = true key3 = value3"); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/analyzerconfig:" + analyzerConfig.Path, "/analyzerconfig:" + globalConfig.Path, "/analyzer:" + Assembly.GetExecutingAssembly().Location, "/nowarn:8032,Warning01", "/additionalfile:" + additionalFile.Path, src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal("", outWriter.ToString()); Assert.Equal(0, exitCode); var comp = cmd.Compilation; var tree = comp.SyntaxTrees.Single(); var provider = cmd.AnalyzerOptions.AnalyzerConfigOptionsProvider; var options = provider.GetOptions(tree); Assert.NotNull(options); Assert.True(options.TryGetValue("key1", out string val)); Assert.Equal("value1", val); Assert.False(options.TryGetValue("key2", out _)); Assert.True(options.TryGetValue("key3", out val)); Assert.Equal("value3", val); options = provider.GetOptions(cmd.AnalyzerOptions.AdditionalFiles.Single()); Assert.NotNull(options); Assert.False(options.TryGetValue("key1", out _)); Assert.True(options.TryGetValue("key2", out val)); Assert.Equal("value2", val); Assert.True(options.TryGetValue("key3", out val)); Assert.Equal("value3", val); options = provider.GlobalOptions; Assert.NotNull(options); Assert.False(options.TryGetValue("key1", out _)); Assert.False(options.TryGetValue("key2", out _)); Assert.True(options.TryGetValue("key3", out val)); Assert.Equal("value3", val); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")] public void GlobalAnalyzerConfigDiagnosticOptionsCanBeOverridenByCommandLine() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M() { label1:; } }"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText(@" is_global = true dotnet_diagnostic.CS0164.severity = error; "); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.CS0164.severity = warning; "); var none = Array.Empty<TempFile>(); var globalOnly = new[] { globalConfig }; var globalAndSpecific = new[] { globalConfig, analyzerConfig }; // by default a warning, which can be suppressed via cmdline verify(configs: none, expectedWarnings: 1); verify(configs: none, noWarn: "CS0164", expectedWarnings: 0); // the global analyzer config ups the warning to an error, but the cmdline setting overrides it verify(configs: globalOnly, expectedErrors: 1); verify(configs: globalOnly, noWarn: "CS0164", expectedWarnings: 0); verify(configs: globalOnly, noWarn: "164", expectedWarnings: 0); // cmdline can be shortened, but still works // the editor config downgrades the error back to warning, but the cmdline setting overrides it verify(configs: globalAndSpecific, expectedWarnings: 1); verify(configs: globalAndSpecific, noWarn: "CS0164", expectedWarnings: 0); void verify(TempFile[] configs, int expectedWarnings = 0, int expectedErrors = 0, string noWarn = "0") => VerifyOutput(dir, src, expectedErrorCount: expectedErrors, expectedWarningCount: expectedWarnings, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: null, additionalFlags: configs.SelectAsArray(c => "/analyzerconfig:" + c.Path) .Add("/noWarn:" + noWarn).ToArray()); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")] public void GlobalAnalyzerConfigSpecificDiagnosticOptionsOverrideGeneralCommandLineOptions() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M() { label1:; } }"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText($@" is_global = true dotnet_diagnostic.CS0164.severity = none; "); VerifyOutput(dir, src, additionalFlags: new[] { "/warnaserror+", "/analyzerconfig:" + globalConfig.Path }, includeCurrentAssemblyAsAnalyzerReference: false); } [Theory, CombinatorialData] [WorkItem(43051, "https://github.com/dotnet/roslyn/issues/43051")] public void WarnAsErrorIsRespectedForForWarningsConfiguredInRulesetOrGlobalConfig(bool useGlobalConfig) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M() { label1:; } }"); var additionalFlags = new[] { "/warnaserror+" }; if (useGlobalConfig) { var globalConfig = dir.CreateFile(".globalconfig").WriteAllText($@" is_global = true dotnet_diagnostic.CS0164.severity = warning; "); additionalFlags = additionalFlags.Append("/analyzerconfig:" + globalConfig.Path).ToArray(); } else { string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""15.0""> <Rules AnalyzerId=""Compiler"" RuleNamespace=""Compiler""> <Rule Id=""CS0164"" Action=""Warning"" /> </Rules> </RuleSet> "; _ = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); additionalFlags = additionalFlags.Append("/ruleset:Rules.ruleset").ToArray(); } VerifyOutput(dir, src, additionalFlags: additionalFlags, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")] public void GlobalAnalyzerConfigSectionsDoNotOverrideCommandLine() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M() { label1:; } }"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText($@" is_global = true [{PathUtilities.NormalizeWithForwardSlash(src.Path)}] dotnet_diagnostic.CS0164.severity = error; "); VerifyOutput(dir, src, additionalFlags: new[] { "/nowarn:0164", "/analyzerconfig:" + globalConfig.Path }, expectedErrorCount: 0, includeCurrentAssemblyAsAnalyzerReference: false); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")] public void GlobalAnalyzerConfigCanSetDiagnosticWithNoLocation() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { }"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText(@" is_global = true dotnet_diagnostic.Warning01.severity = error; "); VerifyOutput(dir, src, additionalFlags: new[] { "/analyzerconfig:" + globalConfig.Path }, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: new WarningDiagnosticAnalyzer()); VerifyOutput(dir, src, additionalFlags: new[] { "/nowarn:Warning01", "/analyzerconfig:" + globalConfig.Path }, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: new WarningDiagnosticAnalyzer()); } [Theory, CombinatorialData] public void TestAdditionalFileAnalyzer(bool registerFromInitialize) { var srcDirectory = Temp.CreateDirectory(); var source = "class C { }"; var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); var additionalText = "Additional Text"; var additionalFile = srcDirectory.CreateFile("b.txt"); additionalFile.WriteAllText(additionalText); var diagnosticSpan = new TextSpan(2, 2); var analyzer = new AdditionalFileAnalyzer(registerFromInitialize, diagnosticSpan); var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/additionalfile:" + additionalFile.Path }, analyzers: analyzer); Assert.Contains("b.txt(1,3): warning ID0001", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcDirectory.Path); } [Theory] // "/warnaserror" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/warnaserror", /*expectError*/true, /*expectWarning*/false)] // "/warnaserror:CS0169" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror:CS0169", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror:CS0169", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/warnaserror:CS0169", /*expectError*/true, /*expectWarning*/false)] // "/nowarn" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/nowarn:CS0169", /*expectError*/false, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/nowarn:CS0169", /*expectError*/false, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/nowarn:CS0169", /*expectError*/false, /*expectWarning*/false)] // Neither "/nowarn" nor "/warnaserror" tests [InlineData(/*analyzerConfigSeverity*/"warning", /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)] [InlineData(/*analyzerConfigSeverity*/"error", /*additionalArg*/null, /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)] [WorkItem(43051, "https://github.com/dotnet/roslyn/issues/43051")] public void TestCompilationOptionsOverrideAnalyzerConfig_CompilerWarning(string analyzerConfigSeverity, string additionalArg, bool expectError, bool expectWarning) { var src = @" class C { int _f; // CS0169: unused field }"; TestCompilationOptionsOverrideAnalyzerConfigCore(src, diagnosticId: "CS0169", analyzerConfigSeverity, additionalArg, expectError, expectWarning); } [Theory] // "/warnaserror" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/warnaserror", /*expectError*/true, /*expectWarning*/false)] // "/warnaserror:DiagnosticId" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/warnaserror:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/true, /*expectWarning*/false)] // "/nowarn" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/nowarn:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/false, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/nowarn:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/false, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/nowarn:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/false, /*expectWarning*/false)] // Neither "/nowarn" nor "/warnaserror" tests [InlineData(/*analyzerConfigSeverity*/"warning", /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)] [InlineData(/*analyzerConfigSeverity*/"error", /*additionalArg*/null, /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)] [WorkItem(43051, "https://github.com/dotnet/roslyn/issues/43051")] public void TestCompilationOptionsOverrideAnalyzerConfig_AnalyzerWarning(string analyzerConfigSeverity, string additionalArg, bool expectError, bool expectWarning) { var analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Warning, configurable: true); var src = @"class C { }"; TestCompilationOptionsOverrideAnalyzerConfigCore(src, CompilationAnalyzerWithSeverity.DiagnosticId, analyzerConfigSeverity, additionalArg, expectError, expectWarning, analyzer); } private void TestCompilationOptionsOverrideAnalyzerConfigCore( string source, string diagnosticId, string analyzerConfigSeverity, string additionalArg, bool expectError, bool expectWarning, params DiagnosticAnalyzer[] analyzers) { Assert.True(!expectError || !expectWarning); var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(source); var additionalArgs = Array.Empty<string>(); if (analyzerConfigSeverity != null) { var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText($@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = {analyzerConfigSeverity}"); additionalArgs = additionalArgs.Append("/analyzerconfig:" + analyzerConfig.Path).ToArray(); } if (!string.IsNullOrEmpty(additionalArg)) { additionalArgs = additionalArgs.Append(additionalArg); } var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectError ? 1 : 0, expectedWarningCount: expectWarning ? 1 : 0, analyzers: analyzers); if (expectError) { Assert.Contains($"error {diagnosticId}", output); } else if (expectWarning) { Assert.Contains($"warning {diagnosticId}", output); } else { Assert.DoesNotContain(diagnosticId, output); } } [ConditionalFact(typeof(CoreClrOnly), Reason = "Can't load a coreclr targeting generator on net framework / mono")] public void TestGeneratorsCantTargetNetFramework() { var directory = Temp.CreateDirectory(); var src = directory.CreateFile("test.cs").WriteAllText(@" class C { }"); // core var coreGenerator = emitGenerator(".NETCoreApp,Version=v5.0"); VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + coreGenerator }); // netstandard var nsGenerator = emitGenerator(".NETStandard,Version=v2.0"); VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + nsGenerator }); // no target var ntGenerator = emitGenerator(targetFramework: null); VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + ntGenerator }); // framework var frameworkGenerator = emitGenerator(".NETFramework,Version=v4.7.2"); var output = VerifyOutput(directory, src, expectedWarningCount: 2, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + frameworkGenerator }); Assert.Contains("CS8850", output); // ref's net fx Assert.Contains("CS8033", output); // no analyzers in assembly // framework, suppressed output = VerifyOutput(directory, src, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:CS8850", "/analyzer:" + frameworkGenerator }); Assert.Contains("CS8033", output); VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:CS8850,CS8033", "/analyzer:" + frameworkGenerator }); string emitGenerator(string targetFramework) { string targetFrameworkAttributeText = targetFramework is object ? $"[assembly: System.Runtime.Versioning.TargetFramework(\"{targetFramework}\")]" : string.Empty; string generatorSource = $@" using Microsoft.CodeAnalysis; {targetFrameworkAttributeText} [Generator] public class Generator : ISourceGenerator {{ public void Execute(GeneratorExecutionContext context) {{ }} public void Initialize(GeneratorInitializationContext context) {{ }} }}"; var directory = Temp.CreateDirectory(); var generatorPath = Path.Combine(directory.Path, "generator.dll"); var compilation = CSharpCompilation.Create($"generator", new[] { CSharpSyntaxTree.ParseText(generatorSource) }, TargetFrameworkUtil.GetReferences(TargetFramework.Standard, new[] { MetadataReference.CreateFromAssemblyInternal(typeof(ISourceGenerator).Assembly) }), new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); compilation.VerifyDiagnostics(); var result = compilation.Emit(generatorPath); Assert.True(result.Success); return generatorPath; } } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal abstract class CompilationStartedAnalyzer : DiagnosticAnalyzer { public abstract override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } public abstract void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context); public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction(CreateAnalyzerWithinCompilation); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal class HiddenDiagnosticAnalyzer : CompilationStartedAnalyzer { internal static readonly DiagnosticDescriptor Hidden01 = new DiagnosticDescriptor("Hidden01", "", "Throwing a diagnostic for #region", "", DiagnosticSeverity.Hidden, isEnabledByDefault: true); internal static readonly DiagnosticDescriptor Hidden02 = new DiagnosticDescriptor("Hidden02", "", "Throwing a diagnostic for something else", "", DiagnosticSeverity.Hidden, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Hidden01, Hidden02); } } private void AnalyzeNode(SyntaxNodeAnalysisContext context) { context.ReportDiagnostic(Diagnostic.Create(Hidden01, context.Node.GetLocation())); } public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.RegionDirectiveTrivia); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal class InfoDiagnosticAnalyzer : CompilationStartedAnalyzer { internal static readonly DiagnosticDescriptor Info01 = new DiagnosticDescriptor("Info01", "", "Throwing a diagnostic for #pragma restore", "", DiagnosticSeverity.Info, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Info01); } } private void AnalyzeNode(SyntaxNodeAnalysisContext context) { if ((context.Node as PragmaWarningDirectiveTriviaSyntax).DisableOrRestoreKeyword.IsKind(SyntaxKind.RestoreKeyword)) { context.ReportDiagnostic(Diagnostic.Create(Info01, context.Node.GetLocation())); } } public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.PragmaWarningDirectiveTrivia); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal class WarningDiagnosticAnalyzer : CompilationStartedAnalyzer { internal static readonly DiagnosticDescriptor Warning01 = new DiagnosticDescriptor("Warning01", "", "Throwing a diagnostic for types declared", "", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Warning01); } } public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSymbolAction( (symbolContext) => { symbolContext.ReportDiagnostic(Diagnostic.Create(Warning01, symbolContext.Symbol.Locations.First())); }, SymbolKind.NamedType); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal class ErrorDiagnosticAnalyzer : CompilationStartedAnalyzer { internal static readonly DiagnosticDescriptor Error01 = new DiagnosticDescriptor("Error01", "", "Throwing a diagnostic for #pragma disable", "", DiagnosticSeverity.Error, isEnabledByDefault: true); internal static readonly DiagnosticDescriptor Error02 = new DiagnosticDescriptor("Error02", "", "Throwing a diagnostic for something else", "", DiagnosticSeverity.Error, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Error01, Error02); } } public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSyntaxNodeAction( (nodeContext) => { if ((nodeContext.Node as PragmaWarningDirectiveTriviaSyntax).DisableOrRestoreKeyword.IsKind(SyntaxKind.DisableKeyword)) { nodeContext.ReportDiagnostic(Diagnostic.Create(Error01, nodeContext.Node.GetLocation())); } }, SyntaxKind.PragmaWarningDirectiveTrivia ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using System.Globalization; using System.IO; using System.IO.MemoryMappedFiles; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Resources.Proprietary; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.DiaSymReader; using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Utilities; using Xunit; using Basic.Reference.Assemblies; using static Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers; using static Roslyn.Test.Utilities.SharedResourceHelpers; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests { public class CommandLineTests : CommandLineTestBase { #if NETCOREAPP private static readonly string s_CSharpCompilerExecutable; private static readonly string s_DotnetCscRun; #else private static readonly string s_CSharpCompilerExecutable = Path.Combine( Path.GetDirectoryName(typeof(CommandLineTests).GetTypeInfo().Assembly.Location), Path.Combine("dependency", "csc.exe")); private static readonly string s_DotnetCscRun = ExecutionConditionUtil.IsMono ? "mono" : string.Empty; #endif private static readonly string s_CSharpScriptExecutable; private static readonly string s_compilerVersion = CommonCompiler.GetProductVersion(typeof(CommandLineTests)); static CommandLineTests() { #if NETCOREAPP var cscDllPath = Path.Combine( Path.GetDirectoryName(typeof(CommandLineTests).GetTypeInfo().Assembly.Location), Path.Combine("dependency", "csc.dll")); var dotnetExe = DotNetCoreSdk.ExePath; var netStandardDllPath = AppDomain.CurrentDomain.GetAssemblies() .FirstOrDefault(assembly => !assembly.IsDynamic && assembly.Location.EndsWith("netstandard.dll")).Location; var netStandardDllDir = Path.GetDirectoryName(netStandardDllPath); // Since we are using references based on the UnitTest's runtime, we need to use // its runtime config when executing out program. var runtimeConfigPath = Path.ChangeExtension(Assembly.GetExecutingAssembly().Location, "runtimeconfig.json"); s_CSharpCompilerExecutable = $@"""{dotnetExe}"" ""{cscDllPath}"" /r:""{netStandardDllPath}"" /r:""{netStandardDllDir}/System.Private.CoreLib.dll"" /r:""{netStandardDllDir}/System.Console.dll"" /r:""{netStandardDllDir}/System.Runtime.dll"""; s_DotnetCscRun = $@"""{dotnetExe}"" exec --runtimeconfig ""{runtimeConfigPath}"""; s_CSharpScriptExecutable = s_CSharpCompilerExecutable.Replace("csc.dll", Path.Combine("csi", "csi.dll")); #else s_CSharpScriptExecutable = s_CSharpCompilerExecutable.Replace("csc.exe", Path.Combine("csi", "csi.exe")); #endif } private class TestCommandLineParser : CSharpCommandLineParser { private readonly Dictionary<string, string> _responseFiles; private readonly Dictionary<string, string[]> _recursivePatterns; private readonly Dictionary<string, string[]> _patterns; public TestCommandLineParser( Dictionary<string, string> responseFiles = null, Dictionary<string, string[]> patterns = null, Dictionary<string, string[]> recursivePatterns = null, bool isInteractive = false) : base(isInteractive) { _responseFiles = responseFiles; _recursivePatterns = recursivePatterns; _patterns = patterns; } internal override IEnumerable<string> EnumerateFiles(string directory, string fileNamePattern, SearchOption searchOption) { var key = directory + "|" + fileNamePattern; if (searchOption == SearchOption.TopDirectoryOnly) { return _patterns[key]; } else { return _recursivePatterns[key]; } } internal override TextReader CreateTextFileReader(string fullPath) { return new StringReader(_responseFiles[fullPath]); } } private CSharpCommandLineArguments ScriptParse(IEnumerable<string> args, string baseDirectory) { return CSharpCommandLineParser.Script.Parse(args, baseDirectory, SdkDirectory); } private CSharpCommandLineArguments FullParse(string commandLine, string baseDirectory, string sdkDirectory = null, string additionalReferenceDirectories = null) { sdkDirectory = sdkDirectory ?? SdkDirectory; var args = CommandLineParser.SplitCommandLineIntoArguments(commandLine, removeHashComments: true); return CSharpCommandLineParser.Default.Parse(args, baseDirectory, sdkDirectory, additionalReferenceDirectories); } [ConditionalFact(typeof(WindowsDesktopOnly))] [WorkItem(34101, "https://github.com/dotnet/roslyn/issues/34101")] public void SuppressedWarnAsErrorsStillEmit() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" #pragma warning disable 1591 public class P { public static void Main() {} }"); const string docName = "doc.xml"; var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/errorlog:errorlog", $"/doc:{docName}", "/warnaserror", src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); string exePath = Path.Combine(dir.Path, "temp.exe"); Assert.True(File.Exists(exePath)); var result = ProcessUtilities.Run(exePath, arguments: ""); Assert.Equal(0, result.ExitCode); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] public void XmlMemoryMapped() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText("class C {}"); const string docName = "doc.xml"; var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", $"/doc:{docName}", src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); var xmlPath = Path.Combine(dir.Path, docName); using (var fileStream = new FileStream(xmlPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var mmf = MemoryMappedFile.CreateFromFile(fileStream, "xmlMap", 0, MemoryMappedFileAccess.Read, HandleInheritability.None, leaveOpen: true)) { exitCode = cmd.Run(outWriter); Assert.StartsWith($"error CS0016: Could not write to output file '{xmlPath}' -- ", outWriter.ToString()); Assert.Equal(1, exitCode); } } [Fact] public void SimpleAnalyzerConfig() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.cs0169.severity = none"); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path }); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); Assert.Null(cmd.AnalyzerOptions); } [Fact] public void AnalyzerConfigWithOptions() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var additionalFile = dir.CreateFile("file.txt"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.cs0169.severity = none dotnet_diagnostic.Warning01.severity = none my_option = my_val [*.txt] dotnet_diagnostic.cs0169.severity = none my_option2 = my_val2"); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/analyzerconfig:" + analyzerConfig.Path, "/analyzer:" + Assembly.GetExecutingAssembly().Location, "/nowarn:8032", "/additionalfile:" + additionalFile.Path, src.Path }); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal("", outWriter.ToString()); Assert.Equal(0, exitCode); var comp = cmd.Compilation; var tree = comp.SyntaxTrees.Single(); var compilerTreeOptions = comp.Options.SyntaxTreeOptionsProvider; Assert.True(compilerTreeOptions.TryGetDiagnosticValue(tree, "cs0169", CancellationToken.None, out var severity)); Assert.Equal(ReportDiagnostic.Suppress, severity); Assert.True(compilerTreeOptions.TryGetDiagnosticValue(tree, "warning01", CancellationToken.None, out severity)); Assert.Equal(ReportDiagnostic.Suppress, severity); var analyzerOptions = cmd.AnalyzerOptions.AnalyzerConfigOptionsProvider; var options = analyzerOptions.GetOptions(tree); Assert.NotNull(options); Assert.True(options.TryGetValue("my_option", out string val)); Assert.Equal("my_val", val); Assert.False(options.TryGetValue("my_option2", out _)); Assert.False(options.TryGetValue("dotnet_diagnostic.cs0169.severity", out _)); options = analyzerOptions.GetOptions(cmd.AnalyzerOptions.AdditionalFiles.Single()); Assert.NotNull(options); Assert.True(options.TryGetValue("my_option2", out val)); Assert.Equal("my_val2", val); Assert.False(options.TryGetValue("my_option", out _)); Assert.False(options.TryGetValue("dotnet_diagnostic.cs0169.severity", out _)); } [Fact] public void AnalyzerConfigBadSeverity() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.cs0169.severity = garbage"); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path }); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal( $@"warning InvalidSeverityInAnalyzerConfig: The diagnostic 'cs0169' was given an invalid severity 'garbage' in the analyzer config file at '{analyzerConfig.Path}'. test.cs(4,9): warning CS0169: The field 'C._f' is never used ", outWriter.ToString()); Assert.Null(cmd.AnalyzerOptions); } [Fact] public void AnalyzerConfigsInSameDir() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var configText = @" [*.cs] dotnet_diagnostic.cs0169.severity = suppress"; var analyzerConfig1 = dir.CreateFile("analyzerconfig1").WriteAllText(configText); var analyzerConfig2 = dir.CreateFile("analyzerconfig2").WriteAllText(configText); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig1.Path, "/analyzerconfig:" + analyzerConfig2.Path, src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal( $"error CS8700: Multiple analyzer config files cannot be in the same directory ('{dir.Path}').", outWriter.ToString().TrimEnd()); } // This test should only run when the machine's default encoding is shift-JIS [ConditionalFact(typeof(WindowsDesktopOnly), typeof(HasShiftJisDefaultEncoding), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void CompileShiftJisOnShiftJis() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("sjis.cs").WriteAllBytes(TestResources.General.ShiftJisSource); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", src.Path }); Assert.Null(cmd.Arguments.Encoding); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); var result = ProcessUtilities.Run(Path.Combine(dir.Path, "sjis.exe"), arguments: "", workingDirectory: dir.Path); Assert.Equal(0, result.ExitCode); Assert.Equal("星野 八郎太", File.ReadAllText(Path.Combine(dir.Path, "output.txt"), Encoding.GetEncoding(932))); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void RunWithShiftJisFile() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("sjis.cs").WriteAllBytes(TestResources.General.ShiftJisSource); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/codepage:932", src.Path }); Assert.Equal(932, cmd.Arguments.Encoding?.WindowsCodePage); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); var result = ProcessUtilities.Run(Path.Combine(dir.Path, "sjis.exe"), arguments: "", workingDirectory: dir.Path); Assert.Equal(0, result.ExitCode); Assert.Equal("星野 八郎太", File.ReadAllText(Path.Combine(dir.Path, "output.txt"), Encoding.GetEncoding(932))); } [WorkItem(946954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/946954")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void CompilerBinariesAreAnyCPU() { Assert.Equal(ProcessorArchitecture.MSIL, AssemblyName.GetAssemblyName(s_CSharpCompilerExecutable).ProcessorArchitecture); } [Fact] public void ResponseFiles1() { string rsp = Temp.CreateFile().WriteAllText(@" /r:System.dll /nostdlib # this is ignored System.Console.WriteLine(""*?""); # this is error a.cs ").Path; var cmd = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { "b.cs" }); cmd.Arguments.Errors.Verify( // error CS2001: Source file 'System.Console.WriteLine(*?);' could not be found Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments("System.Console.WriteLine(*?);")); AssertEx.Equal(new[] { "System.dll" }, cmd.Arguments.MetadataReferences.Select(r => r.Reference)); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "a.cs"), Path.Combine(WorkingDirectory, "b.cs") }, cmd.Arguments.SourceFiles.Select(file => file.Path)); CleanupAllGeneratedFiles(rsp); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] public void ResponseFiles_RelativePaths() { var parentDir = Temp.CreateDirectory(); var baseDir = parentDir.CreateDirectory("temp"); var dirX = baseDir.CreateDirectory("x"); var dirAB = baseDir.CreateDirectory("a b"); var dirSubDir = baseDir.CreateDirectory("subdir"); var dirGoo = parentDir.CreateDirectory("goo"); var dirBar = parentDir.CreateDirectory("bar"); string basePath = baseDir.Path; Func<string, string> prependBasePath = fileName => Path.Combine(basePath, fileName); var parser = new TestCommandLineParser(responseFiles: new Dictionary<string, string>() { { prependBasePath(@"a.rsp"), @" ""@subdir\b.rsp"" /r:..\v4.0.30319\System.dll /r:.\System.Data.dll a.cs @""..\c.rsp"" @\d.rsp /libpaths:..\goo;../bar;""a b"" " }, { Path.Combine(dirSubDir.Path, @"b.rsp"), @" b.cs " }, { prependBasePath(@"..\c.rsp"), @" c.cs /lib:x " }, { Path.Combine(Path.GetPathRoot(basePath), @"d.rsp"), @" # comment d.cs " } }, isInteractive: false); var args = parser.Parse(new[] { "first.cs", "second.cs", "@a.rsp", "last.cs" }, basePath, SdkDirectory); args.Errors.Verify(); Assert.False(args.IsScriptRunner); string[] resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); string[] references = args.MetadataReferences.Select(r => r.Reference).ToArray(); AssertEx.Equal(new[] { "first.cs", "second.cs", "b.cs", "a.cs", "c.cs", "d.cs", "last.cs" }.Select(prependBasePath), resolvedSourceFiles); AssertEx.Equal(new[] { typeof(object).Assembly.Location, @"..\v4.0.30319\System.dll", @".\System.Data.dll" }, references); AssertEx.Equal(new[] { RuntimeEnvironment.GetRuntimeDirectory() }.Concat(new[] { @"x", @"..\goo", @"../bar", @"a b" }.Select(prependBasePath)), args.ReferencePaths.ToArray()); Assert.Equal(basePath, args.BaseDirectory); } #nullable enable [ConditionalFact(typeof(WindowsOnly))] public void NullBaseDirectoryNotAddedToKeyFileSearchPaths() { var parser = CSharpCommandLineParser.Default.Parse(new[] { "c:/test.cs" }, baseDirectory: null, SdkDirectory); AssertEx.Equal(ImmutableArray.Create<string>(), parser.KeyFileSearchPaths); Assert.Null(parser.OutputDirectory); parser.Errors.Verify( // error CS8762: Output directory could not be determined Diagnostic(ErrorCode.ERR_NoOutputDirectory).WithLocation(1, 1) ); } [ConditionalFact(typeof(WindowsOnly))] public void NullBaseDirectoryWithAdditionalFiles() { var parser = CSharpCommandLineParser.Default.Parse(new[] { "/additionalfile:web.config", "c:/test.cs" }, baseDirectory: null, SdkDirectory); AssertEx.Equal(ImmutableArray.Create<string>(), parser.KeyFileSearchPaths); Assert.Null(parser.OutputDirectory); parser.Errors.Verify( // error CS2021: File name 'web.config' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("web.config").WithLocation(1, 1), // error CS8762: Output directory could not be determined Diagnostic(ErrorCode.ERR_NoOutputDirectory).WithLocation(1, 1) ); } [ConditionalFact(typeof(WindowsOnly))] public void NullBaseDirectoryWithAdditionalFiles_Wildcard() { var parser = CSharpCommandLineParser.Default.Parse(new[] { "/additionalfile:*", "c:/test.cs" }, baseDirectory: null, SdkDirectory); AssertEx.Equal(ImmutableArray.Create<string>(), parser.KeyFileSearchPaths); Assert.Null(parser.OutputDirectory); parser.Errors.Verify( // error CS2001: Source file '*' could not be found. Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments("*").WithLocation(1, 1), // error CS8762: Output directory could not be determined Diagnostic(ErrorCode.ERR_NoOutputDirectory).WithLocation(1, 1) ); } #nullable disable [Fact, WorkItem(29252, "https://github.com/dotnet/roslyn/issues/29252")] public void NoSdkPath() { var parentDir = Temp.CreateDirectory(); var parser = CSharpCommandLineParser.Default.Parse(new[] { "file.cs", $"-out:{parentDir.Path}", "/noSdkPath" }, parentDir.Path, null); AssertEx.Equal(ImmutableArray<string>.Empty, parser.ReferencePaths); } [Fact, WorkItem(29252, "https://github.com/dotnet/roslyn/issues/29252")] public void NoSdkPathReferenceSystemDll() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/nosdkpath", "/r:System.dll", "a.cs" }); var exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS0006: Metadata file 'System.dll' could not be found", outWriter.ToString().Trim()); } [ConditionalFact(typeof(WindowsOnly))] public void SourceFiles_Patterns() { var parser = new TestCommandLineParser( patterns: new Dictionary<string, string[]>() { { @"C:\temp|*.cs", new[] { "a.cs", "b.cs", "c.cs" } } }, recursivePatterns: new Dictionary<string, string[]>() { { @"C:\temp\a|*.cs", new[] { @"a\x.cs", @"a\b\b.cs", @"a\c.cs" } }, }); var args = parser.Parse(new[] { @"*.cs", @"/recurse:a\*.cs" }, @"C:\temp", SdkDirectory); args.Errors.Verify(); string[] resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); AssertEx.Equal(new[] { @"C:\temp\a.cs", @"C:\temp\b.cs", @"C:\temp\c.cs", @"C:\temp\a\x.cs", @"C:\temp\a\b\b.cs", @"C:\temp\a\c.cs" }, resolvedSourceFiles); } [Fact] public void ParseQuotedMainType() { // Verify the main switch are unquoted when used because of the issue with // MSBuild quoting some usages and not others. A quote character is not valid in either // these names. CSharpCommandLineArguments args; var folder = Temp.CreateDirectory(); CreateFile(folder, "a.cs"); args = DefaultParse(new[] { "/main:Test", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/main:\"Test\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/main:\"Test.Class1\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test.Class1", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/m:Test", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/m:\"Test\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/m:\"Test.Class1\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test.Class1", args.CompilationOptions.MainTypeName); // Use of Cyrillic namespace args = DefaultParse(new[] { "/m:\"решения.Class1\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("решения.Class1", args.CompilationOptions.MainTypeName); } [Fact] [WorkItem(21508, "https://github.com/dotnet/roslyn/issues/21508")] public void ArgumentStartWithDashAndContainingSlash() { CSharpCommandLineArguments args; var folder = Temp.CreateDirectory(); args = DefaultParse(new[] { "-debug+/debug:portable" }, folder.Path); args.Errors.Verify( // error CS2007: Unrecognized option: '-debug+/debug:portable' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("-debug+/debug:portable").WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1) ); } [WorkItem(546009, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546009")] [WorkItem(545991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545991")] [ConditionalFact(typeof(WindowsOnly))] public void SourceFiles_Patterns2() { var folder = Temp.CreateDirectory(); CreateFile(folder, "a.cs"); CreateFile(folder, "b.vb"); CreateFile(folder, "c.cpp"); var folderA = folder.CreateDirectory("A"); CreateFile(folderA, "A_a.cs"); CreateFile(folderA, "A_b.cs"); CreateFile(folderA, "A_c.vb"); var folderB = folder.CreateDirectory("B"); CreateFile(folderB, "B_a.cs"); CreateFile(folderB, "B_b.vb"); CreateFile(folderB, "B_c.cpx"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse:.", "/out:abc.dll" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse:. ", "/out:abc.dll" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse: . ", "/out:abc.dll" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse:././.", "/out:abc.dll" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim()); CSharpCommandLineArguments args; string[] resolvedSourceFiles; args = DefaultParse(new[] { @"/recurse:*.cp*", @"/recurse:a\*.c*", @"/out:a.dll" }, folder.Path); args.Errors.Verify(); resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); AssertEx.Equal(new[] { folder.Path + @"\c.cpp", folder.Path + @"\B\B_c.cpx", folder.Path + @"\a\A_a.cs", folder.Path + @"\a\A_b.cs", }, resolvedSourceFiles); args = DefaultParse(new[] { @"/recurse:.\\\\\\*.cs", @"/out:a.dll" }, folder.Path); args.Errors.Verify(); resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); Assert.Equal(4, resolvedSourceFiles.Length); args = DefaultParse(new[] { @"/recurse:.////*.cs", @"/out:a.dll" }, folder.Path); args.Errors.Verify(); resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); Assert.Equal(4, resolvedSourceFiles.Length); } [ConditionalFact(typeof(WindowsOnly))] public void SourceFile_BadPath() { var args = DefaultParse(new[] { @"e:c:\test\test.cs", "/t:library" }, WorkingDirectory); Assert.Equal(3, args.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, args.Errors[0].Code); Assert.Equal((int)ErrorCode.WRN_NoSources, args.Errors[1].Code); Assert.Equal((int)ErrorCode.ERR_OutputNeedsName, args.Errors[2].Code); } private void CreateFile(TempDirectory folder, string file) { var f = folder.CreateFile(file); f.WriteAllText(""); } [Fact, WorkItem(546023, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546023")] public void Win32ResourceArguments() { string[] args = new string[] { @"/win32manifest:..\here\there\everywhere\nonexistent" }; var parsedArgs = DefaultParse(args, WorkingDirectory); var compilation = CreateCompilation(new SyntaxTree[0]); IEnumerable<DiagnosticInfo> errors; CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Manifest, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32icon:\bogus" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenIcon, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32Res:\bogus" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Res, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32Res:goo.win32data:bar.win32data2" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Res, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32icon:goo.win32data:bar.win32data2" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenIcon, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32manifest:goo.win32data:bar.win32data2" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Manifest, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); } [Fact] public void Win32ResConflicts() { var parsedArgs = DefaultParse(new[] { "/win32res:goo", "/win32icon:goob", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_CantHaveWin32ResAndIcon, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "/win32res:goo", "/win32manifest:goob", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_CantHaveWin32ResAndManifest, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "/win32res:", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_NoFileSpec, parsedArgs.Errors.First().Code); Assert.Equal(1, parsedArgs.Errors.First().Arguments.Count); parsedArgs = DefaultParse(new[] { "/win32Icon: ", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_NoFileSpec, parsedArgs.Errors.First().Code); Assert.Equal(1, parsedArgs.Errors.First().Arguments.Count); parsedArgs = DefaultParse(new[] { "/win32Manifest:", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_NoFileSpec, parsedArgs.Errors.First().Code); Assert.Equal(1, parsedArgs.Errors.First().Arguments.Count); parsedArgs = DefaultParse(new[] { "/win32Manifest:goo", "/noWin32Manifest", "a.cs" }, WorkingDirectory); Assert.Equal(0, parsedArgs.Errors.Length); Assert.True(parsedArgs.NoWin32Manifest); Assert.Null(parsedArgs.Win32Manifest); } [Fact] public void Win32ResInvalid() { var parsedArgs = DefaultParse(new[] { "/win32res", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/win32res")); parsedArgs = DefaultParse(new[] { "/win32res+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/win32res+")); parsedArgs = DefaultParse(new[] { "/win32icon", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/win32icon")); parsedArgs = DefaultParse(new[] { "/win32icon+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/win32icon+")); parsedArgs = DefaultParse(new[] { "/win32manifest", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/win32manifest")); parsedArgs = DefaultParse(new[] { "/win32manifest+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/win32manifest+")); } [Fact] public void Win32IconContainsGarbage() { string tmpFileName = Temp.CreateFile().WriteAllBytes(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }).Path; var parsedArgs = DefaultParse(new[] { "/win32icon:" + tmpFileName, "a.cs" }, WorkingDirectory); var compilation = CreateCompilation(new SyntaxTree[0]); IEnumerable<DiagnosticInfo> errors; CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_ErrorBuildingWin32Resources, errors.First().Code); Assert.Equal(1, errors.First().Arguments.Count()); CleanupAllGeneratedFiles(tmpFileName); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void Win32ResQuotes() { string[] responseFile = new string[] { @" /win32res:d:\\""abc def""\a""b c""d\a.res", }; CSharpCommandLineArguments args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\"); Assert.Equal(@"d:\abc def\ab cd\a.res", args.Win32ResourceFile); responseFile = new string[] { @" /win32icon:d:\\""abc def""\a""b c""d\a.ico", }; args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\"); Assert.Equal(@"d:\abc def\ab cd\a.ico", args.Win32Icon); responseFile = new string[] { @" /win32manifest:d:\\""abc def""\a""b c""d\a.manifest", }; args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\"); Assert.Equal(@"d:\abc def\ab cd\a.manifest", args.Win32Manifest); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseResources() { var diags = new List<Diagnostic>(); ResourceDescription desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,someName", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("someName", desc.ResourceName); desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\s""ome Fil""e.goo.bar,someName", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"some File.goo.bar", desc.FileName); Assert.Equal("someName", desc.ResourceName); desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,""some Name"",public", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("some Name", desc.ResourceName); Assert.True(desc.IsPublic); // Use file name in place of missing resource name. desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); Assert.False(desc.IsPublic); // Quoted accessibility is fine. desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,""private""", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); Assert.False(desc.IsPublic); // Leading commas are not ignored... desc = CSharpCommandLineParser.ParseResourceDescription("", @",,\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option '\somepath\someFile.goo.bar'; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(@"\somepath\someFile.goo.bar")); diags.Clear(); Assert.Null(desc); // ...even if there's whitespace between them. desc = CSharpCommandLineParser.ParseResourceDescription("", @", ,\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option '\somepath\someFile.goo.bar'; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(@"\somepath\someFile.goo.bar")); diags.Clear(); Assert.Null(desc); // Trailing commas are ignored... desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false); diags.Verify(); diags.Clear(); Assert.Equal("someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); Assert.False(desc.IsPublic); // ...even if there's whitespace between them. desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,private, ,", WorkingDirectory, diags, embedded: false); diags.Verify(); diags.Clear(); Assert.Equal("someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); Assert.False(desc.IsPublic); desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,someName,publi", WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments("publi")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", @"D:rive\relative\path,someName,public", WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"D:rive\relative\path")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", @"inva\l*d?path,someName,public", WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"inva\l*d?path")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", (string)null, WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", "", WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", " ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", " , ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path, ", WorkingDirectory, diags, embedded: false); diags.Verify(); diags.Clear(); Assert.Equal("path", desc.FileName); Assert.Equal("path", desc.ResourceName); Assert.True(desc.IsPublic); desc = CSharpCommandLineParser.ParseResourceDescription("", " ,name", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", " , , ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option ' '; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" ")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path, , ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option ' '; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" ")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", " ,name, ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option ' '; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" ")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", " , ,private", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path,name,", WorkingDirectory, diags, embedded: false); diags.Verify( // CONSIDER: Dev10 actually prints "Invalid option '|'" (note the pipe) // error CS1906: Invalid option ''; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments("")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path,name,,", WorkingDirectory, diags, embedded: false); diags.Verify( // CONSIDER: Dev10 actually prints "Invalid option '|'" (note the pipe) // error CS1906: Invalid option ''; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments("")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path,name, ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option ''; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" ")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path, ,private", WorkingDirectory, diags, embedded: false); diags.Verify(); diags.Clear(); Assert.Equal("path", desc.FileName); Assert.Equal("path", desc.ResourceName); Assert.False(desc.IsPublic); desc = CSharpCommandLineParser.ParseResourceDescription("", " ,name,private", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); var longE = new String('e', 1024); desc = CSharpCommandLineParser.ParseResourceDescription("", String.Format("path,{0},private", longE), WorkingDirectory, diags, embedded: false); diags.Verify(); // Now checked during emit. diags.Clear(); Assert.Equal("path", desc.FileName); Assert.Equal(longE, desc.ResourceName); Assert.False(desc.IsPublic); var longI = new String('i', 260); desc = CSharpCommandLineParser.ParseResourceDescription("", String.Format("{0},e,private", longI), WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2021: File name 'iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii").WithLocation(1, 1)); } [Fact] public void ManagedResourceOptions() { CSharpCommandLineArguments parsedArgs; ResourceDescription resourceDescription; parsedArgs = DefaultParse(new[] { "/resource:a", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); resourceDescription = parsedArgs.ManifestResources.Single(); Assert.Null(resourceDescription.FileName); // since embedded Assert.Equal("a", resourceDescription.ResourceName); parsedArgs = DefaultParse(new[] { "/res:b", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); resourceDescription = parsedArgs.ManifestResources.Single(); Assert.Null(resourceDescription.FileName); // since embedded Assert.Equal("b", resourceDescription.ResourceName); parsedArgs = DefaultParse(new[] { "/linkresource:c", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); resourceDescription = parsedArgs.ManifestResources.Single(); Assert.Equal("c", resourceDescription.FileName); Assert.Equal("c", resourceDescription.ResourceName); parsedArgs = DefaultParse(new[] { "/linkres:d", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); resourceDescription = parsedArgs.ManifestResources.Single(); Assert.Equal("d", resourceDescription.FileName); Assert.Equal("d", resourceDescription.ResourceName); } [Fact] public void ManagedResourceOptions_SimpleErrors() { var parsedArgs = DefaultParse(new[] { "/resource:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/resource:")); parsedArgs = DefaultParse(new[] { "/resource: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/resource:")); parsedArgs = DefaultParse(new[] { "/res", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/res")); parsedArgs = DefaultParse(new[] { "/RES+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/RES+")); parsedArgs = DefaultParse(new[] { "/res-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/res-:")); parsedArgs = DefaultParse(new[] { "/linkresource:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/linkresource:")); parsedArgs = DefaultParse(new[] { "/linkresource: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/linkresource:")); parsedArgs = DefaultParse(new[] { "/linkres", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/linkres")); parsedArgs = DefaultParse(new[] { "/linkRES+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/linkRES+")); parsedArgs = DefaultParse(new[] { "/linkres-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/linkres-:")); } [Fact] public void Link_SimpleTests() { var parsedArgs = DefaultParse(new[] { "/link:a", "/link:b,,,,c", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "a", "b", "c" }, parsedArgs.MetadataReferences. Where((res) => res.Properties.EmbedInteropTypes). Select((res) => res.Reference)); parsedArgs = DefaultParse(new[] { "/Link: ,,, b ,,", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { " b " }, parsedArgs.MetadataReferences. Where((res) => res.Properties.EmbedInteropTypes). Select((res) => res.Reference)); parsedArgs = DefaultParse(new[] { "/l:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/l:")); parsedArgs = DefaultParse(new[] { "/L", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/L")); parsedArgs = DefaultParse(new[] { "/l+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/l+")); parsedArgs = DefaultParse(new[] { "/link-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/link-:")); } [ConditionalFact(typeof(WindowsOnly))] public void Recurse_SimpleTests() { var dir = Temp.CreateDirectory(); var file1 = dir.CreateFile("a.cs"); var file2 = dir.CreateFile("b.cs"); var file3 = dir.CreateFile("c.txt"); var file4 = dir.CreateDirectory("d1").CreateFile("d.txt"); var file5 = dir.CreateDirectory("d2").CreateFile("e.cs"); file1.WriteAllText(""); file2.WriteAllText(""); file3.WriteAllText(""); file4.WriteAllText(""); file5.WriteAllText(""); var parsedArgs = DefaultParse(new[] { "/recurse:" + dir.ToString() + "\\*.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "{DIR}\\a.cs", "{DIR}\\b.cs", "{DIR}\\d2\\e.cs" }, parsedArgs.SourceFiles.Select((file) => file.Path.Replace(dir.ToString(), "{DIR}"))); parsedArgs = DefaultParse(new[] { "*.cs" }, dir.ToString()); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "{DIR}\\a.cs", "{DIR}\\b.cs" }, parsedArgs.SourceFiles.Select((file) => file.Path.Replace(dir.ToString(), "{DIR}"))); parsedArgs = DefaultParse(new[] { "/reCURSE:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/reCURSE:")); parsedArgs = DefaultParse(new[] { "/RECURSE: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/RECURSE:")); parsedArgs = DefaultParse(new[] { "/recurse", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/recurse")); parsedArgs = DefaultParse(new[] { "/recurse+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/recurse+")); parsedArgs = DefaultParse(new[] { "/recurse-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/recurse-:")); CleanupAllGeneratedFiles(file1.Path); CleanupAllGeneratedFiles(file2.Path); CleanupAllGeneratedFiles(file3.Path); CleanupAllGeneratedFiles(file4.Path); CleanupAllGeneratedFiles(file5.Path); } [Fact] public void Reference_SimpleTests() { var parsedArgs = DefaultParse(new[] { "/nostdlib", "/r:a", "/REFERENCE:b,,,,c", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "a", "b", "c" }, parsedArgs.MetadataReferences. Where((res) => !res.Properties.EmbedInteropTypes). Select((res) => res.Reference)); parsedArgs = DefaultParse(new[] { "/Reference: ,,, b ,,", "/nostdlib", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { " b " }, parsedArgs.MetadataReferences. Where((res) => !res.Properties.EmbedInteropTypes). Select((res) => res.Reference)); parsedArgs = DefaultParse(new[] { "/Reference:a=b,,,", "/nostdlib", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.MetadataReferences.Single().Properties.Aliases.Single()); Assert.Equal("b", parsedArgs.MetadataReferences.Single().Reference); parsedArgs = DefaultParse(new[] { "/r:a=b,,,c", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_OneAliasPerReference).WithArguments("b,,,c")); parsedArgs = DefaultParse(new[] { "/r:1=b", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadExternIdentifier).WithArguments("1")); parsedArgs = DefaultParse(new[] { "/r:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/r:")); parsedArgs = DefaultParse(new[] { "/R", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/R")); parsedArgs = DefaultParse(new[] { "/reference+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/reference+")); parsedArgs = DefaultParse(new[] { "/reference-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/reference-:")); } [Fact] public void Target_SimpleTests() { var parsedArgs = DefaultParse(new[] { "/target:exe", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.ConsoleApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/t:module", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:library", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.DynamicallyLinkedLibrary, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/TARGET:winexe", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.WindowsApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:appcontainerexe", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.WindowsRuntimeApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:winmdobj", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.WindowsRuntimeMetadata, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:winexe", "/T:exe", "/target:module", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/t", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/t")); parsedArgs = DefaultParse(new[] { "/target:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_InvalidTarget)); parsedArgs = DefaultParse(new[] { "/target:xyz", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_InvalidTarget)); parsedArgs = DefaultParse(new[] { "/T+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/T+")); parsedArgs = DefaultParse(new[] { "/TARGET-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/TARGET-:")); } [Fact] public void Target_SimpleTestsNoSource() { var parsedArgs = DefaultParse(new[] { "/target:exe" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.ConsoleApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/t:module" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:library" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.DynamicallyLinkedLibrary, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/TARGET:winexe" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.WindowsApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:appcontainerexe" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.WindowsRuntimeApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:winmdobj" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.WindowsRuntimeMetadata, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:winexe", "/T:exe", "/target:module" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/t" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/t' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/t").WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/target:" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2019: Invalid target type for /target: must specify 'exe', 'winexe', 'library', or 'module' Diagnostic(ErrorCode.FTL_InvalidTarget).WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/target:xyz" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2019: Invalid target type for /target: must specify 'exe', 'winexe', 'library', or 'module' Diagnostic(ErrorCode.FTL_InvalidTarget).WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/T+" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/T+' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/T+").WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/TARGET-:" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/TARGET-:' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/TARGET-:").WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); } [Fact] public void ModuleManifest() { CSharpCommandLineArguments args = DefaultParse(new[] { "/win32manifest:blah", "/target:module", "a.cs" }, WorkingDirectory); args.Errors.Verify( // warning CS1927: Ignoring /win32manifest for module because it only applies to assemblies Diagnostic(ErrorCode.WRN_CantHaveManifestForModule)); // Illegal, but not clobbered. Assert.Equal("blah", args.Win32Manifest); } [Fact] public void ArgumentParsing() { var sdkDirectory = SdkDirectory; var parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "a + b" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "a + b; c" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/help" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayHelp); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/version" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayVersion); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/langversion:?" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayLangVersions); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "//langversion:?" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS2001: Source file '//langversion:?' could not be found. Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments("//langversion:?").WithLocation(1, 1) ); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/version", "c.csx" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayVersion); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/version:something" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayVersion); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/?" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayHelp); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "c.csx /langversion:6" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/langversion:-1", "c.csx", }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS1617: Invalid option '-1' for /langversion. Use '/langversion:?' to list supported values. Diagnostic(ErrorCode.ERR_BadCompatMode).WithArguments("-1").WithLocation(1, 1)); Assert.False(parsedArgs.DisplayHelp); Assert.Equal(1, parsedArgs.SourceFiles.Length); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "c.csx /r:s=d /r:d.dll" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "@roslyn_test_non_existing_file" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS2011: Error opening response file 'D:\R0\Main\Binaries\Debug\dd' Diagnostic(ErrorCode.ERR_OpenResponseFile).WithArguments(Path.Combine(WorkingDirectory, @"roslyn_test_non_existing_file"))); Assert.False(parsedArgs.DisplayHelp); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "c /define:DEBUG" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "\\" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/r:d.dll", "c.csx" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/define:goo", "c.csx" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/define:goo' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/define:goo")); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "\"/r d.dll\"" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/r: d.dll", "a.cs" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); } [Theory] [InlineData("iso-1", LanguageVersion.CSharp1)] [InlineData("iso-2", LanguageVersion.CSharp2)] [InlineData("1", LanguageVersion.CSharp1)] [InlineData("1.0", LanguageVersion.CSharp1)] [InlineData("2", LanguageVersion.CSharp2)] [InlineData("2.0", LanguageVersion.CSharp2)] [InlineData("3", LanguageVersion.CSharp3)] [InlineData("3.0", LanguageVersion.CSharp3)] [InlineData("4", LanguageVersion.CSharp4)] [InlineData("4.0", LanguageVersion.CSharp4)] [InlineData("5", LanguageVersion.CSharp5)] [InlineData("5.0", LanguageVersion.CSharp5)] [InlineData("6", LanguageVersion.CSharp6)] [InlineData("6.0", LanguageVersion.CSharp6)] [InlineData("7", LanguageVersion.CSharp7)] [InlineData("7.0", LanguageVersion.CSharp7)] [InlineData("7.1", LanguageVersion.CSharp7_1)] [InlineData("7.2", LanguageVersion.CSharp7_2)] [InlineData("7.3", LanguageVersion.CSharp7_3)] [InlineData("8", LanguageVersion.CSharp8)] [InlineData("8.0", LanguageVersion.CSharp8)] [InlineData("9", LanguageVersion.CSharp9)] [InlineData("9.0", LanguageVersion.CSharp9)] [InlineData("preview", LanguageVersion.Preview)] public void LangVersion_CanParseCorrectVersions(string value, LanguageVersion expectedVersion) { var parsedArgs = DefaultParse(new[] { $"/langversion:{value}", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(expectedVersion, parsedArgs.ParseOptions.LanguageVersion); Assert.Equal(expectedVersion, parsedArgs.ParseOptions.SpecifiedLanguageVersion); var scriptParsedArgs = ScriptParse(new[] { $"/langversion:{value}" }, WorkingDirectory); scriptParsedArgs.Errors.Verify(); Assert.Equal(expectedVersion, scriptParsedArgs.ParseOptions.LanguageVersion); Assert.Equal(expectedVersion, scriptParsedArgs.ParseOptions.SpecifiedLanguageVersion); } [Theory] [InlineData("6", "7", LanguageVersion.CSharp7)] [InlineData("7", "6", LanguageVersion.CSharp6)] [InlineData("7", "1", LanguageVersion.CSharp1)] [InlineData("6", "iso-1", LanguageVersion.CSharp1)] [InlineData("6", "iso-2", LanguageVersion.CSharp2)] [InlineData("6", "default", LanguageVersion.Default)] [InlineData("7", "default", LanguageVersion.Default)] [InlineData("iso-2", "6", LanguageVersion.CSharp6)] public void LangVersion_LatterVersionOverridesFormerOne(string formerValue, string latterValue, LanguageVersion expectedVersion) { var parsedArgs = DefaultParse(new[] { $"/langversion:{formerValue}", $"/langversion:{latterValue}", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(expectedVersion, parsedArgs.ParseOptions.SpecifiedLanguageVersion); } [Fact] public void LangVersion_DefaultMapsCorrectly() { LanguageVersion defaultEffectiveVersion = LanguageVersion.Default.MapSpecifiedToEffectiveVersion(); Assert.NotEqual(LanguageVersion.Default, defaultEffectiveVersion); var parsedArgs = DefaultParse(new[] { "/langversion:default", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(LanguageVersion.Default, parsedArgs.ParseOptions.SpecifiedLanguageVersion); Assert.Equal(defaultEffectiveVersion, parsedArgs.ParseOptions.LanguageVersion); } [Fact] public void LangVersion_LatestMapsCorrectly() { LanguageVersion latestEffectiveVersion = LanguageVersion.Latest.MapSpecifiedToEffectiveVersion(); Assert.NotEqual(LanguageVersion.Latest, latestEffectiveVersion); var parsedArgs = DefaultParse(new[] { "/langversion:latest", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(LanguageVersion.Latest, parsedArgs.ParseOptions.SpecifiedLanguageVersion); Assert.Equal(latestEffectiveVersion, parsedArgs.ParseOptions.LanguageVersion); } [Fact] public void LangVersion_NoValueSpecified() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(LanguageVersion.Default, parsedArgs.ParseOptions.SpecifiedLanguageVersion); } [Theory] [InlineData("iso-3")] [InlineData("iso1")] [InlineData("8.1")] [InlineData("10.1")] [InlineData("11")] [InlineData("1000")] public void LangVersion_BadVersion(string value) { DefaultParse(new[] { $"/langversion:{value}", "a.cs" }, WorkingDirectory).Errors.Verify( // error CS1617: Invalid option 'XXX' for /langversion. Use '/langversion:?' to list supported values. Diagnostic(ErrorCode.ERR_BadCompatMode).WithArguments(value).WithLocation(1, 1) ); } [Theory] [InlineData("0")] [InlineData("05")] [InlineData("07")] [InlineData("07.1")] [InlineData("08")] [InlineData("09")] public void LangVersion_LeadingZeroes(string value) { DefaultParse(new[] { $"/langversion:{value}", "a.cs" }, WorkingDirectory).Errors.Verify( // error CS8303: Specified language version 'XXX' cannot have leading zeroes Diagnostic(ErrorCode.ERR_LanguageVersionCannotHaveLeadingZeroes).WithArguments(value).WithLocation(1, 1)); } [Theory] [InlineData("/langversion")] [InlineData("/langversion:")] [InlineData("/LANGversion:")] public void LangVersion_NoVersion(string option) { DefaultParse(new[] { option, "a.cs" }, WorkingDirectory).Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/langversion:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/langversion:").WithLocation(1, 1)); } [Fact] public void LangVersion_LangVersions() { var args = DefaultParse(new[] { "/langversion:?" }, WorkingDirectory); args.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1) ); Assert.True(args.DisplayLangVersions); } [Fact] public void LanguageVersionAdded_Canary() { // When a new version is added, this test will break. This list must be checked: // - update the "UpgradeProject" codefixer // - update all the tests that call this canary // - update MaxSupportedLangVersion (a relevant test should break when new version is introduced) // - email release management to add to the release notes (see old example: https://github.com/dotnet/core/pull/1454) AssertEx.SetEqual(new[] { "default", "1", "2", "3", "4", "5", "6", "7.0", "7.1", "7.2", "7.3", "8.0", "9.0", "10.0", "latest", "latestmajor", "preview" }, Enum.GetValues(typeof(LanguageVersion)).Cast<LanguageVersion>().Select(v => v.ToDisplayString())); // For minor versions and new major versions, the format should be "x.y", such as "7.1" } [Fact] public void LanguageVersion_GetErrorCode() { var versions = Enum.GetValues(typeof(LanguageVersion)) .Cast<LanguageVersion>() .Except(new[] { LanguageVersion.Default, LanguageVersion.Latest, LanguageVersion.LatestMajor, LanguageVersion.Preview }) .Select(v => v.GetErrorCode()); var errorCodes = new[] { ErrorCode.ERR_FeatureNotAvailableInVersion1, ErrorCode.ERR_FeatureNotAvailableInVersion2, ErrorCode.ERR_FeatureNotAvailableInVersion3, ErrorCode.ERR_FeatureNotAvailableInVersion4, ErrorCode.ERR_FeatureNotAvailableInVersion5, ErrorCode.ERR_FeatureNotAvailableInVersion6, ErrorCode.ERR_FeatureNotAvailableInVersion7, ErrorCode.ERR_FeatureNotAvailableInVersion7_1, ErrorCode.ERR_FeatureNotAvailableInVersion7_2, ErrorCode.ERR_FeatureNotAvailableInVersion7_3, ErrorCode.ERR_FeatureNotAvailableInVersion8, ErrorCode.ERR_FeatureNotAvailableInVersion9, ErrorCode.ERR_FeatureNotAvailableInVersion10, }; AssertEx.SetEqual(versions, errorCodes); // The canary check is a reminder that this test needs to be updated when a language version is added LanguageVersionAdded_Canary(); } [Theory, InlineData(LanguageVersion.CSharp1, LanguageVersion.CSharp1), InlineData(LanguageVersion.CSharp2, LanguageVersion.CSharp2), InlineData(LanguageVersion.CSharp3, LanguageVersion.CSharp3), InlineData(LanguageVersion.CSharp4, LanguageVersion.CSharp4), InlineData(LanguageVersion.CSharp5, LanguageVersion.CSharp5), InlineData(LanguageVersion.CSharp6, LanguageVersion.CSharp6), InlineData(LanguageVersion.CSharp7, LanguageVersion.CSharp7), InlineData(LanguageVersion.CSharp7_1, LanguageVersion.CSharp7_1), InlineData(LanguageVersion.CSharp7_2, LanguageVersion.CSharp7_2), InlineData(LanguageVersion.CSharp7_3, LanguageVersion.CSharp7_3), InlineData(LanguageVersion.CSharp8, LanguageVersion.CSharp8), InlineData(LanguageVersion.CSharp9, LanguageVersion.CSharp9), InlineData(LanguageVersion.CSharp10, LanguageVersion.CSharp10), InlineData(LanguageVersion.CSharp10, LanguageVersion.LatestMajor), InlineData(LanguageVersion.CSharp10, LanguageVersion.Latest), InlineData(LanguageVersion.CSharp10, LanguageVersion.Default), InlineData(LanguageVersion.Preview, LanguageVersion.Preview), ] public void LanguageVersion_MapSpecifiedToEffectiveVersion(LanguageVersion expectedMappedVersion, LanguageVersion input) { Assert.Equal(expectedMappedVersion, input.MapSpecifiedToEffectiveVersion()); Assert.True(expectedMappedVersion.IsValid()); // The canary check is a reminder that this test needs to be updated when a language version is added LanguageVersionAdded_Canary(); } [Theory, InlineData("iso-1", true, LanguageVersion.CSharp1), InlineData("ISO-1", true, LanguageVersion.CSharp1), InlineData("iso-2", true, LanguageVersion.CSharp2), InlineData("1", true, LanguageVersion.CSharp1), InlineData("1.0", true, LanguageVersion.CSharp1), InlineData("2", true, LanguageVersion.CSharp2), InlineData("2.0", true, LanguageVersion.CSharp2), InlineData("3", true, LanguageVersion.CSharp3), InlineData("3.0", true, LanguageVersion.CSharp3), InlineData("4", true, LanguageVersion.CSharp4), InlineData("4.0", true, LanguageVersion.CSharp4), InlineData("5", true, LanguageVersion.CSharp5), InlineData("5.0", true, LanguageVersion.CSharp5), InlineData("05", false, LanguageVersion.Default), InlineData("6", true, LanguageVersion.CSharp6), InlineData("6.0", true, LanguageVersion.CSharp6), InlineData("7", true, LanguageVersion.CSharp7), InlineData("7.0", true, LanguageVersion.CSharp7), InlineData("07", false, LanguageVersion.Default), InlineData("7.1", true, LanguageVersion.CSharp7_1), InlineData("7.2", true, LanguageVersion.CSharp7_2), InlineData("7.3", true, LanguageVersion.CSharp7_3), InlineData("8", true, LanguageVersion.CSharp8), InlineData("8.0", true, LanguageVersion.CSharp8), InlineData("9", true, LanguageVersion.CSharp9), InlineData("9.0", true, LanguageVersion.CSharp9), InlineData("10", true, LanguageVersion.CSharp10), InlineData("10.0", true, LanguageVersion.CSharp10), InlineData("08", false, LanguageVersion.Default), InlineData("07.1", false, LanguageVersion.Default), InlineData("default", true, LanguageVersion.Default), InlineData("latest", true, LanguageVersion.Latest), InlineData("latestmajor", true, LanguageVersion.LatestMajor), InlineData("preview", true, LanguageVersion.Preview), InlineData("latestpreview", false, LanguageVersion.Default), InlineData(null, true, LanguageVersion.Default), InlineData("bad", false, LanguageVersion.Default)] public void LanguageVersion_TryParseDisplayString(string input, bool success, LanguageVersion expected) { Assert.Equal(success, LanguageVersionFacts.TryParse(input, out var version)); Assert.Equal(expected, version); // The canary check is a reminder that this test needs to be updated when a language version is added LanguageVersionAdded_Canary(); } [Fact] public void LanguageVersion_TryParseTurkishDisplayString() { var originalCulture = Thread.CurrentThread.CurrentCulture; Thread.CurrentThread.CurrentCulture = new CultureInfo("tr-TR", useUserOverride: false); Assert.True(LanguageVersionFacts.TryParse("ISO-1", out var version)); Assert.Equal(LanguageVersion.CSharp1, version); Thread.CurrentThread.CurrentCulture = originalCulture; } [Fact] public void LangVersion_ListLangVersions() { var dir = Temp.CreateDirectory(); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/langversion:?" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var expected = Enum.GetValues(typeof(LanguageVersion)).Cast<LanguageVersion>() .Select(v => v.ToDisplayString()); var actual = outWriter.ToString(); var acceptableSurroundingChar = new[] { '\r', '\n', '(', ')', ' ' }; foreach (var version in expected) { if (version == "latest") continue; var foundIndex = actual.IndexOf(version); Assert.True(foundIndex > 0, $"Missing version '{version}'"); Assert.True(Array.IndexOf(acceptableSurroundingChar, actual[foundIndex - 1]) >= 0); Assert.True(Array.IndexOf(acceptableSurroundingChar, actual[foundIndex + version.Length]) >= 0); } } [Fact] [WorkItem(546961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546961")] public void Define() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); Assert.Equal(0, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count()); Assert.False(parsedArgs.Errors.Any()); parsedArgs = DefaultParse(new[] { "/d:GOO", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count()); Assert.Contains("GOO", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.False(parsedArgs.Errors.Any()); parsedArgs = DefaultParse(new[] { "/d:GOO;BAR,ZIP", "a.cs" }, WorkingDirectory); Assert.Equal(3, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count()); Assert.Contains("GOO", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.Contains("BAR", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.Contains("ZIP", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.False(parsedArgs.Errors.Any()); parsedArgs = DefaultParse(new[] { "/d:GOO;4X", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count()); Assert.Contains("GOO", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.WRN_DefineIdentifierRequired, parsedArgs.Errors.First().Code); Assert.Equal("4X", parsedArgs.Errors.First().Arguments[0]); IEnumerable<Diagnostic> diagnostics; // The docs say /d:def1[;def2] string compliant = "def1;def2;def3"; var expected = new[] { "def1", "def2", "def3" }; var parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(compliant, out diagnostics); diagnostics.Verify(); Assert.Equal<string>(expected, parsed); // Bug 17360: Dev11 allows for a terminating semicolon var dev11Compliant = "def1;def2;def3;"; parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(dev11Compliant, out diagnostics); diagnostics.Verify(); Assert.Equal<string>(expected, parsed); // And comma dev11Compliant = "def1,def2,def3,"; parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(dev11Compliant, out diagnostics); diagnostics.Verify(); Assert.Equal<string>(expected, parsed); // This breaks everything var nonCompliant = "def1;;def2;"; parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(nonCompliant, out diagnostics); diagnostics.Verify( // warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("")); Assert.Equal(new[] { "def1", "def2" }, parsed); // Bug 17360 parsedArgs = DefaultParse(new[] { "/d:public1;public2;", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); } [Fact] public void Debug() { var platformPdbKind = PathUtilities.IsUnixLikePlatform ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb; var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.False(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.False(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.True(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.True(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug+", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.False(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:full", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:FULL", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:portable", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(DebugInformationFormat.PortablePdb, parsedArgs.EmitOptions.DebugInformationFormat); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/debug:embedded", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(DebugInformationFormat.Embedded, parsedArgs.EmitOptions.DebugInformationFormat); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/debug:PDBONLY", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:full", "/debug:pdbonly", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug:full", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug-", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug-", "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:embedded", "/debug-", "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(DebugInformationFormat.Embedded, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:embedded", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.Equal(DebugInformationFormat.Embedded, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "debug")); parsedArgs = DefaultParse(new[] { "/debug:+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadDebugType).WithArguments("+")); parsedArgs = DefaultParse(new[] { "/debug:invalid", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadDebugType).WithArguments("invalid")); parsedArgs = DefaultParse(new[] { "/debug-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/debug-:")); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void Pdb() { var parsedArgs = DefaultParse(new[] { "/pdb:something", "a.cs" }, WorkingDirectory); Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.PdbPath); Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.GetPdbFilePath("a.dll")); Assert.False(parsedArgs.EmitPdbFile); parsedArgs = DefaultParse(new[] { "/pdb:something", "/debug:embedded", "a.cs" }, WorkingDirectory); Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.PdbPath); Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.GetPdbFilePath("a.dll")); Assert.False(parsedArgs.EmitPdbFile); parsedArgs = DefaultParse(new[] { "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.PdbPath); Assert.True(parsedArgs.EmitPdbFile); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/pdb")); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/pdb:", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/pdb:")); parsedArgs = DefaultParse(new[] { "/pdb:something", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // temp: path changed //parsedArgs = DefaultParse(new[] { "/debug", "/pdb:.x", "a.cs" }, baseDirectory); //parsedArgs.Errors.Verify( // // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x")); parsedArgs = DefaultParse(new[] { @"/pdb:""""", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for '/pdb:""' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments(@"/pdb:""""").WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/pdb:C:\\", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("C:\\")); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/pdb:C:\MyFolder\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\MyFolder\MyPdb.pdb", parsedArgs.PdbPath); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/pdb:c:\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"c:\MyPdb.pdb", parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { @"/pdb:\MyFolder\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(Path.GetPathRoot(WorkingDirectory), @"MyFolder\MyPdb.pdb"), parsedArgs.PdbPath); // Should handle quotes parsedArgs = DefaultParse(new[] { @"/pdb:""C:\My Folder\MyPdb.pdb""", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\My Folder\MyPdb.pdb", parsedArgs.PdbPath); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/pdb:MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(FileUtilities.ResolveRelativePath("MyPdb.pdb", WorkingDirectory), parsedArgs.PdbPath); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/pdb:..\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // Temp: Path info changed // Assert.Equal(FileUtilities.ResolveRelativePath("MyPdb.pdb", "..\\", baseDirectory), parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { @"/pdb:\\b", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b")); Assert.Null(parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { @"/pdb:\\b\OkFileName.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b\OkFileName.pdb")); Assert.Null(parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { @"/pdb:\\server\share\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"\\server\share\MyPdb.pdb", parsedArgs.PdbPath); // invalid name: parsedArgs = DefaultParse(new[] { "/pdb:a.b\0b", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b")); Assert.Null(parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { "/pdb:a\uD800b.pdb", "/debug", "a.cs" }, WorkingDirectory); //parsedArgs.Errors.Verify( // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a\uD800b.pdb")); Assert.Null(parsedArgs.PdbPath); // Dev11 reports CS0016: Could not write to output file 'd:\Temp\q\a<>.z' parsedArgs = DefaultParse(new[] { @"/pdb:""a<>.pdb""", "a.vb" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'a<>.pdb' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.pdb")); Assert.Null(parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { "/pdb:.x", "/debug", "a.cs" }, WorkingDirectory); //parsedArgs.Errors.Verify( // // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x")); Assert.Null(parsedArgs.PdbPath); } [Fact] public void SourceLink() { var parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:portable", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "sl.json"), parsedArgs.SourceLink); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:embedded", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "sl.json"), parsedArgs.SourceLink); parsedArgs = DefaultParse(new[] { @"/sourcelink:""s l.json""", "/debug:embedded", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "s l.json"), parsedArgs.SourceLink); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:full", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:pdbonly", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SourceLinkRequiresPdb)); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SourceLinkRequiresPdb)); } [Fact] public void SourceLink_EndToEnd_EmbeddedPortable() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText(@"class C { public static void Main() {} }"); var sl = dir.CreateFile("sl.json"); sl.WriteAllText(@"{ ""documents"" : {} }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/debug:embedded", "/sourcelink:sl.json", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var peStream = File.OpenRead(Path.Combine(dir.Path, "a.exe")); using (var peReader = new PEReader(peStream)) { var entry = peReader.ReadDebugDirectory().Single(e => e.Type == DebugDirectoryEntryType.EmbeddedPortablePdb); using (var mdProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(entry)) { var blob = mdProvider.GetMetadataReader().GetSourceLinkBlob(); AssertEx.Equal(File.ReadAllBytes(sl.Path), blob); } } // Clean up temp files CleanupAllGeneratedFiles(src.Path); } [Fact] public void SourceLink_EndToEnd_Portable() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText(@"class C { public static void Main() {} }"); var sl = dir.CreateFile("sl.json"); sl.WriteAllText(@"{ ""documents"" : {} }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/debug:portable", "/sourcelink:sl.json", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var pdbStream = File.OpenRead(Path.Combine(dir.Path, "a.pdb")); using (var mdProvider = MetadataReaderProvider.FromPortablePdbStream(pdbStream)) { var blob = mdProvider.GetMetadataReader().GetSourceLinkBlob(); AssertEx.Equal(File.ReadAllBytes(sl.Path), blob); } // Clean up temp files CleanupAllGeneratedFiles(src.Path); } [Fact] public void SourceLink_EndToEnd_Windows() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText(@"class C { public static void Main() {} }"); var sl = dir.CreateFile("sl.json"); byte[] slContent = Encoding.UTF8.GetBytes(@"{ ""documents"" : {} }"); sl.WriteAllBytes(slContent); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/debug:full", "/sourcelink:sl.json", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var pdbStream = File.OpenRead(Path.Combine(dir.Path, "a.pdb")); var actualData = PdbValidation.GetSourceLinkData(pdbStream); AssertEx.Equal(slContent, actualData); // Clean up temp files CleanupAllGeneratedFiles(src.Path); } [Fact] public void Embed() { var parsedArgs = DefaultParse(new[] { "a.cs " }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Empty(parsedArgs.EmbeddedFiles); parsedArgs = DefaultParse(new[] { "/embed", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(parsedArgs.SourceFiles, parsedArgs.EmbeddedFiles); AssertEx.Equal( new[] { "a.cs", "b.cs", "c.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed:a.cs", "/embed:b.cs", "/debug:embedded", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal( new[] { "a.cs", "b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed:a.cs;b.cs", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal( new[] { "a.cs", "b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed:a.cs,b.cs", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal( new[] { "a.cs", "b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { @"/embed:""a,b.cs""", "/debug:portable", "a,b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal( new[] { "a,b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed:a.txt", "/embed", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); ; AssertEx.Equal( new[] { "a.txt", "a.cs", "b.cs", "c.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb)); parsedArgs = DefaultParse(new[] { "/embed:a.txt", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb)); parsedArgs = DefaultParse(new[] { "/embed", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb)); parsedArgs = DefaultParse(new[] { "/embed:a.txt", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb)); parsedArgs = DefaultParse(new[] { "/embed", "/debug:full", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/embed", "/debug:pdbonly", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/embed", "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); } [Theory] [InlineData("/debug:portable", "/embed", new[] { "embed.cs", "embed2.cs", "embed.xyz" })] [InlineData("/debug:portable", "/embed:embed.cs", new[] { "embed.cs", "embed.xyz" })] [InlineData("/debug:portable", "/embed:embed2.cs", new[] { "embed2.cs" })] [InlineData("/debug:portable", "/embed:embed.xyz", new[] { "embed.xyz" })] [InlineData("/debug:embedded", "/embed", new[] { "embed.cs", "embed2.cs", "embed.xyz" })] [InlineData("/debug:embedded", "/embed:embed.cs", new[] { "embed.cs", "embed.xyz" })] [InlineData("/debug:embedded", "/embed:embed2.cs", new[] { "embed2.cs" })] [InlineData("/debug:embedded", "/embed:embed.xyz", new[] { "embed.xyz" })] public void Embed_EndToEnd_Portable(string debugSwitch, string embedSwitch, string[] expectedEmbedded) { // embed.cs: large enough to compress, has #line directives const string embed_cs = @"/////////////////////////////////////////////////////////////////////////////// class Program { static void Main() { #line 1 ""embed.xyz"" System.Console.WriteLine(""Hello, World""); #line 3 System.Console.WriteLine(""Goodbye, World""); } } ///////////////////////////////////////////////////////////////////////////////"; // embed2.cs: small enough to not compress, no sequence points const string embed2_cs = @"class C { }"; // target of #line const string embed_xyz = @"print Hello, World print Goodbye, World"; Assert.True(embed_cs.Length >= EmbeddedText.CompressionThreshold); Assert.True(embed2_cs.Length < EmbeddedText.CompressionThreshold); var dir = Temp.CreateDirectory(); var src = dir.CreateFile("embed.cs"); var src2 = dir.CreateFile("embed2.cs"); var txt = dir.CreateFile("embed.xyz"); src.WriteAllText(embed_cs); src2.WriteAllText(embed2_cs); txt.WriteAllText(embed_xyz); var expectedEmbeddedMap = new Dictionary<string, string>(); if (expectedEmbedded.Contains("embed.cs")) { expectedEmbeddedMap.Add(src.Path, embed_cs); } if (expectedEmbedded.Contains("embed2.cs")) { expectedEmbeddedMap.Add(src2.Path, embed2_cs); } if (expectedEmbedded.Contains("embed.xyz")) { expectedEmbeddedMap.Add(txt.Path, embed_xyz); } var output = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", debugSwitch, embedSwitch, "embed.cs", "embed2.cs" }); int exitCode = csc.Run(output); Assert.Equal("", output.ToString().Trim()); Assert.Equal(0, exitCode); switch (debugSwitch) { case "/debug:embedded": ValidateEmbeddedSources_Portable(expectedEmbeddedMap, dir, isEmbeddedPdb: true); break; case "/debug:portable": ValidateEmbeddedSources_Portable(expectedEmbeddedMap, dir, isEmbeddedPdb: false); break; case "/debug:full": ValidateEmbeddedSources_Windows(expectedEmbeddedMap, dir); break; } Assert.Empty(expectedEmbeddedMap); CleanupAllGeneratedFiles(src.Path); } private static void ValidateEmbeddedSources_Portable(Dictionary<string, string> expectedEmbeddedMap, TempDirectory dir, bool isEmbeddedPdb) { using (var peReader = new PEReader(File.OpenRead(Path.Combine(dir.Path, "embed.exe")))) { var entry = peReader.ReadDebugDirectory().SingleOrDefault(e => e.Type == DebugDirectoryEntryType.EmbeddedPortablePdb); Assert.Equal(isEmbeddedPdb, entry.DataSize > 0); using (var mdProvider = isEmbeddedPdb ? peReader.ReadEmbeddedPortablePdbDebugDirectoryData(entry) : MetadataReaderProvider.FromPortablePdbStream(File.OpenRead(Path.Combine(dir.Path, "embed.pdb")))) { var mdReader = mdProvider.GetMetadataReader(); foreach (var handle in mdReader.Documents) { var doc = mdReader.GetDocument(handle); var docPath = mdReader.GetString(doc.Name); SourceText embeddedSource = mdReader.GetEmbeddedSource(handle); if (embeddedSource == null) { continue; } Assert.Equal(expectedEmbeddedMap[docPath], embeddedSource.ToString()); Assert.True(expectedEmbeddedMap.Remove(docPath)); } } } } private static void ValidateEmbeddedSources_Windows(Dictionary<string, string> expectedEmbeddedMap, TempDirectory dir) { ISymUnmanagedReader5 symReader = null; try { symReader = SymReaderFactory.CreateReader(File.OpenRead(Path.Combine(dir.Path, "embed.pdb"))); foreach (var doc in symReader.GetDocuments()) { var docPath = doc.GetName(); var sourceBlob = doc.GetEmbeddedSource(); if (sourceBlob.Array == null) { continue; } var sourceStr = Encoding.UTF8.GetString(sourceBlob.Array, sourceBlob.Offset, sourceBlob.Count); Assert.Equal(expectedEmbeddedMap[docPath], sourceStr); Assert.True(expectedEmbeddedMap.Remove(docPath)); } } catch { symReader?.Dispose(); } } private static void ValidateWrittenSources(Dictionary<string, Dictionary<string, string>> expectedFilesMap, Encoding encoding = null) { foreach ((var dirPath, var fileMap) in expectedFilesMap.ToArray()) { foreach (var file in Directory.GetFiles(dirPath)) { var name = Path.GetFileName(file); var content = File.ReadAllText(file, encoding ?? Encoding.UTF8); Assert.Equal(fileMap[name], content); Assert.True(fileMap.Remove(name)); } Assert.Empty(fileMap); Assert.True(expectedFilesMap.Remove(dirPath)); } Assert.Empty(expectedFilesMap); } [Fact] public void Optimize() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(new CSharpCompilationOptions(OutputKind.ConsoleApplication).OptimizationLevel, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize+", "/optimize-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize:+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/optimize:+")); parsedArgs = DefaultParse(new[] { "/optimize:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/optimize:")); parsedArgs = DefaultParse(new[] { "/optimize-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/optimize-:")); parsedArgs = DefaultParse(new[] { "/o-", "a.cs" }, WorkingDirectory); Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new string[] { "/o", "a.cs" }, WorkingDirectory); Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new string[] { "/o+", "a.cs" }, WorkingDirectory); Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new string[] { "/o+", "/optimize-", "a.cs" }, WorkingDirectory); Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new string[] { "/o:+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/o:+")); parsedArgs = DefaultParse(new string[] { "/o:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/o:")); parsedArgs = DefaultParse(new string[] { "/o-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/o-:")); } [Fact] public void Deterministic() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.Deterministic); parsedArgs = DefaultParse(new[] { "/deterministic+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.Deterministic); parsedArgs = DefaultParse(new[] { "/deterministic", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.Deterministic); parsedArgs = DefaultParse(new[] { "/deterministic-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.Deterministic); } [Fact] public void ParseReferences() { var parsedArgs = DefaultParse(new string[] { "/r:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.MetadataReferences.Length); parsedArgs = DefaultParse(new string[] { "/r:goo.dll;", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.MetadataReferences.Length); Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties); Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[1].Properties); parsedArgs = DefaultParse(new string[] { @"/l:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.MetadataReferences.Length); Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties); Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataReferenceProperties.Assembly.WithEmbedInteropTypes(true), parsedArgs.MetadataReferences[1].Properties); parsedArgs = DefaultParse(new string[] { @"/addmodule:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.MetadataReferences.Length); Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties); Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataReferenceProperties.Module, parsedArgs.MetadataReferences[1].Properties); parsedArgs = DefaultParse(new string[] { @"/r:a=goo.dll", "/l:b=bar.dll", "/addmodule:c=mod.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(4, parsedArgs.MetadataReferences.Length); Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties); Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataReferenceProperties.Assembly.WithAliases(new[] { "a" }), parsedArgs.MetadataReferences[1].Properties); Assert.Equal("bar.dll", parsedArgs.MetadataReferences[2].Reference); Assert.Equal(MetadataReferenceProperties.Assembly.WithAliases(new[] { "b" }).WithEmbedInteropTypes(true), parsedArgs.MetadataReferences[2].Properties); Assert.Equal("c=mod.dll", parsedArgs.MetadataReferences[3].Reference); Assert.Equal(MetadataReferenceProperties.Module, parsedArgs.MetadataReferences[3].Properties); // TODO: multiple files, quotes, etc. } [Fact] public void ParseAnalyzers() { var parsedArgs = DefaultParse(new string[] { @"/a:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(1, parsedArgs.AnalyzerReferences.Length); Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath); parsedArgs = DefaultParse(new string[] { @"/analyzer:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(1, parsedArgs.AnalyzerReferences.Length); Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath); parsedArgs = DefaultParse(new string[] { "/analyzer:\"goo.dll\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(1, parsedArgs.AnalyzerReferences.Length); Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath); parsedArgs = DefaultParse(new string[] { @"/a:goo.dll;bar.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.AnalyzerReferences.Length); Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath); Assert.Equal("bar.dll", parsedArgs.AnalyzerReferences[1].FilePath); parsedArgs = DefaultParse(new string[] { @"/a:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/a:")); parsedArgs = DefaultParse(new string[] { "/a", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/a")); } [Fact] public void Analyzers_Missing() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/a:missing.dll", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS0006: Metadata file 'missing.dll' could not be found", outWriter.ToString().Trim()); // Clean up temp files CleanupAllGeneratedFiles(file.Path); } [Fact] public void Analyzers_Empty() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + typeof(object).Assembly.Location, "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.DoesNotContain("warning", outWriter.ToString()); CleanupAllGeneratedFiles(file.Path); } private TempFile CreateRuleSetFile(string source) { var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.ruleset"); file.WriteAllText(source); return file; } [Fact] public void RuleSetSwitchPositive() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> <Rule Id=""CA1013"" Action=""Warning"" /> <Rule Id=""CA1014"" Action=""None"" /> </Rules> </RuleSet> "; var file = CreateRuleSetFile(source); var parsedArgs = DefaultParse(new string[] { @"/ruleset:" + file.Path, "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(expected: file.Path, actual: parsedArgs.RuleSetPath); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1012")); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions["CA1012"] == ReportDiagnostic.Error); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1013")); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions["CA1013"] == ReportDiagnostic.Warn); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1014")); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions["CA1014"] == ReportDiagnostic.Suppress); Assert.True(parsedArgs.CompilationOptions.GeneralDiagnosticOption == ReportDiagnostic.Warn); } [Fact] public void RuleSetSwitchQuoted() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> <Rule Id=""CA1013"" Action=""Warning"" /> <Rule Id=""CA1014"" Action=""None"" /> </Rules> </RuleSet> "; var file = CreateRuleSetFile(source); var parsedArgs = DefaultParse(new string[] { @"/ruleset:" + "\"" + file.Path + "\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(expected: file.Path, actual: parsedArgs.RuleSetPath); } [Fact] public void RuleSetSwitchParseErrors() { var parsedArgs = DefaultParse(new string[] { @"/ruleset", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "ruleset")); Assert.Null(parsedArgs.RuleSetPath); parsedArgs = DefaultParse(new string[] { @"/ruleset:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "ruleset")); Assert.Null(parsedArgs.RuleSetPath); parsedArgs = DefaultParse(new string[] { @"/ruleset:blah", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_CantReadRulesetFile).WithArguments(Path.Combine(TempRoot.Root, "blah"), "File not found.")); Assert.Equal(expected: Path.Combine(TempRoot.Root, "blah"), actual: parsedArgs.RuleSetPath); parsedArgs = DefaultParse(new string[] { @"/ruleset:blah;blah.ruleset", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_CantReadRulesetFile).WithArguments(Path.Combine(TempRoot.Root, "blah;blah.ruleset"), "File not found.")); Assert.Equal(expected: Path.Combine(TempRoot.Root, "blah;blah.ruleset"), actual: parsedArgs.RuleSetPath); var file = CreateRuleSetFile("Random text"); parsedArgs = DefaultParse(new string[] { @"/ruleset:" + file.Path, "a.cs" }, WorkingDirectory); //parsedArgs.Errors.Verify( // Diagnostic(ErrorCode.ERR_CantReadRulesetFile).WithArguments(file.Path, "Data at the root level is invalid. Line 1, position 1.")); Assert.Equal(expected: file.Path, actual: parsedArgs.RuleSetPath); var err = parsedArgs.Errors.Single(); Assert.Equal((int)ErrorCode.ERR_CantReadRulesetFile, err.Code); Assert.Equal(2, err.Arguments.Count); Assert.Equal(file.Path, (string)err.Arguments[0]); var currentUICultureName = Thread.CurrentThread.CurrentUICulture.Name; if (currentUICultureName.Length == 0 || currentUICultureName.StartsWith("en", StringComparison.OrdinalIgnoreCase)) { Assert.Equal("Data at the root level is invalid. Line 1, position 1.", (string)err.Arguments[1]); } } [WorkItem(892467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/892467")] [Fact] public void Analyzers_Found() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation. var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); // Diagnostic thrown Assert.True(outWriter.ToString().Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared")); // Diagnostic cannot be instantiated Assert.True(outWriter.ToString().Contains("warning CS8032")); CleanupAllGeneratedFiles(file.Path); } [Fact] public void Analyzers_WithRuleSet() { string source = @" class C { int x; } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); string rulesetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Warning01"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSetFile = CreateRuleSetFile(rulesetSource); var outWriter = new StringWriter(CultureInfo.InvariantCulture); // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation. var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/ruleset:" + ruleSetFile.Path }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); // Diagnostic thrown as error. Assert.True(outWriter.ToString().Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared")); // Clean up temp files CleanupAllGeneratedFiles(file.Path); } [WorkItem(912906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912906")] [Fact] public void Analyzers_CommandLineOverridesRuleset1() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); string rulesetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> </RuleSet> "; var ruleSetFile = CreateRuleSetFile(rulesetSource); var outWriter = new StringWriter(CultureInfo.InvariantCulture); // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation. var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/ruleset:" + ruleSetFile.Path, "/warnaserror+", "/nowarn:8032" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); // Diagnostic thrown as error: command line always overrides ruleset. Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/warnaserror+", "/ruleset:" + ruleSetFile.Path, "/nowarn:8032" }); exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); // Diagnostic thrown as error: command line always overrides ruleset. Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", outWriter.ToString(), StringComparison.Ordinal); // Clean up temp files CleanupAllGeneratedFiles(file.Path); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_GeneralCommandLineOptionOverridesGeneralRuleSetOption() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_GeneralWarnAsErrorPromotesWarningFromRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Error); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_GeneralWarnAsErrorDoesNotPromoteInfoFromRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Info"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Info); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_SpecificWarnAsErrorPromotesInfoFromRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Info"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Default); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Error); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_GeneralWarnAsErrorMinusResetsRules() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "/warnaserror-", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Default); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Warn); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_SpecificWarnAsErrorMinusResetsRules() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "/warnaserror-:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Warn); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_SpecificWarnAsErrorMinusDefaultsRuleNotInRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+:Test002", "/warnaserror-:Test002", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Default); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Warn); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test002"], expected: ReportDiagnostic.Default); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void NoWarn_SpecificNoWarnOverridesRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/nowarn:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: 1, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void NoWarn_SpecificNoWarnOverridesGeneralWarnAsError() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "/nowarn:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Error, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: 1, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void NoWarn_SpecificNoWarnOverridesSpecificWarnAsError() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/nowarn:Test001", "/warnaserror+:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: 1, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]); } [Fact] [WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void NoWarn_Nullable() { var dir = Temp.CreateDirectory(); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/nowarn:nullable", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 2, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); foreach (string warning in ErrorFacts.NullableWarnings) { Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]); } Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]); } [Fact] [WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void NoWarn_Nullable_Capitalization() { var dir = Temp.CreateDirectory(); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/nowarn:NullABLE", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 2, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); foreach (string warning in ErrorFacts.NullableWarnings) { Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]); } Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]); } [Fact] [WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void NoWarn_Nullable_MultipleArguments() { var dir = Temp.CreateDirectory(); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/nowarn:nullable,Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 3, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); foreach (string warning in ErrorFacts.NullableWarnings) { Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]); } Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]); } [Fact] [WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void WarnAsError_Nullable() { var dir = Temp.CreateDirectory(); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/warnaserror:nullable", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 2, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); foreach (string warning in ErrorFacts.NullableWarnings) { Assert.Equal(expected: ReportDiagnostic.Error, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]); } Assert.Equal(expected: ReportDiagnostic.Error, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]); Assert.Equal(expected: ReportDiagnostic.Error, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]); } [WorkItem(912906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912906")] [Fact] public void Analyzers_CommandLineOverridesRuleset2() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); string rulesetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Warning01"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSetFile = CreateRuleSetFile(rulesetSource); var outWriter = new StringWriter(CultureInfo.InvariantCulture); // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation. var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/ruleset:" + ruleSetFile.Path, "/warn:0" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); // Diagnostic suppressed: commandline always overrides ruleset. Assert.DoesNotContain("Warning01", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/warn:0", "/ruleset:" + ruleSetFile.Path }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); // Diagnostic suppressed: commandline always overrides ruleset. Assert.DoesNotContain("Warning01", outWriter.ToString(), StringComparison.Ordinal); // Clean up temp files CleanupAllGeneratedFiles(file.Path); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void DiagnosticFormatting() { string source = @" using System; class C { public static void Main() { Goo(0); #line 10 ""c:\temp\a\1.cs"" Goo(1); #line 20 ""C:\a\..\b.cs"" Goo(2); #line 30 ""C:\a\../B.cs"" Goo(3); #line 40 ""../b.cs"" Goo(4); #line 50 ""..\b.cs"" Goo(5); #line 60 ""C:\X.cs"" Goo(6); #line 70 ""C:\x.cs"" Goo(7); #line 90 "" "" Goo(9); #line 100 ""C:\*.cs"" Goo(10); #line 110 """" Goo(11); #line hidden Goo(12); #line default Goo(13); #line 140 ""***"" Goo(14); } } "; var dir = Temp.CreateDirectory(); dir.CreateFile("a.cs").WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); // with /fullpaths off string expected = @" a.cs(8,13): error CS0103: The name 'Goo' does not exist in the current context c:\temp\a\1.cs(10,13): error CS0103: The name 'Goo' does not exist in the current context C:\b.cs(20,13): error CS0103: The name 'Goo' does not exist in the current context C:\B.cs(30,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(40,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(50,13): error CS0103: The name 'Goo' does not exist in the current context C:\X.cs(60,13): error CS0103: The name 'Goo' does not exist in the current context C:\x.cs(70,13): error CS0103: The name 'Goo' does not exist in the current context (90,7): error CS0103: The name 'Goo' does not exist in the current context C:\*.cs(100,7): error CS0103: The name 'Goo' does not exist in the current context (110,7): error CS0103: The name 'Goo' does not exist in the current context (112,13): error CS0103: The name 'Goo' does not exist in the current context a.cs(32,13): error CS0103: The name 'Goo' does not exist in the current context ***(140,13): error CS0103: The name 'Goo' does not exist in the current context"; AssertEx.Equal( expected.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries), outWriter.ToString().Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries), itemSeparator: "\r\n"); // with /fullpaths on outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/fullpaths", "a.cs" }); exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); expected = @" " + Path.Combine(dir.Path, @"a.cs") + @"(8,13): error CS0103: The name 'Goo' does not exist in the current context c:\temp\a\1.cs(10,13): error CS0103: The name 'Goo' does not exist in the current context C:\b.cs(20,13): error CS0103: The name 'Goo' does not exist in the current context C:\B.cs(30,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(40,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(50,13): error CS0103: The name 'Goo' does not exist in the current context C:\X.cs(60,13): error CS0103: The name 'Goo' does not exist in the current context C:\x.cs(70,13): error CS0103: The name 'Goo' does not exist in the current context (90,7): error CS0103: The name 'Goo' does not exist in the current context C:\*.cs(100,7): error CS0103: The name 'Goo' does not exist in the current context (110,7): error CS0103: The name 'Goo' does not exist in the current context (112,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.Combine(dir.Path, @"a.cs") + @"(32,13): error CS0103: The name 'Goo' does not exist in the current context ***(140,13): error CS0103: The name 'Goo' does not exist in the current context"; AssertEx.Equal( expected.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries), outWriter.ToString().Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries), itemSeparator: "\r\n"); } [WorkItem(540891, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540891")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseOut() { const string baseDirectory = @"C:\abc\def\baz"; var parsedArgs = DefaultParse(new[] { @"/out:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '' contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("")); parsedArgs = DefaultParse(new[] { @"/out:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for '/out:' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/out:")); parsedArgs = DefaultParse(new[] { @"/refout:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for '/refout:' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/refout:")); parsedArgs = DefaultParse(new[] { @"/refout:ref.dll", "/refonly", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS8301: Do not use refout when using refonly. Diagnostic(ErrorCode.ERR_NoRefOutWhenRefOnly).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { @"/refout:ref.dll", "/link:b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/refonly", "/link:b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/refonly:incorrect", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/refonly:incorrect' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/refonly:incorrect").WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/refout:ref.dll", "/target:module", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS8302: Cannot compile net modules when using /refout or /refonly. Diagnostic(ErrorCode.ERR_NoNetModuleOutputWhenRefOutOrRefOnly).WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/refonly", "/target:module", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS8302: Cannot compile net modules when using /refout or /refonly. Diagnostic(ErrorCode.ERR_NoNetModuleOutputWhenRefOutOrRefOnly).WithLocation(1, 1) ); // Dev11 reports CS2007: Unrecognized option: '/out' parsedArgs = DefaultParse(new[] { @"/out", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for '/out' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/out")); parsedArgs = DefaultParse(new[] { @"/out+", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/out+")); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/out:C:\MyFolder\MyBinary.dll", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("MyBinary", parsedArgs.CompilationName); Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName); Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(@"C:\MyFolder", parsedArgs.OutputDirectory); Assert.Equal(@"C:\MyFolder\MyBinary.dll", parsedArgs.GetOutputFilePath(parsedArgs.OutputFileName)); // Should handle quotes parsedArgs = DefaultParse(new[] { @"/out:""C:\My Folder\MyBinary.dll""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"MyBinary", parsedArgs.CompilationName); Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName); Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(@"C:\My Folder", parsedArgs.OutputDirectory); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/out:MyBinary.dll", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("MyBinary", parsedArgs.CompilationName); Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName); Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); Assert.Equal(Path.Combine(baseDirectory, "MyBinary.dll"), parsedArgs.GetOutputFilePath(parsedArgs.OutputFileName)); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/out:..\MyBinary.dll", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("MyBinary", parsedArgs.CompilationName); Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName); Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(@"C:\abc\def", parsedArgs.OutputDirectory); // not specified: exe parsedArgs = DefaultParse(new[] { @"a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // not specified: dll parsedArgs = DefaultParse(new[] { @"/target:library", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.CompilationName); Assert.Equal("a.dll", parsedArgs.OutputFileName); Assert.Equal("a.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // not specified: module parsedArgs = DefaultParse(new[] { @"/target:module", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.CompilationName); Assert.Equal("a.netmodule", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // not specified: appcontainerexe parsedArgs = DefaultParse(new[] { @"/target:appcontainerexe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // not specified: winmdobj parsedArgs = DefaultParse(new[] { @"/target:winmdobj", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.CompilationName); Assert.Equal("a.winmdobj", parsedArgs.OutputFileName); Assert.Equal("a.winmdobj", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // drive-relative path: char currentDrive = Directory.GetCurrentDirectory()[0]; parsedArgs = DefaultParse(new[] { currentDrive + @":a.cs", "b.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'D:a.cs' is contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + ":a.cs")); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // UNC parsedArgs = DefaultParse(new[] { @"/out:\\b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/out:\\server\share\file.exe", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"\\server\share", parsedArgs.OutputDirectory); Assert.Equal("file.exe", parsedArgs.OutputFileName); Assert.Equal("file", parsedArgs.CompilationName); Assert.Equal("file.exe", parsedArgs.CompilationOptions.ModuleName); // invalid name: parsedArgs = DefaultParse(new[] { "/out:a.b\0b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); // Temporary skip following scenarios because of the error message changed (path) //parsedArgs = DefaultParse(new[] { "/out:a\uD800b.dll", "a.cs" }, baseDirectory); //parsedArgs.Errors.Verify( // // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a\uD800b.dll")); // Dev11 reports CS0016: Could not write to output file 'd:\Temp\q\a<>.z' parsedArgs = DefaultParse(new[] { @"/out:""a<>.dll""", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'a<>.dll' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.dll")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/out:.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.exe' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".exe") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:exe", @"/out:.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.exe' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".exe") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:library", @"/out:.dll", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.dll' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".dll") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:module", @"/out:.netmodule", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.netmodule' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".netmodule") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { ".cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:exe", ".cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:library", ".cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.dll' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".dll") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:module", ".cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(".netmodule", parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Equal(".netmodule", parsedArgs.CompilationOptions.ModuleName); } [WorkItem(546012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546012")] [WorkItem(546007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546007")] [Fact] public void ParseOut2() { var parsedArgs = DefaultParse(new[] { "/out:.x", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { "/out:.x", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); } [Fact] public void ParseInstrumentTestNames() { var parsedArgs = DefaultParse(SpecializedCollections.EmptyEnumerable<string>(), WorkingDirectory); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { @"/instrument", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { @"/instrument:""""", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { @"/instrument:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { "/instrument:", "Test.Flag.Name", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { "/instrument:InvalidOption", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_InvalidInstrumentationKind).WithArguments("InvalidOption")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { "/instrument:None", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_InvalidInstrumentationKind).WithArguments("None")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage,InvalidOption", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_InvalidInstrumentationKind).WithArguments("InvalidOption")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { @"/instrument:""TestCoverage""", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { @"/instrument:""TESTCOVERAGE""", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage,TestCoverage", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage", "/instrument:TestCoverage", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseDoc() { const string baseDirectory = @"C:\abc\def\baz"; var parsedArgs = DefaultParse(new[] { @"/doc:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/doc:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/doc:")); Assert.Null(parsedArgs.DocumentationPath); parsedArgs = DefaultParse(new[] { @"/doc:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/doc:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/doc:")); Assert.Null(parsedArgs.DocumentationPath); // NOTE: no colon in error message '/doc' parsedArgs = DefaultParse(new[] { @"/doc", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/doc' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/doc")); Assert.Null(parsedArgs.DocumentationPath); parsedArgs = DefaultParse(new[] { @"/doc+", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/doc+")); Assert.Null(parsedArgs.DocumentationPath); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/doc:C:\MyFolder\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\MyFolder\MyBinary.xml", parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // Should handle quotes parsedArgs = DefaultParse(new[] { @"/doc:""C:\My Folder\MyBinary.xml""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\My Folder\MyBinary.xml", parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/doc:MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "MyBinary.xml"), parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/doc:..\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\MyBinary.xml", parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // drive-relative path: char currentDrive = Directory.GetCurrentDirectory()[0]; parsedArgs = DefaultParse(new[] { "/doc:" + currentDrive + @":a.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'D:a.xml' is contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + ":a.xml")); Assert.Null(parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect // UNC parsedArgs = DefaultParse(new[] { @"/doc:\\b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b")); Assert.Null(parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect parsedArgs = DefaultParse(new[] { @"/doc:\\server\share\file.xml", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"\\server\share\file.xml", parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // invalid name: parsedArgs = DefaultParse(new[] { "/doc:a.b\0b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b")); Assert.Null(parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect // Temp // parsedArgs = DefaultParse(new[] { "/doc:a\uD800b.xml", "a.cs" }, baseDirectory); // parsedArgs.Errors.Verify( // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a\uD800b.xml")); // Assert.Null(parsedArgs.DocumentationPath); // Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect parsedArgs = DefaultParse(new[] { @"/doc:""a<>.xml""", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'a<>.xml' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.xml")); Assert.Null(parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseErrorLog() { const string baseDirectory = @"C:\abc\def\baz"; var parsedArgs = DefaultParse(new[] { @"/errorlog:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<(error log option format>' for '/errorlog:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(CSharpCommandLineParser.ErrorLogOptionFormat, "/errorlog:")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); parsedArgs = DefaultParse(new[] { @"/errorlog:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<(error log option format>' for '/errorlog:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(CSharpCommandLineParser.ErrorLogOptionFormat, "/errorlog:")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); parsedArgs = DefaultParse(new[] { @"/errorlog", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<(error log option format>' for '/errorlog' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(CSharpCommandLineParser.ErrorLogOptionFormat, "/errorlog")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/errorlog:C:\MyFolder\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\MyFolder\MyBinary.xml", parsedArgs.ErrorLogOptions.Path); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Escaped quote in the middle is an error parsedArgs = DefaultParse(new[] { @"/errorlog:C:\""My Folder""\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"C:""My Folder\MyBinary.xml").WithLocation(1, 1)); // Should handle quotes parsedArgs = DefaultParse(new[] { @"/errorlog:""C:\My Folder\MyBinary.xml""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\My Folder\MyBinary.xml", parsedArgs.ErrorLogOptions.Path); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/errorlog:MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "MyBinary.xml"), parsedArgs.ErrorLogOptions.Path); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/errorlog:..\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\MyBinary.xml", parsedArgs.ErrorLogOptions.Path); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // drive-relative path: char currentDrive = Directory.GetCurrentDirectory()[0]; parsedArgs = DefaultParse(new[] { "/errorlog:" + currentDrive + @":a.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'D:a.xml' is contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + ":a.xml")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // UNC parsedArgs = DefaultParse(new[] { @"/errorlog:\\b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); parsedArgs = DefaultParse(new[] { @"/errorlog:\\server\share\file.xml", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"\\server\share\file.xml", parsedArgs.ErrorLogOptions.Path); // invalid name: parsedArgs = DefaultParse(new[] { "/errorlog:a.b\0b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); parsedArgs = DefaultParse(new[] { @"/errorlog:""a<>.xml""", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'a<>.xml' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.xml")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Parses SARIF version. parsedArgs = DefaultParse(new[] { @"/errorlog:C:\MyFolder\MyBinary.xml,version=2", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\MyFolder\MyBinary.xml", parsedArgs.ErrorLogOptions.Path); Assert.Equal(SarifVersion.Sarif2, parsedArgs.ErrorLogOptions.SarifVersion); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Invalid SARIF version. string[] invalidSarifVersions = new string[] { @"C:\MyFolder\MyBinary.xml,version=1.0.0", @"C:\MyFolder\MyBinary.xml,version=2.1.0", @"C:\MyFolder\MyBinary.xml,version=42" }; foreach (string invalidSarifVersion in invalidSarifVersions) { parsedArgs = DefaultParse(new[] { $"/errorlog:{invalidSarifVersion}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2046: Command-line syntax error: 'C:\MyFolder\MyBinary.xml,version=42' is not a valid value for the '/errorlog:' option. The value must be of the form '<file>[,version={1|1.0|2|2.1}]'. Diagnostic(ErrorCode.ERR_BadSwitchValue).WithArguments(invalidSarifVersion, "/errorlog:", CSharpCommandLineParser.ErrorLogOptionFormat)); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); } // Invalid errorlog qualifier. const string InvalidErrorLogQualifier = @"C:\MyFolder\MyBinary.xml,invalid=42"; parsedArgs = DefaultParse(new[] { $"/errorlog:{InvalidErrorLogQualifier}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2046: Command-line syntax error: 'C:\MyFolder\MyBinary.xml,invalid=42' is not a valid value for the '/errorlog:' option. The value must be of the form '<file>[,version={1|1.0|2|2.1}]'. Diagnostic(ErrorCode.ERR_BadSwitchValue).WithArguments(InvalidErrorLogQualifier, "/errorlog:", CSharpCommandLineParser.ErrorLogOptionFormat)); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Too many errorlog qualifiers. const string TooManyErrorLogQualifiers = @"C:\MyFolder\MyBinary.xml,version=2,version=2"; parsedArgs = DefaultParse(new[] { $"/errorlog:{TooManyErrorLogQualifiers}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2046: Command-line syntax error: 'C:\MyFolder\MyBinary.xml,version=2,version=2' is not a valid value for the '/errorlog:' option. The value must be of the form '<file>[,version={1|1.0|2|2.1}]'. Diagnostic(ErrorCode.ERR_BadSwitchValue).WithArguments(TooManyErrorLogQualifiers, "/errorlog:", CSharpCommandLineParser.ErrorLogOptionFormat)); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); } [ConditionalFact(typeof(WindowsOnly))] public void AppConfigParse() { const string baseDirectory = @"C:\abc\def\baz"; var parsedArgs = DefaultParse(new[] { @"/appconfig:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing ':<text>' for '/appconfig:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(":<text>", "/appconfig:")); Assert.Null(parsedArgs.AppConfigPath); parsedArgs = DefaultParse(new[] { "/appconfig:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing ':<text>' for '/appconfig:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(":<text>", "/appconfig:")); Assert.Null(parsedArgs.AppConfigPath); parsedArgs = DefaultParse(new[] { "/appconfig", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing ':<text>' for '/appconfig' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(":<text>", "/appconfig")); Assert.Null(parsedArgs.AppConfigPath); parsedArgs = DefaultParse(new[] { "/appconfig:a.exe.config", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\a.exe.config", parsedArgs.AppConfigPath); // If ParseDoc succeeds, all other possible AppConfig paths should succeed as well -- they both call ParseGenericFilePath } [Fact] public void AppConfigBasic() { var srcFile = Temp.CreateFile().WriteAllText(@"class A { static void Main(string[] args) { } }"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var appConfigFile = Temp.CreateFile().WriteAllText( @"<?xml version=""1.0"" encoding=""utf-8"" ?> <configuration> <runtime> <assemblyBinding xmlns=""urn:schemas-microsoft-com:asm.v1""> <supportPortability PKT=""7cec85d7bea7798e"" enable=""false""/> </assemblyBinding> </runtime> </configuration>"); var silverlight = Temp.CreateFile().WriteAllBytes(ProprietaryTestResources.silverlight_v5_0_5_0.System_v5_0_5_0_silverlight).Path; var net4_0dll = Temp.CreateFile().WriteAllBytes(ResourcesNet451.System).Path; // Test linking two appconfig dlls with simple src var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = CreateCSharpCompiler(null, srcDirectory, new[] { "/nologo", "/r:" + silverlight, "/r:" + net4_0dll, "/appconfig:" + appConfigFile.Path, srcFile.Path }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(srcFile.Path); CleanupAllGeneratedFiles(appConfigFile.Path); } [ConditionalFact(typeof(WindowsOnly))] public void AppConfigBasicFail() { var srcFile = Temp.CreateFile().WriteAllText(@"class A { static void Main(string[] args) { } }"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); string root = Path.GetPathRoot(srcDirectory); // Make sure we pick a drive that exists and is plugged in to avoid 'Drive not ready' var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = CreateCSharpCompiler(null, srcDirectory, new[] { "/nologo", "/preferreduilang:en", $@"/appconfig:{root}DoesNotExist\NOwhere\bonobo.exe.config" , srcFile.Path }).Run(outWriter); Assert.NotEqual(0, exitCode); Assert.Equal($@"error CS7093: Cannot read config file '{root}DoesNotExist\NOwhere\bonobo.exe.config' -- 'Could not find a part of the path '{root}DoesNotExist\NOwhere\bonobo.exe.config'.'", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(srcFile.Path); } [ConditionalFact(typeof(WindowsOnly))] public void ParseDocAndOut() { const string baseDirectory = @"C:\abc\def\baz"; // Can specify separate directories for binary and XML output. var parsedArgs = DefaultParse(new[] { @"/doc:a\b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\a\b.xml", parsedArgs.DocumentationPath); Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory); Assert.Equal("d.exe", parsedArgs.OutputFileName); // XML does not fall back on output directory. parsedArgs = DefaultParse(new[] { @"/doc:b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\b.xml", parsedArgs.DocumentationPath); Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory); Assert.Equal("d.exe", parsedArgs.OutputFileName); } [ConditionalFact(typeof(WindowsOnly))] public void ParseErrorLogAndOut() { const string baseDirectory = @"C:\abc\def\baz"; // Can specify separate directories for binary and error log output. var parsedArgs = DefaultParse(new[] { @"/errorlog:a\b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\a\b.xml", parsedArgs.ErrorLogOptions.Path); Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory); Assert.Equal("d.exe", parsedArgs.OutputFileName); // XML does not fall back on output directory. parsedArgs = DefaultParse(new[] { @"/errorlog:b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\b.xml", parsedArgs.ErrorLogOptions.Path); Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory); Assert.Equal("d.exe", parsedArgs.OutputFileName); } [Fact] public void ModuleAssemblyName() { var parsedArgs = DefaultParse(new[] { @"/target:module", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("goo", parsedArgs.CompilationName); Assert.Equal("a.netmodule", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:library", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS0734: The /moduleassemblyname option may only be specified when building a target type of 'module' Diagnostic(ErrorCode.ERR_AssemblyNameOnNonModule)); parsedArgs = DefaultParse(new[] { @"/target:exe", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS0734: The /moduleassemblyname option may only be specified when building a target type of 'module' Diagnostic(ErrorCode.ERR_AssemblyNameOnNonModule)); parsedArgs = DefaultParse(new[] { @"/target:winexe", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS0734: The /moduleassemblyname option may only be specified when building a target type of 'module' Diagnostic(ErrorCode.ERR_AssemblyNameOnNonModule)); } [Fact] public void ModuleName() { var parsedArgs = DefaultParse(new[] { @"/target:module", "/modulename:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("goo", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:library", "/modulename:bar", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("bar", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:exe", "/modulename:CommonLanguageRuntimeLibrary", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("CommonLanguageRuntimeLibrary", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:winexe", "/modulename:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("goo", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:exe", "/modulename:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'modulename' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "modulename").WithLocation(1, 1) ); } [Fact] public void ModuleName001() { var dir = Temp.CreateDirectory(); var file1 = dir.CreateFile("a.cs"); file1.WriteAllText(@" class c1 { public static void Main(){} } "); var exeName = "aa.exe"; var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/modulename:hocusPocus ", "/out:" + exeName + " ", file1.Path }); int exitCode = csc.Run(outWriter); if (exitCode != 0) { Console.WriteLine(outWriter.ToString()); Assert.Equal(0, exitCode); } Assert.Equal(1, Directory.EnumerateFiles(dir.Path, exeName).Count()); using (var metadata = ModuleMetadata.CreateFromImage(File.ReadAllBytes(Path.Combine(dir.Path, "aa.exe")))) { var peReader = metadata.Module.GetMetadataReader(); Assert.True(peReader.IsAssembly); Assert.Equal("aa", peReader.GetString(peReader.GetAssemblyDefinition().Name)); Assert.Equal("hocusPocus", peReader.GetString(peReader.GetModuleDefinition().Name)); } if (System.IO.File.Exists(exeName)) { System.IO.File.Delete(exeName); } CleanupAllGeneratedFiles(file1.Path); } [Fact] public void ParsePlatform() { var parsedArgs = DefaultParse(new[] { @"/platform:x64", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.Equal(Platform.X64, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { @"/platform:X86", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.Equal(Platform.X86, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { @"/platform:itanum", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadPlatformType, parsedArgs.Errors.First().Code); Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform:itanium", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Platform.Itanium, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform:anycpu", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform:anycpu32bitpreferred", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Platform.AnyCpu32BitPreferred, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform:arm", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Platform.Arm, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<string>' for 'platform' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<string>", "/platform")); Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform); //anycpu is default parsedArgs = DefaultParse(new[] { "/platform:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<string>' for 'platform' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<string>", "/platform:")); Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform); //anycpu is default } [WorkItem(546016, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546016")] [WorkItem(545997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545997")] [WorkItem(546019, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546019")] [WorkItem(546029, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546029")] [Fact] public void ParseBaseAddress() { var parsedArgs = DefaultParse(new[] { @"/baseaddress:x64", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadBaseNumber, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:0x8000000000011111", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.Equal(0x8000000000011111ul, parsedArgs.EmitOptions.BaseAddress); parsedArgs = DefaultParse(new[] { @"/platform:x86", @"/baseaddress:0x8000000000011111", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadBaseNumber, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { @"/baseaddress:", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_SwitchNeedsNumber, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { @"/baseaddress:-23", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadBaseNumber, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:01777777777777777777777", "a.cs" }, WorkingDirectory); Assert.Equal(ulong.MaxValue, parsedArgs.EmitOptions.BaseAddress); parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:0x0000000100000000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:0xffff8000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "test.cs", "/platform:x86", "/baseaddress:0xffffffff" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFFFFFF")); parsedArgs = DefaultParse(new[] { "test.cs", "/platform:x86", "/baseaddress:0xffff8000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF8000")); parsedArgs = DefaultParse(new[] { "test.cs", "/baseaddress:0xffff8000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF8000")); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x86", "/baseaddress:0xffff7fff" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x64", "/baseaddress:0xffff8000" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x64", "/baseaddress:0x100000000" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "test.cs", "/baseaddress:0xFFFF0000FFFF0000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF0000FFFF0000")); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x64", "/baseaddress:0x10000000000000000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0x10000000000000000")); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/baseaddress:0xFFFF0000FFFF0000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF0000FFFF0000")); } [Fact] public void ParseFileAlignment() { var parsedArgs = DefaultParse(new[] { @"/filealign:x64", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2024: Invalid file section alignment number 'x64' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("x64")); parsedArgs = DefaultParse(new[] { @"/filealign:0x200", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(0x200, parsedArgs.EmitOptions.FileAlignment); parsedArgs = DefaultParse(new[] { @"/filealign:512", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(512, parsedArgs.EmitOptions.FileAlignment); parsedArgs = DefaultParse(new[] { @"/filealign:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for 'filealign' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("filealign")); parsedArgs = DefaultParse(new[] { @"/filealign:-23", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2024: Invalid file section alignment number '-23' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("-23")); parsedArgs = DefaultParse(new[] { @"/filealign:020000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(8192, parsedArgs.EmitOptions.FileAlignment); parsedArgs = DefaultParse(new[] { @"/filealign:0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2024: Invalid file section alignment number '0' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("0")); parsedArgs = DefaultParse(new[] { @"/filealign:123", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2024: Invalid file section alignment number '123' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("123")); } [ConditionalFact(typeof(WindowsOnly))] public void SdkPathAndLibEnvVariable() { var dir = Temp.CreateDirectory(); var lib1 = dir.CreateDirectory("lib1"); var lib2 = dir.CreateDirectory("lib2"); var lib3 = dir.CreateDirectory("lib3"); var sdkDirectory = SdkDirectory; var parsedArgs = DefaultParse(new[] { @"/lib:lib1", @"/libpath:lib2", @"/libpaths:lib3", "a.cs" }, dir.Path, sdkDirectory: sdkDirectory); AssertEx.Equal(new[] { sdkDirectory, lib1.Path, lib2.Path, lib3.Path }, parsedArgs.ReferencePaths); } [ConditionalFact(typeof(WindowsOnly))] public void SdkPathAndLibEnvVariable_Errors() { var parsedArgs = DefaultParse(new[] { @"/lib:c:lib2", @"/lib:o:\sdk1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS1668: Invalid search path 'c:lib2' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"c:lib2", "/LIB option", "path is too long or invalid"), // warning CS1668: Invalid search path 'o:\sdk1' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"o:\sdk1", "/LIB option", "directory does not exist")); parsedArgs = DefaultParse(new[] { @"/lib:c:\Windows,o:\Windows;e:;", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS1668: Invalid search path 'o:\Windows' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"o:\Windows", "/LIB option", "directory does not exist"), // warning CS1668: Invalid search path 'e:' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"e:", "/LIB option", "path is too long or invalid")); parsedArgs = DefaultParse(new[] { @"/lib:c:\Windows,.\Windows;e;", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS1668: Invalid search path '.\Windows' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@".\Windows", "/LIB option", "directory does not exist"), // warning CS1668: Invalid search path 'e' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"e", "/LIB option", "directory does not exist")); parsedArgs = DefaultParse(new[] { @"/lib:c:\Windows,o:\Windows;e:; ; ; ; ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS1668: Invalid search path 'o:\Windows' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"o:\Windows", "/LIB option", "directory does not exist"), // warning CS1668: Invalid search path 'e:' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("e:", "/LIB option", "path is too long or invalid"), // warning CS1668: Invalid search path ' ' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(" ", "/LIB option", "path is too long or invalid"), // warning CS1668: Invalid search path ' ' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(" ", "/LIB option", "path is too long or invalid"), // warning CS1668: Invalid search path ' ' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(" ", "/LIB option", "path is too long or invalid")); parsedArgs = DefaultParse(new[] { @"/lib", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<path list>", "lib")); parsedArgs = DefaultParse(new[] { @"/lib:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<path list>", "lib")); parsedArgs = DefaultParse(new[] { @"/lib+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/lib+")); parsedArgs = DefaultParse(new[] { @"/lib: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<path list>", "lib")); } [Fact, WorkItem(546005, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546005")] public void SdkPathAndLibEnvVariable_Relative_csc() { var tempFolder = Temp.CreateDirectory(); var baseDirectory = tempFolder.ToString(); var subFolder = tempFolder.CreateDirectory("temp"); var subDirectory = subFolder.ToString(); var src = Temp.CreateFile("a.cs"); src.WriteAllText("public class C{}"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, subDirectory, new[] { "/nologo", "/t:library", "/out:abc.xyz", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDirectory, new[] { "/nologo", "/lib:temp", "/r:abc.xyz", "/t:library", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(src.Path); } [Fact] public void UnableWriteOutput() { var tempFolder = Temp.CreateDirectory(); var baseDirectory = tempFolder.ToString(); var subFolder = tempFolder.CreateDirectory("temp"); var src = Temp.CreateFile("a.cs"); src.WriteAllText("public class C{}"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/out:" + subFolder.ToString(), src.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.True(outWriter.ToString().Trim().StartsWith("error CS2012: Cannot open '" + subFolder.ToString() + "' for writing -- '", StringComparison.Ordinal)); // Cannot create a file when that file already exists. CleanupAllGeneratedFiles(src.Path); } [Fact] public void ParseHighEntropyVA() { var parsedArgs = DefaultParse(new[] { @"/highentropyva", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.True(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); parsedArgs = DefaultParse(new[] { @"/highentropyva+", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.True(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); parsedArgs = DefaultParse(new[] { @"/highentropyva-", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.False(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); parsedArgs = DefaultParse(new[] { @"/highentropyva:-", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal(EmitOptions.Default.HighEntropyVirtualAddressSpace, parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); parsedArgs = DefaultParse(new[] { @"/highentropyva:", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal(EmitOptions.Default.HighEntropyVirtualAddressSpace, parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); //last one wins parsedArgs = DefaultParse(new[] { @"/highenTROPyva+", @"/HIGHentropyva-", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.False(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); } [Fact] public void Checked() { var parsedArgs = DefaultParse(new[] { @"/checked+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.CheckOverflow); parsedArgs = DefaultParse(new[] { @"/checked-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.CheckOverflow); parsedArgs = DefaultParse(new[] { @"/checked", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.CheckOverflow); parsedArgs = DefaultParse(new[] { @"/checked-", @"/checked", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.CheckOverflow); parsedArgs = DefaultParse(new[] { @"/checked:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/checked:")); } [Fact] public void Nullable() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enabled' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.0", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:yes", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'yes' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("yes").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:enable", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enable' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.0", "8.0").WithLocation(1, 1)); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:disable", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:yes", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'yes' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("yes").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:eNable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:disablE", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Safeonly", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'Safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("Safeonly").WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:safeonly", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:safeonly", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1), // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1), // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:safeonly", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1), // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:yeS", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'yeS' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("yeS").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enable' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enabled' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:enable", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enabled' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:disable", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { "a.cs", "/langversion:8" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { "a.cs", "/langversion:7.3" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:""safeonly""", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:\""enable\""", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option '"enable"' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("\"enable\"").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:\\disable\\", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option '\\disable\\' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("\\\\disable\\\\").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:\\""enable\\""", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option '\enable\' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("\\enable\\").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonlywarnings", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonlywarnings' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonlywarnings").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:SafeonlyWarnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'SafeonlyWarnings' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("SafeonlyWarnings").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:safeonlyWarnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonlyWarnings' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonlyWarnings").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:warnings", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Warnings' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Warnings", "7.0", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Annotations' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Warnings", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:annotations", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Annotations' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Annotations", "7.0", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Annotations' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Annotations", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); } [Fact] public void Usings() { CSharpCommandLineArguments parsedArgs; var sdkDirectory = SdkDirectory; parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:Goo.Bar" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "Goo.Bar" }, parsedArgs.CompilationOptions.Usings.AsEnumerable()); parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:Goo.Bar;Baz", "/using:System.Core;System" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "Goo.Bar", "Baz", "System.Core", "System" }, parsedArgs.CompilationOptions.Usings.AsEnumerable()); parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:Goo;;Bar" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "Goo", "Bar" }, parsedArgs.CompilationOptions.Usings.AsEnumerable()); parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<namespace>' for '/u:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<namespace>", "/u:")); } [Fact] public void WarningsErrors() { var parsedArgs = DefaultParse(new string[] { "/nowarn", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for 'nowarn' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("nowarn")); parsedArgs = DefaultParse(new string[] { "/nowarn:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for 'nowarn' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("nowarn")); // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied via /nowarn or /warnaserror. // We no longer generate a warning in such cases. parsedArgs = DefaultParse(new string[] { "/nowarn:-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/nowarn:abc", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warnaserror:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for 'warnaserror' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warnaserror")); parsedArgs = DefaultParse(new string[] { "/warnaserror:-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warnaserror:70000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warnaserror:abc", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warnaserror+:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/warnaserror+:' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warnaserror+")); parsedArgs = DefaultParse(new string[] { "/warnaserror-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/warnaserror-:' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warnaserror-")); parsedArgs = DefaultParse(new string[] { "/w", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/w' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("w")); parsedArgs = DefaultParse(new string[] { "/w:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/w:' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("w")); parsedArgs = DefaultParse(new string[] { "/warn:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/warn:' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warn")); parsedArgs = DefaultParse(new string[] { "/w:-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS1900: Warning level must be zero or greater Diagnostic(ErrorCode.ERR_BadWarningLevel).WithArguments("w")); parsedArgs = DefaultParse(new string[] { "/w:5", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warn:-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS1900: Warning level must be zero or greater Diagnostic(ErrorCode.ERR_BadWarningLevel).WithArguments("warn")); parsedArgs = DefaultParse(new string[] { "/warn:5", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied via /nowarn or /warnaserror. // We no longer generate a warning in such cases. parsedArgs = DefaultParse(new string[] { "/warnaserror:1,2,3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/nowarn:1,2,3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/nowarn:1;2;;3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); } private static void AssertSpecificDiagnostics(int[] expectedCodes, ReportDiagnostic[] expectedOptions, CSharpCommandLineArguments args) { var actualOrdered = args.CompilationOptions.SpecificDiagnosticOptions.OrderBy(entry => entry.Key); AssertEx.Equal( expectedCodes.Select(i => MessageProvider.Instance.GetIdForErrorCode(i)), actualOrdered.Select(entry => entry.Key)); AssertEx.Equal(expectedOptions, actualOrdered.Select(entry => entry.Value)); } [Fact] public void WarningsParse() { var parsedArgs = DefaultParse(new string[] { "/warnaserror", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Error, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); Assert.Equal(0, parsedArgs.CompilationOptions.SpecificDiagnosticOptions.Count); parsedArgs = DefaultParse(new string[] { "/warnaserror:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror:+1062,+1066,+1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Error, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror+:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror-:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Default, ReportDiagnostic.Default, ReportDiagnostic.Default }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror+:1062,1066,1734", "/warnaserror-:1762,1974", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics( new[] { 1062, 1066, 1734, 1762, 1974 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Default, ReportDiagnostic.Default }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror+:1062,1066,1734", "/warnaserror-:1062,1974", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); Assert.Equal(4, parsedArgs.CompilationOptions.SpecificDiagnosticOptions.Count); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1974 }, new[] { ReportDiagnostic.Default, ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Default }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror-:1062,1066,1734", "/warnaserror+:1062,1974", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1974 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Default, ReportDiagnostic.Default, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/w:1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(1, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs); parsedArgs = DefaultParse(new string[] { "/warn:1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(1, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs); parsedArgs = DefaultParse(new string[] { "/warn:1", "/warnaserror+:1062,1974", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(1, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1974 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/nowarn:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress }, parsedArgs); parsedArgs = DefaultParse(new string[] { @"/nowarn:""1062 1066 1734""", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/nowarn:1062,1066,1734", "/warnaserror:1066,1762", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1762 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror:1066,1762", "/nowarn:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1762 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Error }, parsedArgs); } [Fact] public void AllowUnsafe() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/unsafe", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "/unsafe+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "/UNSAFE-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "/unsafe-", "/unsafe+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); // default parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "/unsafe:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/unsafe:")); parsedArgs = DefaultParse(new[] { "/unsafe:+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/unsafe:+")); parsedArgs = DefaultParse(new[] { "/unsafe-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/unsafe-:")); } [Fact] public void DelaySign() { CSharpCommandLineArguments parsedArgs; parsedArgs = DefaultParse(new[] { "/delaysign", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.NotNull(parsedArgs.CompilationOptions.DelaySign); Assert.True((bool)parsedArgs.CompilationOptions.DelaySign); parsedArgs = DefaultParse(new[] { "/delaysign+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.NotNull(parsedArgs.CompilationOptions.DelaySign); Assert.True((bool)parsedArgs.CompilationOptions.DelaySign); parsedArgs = DefaultParse(new[] { "/DELAYsign-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.NotNull(parsedArgs.CompilationOptions.DelaySign); Assert.False((bool)parsedArgs.CompilationOptions.DelaySign); parsedArgs = DefaultParse(new[] { "/delaysign:-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/delaysign:-' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/delaysign:-")); Assert.Null(parsedArgs.CompilationOptions.DelaySign); } [Fact] public void PublicSign() { var parsedArgs = DefaultParse(new[] { "/publicsign", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.PublicSign); parsedArgs = DefaultParse(new[] { "/publicsign+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.PublicSign); parsedArgs = DefaultParse(new[] { "/PUBLICsign-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.PublicSign); parsedArgs = DefaultParse(new[] { "/publicsign:-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/publicsign:-' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/publicsign:-").WithLocation(1, 1)); Assert.False(parsedArgs.CompilationOptions.PublicSign); } [WorkItem(8360, "https://github.com/dotnet/roslyn/issues/8360")] [Fact] public void PublicSign_KeyFileRelativePath() { var parsedArgs = DefaultParse(new[] { "/publicsign", "/keyfile:test.snk", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "test.snk"), parsedArgs.CompilationOptions.CryptoKeyFile); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void PublicSignWithEmptyKeyPath() { DefaultParse(new[] { "/publicsign", "/keyfile:", "a.cs" }, WorkingDirectory).Errors.Verify( // error CS2005: Missing file specification for 'keyfile' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile").WithLocation(1, 1)); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void PublicSignWithEmptyKeyPath2() { DefaultParse(new[] { "/publicsign", "/keyfile:\"\"", "a.cs" }, WorkingDirectory).Errors.Verify( // error CS2005: Missing file specification for 'keyfile' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile").WithLocation(1, 1)); } [WorkItem(546301, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546301")] [Fact] public void SubsystemVersionTests() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/subsystemversion:4.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SubsystemVersion.Create(4, 0), parsedArgs.EmitOptions.SubsystemVersion); // wrongly supported subsystem version. CompilationOptions data will be faithful to the user input. // It is normalized at the time of emit. parsedArgs = DefaultParse(new[] { "/subsystemversion:0.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // no error in Dev11 Assert.Equal(SubsystemVersion.Create(0, 0), parsedArgs.EmitOptions.SubsystemVersion); parsedArgs = DefaultParse(new[] { "/subsystemversion:0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // no error in Dev11 Assert.Equal(SubsystemVersion.Create(0, 0), parsedArgs.EmitOptions.SubsystemVersion); parsedArgs = DefaultParse(new[] { "/subsystemversion:3.99", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // no error in Dev11 Assert.Equal(SubsystemVersion.Create(3, 99), parsedArgs.EmitOptions.SubsystemVersion); parsedArgs = DefaultParse(new[] { "/subsystemversion:4.0", "/SUBsystemversion:5.333", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SubsystemVersion.Create(5, 333), parsedArgs.EmitOptions.SubsystemVersion); parsedArgs = DefaultParse(new[] { "/subsystemversion:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "subsystemversion")); parsedArgs = DefaultParse(new[] { "/subsystemversion", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "subsystemversion")); parsedArgs = DefaultParse(new[] { "/subsystemversion-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/subsystemversion-")); parsedArgs = DefaultParse(new[] { "/subsystemversion: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "subsystemversion")); parsedArgs = DefaultParse(new[] { "/subsystemversion: 4.1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments(" 4.1")); parsedArgs = DefaultParse(new[] { "/subsystemversion:4 .0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4 .0")); parsedArgs = DefaultParse(new[] { "/subsystemversion:4. 0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4. 0")); parsedArgs = DefaultParse(new[] { "/subsystemversion:.", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments(".")); parsedArgs = DefaultParse(new[] { "/subsystemversion:4.", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4.")); parsedArgs = DefaultParse(new[] { "/subsystemversion:.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments(".0")); parsedArgs = DefaultParse(new[] { "/subsystemversion:4.2 ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/subsystemversion:4.65536", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4.65536")); parsedArgs = DefaultParse(new[] { "/subsystemversion:65536.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("65536.0")); parsedArgs = DefaultParse(new[] { "/subsystemversion:-4.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("-4.0")); // TODO: incompatibilities: versions lower than '6.2' and 'arm', 'winmdobj', 'appcontainer' } [Fact] public void MainType() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/m:A.B.C", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("A.B.C", parsedArgs.CompilationOptions.MainTypeName); parsedArgs = DefaultParse(new[] { "/m: ", "a.cs" }, WorkingDirectory); // Mimicking Dev11 parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "m")); Assert.Null(parsedArgs.CompilationOptions.MainTypeName); // overriding the value parsedArgs = DefaultParse(new[] { "/m:A.B.C", "/MAIN:X.Y.Z", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("X.Y.Z", parsedArgs.CompilationOptions.MainTypeName); // error parsedArgs = DefaultParse(new[] { "/maiN:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "main")); parsedArgs = DefaultParse(new[] { "/MAIN+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/MAIN+")); parsedArgs = DefaultParse(new[] { "/M", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "m")); // incompatible values /main && /target parsedArgs = DefaultParse(new[] { "/main:a", "/t:library", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoMainOnDLL)); parsedArgs = DefaultParse(new[] { "/main:a", "/t:module", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoMainOnDLL)); } [Fact] public void Codepage() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/CodePage:1200", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("Unicode", parsedArgs.Encoding.EncodingName); parsedArgs = DefaultParse(new[] { "/CodePage:1200", "/codePAGE:65001", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("Unicode (UTF-8)", parsedArgs.Encoding.EncodingName); // error parsedArgs = DefaultParse(new[] { "/codepage:0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("0")); parsedArgs = DefaultParse(new[] { "/codepage:abc", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("abc")); parsedArgs = DefaultParse(new[] { "/codepage:-5", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("-5")); parsedArgs = DefaultParse(new[] { "/codepage: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("")); parsedArgs = DefaultParse(new[] { "/codepage:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("")); parsedArgs = DefaultParse(new[] { "/codepage", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "codepage")); parsedArgs = DefaultParse(new[] { "/codepage+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/codepage+")); } [Fact, WorkItem(24735, "https://github.com/dotnet/roslyn/issues/24735")] public void ChecksumAlgorithm() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sHa1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SourceHashAlgorithm.Sha1, parsedArgs.ChecksumAlgorithm); Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sha256", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SourceHashAlgorithm.Sha256, parsedArgs.ChecksumAlgorithm); Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm); parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SourceHashAlgorithm.Sha256, parsedArgs.ChecksumAlgorithm); Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm); // error parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:256", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadChecksumAlgorithm).WithArguments("256")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sha-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadChecksumAlgorithm).WithArguments("sha-1")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sha", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadChecksumAlgorithm).WithArguments("sha")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "checksumalgorithm")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "checksumalgorithm")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "checksumalgorithm")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/checksumAlgorithm+")); } [Fact] public void AddModule() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/noconfig", "/nostdlib", "/addmodule:abc.netmodule", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(1, parsedArgs.MetadataReferences.Length); Assert.Equal("abc.netmodule", parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[0].Properties.Kind); parsedArgs = DefaultParse(new[] { "/noconfig", "/nostdlib", "/aDDmodule:c:\\abc;c:\\abc;d:\\xyz", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(3, parsedArgs.MetadataReferences.Length); Assert.Equal("c:\\abc", parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[0].Properties.Kind); Assert.Equal("c:\\abc", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[1].Properties.Kind); Assert.Equal("d:\\xyz", parsedArgs.MetadataReferences[2].Reference); Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[2].Properties.Kind); // error parsedArgs = DefaultParse(new[] { "/ADDMODULE", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/addmodule:")); parsedArgs = DefaultParse(new[] { "/ADDMODULE+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/ADDMODULE+")); parsedArgs = DefaultParse(new[] { "/ADDMODULE:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/ADDMODULE:")); } [Fact, WorkItem(530751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530751")] public void CS7061fromCS0647_ModuleWithCompilationRelaxations() { string source1 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" using System.Runtime.CompilerServices; [assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)] public class Mod { }").Path; string source2 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" using System.Runtime.CompilerServices; [assembly: CompilationRelaxations(4)] public class Mod { }").Path; string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" using System.Runtime.CompilerServices; [assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)] class Test { static void Main() {} }").Path; var baseDir = Path.GetDirectoryName(source); // === Scenario 1 === var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source1 }).Run(outWriter); Assert.Equal(0, exitCode); var modfile = source1.Substring(0, source1.Length - 2) + "netmodule"; outWriter = new StringWriter(CultureInfo.InvariantCulture); var parsedArgs = DefaultParse(new[] { "/nologo", "/addmodule:" + modfile, source }, WorkingDirectory); parsedArgs.Errors.Verify(); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/addmodule:" + modfile, source }).Run(outWriter); Assert.Empty(outWriter.ToString()); // === Scenario 2 === outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source2 }).Run(outWriter); Assert.Equal(0, exitCode); modfile = source2.Substring(0, source2.Length - 2) + "netmodule"; outWriter = new StringWriter(CultureInfo.InvariantCulture); parsedArgs = DefaultParse(new[] { "/nologo", "/addmodule:" + modfile, source }, WorkingDirectory); parsedArgs.Errors.Verify(); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/addmodule:" + modfile, source }).Run(outWriter); Assert.Equal(1, exitCode); // Dev11: CS0647 (Emit) Assert.Contains("error CS7061: Duplicate 'CompilationRelaxationsAttribute' attribute in", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source1); CleanupAllGeneratedFiles(source2); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(530780, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530780")] public void AddModuleWithExtensionMethod() { string source1 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"public static class Extensions { public static bool EB(this bool b) { return b; } }").Path; string source2 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class C { static void Main() {} }").Path; var baseDir = Path.GetDirectoryName(source2); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source1 }).Run(outWriter); Assert.Equal(0, exitCode); var modfile = source1.Substring(0, source1.Length - 2) + "netmodule"; outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/addmodule:" + modfile, source2 }).Run(outWriter); Assert.Equal(0, exitCode); CleanupAllGeneratedFiles(source1); CleanupAllGeneratedFiles(source2); } [Fact, WorkItem(546297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546297")] public void OLDCS0013FTL_MetadataEmitFailureSameModAndRes() { string source1 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class Mod { }").Path; string source2 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class C { static void Main() {} }").Path; var baseDir = Path.GetDirectoryName(source2); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source1 }).Run(outWriter); Assert.Equal(0, exitCode); var modfile = source1.Substring(0, source1.Length - 2) + "netmodule"; outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/addmodule:" + modfile, "/linkres:" + modfile, source2 }).Run(outWriter); Assert.Equal(1, exitCode); // Native gives CS0013 at emit stage Assert.Equal("error CS7041: Each linked resource and module must have a unique filename. Filename '" + Path.GetFileName(modfile) + "' is specified more than once in this assembly", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source1); CleanupAllGeneratedFiles(source2); } [Fact] public void Utf8Output() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/utf8output", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True((bool)parsedArgs.Utf8Output); parsedArgs = DefaultParse(new[] { "/utf8output", "/utf8output", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True((bool)parsedArgs.Utf8Output); parsedArgs = DefaultParse(new[] { "/utf8output:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/utf8output:")); } [Fact] public void CscCompile_WithSourceCodeRedirectedViaStandardInput_ProducesRunnableProgram() { string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C echo ^ class A ^ {{ ^ public static void Main() =^^^> ^ System.Console.WriteLine(""Hello World!""); ^ }} | {s_CSharpCompilerExecutable} /nologo /t:exe -" .Replace(Environment.NewLine, string.Empty), workingDirectory: tempDir) : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo \ class A \ {{ \ public static void Main\(\) =\> \ System.Console.WriteLine\(\\\""Hello World\!\\\""\)\; \ }} | {s_CSharpCompilerExecutable} /nologo /t:exe -""", workingDirectory: tempDir, // we are testing shell's piped/redirected stdin behavior explicitly // instead of using Process.StandardInput.Write(), so we set // redirectStandardInput to true, which implies that isatty of child // process is false and thereby Console.IsInputRedirected will return // true in csc code. redirectStandardInput: true); Assert.False(result.ContainsErrors, $"Compilation error(s) occurred: {result.Output} {result.Errors}"); string output = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.RunAndGetOutput("cmd.exe", $@"/C ""{s_DotnetCscRun} -.exe""", expectedRetCode: 0, startFolder: tempDir) : ProcessUtilities.RunAndGetOutput("sh", $@"-c ""{s_DotnetCscRun} -.exe""", expectedRetCode: 0, startFolder: tempDir); Assert.Equal("Hello World!", output.Trim()); } [Fact] public void CscCompile_WithSourceCodeRedirectedViaStandardInput_ProducesLibrary() { var name = Guid.NewGuid().ToString() + ".dll"; string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C echo ^ class A ^ {{ ^ public A Get() =^^^> default; ^ }} | {s_CSharpCompilerExecutable} /nologo /t:library /out:{name} -" .Replace(Environment.NewLine, string.Empty), workingDirectory: tempDir) : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo \ class A \ {{ \ public A Get\(\) =\> default\; \ }} | {s_CSharpCompilerExecutable} /nologo /t:library /out:{name} -""", workingDirectory: tempDir, // we are testing shell's piped/redirected stdin behavior explicitly // instead of using Process.StandardInput.Write(), so we set // redirectStandardInput to true, which implies that isatty of child // process is false and thereby Console.IsInputRedirected will return // true in csc code. redirectStandardInput: true); Assert.False(result.ContainsErrors, $"Compilation error(s) occurred: {result.Output} {result.Errors}"); var assemblyName = AssemblyName.GetAssemblyName(Path.Combine(tempDir, name)); Assert.Equal(name.Replace(".dll", ", Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), assemblyName.ToString()); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/55727")] public void CsiScript_WithSourceCodeRedirectedViaStandardInput_ExecutesNonInteractively() { string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C echo Console.WriteLine(""Hello World!"") | {s_CSharpScriptExecutable} -") : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo Console.WriteLine\(\\\""Hello World\!\\\""\) | {s_CSharpScriptExecutable} -""", workingDirectory: tempDir, // we are testing shell's piped/redirected stdin behavior explicitly // instead of using Process.StandardInput.Write(), so we set // redirectStandardInput to true, which implies that isatty of child // process is false and thereby Console.IsInputRedirected will return // true in csc code. redirectStandardInput: true); Assert.False(result.ContainsErrors, $"Compilation error(s) occurred: {result.Output} {result.Errors}"); Assert.Equal("Hello World!", result.Output.Trim()); } [Fact] public void CscCompile_WithRedirectedInputIndicatorAndStandardInputNotRedirected_ReportsCS8782() { if (Console.IsInputRedirected) { // [applicable to both Windows and Unix] // if our parent (xunit) process itself has input redirected, we cannot test this // error case because our child process will inherit it and we cannot achieve what // we are aiming for: isatty(0):true and thereby Console.IsInputerRedirected:false in // child. running this case will make StreamReader to hang (waiting for input, that // we do not propagate: parent.In->child.In). // // note: in Unix we can "close" fd0 by appending `0>&-` in the `sh -c` command below, // but that will also not impact the result of isatty(), and in turn causes a different // compiler error. return; } string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C ""{s_CSharpCompilerExecutable} /nologo /t:exe -""", workingDirectory: tempDir) : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""{s_CSharpCompilerExecutable} /nologo /t:exe -""", workingDirectory: tempDir); Assert.True(result.ContainsErrors); Assert.Contains(((int)ErrorCode.ERR_StdInOptionProvidedButConsoleInputIsNotRedirected).ToString(), result.Output); } [Fact] public void CscCompile_WithMultipleStdInOperators_WarnsCS2002() { string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C echo ^ class A ^ {{ ^ public static void Main() =^^^> ^ System.Console.WriteLine(""Hello World!""); ^ }} | {s_CSharpCompilerExecutable} /nologo - /t:exe -" .Replace(Environment.NewLine, string.Empty)) : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo \ class A \ {{ \ public static void Main\(\) =\> \ System.Console.WriteLine\(\\\""Hello World\!\\\""\)\; \ }} | {s_CSharpCompilerExecutable} /nologo - /t:exe -""", workingDirectory: tempDir, // we are testing shell's piped/redirected stdin behavior explicitly // instead of using Process.StandardInput.Write(), so we set // redirectStandardInput to true, which implies that isatty of child // process is false and thereby Console.IsInputRedirected will return // true in csc code. redirectStandardInput: true); Assert.Contains(((int)ErrorCode.WRN_FileAlreadyIncluded).ToString(), result.Output); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void CscUtf8Output_WithRedirecting_Off() { var srcFile = Temp.CreateFile().WriteAllText("\u265A").Path; var tempOut = Temp.CreateFile(); var output = ProcessUtilities.RunAndGetOutput("cmd", "/C \"" + s_CSharpCompilerExecutable + "\" /nologo /preferreduilang:en /t:library " + srcFile + " > " + tempOut.Path, expectedRetCode: 1); Assert.Equal("", output.Trim()); Assert.Equal("SRC.CS(1,1): error CS1056: Unexpected character '?'", tempOut.ReadAllText().Trim().Replace(srcFile, "SRC.CS")); CleanupAllGeneratedFiles(srcFile); CleanupAllGeneratedFiles(tempOut.Path); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void CscUtf8Output_WithRedirecting_On() { var srcFile = Temp.CreateFile().WriteAllText("\u265A").Path; var tempOut = Temp.CreateFile(); var output = ProcessUtilities.RunAndGetOutput("cmd", "/C \"" + s_CSharpCompilerExecutable + "\" /utf8output /nologo /preferreduilang:en /t:library " + srcFile + " > " + tempOut.Path, expectedRetCode: 1); Assert.Equal("", output.Trim()); Assert.Equal("SRC.CS(1,1): error CS1056: Unexpected character '♚'", tempOut.ReadAllText().Trim().Replace(srcFile, "SRC.CS")); CleanupAllGeneratedFiles(srcFile); CleanupAllGeneratedFiles(tempOut.Path); } [WorkItem(546653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546653")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void NoSourcesWithModule() { var folder = Temp.CreateDirectory(); var aCs = folder.CreateFile("a.cs"); aCs.WriteAllText("public class C {}"); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/nologo /t:module /out:a.netmodule \"{aCs}\"", startFolder: folder.ToString()); Assert.Equal("", output.Trim()); output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /t:library /out:b.dll /addmodule:a.netmodule ", startFolder: folder.ToString()); Assert.Equal("", output.Trim()); output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /preferreduilang:en /t:module /out:b.dll /addmodule:a.netmodule ", startFolder: folder.ToString()); Assert.Equal("warning CS2008: No source files specified.", output.Trim()); CleanupAllGeneratedFiles(aCs.Path); } [WorkItem(546653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546653")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void NoSourcesWithResource() { var folder = Temp.CreateDirectory(); var aCs = folder.CreateFile("a.cs"); aCs.WriteAllText("public class C {}"); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /t:library /out:b.dll /resource:a.cs", startFolder: folder.ToString()); Assert.Equal("", output.Trim()); CleanupAllGeneratedFiles(aCs.Path); } [WorkItem(546653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546653")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void NoSourcesWithLinkResource() { var folder = Temp.CreateDirectory(); var aCs = folder.CreateFile("a.cs"); aCs.WriteAllText("public class C {}"); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /t:library /out:b.dll /linkresource:a.cs", startFolder: folder.ToString()); Assert.Equal("", output.Trim()); CleanupAllGeneratedFiles(aCs.Path); } [Fact] public void KeyContainerAndKeyFile() { // KEYCONTAINER CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/keycontainer:RIPAdamYauch", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("RIPAdamYauch", parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keycontainer", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'keycontainer' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "keycontainer")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keycontainer-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/keycontainer-' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/keycontainer-")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keycontainer:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'keycontainer' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "keycontainer")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keycontainer: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "keycontainer")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); // KEYFILE parsedArgs = DefaultParse(new[] { @"/keyfile:\somepath\s""ome Fil""e.goo.bar", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); //EDMAURER let's not set the option in the event that there was an error. //Assert.Equal(@"\somepath\some File.goo.bar", parsedArgs.CompilationOptions.CryptoKeyFile); parsedArgs = DefaultParse(new[] { "/keyFile", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for 'keyfile' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile); parsedArgs = DefaultParse(new[] { "/keyFile: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile); parsedArgs = DefaultParse(new[] { "/keyfile-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/keyfile-' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/keyfile-")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile); // DEFAULTS parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); // KEYFILE | KEYCONTAINER conflicts parsedArgs = DefaultParse(new[] { "/keyFile:a", "/keyContainer:b", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.CompilationOptions.CryptoKeyFile); Assert.Equal("b", parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keyContainer:b", "/keyFile:a", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.CompilationOptions.CryptoKeyFile); Assert.Equal("b", parsedArgs.CompilationOptions.CryptoKeyContainer); } [Fact, WorkItem(554551, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554551")] public void CS1698WRN_AssumedMatchThis() { // compile with: /target:library /keyfile:mykey.snk var text1 = @"[assembly:System.Reflection.AssemblyVersion(""2"")] public class CS1698_a {} "; // compile with: /target:library /reference:CS1698_a.dll /keyfile:mykey.snk var text2 = @"public class CS1698_b : CS1698_a {} "; //compile with: /target:library /out:cs1698_a.dll /reference:cs1698_b.dll /keyfile:mykey.snk var text = @"[assembly:System.Reflection.AssemblyVersion(""3"")] public class CS1698_c : CS1698_b {} public class CS1698_a {} "; var folder = Temp.CreateDirectory(); var cs1698a = folder.CreateFile("CS1698a.cs"); cs1698a.WriteAllText(text1); var cs1698b = folder.CreateFile("CS1698b.cs"); cs1698b.WriteAllText(text2); var cs1698 = folder.CreateFile("CS1698.cs"); cs1698.WriteAllText(text); var snkFile = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey); var kfile = "/keyfile:" + snkFile.Path; CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/t:library", kfile, "CS1698a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/t:library", kfile, "/r:" + cs1698a.Path, "CS1698b.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/t:library", kfile, "/r:" + cs1698b.Path, "/out:" + cs1698a.Path, "CS1698.cs" }, WorkingDirectory); // Roslyn no longer generates a warning for this...since this was only a warning, we're not really // saving anyone...does not provide high value to implement... // warning CS1698: Circular assembly reference 'CS1698a, Version=2.0.0.0, Culture=neutral,PublicKeyToken = 9e9d6755e7bb4c10' // does not match the output assembly name 'CS1698a, Version = 3.0.0.0, Culture = neutral, PublicKeyToken = 9e9d6755e7bb4c10'. // Try adding a reference to 'CS1698a, Version = 2.0.0.0, Culture = neutral, PublicKeyToken = 9e9d6755e7bb4c10' or changing the output assembly name to match. parsedArgs.Errors.Verify(); CleanupAllGeneratedFiles(snkFile.Path); CleanupAllGeneratedFiles(cs1698a.Path); CleanupAllGeneratedFiles(cs1698b.Path); CleanupAllGeneratedFiles(cs1698.Path); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/dotnet/roslyn/issues/30926")] public void BinaryFileErrorTest() { var binaryPath = Temp.CreateFile().WriteAllBytes(ResourcesNet451.mscorlib).Path; var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", binaryPath }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal( "error CS2015: '" + binaryPath + "' is a binary file instead of a text file", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(binaryPath); } #if !NETCOREAPP [WorkItem(530221, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530221")] [WorkItem(5660, "https://github.com/dotnet/roslyn/issues/5660")] [ConditionalFact(typeof(WindowsOnly), typeof(IsEnglishLocal))] public void Bug15538() { // Several Jenkins VMs are still running with local systems permissions. This suite won't run properly // in that environment. Removing this check is being tracked by issue #79. using (var identity = System.Security.Principal.WindowsIdentity.GetCurrent()) { if (identity.IsSystem) { return; } // The icacls command fails on our Helix machines and it appears to be related to the use of the $ in // the username. // https://github.com/dotnet/roslyn/issues/28836 if (StringComparer.OrdinalIgnoreCase.Equals(Environment.UserDomainName, "WORKGROUP")) { return; } } var folder = Temp.CreateDirectory(); var source = folder.CreateFile("src.vb").WriteAllText("").Path; var _ref = folder.CreateFile("ref.dll").WriteAllText("").Path; try { var output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " + _ref + " /inheritance:r /Q"); Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim()); output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " + _ref + @" /deny %USERDOMAIN%\%USERNAME%:(r,WDAC) /Q"); Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim()); output = ProcessUtilities.RunAndGetOutput("cmd", "/C \"" + s_CSharpCompilerExecutable + "\" /nologo /preferreduilang:en /r:" + _ref + " /t:library " + source, expectedRetCode: 1); Assert.Equal("error CS0009: Metadata file '" + _ref + "' could not be opened -- Access to the path '" + _ref + "' is denied.", output.Trim()); } finally { var output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " + _ref + " /reset /Q"); Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim()); File.Delete(_ref); } CleanupAllGeneratedFiles(source); } #endif [WorkItem(545832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545832")] [Fact] public void ResponseFilesWithEmptyAliasReference() { string source = Temp.CreateFile("a.cs").WriteAllText(@" // <Area> ExternAlias - command line alias</Area> // <Title> // negative test cases: empty file name ("""") // </Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=error>CS1680:.*myAlias=</Expects> // <Code> class myClass { static int Main() { return 1; } } // </Code> ").Path; string rsp = Temp.CreateFile().WriteAllText(@" /nologo /r:myAlias="""" ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS1680: Invalid reference alias option: 'myAlias=' -- missing filename", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [Fact] public void ResponseFileOrdering() { var rspFilePath1 = Temp.CreateFile().WriteAllText(@" /b /c ").Path; assertOrder( new[] { "/a", "/b", "/c", "/d" }, new[] { "/a", @$"@""{rspFilePath1}""", "/d" }); var rspFilePath2 = Temp.CreateFile().WriteAllText(@" /c /d ").Path; rspFilePath1 = Temp.CreateFile().WriteAllText(@$" /b @""{rspFilePath2}"" ").Path; assertOrder( new[] { "/a", "/b", "/c", "/d", "/e" }, new[] { "/a", @$"@""{rspFilePath1}""", "/e" }); rspFilePath1 = Temp.CreateFile().WriteAllText(@$" /b ").Path; rspFilePath2 = Temp.CreateFile().WriteAllText(@" # this will be ignored /c /d ").Path; assertOrder( new[] { "/a", "/b", "/c", "/d", "/e" }, new[] { "/a", @$"@""{rspFilePath1}""", $@"@""{rspFilePath2}""", "/e" }); void assertOrder(string[] expected, string[] args) { var flattenedArgs = ArrayBuilder<string>.GetInstance(); var diagnostics = new List<Diagnostic>(); CSharpCommandLineParser.Default.FlattenArgs( args, diagnostics, flattenedArgs, scriptArgsOpt: null, baseDirectory: Path.DirectorySeparatorChar == '\\' ? @"c:\" : "/"); Assert.Empty(diagnostics); Assert.Equal(expected, flattenedArgs); flattenedArgs.Free(); } } [WorkItem(545832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545832")] [Fact] public void ResponseFilesWithEmptyAliasReference2() { string source = Temp.CreateFile("a.cs").WriteAllText(@" // <Area> ExternAlias - command line alias</Area> // <Title> // negative test cases: empty file name ("""") // </Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=error>CS1680:.*myAlias=</Expects> // <Code> class myClass { static int Main() { return 1; } } // </Code> ").Path; string rsp = Temp.CreateFile().WriteAllText(@" /nologo /r:myAlias="" "" ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS1680: Invalid reference alias option: 'myAlias=' -- missing filename", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(1784, "https://github.com/dotnet/roslyn/issues/1784")] [Fact] public void QuotedDefineInRespFile() { string source = Temp.CreateFile("a.cs").WriteAllText(@" #if NN class myClass { #endif static int Main() #if DD { return 1; #endif #if AA } #endif #if BB } #endif ").Path; string rsp = Temp.CreateFile().WriteAllText(@" /d:""DD"" /d:""AA;BB"" /d:""N""N ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(1784, "https://github.com/dotnet/roslyn/issues/1784")] [Fact] public void QuotedDefineInRespFileErr() { string source = Temp.CreateFile("a.cs").WriteAllText(@" #if NN class myClass { #endif static int Main() #if DD { return 1; #endif #if AA } #endif #if BB } #endif ").Path; string rsp = Temp.CreateFile().WriteAllText(@" /d:""DD"""" /d:""AA;BB"" /d:""N"" ""N ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [Fact] public void ResponseFileSplitting() { string[] responseFile; responseFile = new string[] { @"a.cs b.cs ""c.cs e.cs""", @"hello world # this is a comment" }; IEnumerable<string> args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { "a.cs", "b.cs", @"c.cs e.cs", "hello", "world" }, args); // Check comment handling; comment character only counts at beginning of argument responseFile = new string[] { @" # ignore this", @" # ignore that ""hello""", @" a.cs #3.cs", @" b#.cs c#d.cs #e.cs", @" ""#f.cs""", @" ""#g.cs #h.cs""" }; args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { "a.cs", "b#.cs", "c#d.cs", "#f.cs", "#g.cs #h.cs" }, args); // Check backslash escaping responseFile = new string[] { @"a\b\c d\\e\\f\\ \\\g\\\h\\\i \\\\ \\\\\k\\\\\", }; args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { @"a\b\c", @"d\\e\\f\\", @"\\\g\\\h\\\i", @"\\\\", @"\\\\\k\\\\\" }, args); // More backslash escaping and quoting responseFile = new string[] { @"a\""a b\\""b c\\\""c d\\\\""d e\\\\\""e f"" g""", }; args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { @"a\""a", @"b\\""b c\\\""c d\\\\""d", @"e\\\\\""e", @"f"" g""" }, args); // Quoting inside argument is valid. responseFile = new string[] { @" /o:""goo.cs"" /o:""abc def""\baz ""/o:baz bar""bing", }; args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { @"/o:""goo.cs""", @"/o:""abc def""\baz", @"""/o:baz bar""bing" }, args); } [ConditionalFact(typeof(WindowsOnly))] private void SourceFileQuoting() { string[] responseFile = new string[] { @"d:\\""abc def""\baz.cs ab""c d""e.cs", }; CSharpCommandLineArguments args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\"); AssertEx.Equal(new[] { @"d:\abc def\baz.cs", @"c:\abc de.cs" }, args.SourceFiles.Select(file => file.Path)); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName1() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from first input (file, not class) name, since DLL. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:library" }, expectedOutputName: "p.dll"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName2() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from command-line option. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:library", "/out:r.dll" }, expectedOutputName: "r.dll"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName3() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe" }, expectedOutputName: "q.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName4() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from command-line option. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe", "/out:r.exe" }, expectedOutputName: "r.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName5() { string source1 = @" class A { static void Main() { } } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint - affected by /main, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe", "/main:A" }, expectedOutputName: "p.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName6() { string source1 = @" class A { static void Main() { } } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint - affected by /main, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe", "/main:B" }, expectedOutputName: "q.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName7() { string source1 = @" partial class A { static partial void Main() { } } "; string source2 = @" partial class A { static partial void Main(); } "; // Name comes from name of file containing entrypoint, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe" }, expectedOutputName: "p.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName8() { string source1 = @" partial class A { static partial void Main(); } "; string source2 = @" partial class A { static partial void Main() { } } "; // Name comes from name of file containing entrypoint, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe" }, expectedOutputName: "q.exe"); } [Fact] public void OutputFileName9() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from first input (file, not class) name, since winmdobj. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:winmdobj" }, expectedOutputName: "p.winmdobj"); } [Fact] public void OutputFileName10() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint, since appcontainerexe. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:appcontainerexe" }, expectedOutputName: "q.exe"); } [Fact] public void OutputFileName_Switch() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe", "/out:r.exe" }, expectedOutputName: "r.exe"); } [Fact] public void OutputFileName_NoEntryPoint() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/target:exe", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.NotEqual(0, exitCode); Assert.Equal("error CS5001: Program does not contain a static 'Main' method suitable for an entry point", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(file.Path); } [Fact, WorkItem(1093063, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1093063")] public void VerifyDiagnosticSeverityNotLocalized() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/target:exe", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.NotEqual(0, exitCode); // If "error" was localized, below assert will fail on PLOC builds. The output would be something like: "!pTCvB!vbc : !FLxft!error 表! CS5001:" Assert.Contains("error CS5001:", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(file.Path); } [Fact] public void NoLogo_1() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/target:library", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal(@"", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(file.Path); } [Fact] public void NoLogo_2() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var patched = Regex.Replace(outWriter.ToString().Trim(), "version \\d+\\.\\d+\\.\\d+(-[\\w\\d]+)*", "version A.B.C-d"); patched = ReplaceCommitHash(patched); Assert.Equal(@" Microsoft (R) Visual C# Compiler version A.B.C-d (HASH) Copyright (C) Microsoft Corporation. All rights reserved.".Trim(), patched); CleanupAllGeneratedFiles(file.Path); } [Theory, InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (<developer build>)", "Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)"), InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (ABCDEF01)", "Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)"), InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (abcdef90)", "Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)"), InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (12345678)", "Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)")] public void TestReplaceCommitHash(string orig, string expected) { Assert.Equal(expected, ReplaceCommitHash(orig)); } private static string ReplaceCommitHash(string s) { // open paren, followed by either <developer build> or 8 hex, followed by close paren return Regex.Replace(s, "(\\((<developer build>|[a-fA-F0-9]{8})\\))", "(HASH)"); } [Fact] public void ExtractShortCommitHash() { Assert.Null(CommonCompiler.ExtractShortCommitHash(null)); Assert.Equal("", CommonCompiler.ExtractShortCommitHash("")); Assert.Equal("<", CommonCompiler.ExtractShortCommitHash("<")); Assert.Equal("<developer build>", CommonCompiler.ExtractShortCommitHash("<developer build>")); Assert.Equal("1", CommonCompiler.ExtractShortCommitHash("1")); Assert.Equal("1234567", CommonCompiler.ExtractShortCommitHash("1234567")); Assert.Equal("12345678", CommonCompiler.ExtractShortCommitHash("12345678")); Assert.Equal("12345678", CommonCompiler.ExtractShortCommitHash("123456789")); } private void CheckOutputFileName(string source1, string source2, string inputName1, string inputName2, string[] commandLineArguments, string expectedOutputName) { var dir = Temp.CreateDirectory(); var file1 = dir.CreateFile(inputName1); file1.WriteAllText(source1); var file2 = dir.CreateFile(inputName2); file2.WriteAllText(source2); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, commandLineArguments.Concat(new[] { inputName1, inputName2 }).ToArray()); int exitCode = csc.Run(outWriter); if (exitCode != 0) { Console.WriteLine(outWriter.ToString()); Assert.Equal(0, exitCode); } Assert.Equal(1, Directory.EnumerateFiles(dir.Path, "*" + PathUtilities.GetExtension(expectedOutputName)).Count()); Assert.Equal(1, Directory.EnumerateFiles(dir.Path, expectedOutputName).Count()); using (var metadata = ModuleMetadata.CreateFromImage(File.ReadAllBytes(Path.Combine(dir.Path, expectedOutputName)))) { var peReader = metadata.Module.GetMetadataReader(); Assert.True(peReader.IsAssembly); Assert.Equal(PathUtilities.RemoveExtension(expectedOutputName), peReader.GetString(peReader.GetAssemblyDefinition().Name)); Assert.Equal(expectedOutputName, peReader.GetString(peReader.GetModuleDefinition().Name)); } if (System.IO.File.Exists(expectedOutputName)) { System.IO.File.Delete(expectedOutputName); } CleanupAllGeneratedFiles(file1.Path); CleanupAllGeneratedFiles(file2.Path); } [Fact] public void MissingReference() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/r:missing.dll", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS0006: Metadata file 'missing.dll' could not be found", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545025")] [ConditionalFact(typeof(WindowsOnly))] public void CompilationWithWarnAsError_01() { string source = @" public class C { public static void Main() { } }"; // Baseline without warning options (expect success) int exitCode = GetExitCode(source, "a.cs", new String[] { }); Assert.Equal(0, exitCode); // The case with /warnaserror (expect to be success, since there will be no warning) exitCode = GetExitCode(source, "b.cs", new[] { "/warnaserror" }); Assert.Equal(0, exitCode); // The case with /warnaserror and /nowarn:1 (expect success) // Note that even though the command line option has a warning, it is not going to become an error // in order to avoid the halt of compilation. exitCode = GetExitCode(source, "c.cs", new[] { "/warnaserror", "/nowarn:1" }); Assert.Equal(0, exitCode); } [WorkItem(545025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545025")] [ConditionalFact(typeof(WindowsOnly))] public void CompilationWithWarnAsError_02() { string source = @" public class C { public static void Main() { int x; // CS0168 } }"; // Baseline without warning options (expect success) int exitCode = GetExitCode(source, "a.cs", new String[] { }); Assert.Equal(0, exitCode); // The case with /warnaserror (expect failure) exitCode = GetExitCode(source, "b.cs", new[] { "/warnaserror" }); Assert.NotEqual(0, exitCode); // The case with /warnaserror:168 (expect failure) exitCode = GetExitCode(source, "c.cs", new[] { "/warnaserror:168" }); Assert.NotEqual(0, exitCode); // The case with /warnaserror:219 (expect success) exitCode = GetExitCode(source, "c.cs", new[] { "/warnaserror:219" }); Assert.Equal(0, exitCode); // The case with /warnaserror and /nowarn:168 (expect success) exitCode = GetExitCode(source, "d.cs", new[] { "/warnaserror", "/nowarn:168" }); Assert.Equal(0, exitCode); } private int GetExitCode(string source, string fileName, string[] commandLineArguments) { var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, commandLineArguments.Concat(new[] { fileName }).ToArray()); int exitCode = csc.Run(outWriter); return exitCode; } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [ConditionalFact(typeof(WindowsOnly))] public void CompilationWithNonExistingOutPath() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:sub\\a.exe" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS2012: Cannot open '" + dir.Path + "\\sub\\a.exe' for writing", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [Fact] public void CompilationWithWrongOutPath_01() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:sub\\" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); var message = outWriter.ToString(); Assert.Contains("error CS2021: File name", message, StringComparison.Ordinal); Assert.Contains("sub", message, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [Fact] public void CompilationWithWrongOutPath_02() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:sub\\ " }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); var message = outWriter.ToString(); Assert.Contains("error CS2021: File name", message, StringComparison.Ordinal); Assert.Contains("sub", message, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [ConditionalFact(typeof(WindowsDesktopOnly))] public void CompilationWithWrongOutPath_03() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:aaa:\\a.exe" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains(@"error CS2021: File name 'aaa:\a.exe' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [Fact] public void CompilationWithWrongOutPath_04() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out: " }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS2005: Missing file specification for '/out:' option", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [Fact] public void EmittedSubsystemVersion() { var compilation = CSharpCompilation.Create("a.dll", references: new[] { MscorlibRef }, options: TestOptions.ReleaseDll); var peHeaders = new PEHeaders(compilation.EmitToStream(options: new EmitOptions(subsystemVersion: SubsystemVersion.Create(5, 1)))); Assert.Equal(5, peHeaders.PEHeader.MajorSubsystemVersion); Assert.Equal(1, peHeaders.PEHeader.MinorSubsystemVersion); } [Fact] public void CreateCompilationWithKeyFile() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "a.cs", "/keyfile:key.snk", }); var comp = cmd.CreateCompilation(TextWriter.Null, new TouchedFileLogger(), NullErrorLogger.Instance); Assert.IsType<DesktopStrongNameProvider>(comp.Options.StrongNameProvider); } [Fact] public void CreateCompilationWithKeyContainer() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "a.cs", "/keycontainer:bbb", }); var comp = cmd.CreateCompilation(TextWriter.Null, new TouchedFileLogger(), NullErrorLogger.Instance); Assert.Equal(typeof(DesktopStrongNameProvider), comp.Options.StrongNameProvider.GetType()); } [Fact] public void CreateCompilationFallbackCommand() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "a.cs", "/keyFile:key.snk", "/features:UseLegacyStrongNameProvider" }); var comp = cmd.CreateCompilation(TextWriter.Null, new TouchedFileLogger(), NullErrorLogger.Instance); Assert.Equal(typeof(DesktopStrongNameProvider), comp.Options.StrongNameProvider.GetType()); } [Fact] public void CreateCompilation_MainAndTargetIncompatibilities() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var compilation = CSharpCompilation.Create("a.dll", options: TestOptions.ReleaseDll); var options = compilation.Options; Assert.Equal(0, options.Errors.Length); options = options.WithMainTypeName("a"); options.Errors.Verify( // error CS2017: Cannot specify /main if building a module or library Diagnostic(ErrorCode.ERR_NoMainOnDLL) ); var comp = CSharpCompilation.Create("a.dll", options: options); comp.GetDiagnostics().Verify( // error CS2017: Cannot specify /main if building a module or library Diagnostic(ErrorCode.ERR_NoMainOnDLL) ); options = options.WithOutputKind(OutputKind.WindowsApplication); options.Errors.Verify(); comp = CSharpCompilation.Create("a.dll", options: options); comp.GetDiagnostics().Verify( // error CS1555: Could not find 'a' specified for Main method Diagnostic(ErrorCode.ERR_MainClassNotFound).WithArguments("a") ); options = options.WithOutputKind(OutputKind.NetModule); options.Errors.Verify( // error CS2017: Cannot specify /main if building a module or library Diagnostic(ErrorCode.ERR_NoMainOnDLL) ); comp = CSharpCompilation.Create("a.dll", options: options); comp.GetDiagnostics().Verify( // error CS2017: Cannot specify /main if building a module or library Diagnostic(ErrorCode.ERR_NoMainOnDLL) ); options = options.WithMainTypeName(null); options.Errors.Verify(); comp = CSharpCompilation.Create("a.dll", options: options); comp.GetDiagnostics().Verify(); CleanupAllGeneratedFiles(file.Path); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30328")] public void SpecifyProperCodePage() { byte[] source = { 0x63, // c 0x6c, // l 0x61, // a 0x73, // s 0x73, // s 0x20, // 0xd0, 0x96, // Utf-8 Cyrillic character 0x7b, // { 0x7d, // } }; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllBytes(source); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/nologo /t:library \"{file}\"", startFolder: dir.Path); Assert.Equal("", output); // Autodetected UTF8, NO ERROR output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/nologo /preferreduilang:en /t:library /codepage:20127 \"{file}\"", expectedRetCode: 1, startFolder: dir.Path); // 20127: US-ASCII // 0xd0, 0x96 ==> ERROR Assert.Equal(@" a.cs(1,7): error CS1001: Identifier expected a.cs(1,7): error CS1514: { expected a.cs(1,7): error CS1513: } expected a.cs(1,7): error CS8803: Top-level statements must precede namespace and type declarations. a.cs(1,7): error CS1525: Invalid expression term '??' a.cs(1,9): error CS1525: Invalid expression term '{' a.cs(1,9): error CS1002: ; expected ".Trim(), Regex.Replace(output, "^.*a.cs", "a.cs", RegexOptions.Multiline).Trim()); CleanupAllGeneratedFiles(file.Path); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultWin32ResForExe() { var source = @" class C { static void Main() { } } "; CheckManifestString(source, OutputKind.ConsoleApplication, explicitManifest: null, expectedManifest: @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""490""> <Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource>"); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultManifestForDll() { var source = @" class C { } "; CheckManifestString(source, OutputKind.DynamicallyLinkedLibrary, explicitManifest: null, expectedManifest: null); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultManifestForWinExe() { var source = @" class C { static void Main() { } } "; CheckManifestString(source, OutputKind.WindowsApplication, explicitManifest: null, expectedManifest: @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""490""> <Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource>"); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultManifestForAppContainerExe() { var source = @" class C { static void Main() { } } "; CheckManifestString(source, OutputKind.WindowsRuntimeApplication, explicitManifest: null, expectedManifest: @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""490""> <Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource>"); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultManifestForWinMD() { var source = @" class C { } "; CheckManifestString(source, OutputKind.WindowsRuntimeMetadata, explicitManifest: null, expectedManifest: null); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultWin32ResForModule() { var source = @" class C { } "; CheckManifestString(source, OutputKind.NetModule, explicitManifest: null, expectedManifest: null); } [ConditionalFact(typeof(WindowsOnly))] public void ExplicitWin32ResForExe() { var source = @" class C { static void Main() { } } "; var explicitManifest = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""Test.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>"; var explicitManifestStream = new MemoryStream(Encoding.UTF8.GetBytes(explicitManifest)); var expectedManifest = @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""476""> <Contents><![CDATA[" + explicitManifest + @"]]></Contents> </ManifestResource>"; CheckManifestString(source, OutputKind.ConsoleApplication, explicitManifest, expectedManifest); } // DLLs don't get the default manifest, but they do respect explicitly set manifests. [ConditionalFact(typeof(WindowsOnly))] public void ExplicitWin32ResForDll() { var source = @" class C { static void Main() { } } "; var explicitManifest = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""Test.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>"; var expectedManifest = @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""476""> <Contents><![CDATA[" + explicitManifest + @"]]></Contents> </ManifestResource>"; CheckManifestString(source, OutputKind.DynamicallyLinkedLibrary, explicitManifest, expectedManifest); } // Modules don't have manifests, even if one is explicitly specified. [ConditionalFact(typeof(WindowsOnly))] public void ExplicitWin32ResForModule() { var source = @" class C { } "; var explicitManifest = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""Test.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>"; CheckManifestString(source, OutputKind.NetModule, explicitManifest, expectedManifest: null); } [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr LoadLibraryEx(string lpFileName, IntPtr hFile, uint dwFlags); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool FreeLibrary([In] IntPtr hFile); private void CheckManifestString(string source, OutputKind outputKind, string explicitManifest, string expectedManifest) { var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("Test.cs").WriteAllText(source); string outputFileName; string target; switch (outputKind) { case OutputKind.ConsoleApplication: outputFileName = "Test.exe"; target = "exe"; break; case OutputKind.WindowsApplication: outputFileName = "Test.exe"; target = "winexe"; break; case OutputKind.DynamicallyLinkedLibrary: outputFileName = "Test.dll"; target = "library"; break; case OutputKind.NetModule: outputFileName = "Test.netmodule"; target = "module"; break; case OutputKind.WindowsRuntimeMetadata: outputFileName = "Test.winmdobj"; target = "winmdobj"; break; case OutputKind.WindowsRuntimeApplication: outputFileName = "Test.exe"; target = "appcontainerexe"; break; default: throw TestExceptionUtilities.UnexpectedValue(outputKind); } MockCSharpCompiler csc; if (explicitManifest == null) { csc = CreateCSharpCompiler(null, dir.Path, new[] { string.Format("/target:{0}", target), string.Format("/out:{0}", outputFileName), Path.GetFileName(sourceFile.Path), }); } else { var manifestFile = dir.CreateFile("Test.config").WriteAllText(explicitManifest); csc = CreateCSharpCompiler(null, dir.Path, new[] { string.Format("/target:{0}", target), string.Format("/out:{0}", outputFileName), string.Format("/win32manifest:{0}", Path.GetFileName(manifestFile.Path)), Path.GetFileName(sourceFile.Path), }); } int actualExitCode = csc.Run(new StringWriter(CultureInfo.InvariantCulture)); Assert.Equal(0, actualExitCode); //Open as data IntPtr lib = LoadLibraryEx(Path.Combine(dir.Path, outputFileName), IntPtr.Zero, 0x00000002); if (lib == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error()); const string resourceType = "#24"; var resourceId = outputKind == OutputKind.DynamicallyLinkedLibrary ? "#2" : "#1"; uint manifestSize; if (expectedManifest == null) { Assert.Throws<Win32Exception>(() => Win32Res.GetResource(lib, resourceId, resourceType, out manifestSize)); } else { IntPtr manifestResourcePointer = Win32Res.GetResource(lib, resourceId, resourceType, out manifestSize); string actualManifest = Win32Res.ManifestResourceToXml(manifestResourcePointer, manifestSize); Assert.Equal(expectedManifest, actualManifest); } FreeLibrary(lib); } [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")] [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ResponseFilesWithNoconfig_01() { string source = Temp.CreateFile("a.cs").WriteAllText(@" public class C { public static void Main() { int x; // CS0168 } }").Path; string rsp = Temp.CreateFile().WriteAllText(@" /warnaserror ").Path; // Checks the base case without /noconfig (expect to see error) var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /noconfig (expect to see warning, instead of error) outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/noconfig", "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /NOCONFIG (expect to see warning, instead of error) outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/NOCONFIG", "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with -noconfig (expect to see warning, instead of error) outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "-noconfig", "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")] [ConditionalFact(typeof(WindowsOnly))] public void ResponseFilesWithNoconfig_02() { string source = Temp.CreateFile("a.cs").WriteAllText(@" public class C { public static void Main() { } }").Path; string rsp = Temp.CreateFile().WriteAllText(@" /noconfig ").Path; // Checks the case with /noconfig inside the response file (expect to see warning) var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /noconfig inside the response file as along with /nowarn (expect to see warning) // to verify that this warning is not suppressed by the /nowarn option (See MSDN). outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en", "/nowarn:2023" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")] [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ResponseFilesWithNoconfig_03() { string source = Temp.CreateFile("a.cs").WriteAllText(@" public class C { public static void Main() { } }").Path; string rsp = Temp.CreateFile().WriteAllText(@" /NOCONFIG ").Path; // Checks the case with /noconfig inside the response file (expect to see warning) var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /NOCONFIG inside the response file as along with /nowarn (expect to see warning) // to verify that this warning is not suppressed by the /nowarn option (See MSDN). outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en", "/nowarn:2023" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")] [ConditionalFact(typeof(WindowsOnly))] public void ResponseFilesWithNoconfig_04() { string source = Temp.CreateFile("a.cs").WriteAllText(@" public class C { public static void Main() { } }").Path; string rsp = Temp.CreateFile().WriteAllText(@" -noconfig ").Path; // Checks the case with /noconfig inside the response file (expect to see warning) var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with -noconfig inside the response file as along with /nowarn (expect to see warning) // to verify that this warning is not suppressed by the /nowarn option (See MSDN). outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en", "/nowarn:2023" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [Fact, WorkItem(530024, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530024")] public void NoStdLib() { var src = Temp.CreateFile("a.cs"); src.WriteAllText("public class C{}"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/t:library", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/nostdlib", "/t:library", src.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("{FILE}(1,14): error CS0518: Predefined type 'System.Object' is not defined or imported", outWriter.ToString().Replace(Path.GetFileName(src.Path), "{FILE}").Trim()); // Bug#15021: breaking change - empty source no error with /nostdlib src.WriteAllText("namespace System { }"); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nostdlib", "/t:library", "/runtimemetadataversion:v4.0.30319", "/langversion:8", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(src.Path); } private string GetDefaultResponseFilePath() { var cscRsp = global::TestResources.ResourceLoader.GetResourceBlob("csc.rsp"); return Temp.CreateFile().WriteAllBytes(cscRsp).Path; } [Fact, WorkItem(530359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530359")] public void NoStdLib02() { #region "source" var source = @" // <Title>A collection initializer can be declared with a user-defined IEnumerable that is declared in a user-defined System.Collections</Title> using System.Collections; class O<T> where T : new() { public T list = new T(); } class C { static StructCollection sc = new StructCollection { 1 }; public static int Main() { ClassCollection cc = new ClassCollection { 2 }; var o1 = new O<ClassCollection> { list = { 5 } }; var o2 = new O<StructCollection> { list = sc }; return 0; } } struct StructCollection : IEnumerable { public int added; #region IEnumerable Members public void Add(int t) { added = t; } #endregion } class ClassCollection : IEnumerable { public int added; #region IEnumerable Members public void Add(int t) { added = t; } #endregion } namespace System.Collections { public interface IEnumerable { void Add(int t); } } "; #endregion #region "mslib" var mslib = @" 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 Exception(string s){} } 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 { } public class Activator { public static T CreateInstance<T>(){return default(T);} } namespace Collections { public interface IEnumerator { } } namespace Runtime { namespace InteropServices { public class OutAttribute { } } namespace CompilerServices { public class RuntimeHelpers { } } } namespace Reflection { public class DefaultMemberAttribute { } } } "; #endregion var src = Temp.CreateFile("NoStdLib02.cs"); src.WriteAllText(source + mslib); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/noconfig", "/nostdlib", "/runtimemetadataversion:v4.0.30319", "/nowarn:8625", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nostdlib", "/runtimemetadataversion:v4.0.30319", "/nowarn:8625", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); string OriginalSource = src.Path; src = Temp.CreateFile("NoStdLib02b.cs"); src.WriteAllText(mslib); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(GetDefaultResponseFilePath(), WorkingDirectory, new[] { "/nologo", "/noconfig", "/nostdlib", "/t:library", "/runtimemetadataversion:v4.0.30319", "/nowarn:8625", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(OriginalSource); CleanupAllGeneratedFiles(src.Path); } [Fact, WorkItem(546018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546018"), WorkItem(546020, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546020"), WorkItem(546024, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546024"), WorkItem(546049, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546049")] public void InvalidDefineSwitch() { var src = Temp.CreateFile("a.cs"); src.WriteAllText("public class C{}"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", src.ToString(), "/define" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2006: Command-line syntax error: Missing '<text>' for '/define' option", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), @"/define:""""" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define: " }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2006: Command-line syntax error: Missing '<text>' for '/define:' option", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2006: Command-line syntax error: Missing '<text>' for '/define:' option", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:,,," }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:,blah,Blah" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:a;;b@" }).Run(outWriter); Assert.Equal(0, exitCode); var errorLines = outWriter.ToString().Trim().Split(new string[] { Environment.NewLine }, StringSplitOptions.None); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", errorLines[0]); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; 'b@' is not a valid identifier", errorLines[1]); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:a,b@;" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; 'b@' is not a valid identifier", outWriter.ToString().Trim()); //Bug 531612 - Native would normally not give the 2nd warning outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), @"/define:OE_WIN32=-1:LANG_HOST_EN=-1:LANG_OE_EN=-1:LANG_PRJ_EN=-1:HOST_COM20SDKEVERETT=-1:EXEMODE=-1:OE_NT5=-1:Win32=-1", @"/d:TRACE=TRUE,DEBUG=TRUE" }).Run(outWriter); Assert.Equal(0, exitCode); errorLines = outWriter.ToString().Trim().Split(new string[] { Environment.NewLine }, StringSplitOptions.None); Assert.Equal(@"warning CS2029: Invalid name for a preprocessing symbol; 'OE_WIN32=-1:LANG_HOST_EN=-1:LANG_OE_EN=-1:LANG_PRJ_EN=-1:HOST_COM20SDKEVERETT=-1:EXEMODE=-1:OE_NT5=-1:Win32=-1' is not a valid identifier", errorLines[0]); Assert.Equal(@"warning CS2029: Invalid name for a preprocessing symbol; 'TRACE=TRUE' is not a valid identifier", errorLines[1]); CleanupAllGeneratedFiles(src.Path); } [WorkItem(733242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/733242")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void Bug733242() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText( @" /// <summary>ABC...XYZ</summary> class C {} "); var xml = dir.CreateFile("a.xml"); xml.WriteAllText("EMPTY"); using (var xmlFileHandle = File.Open(xml.ToString(), FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite)) { var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /t:library /doc:\"{1}\" \"{0}\"", src.ToString(), xml.ToString()), startFolder: dir.ToString()); Assert.Equal("", output.Trim()); Assert.True(File.Exists(Path.Combine(dir.ToString(), "a.xml"))); using (var reader = new StreamReader(xmlFileHandle)) { var content = reader.ReadToEnd(); Assert.Equal( @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""T:C""> <summary>ABC...XYZ</summary> </member> </members> </doc>".Trim(), content.Trim()); } } CleanupAllGeneratedFiles(src.Path); CleanupAllGeneratedFiles(xml.Path); } [WorkItem(768605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768605")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void Bug768605() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText( @" /// <summary>ABC</summary> class C {} /// <summary>XYZ</summary> class E {} "); var xml = dir.CreateFile("a.xml"); xml.WriteAllText("EMPTY"); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /t:library /doc:\"{1}\" \"{0}\"", src.ToString(), xml.ToString()), startFolder: dir.ToString()); Assert.Equal("", output.Trim()); using (var reader = new StreamReader(xml.ToString())) { var content = reader.ReadToEnd(); Assert.Equal( @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""T:C""> <summary>ABC</summary> </member> <member name=""T:E""> <summary>XYZ</summary> </member> </members> </doc>".Trim(), content.Trim()); } src.WriteAllText( @" /// <summary>ABC</summary> class C {} "); output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /t:library /doc:\"{1}\" \"{0}\"", src.ToString(), xml.ToString()), startFolder: dir.ToString()); Assert.Equal("", output.Trim()); using (var reader = new StreamReader(xml.ToString())) { var content = reader.ReadToEnd(); Assert.Equal( @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""T:C""> <summary>ABC</summary> </member> </members> </doc>".Trim(), content.Trim()); } CleanupAllGeneratedFiles(src.Path); CleanupAllGeneratedFiles(xml.Path); } [Fact] public void ParseFullpaths() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.PrintFullPaths); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths" }, WorkingDirectory); Assert.True(parsedArgs.PrintFullPaths); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths:" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths: " }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths+" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths+:" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code); } [Fact] public void CheckFullpaths() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" public class C { public static void Main() { string x; } }").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); // Checks the base case without /fullpaths (expect to see relative path name) // c:\temp> csc.exe c:\temp\a.cs // a.cs(6,16): warning CS0168: The variable 'x' is declared but never used var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, baseDir, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(fileName + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); // Checks the base case without /fullpaths when the file is located in the sub-folder (expect to see relative path name) // c:\temp> csc.exe c:\temp\example\a.cs // example\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, Directory.GetParent(baseDir).FullName, new[] { source, "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(fileName + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); Assert.DoesNotContain(source, outWriter.ToString(), StringComparison.Ordinal); // Checks the base case without /fullpaths when the file is not located under the base directory (expect to see the full path name) // c:\temp> csc.exe c:\test\a.cs // c:\test\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, Temp.CreateDirectory().Path, new[] { source, "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(source + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /fullpaths (expect to see the full paths) // c:\temp> csc.exe c:\temp\a.cs /fullpaths // c:\temp\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, baseDir, new[] { source, "/fullpaths", "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(source + @"(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); // Checks the base case without /fullpaths when the file is located in the sub-folder (expect to see the full path name) // c:\temp> csc.exe c:\temp\example\a.cs /fullpaths // c:\temp\example\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, Directory.GetParent(baseDir).FullName, new[] { source, "/preferreduilang:en", "/fullpaths" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(source + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); // Checks the base case without /fullpaths when the file is not located under the base directory (expect to see the full path name) // c:\temp> csc.exe c:\test\a.cs /fullpaths // c:\test\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, Temp.CreateDirectory().Path, new[] { source, "/preferreduilang:en", "/fullpaths" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(source + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(source)), Path.GetFileName(source))); } [Fact] public void DefaultResponseFile() { var sdkDirectory = SdkDirectory; MockCSharpCompiler csc = new MockCSharpCompiler( GetDefaultResponseFilePath(), RuntimeUtilities.CreateBuildPaths(WorkingDirectory, sdkDirectory), new string[0]); AssertEx.Equal(csc.Arguments.MetadataReferences.Select(r => r.Reference), new string[] { MscorlibFullPath, "Accessibility.dll", "Microsoft.CSharp.dll", "System.Configuration.dll", "System.Configuration.Install.dll", "System.Core.dll", "System.Data.dll", "System.Data.DataSetExtensions.dll", "System.Data.Linq.dll", "System.Data.OracleClient.dll", "System.Deployment.dll", "System.Design.dll", "System.DirectoryServices.dll", "System.dll", "System.Drawing.Design.dll", "System.Drawing.dll", "System.EnterpriseServices.dll", "System.Management.dll", "System.Messaging.dll", "System.Runtime.Remoting.dll", "System.Runtime.Serialization.dll", "System.Runtime.Serialization.Formatters.Soap.dll", "System.Security.dll", "System.ServiceModel.dll", "System.ServiceModel.Web.dll", "System.ServiceProcess.dll", "System.Transactions.dll", "System.Web.dll", "System.Web.Extensions.Design.dll", "System.Web.Extensions.dll", "System.Web.Mobile.dll", "System.Web.RegularExpressions.dll", "System.Web.Services.dll", "System.Windows.Forms.dll", "System.Workflow.Activities.dll", "System.Workflow.ComponentModel.dll", "System.Workflow.Runtime.dll", "System.Xml.dll", "System.Xml.Linq.dll", }, StringComparer.OrdinalIgnoreCase); } [Fact] public void DefaultResponseFileNoConfig() { MockCSharpCompiler csc = CreateCSharpCompiler(GetDefaultResponseFilePath(), WorkingDirectory, new[] { "/noconfig" }); Assert.Equal(csc.Arguments.MetadataReferences.Select(r => r.Reference), new string[] { MscorlibFullPath, }, StringComparer.OrdinalIgnoreCase); } [Fact, WorkItem(545954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545954")] public void TestFilterParseDiagnostics() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" #pragma warning disable 440 using global = A; // CS0440 class A { static void Main() { #pragma warning suppress 440 } }").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal(Path.GetFileName(source) + "(7,17): warning CS1634: Expected 'disable' or 'restore'", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/nowarn:1634", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", Path.Combine(baseDir, "nonexistent.cs"), source.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2001: Source file '" + Path.Combine(baseDir, "nonexistent.cs") + "' could not be found.", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(546058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546058")] public void TestNoWarnParseDiagnostics() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" class Test { static void Main() { //Generates warning CS1522: Empty switch block switch (1) { } //Generates warning CS0642: Possible mistaken empty statement while (false) ; { } } } ").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nowarn:1522,642", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(41610, "https://github.com/dotnet/roslyn/issues/41610")] public void TestWarnAsError_CS8632() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" public class C { public string? field; public static void Main() { } } ").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/warn:3", "/warnaserror:nullable", source.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal( $@"{fileName}(4,18): error CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(546076, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546076")] public void TestWarnAsError_CS1522() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" public class Test { // CS0169 (level 3) private int x; // CS0109 (level 4) public new void Method() { } public static int Main() { int i = 5; // CS1522 (level 1) switch (i) { } return 0; // CS0162 (level 2) i = 6; } } ").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/warn:3", "/warnaserror", source.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal( $@"{fileName}(12,20): error CS1522: Empty switch block {fileName}(15,9): error CS0162: Unreachable code detected {fileName}(5,17): error CS0169: The field 'Test.x' is never used", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [Fact(), WorkItem(546025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546025")] public void TestWin32ResWithBadResFile_CS1583ERR_BadWin32Res_01() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class Test { static void Main() {} }").Path; string badres = Temp.CreateFile().WriteAllBytes(TestResources.DiagnosticTests.badresfile).Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/win32res:" + badres, source }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS1583: Error reading Win32 resources -- Image is too small.", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(badres); } [Fact(), WorkItem(217718, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=217718")] public void TestWin32ResWithBadResFile_CS1583ERR_BadWin32Res_02() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class Test { static void Main() {} }").Path; string badres = Temp.CreateFile().WriteAllBytes(new byte[] { 0, 0 }).Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/win32res:" + badres, source }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS1583: Error reading Win32 resources -- Unrecognized resource file format.", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(badres); } [Fact, WorkItem(546114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546114")] public void TestFilterCommandLineDiagnostics() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" class A { static void Main() { } }").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/target:library", "/out:goo.dll", "/nowarn:2008" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); System.IO.File.Delete(System.IO.Path.Combine(baseDir, "goo.dll")); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(546452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546452")] public void CS1691WRN_BadWarningNumber_Bug15905() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" class Program { #pragma warning disable 1998 public static void Main() { } #pragma warning restore 1998 } ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // Repro case 1 int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/warnaserror", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); // Repro case 2 exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nowarn:1998", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void ExistingPdb() { var dir = Temp.CreateDirectory(); var source1 = dir.CreateFile("program1.cs").WriteAllText(@" class " + new string('a', 10000) + @" { public static void Main() { } }"); var source2 = dir.CreateFile("program2.cs").WriteAllText(@" class Program2 { public static void Main() { } }"); var source3 = dir.CreateFile("program3.cs").WriteAllText(@" class Program3 { public static void Main() { } }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int oldSize = 16 * 1024; var exe = dir.CreateFile("Program.exe"); using (var stream = File.OpenWrite(exe.Path)) { byte[] buffer = new byte[oldSize]; stream.Write(buffer, 0, buffer.Length); } var pdb = dir.CreateFile("Program.pdb"); using (var stream = File.OpenWrite(pdb.Path)) { byte[] buffer = new byte[oldSize]; stream.Write(buffer, 0, buffer.Length); } int exitCode1 = CreateCSharpCompiler(null, dir.Path, new[] { "/debug:full", "/out:Program.exe", source1.Path }).Run(outWriter); Assert.NotEqual(0, exitCode1); ValidateZeroes(exe.Path, oldSize); ValidateZeroes(pdb.Path, oldSize); int exitCode2 = CreateCSharpCompiler(null, dir.Path, new[] { "/debug:full", "/out:Program.exe", source2.Path }).Run(outWriter); Assert.Equal(0, exitCode2); using (var peFile = File.OpenRead(exe.Path)) { PdbValidation.ValidateDebugDirectory(peFile, null, pdb.Path, hashAlgorithm: default, hasEmbeddedPdb: false, isDeterministic: false); } Assert.True(new FileInfo(exe.Path).Length < oldSize); Assert.True(new FileInfo(pdb.Path).Length < oldSize); int exitCode3 = CreateCSharpCompiler(null, dir.Path, new[] { "/debug:full", "/out:Program.exe", source3.Path }).Run(outWriter); Assert.Equal(0, exitCode3); using (var peFile = File.OpenRead(exe.Path)) { PdbValidation.ValidateDebugDirectory(peFile, null, pdb.Path, hashAlgorithm: default, hasEmbeddedPdb: false, isDeterministic: false); } } private static void ValidateZeroes(string path, int count) { using (var stream = File.OpenRead(path)) { byte[] buffer = new byte[count]; stream.Read(buffer, 0, buffer.Length); for (int i = 0; i < buffer.Length; i++) { if (buffer[i] != 0) { Assert.True(false); } } } } /// <summary> /// When the output file is open with <see cref="FileShare.Read"/> | <see cref="FileShare.Delete"/> /// the compiler should delete the file to unblock build while allowing the reader to continue /// reading the previous snapshot of the file content. /// /// On Windows we can read the original data directly from the stream without creating a memory map. /// </summary> [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void FileShareDeleteCompatibility_Windows() { var dir = Temp.CreateDirectory(); var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }"); var libDll = dir.CreateFile("Lib.dll").WriteAllText("DLL"); var libPdb = dir.CreateFile("Lib.pdb").WriteAllText("PDB"); var fsDll = new FileStream(libDll.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var fsPdb = new FileStream(libPdb.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/debug:full", libSrc.Path }).Run(outWriter); if (exitCode != 0) { AssertEx.AssertEqualToleratingWhitespaceDifferences("", outWriter.ToString()); } Assert.Equal(0, exitCode); AssertEx.Equal(new byte[] { 0x4D, 0x5A }, ReadBytes(libDll.Path, 2)); AssertEx.Equal(new[] { (byte)'D', (byte)'L', (byte)'L' }, ReadBytes(fsDll, 3)); AssertEx.Equal(new byte[] { 0x4D, 0x69 }, ReadBytes(libPdb.Path, 2)); AssertEx.Equal(new[] { (byte)'P', (byte)'D', (byte)'B' }, ReadBytes(fsPdb, 3)); fsDll.Dispose(); fsPdb.Dispose(); AssertEx.Equal(new[] { "Lib.cs", "Lib.dll", "Lib.pdb" }, Directory.GetFiles(dir.Path).Select(p => Path.GetFileName(p)).Order()); } /// <summary> /// On Linux/Mac <see cref="FileShare.Delete"/> on its own doesn't do anything. /// We need to create the actual memory map. This works on Windows as well. /// </summary> [WorkItem(8896, "https://github.com/dotnet/roslyn/issues/8896")] [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void FileShareDeleteCompatibility_Xplat() { var bytes = TestResources.MetadataTests.InterfaceAndClass.CSClasses01; var mvid = ReadMvid(new MemoryStream(bytes)); var dir = Temp.CreateDirectory(); var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }"); var libDll = dir.CreateFile("Lib.dll").WriteAllBytes(bytes); var libPdb = dir.CreateFile("Lib.pdb").WriteAllBytes(bytes); var fsDll = new FileStream(libDll.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var fsPdb = new FileStream(libPdb.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var peDll = new PEReader(fsDll); var pePdb = new PEReader(fsPdb); // creates memory map view: var imageDll = peDll.GetEntireImage(); var imagePdb = pePdb.GetEntireImage(); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/target:library /debug:portable \"{libSrc.Path}\"", startFolder: dir.ToString()); AssertEx.AssertEqualToleratingWhitespaceDifferences($@" Microsoft (R) Visual C# Compiler version {s_compilerVersion} Copyright (C) Microsoft Corporation. All rights reserved.", output); // reading original content from the memory map: Assert.Equal(mvid, ReadMvid(new MemoryStream(imageDll.GetContent().ToArray()))); Assert.Equal(mvid, ReadMvid(new MemoryStream(imagePdb.GetContent().ToArray()))); // reading original content directly from the streams: fsDll.Position = 0; fsPdb.Position = 0; Assert.Equal(mvid, ReadMvid(fsDll)); Assert.Equal(mvid, ReadMvid(fsPdb)); // reading new content from the file: using (var fsNewDll = File.OpenRead(libDll.Path)) { Assert.NotEqual(mvid, ReadMvid(fsNewDll)); } // Portable PDB metadata signature: AssertEx.Equal(new[] { (byte)'B', (byte)'S', (byte)'J', (byte)'B' }, ReadBytes(libPdb.Path, 4)); // dispose PEReaders (they dispose the underlying file streams) peDll.Dispose(); pePdb.Dispose(); AssertEx.Equal(new[] { "Lib.cs", "Lib.dll", "Lib.pdb" }, Directory.GetFiles(dir.Path).Select(p => Path.GetFileName(p)).Order()); // files can be deleted now: File.Delete(libSrc.Path); File.Delete(libDll.Path); File.Delete(libPdb.Path); // directory can be deleted (should be empty): Directory.Delete(dir.Path, recursive: false); } private static Guid ReadMvid(Stream stream) { using (var peReader = new PEReader(stream, PEStreamOptions.LeaveOpen)) { var mdReader = peReader.GetMetadataReader(); return mdReader.GetGuid(mdReader.GetModuleDefinition().Mvid); } } // Seems like File.SetAttributes(libDll.Path, FileAttributes.ReadOnly) doesn't restrict access to the file on Mac (Linux passes). [ConditionalFact(typeof(WindowsOnly)), WorkItem(8939, "https://github.com/dotnet/roslyn/issues/8939")] public void FileShareDeleteCompatibility_ReadOnlyFiles() { var dir = Temp.CreateDirectory(); var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }"); var libDll = dir.CreateFile("Lib.dll").WriteAllText("DLL"); File.SetAttributes(libDll.Path, FileAttributes.ReadOnly); var fsDll = new FileStream(libDll.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/preferreduilang:en", libSrc.Path }).Run(outWriter); Assert.Contains($"error CS2012: Cannot open '{libDll.Path}' for writing", outWriter.ToString()); AssertEx.Equal(new[] { (byte)'D', (byte)'L', (byte)'L' }, ReadBytes(libDll.Path, 3)); AssertEx.Equal(new[] { (byte)'D', (byte)'L', (byte)'L' }, ReadBytes(fsDll, 3)); fsDll.Dispose(); AssertEx.Equal(new[] { "Lib.cs", "Lib.dll" }, Directory.GetFiles(dir.Path).Select(p => Path.GetFileName(p)).Order()); } [Fact] public void FileShareDeleteCompatibility_ExistingDirectory() { var dir = Temp.CreateDirectory(); var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }"); var libDll = dir.CreateDirectory("Lib.dll"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/preferreduilang:en", libSrc.Path }).Run(outWriter); Assert.Contains($"error CS2012: Cannot open '{libDll.Path}' for writing", outWriter.ToString()); } private byte[] ReadBytes(Stream stream, int count) { var buffer = new byte[count]; stream.Read(buffer, 0, count); return buffer; } private byte[] ReadBytes(string path, int count) { using (var stream = File.OpenRead(path)) { return ReadBytes(stream, count); } } [Fact] public void IOFailure_DisposeOutputFile() { var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path); var exePath = Path.Combine(Path.GetDirectoryName(srcPath), "test.exe"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", $"/out:{exePath}", srcPath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == exePath) { return new TestStream(backingStream: new MemoryStream(), dispose: () => { throw new IOException("Fake IOException"); }); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Contains($"error CS0016: Could not write to output file '{exePath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString()); } [Fact] public void IOFailure_DisposePdbFile() { var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path); var exePath = Path.Combine(Path.GetDirectoryName(srcPath), "test.exe"); var pdbPath = Path.ChangeExtension(exePath, "pdb"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/debug", $"/out:{exePath}", srcPath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == pdbPath) { return new TestStream(backingStream: new MemoryStream(), dispose: () => { throw new IOException("Fake IOException"); }); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Contains($"error CS0016: Could not write to output file '{pdbPath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString()); } [Fact] public void IOFailure_DisposeXmlFile() { var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path); var xmlPath = Path.Combine(Path.GetDirectoryName(srcPath), "test.xml"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", $"/doc:{xmlPath}", srcPath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == xmlPath) { return new TestStream(backingStream: new MemoryStream(), dispose: () => { throw new IOException("Fake IOException"); }); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Equal($"error CS0016: Could not write to output file '{xmlPath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString()); } [Theory] [InlineData("portable")] [InlineData("full")] public void IOFailure_DisposeSourceLinkFile(string format) { var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path); var sourceLinkPath = Path.Combine(Path.GetDirectoryName(srcPath), "test.json"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/debug:" + format, $"/sourcelink:{sourceLinkPath}", srcPath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == sourceLinkPath) { return new TestStream(backingStream: new MemoryStream(Encoding.UTF8.GetBytes(@" { ""documents"": { ""f:/build/*"" : ""https://raw.githubusercontent.com/my-org/my-project/1111111111111111111111111111111111111111/*"" } } ")), dispose: () => { throw new IOException("Fake IOException"); }); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Equal($"error CS0016: Could not write to output file '{sourceLinkPath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString()); } [Fact] public void IOFailure_OpenOutputFile() { string sourcePath = MakeTrivialExe(); string exePath = Path.Combine(Path.GetDirectoryName(sourcePath), "test.exe"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", $"/out:{exePath}", sourcePath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == exePath) { throw new IOException(); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Contains($"error CS2012: Cannot open '{exePath}' for writing", outWriter.ToString()); System.IO.File.Delete(sourcePath); System.IO.File.Delete(exePath); CleanupAllGeneratedFiles(sourcePath); } [Fact] public void IOFailure_OpenPdbFileNotCalled() { string sourcePath = MakeTrivialExe(); string exePath = Path.Combine(Path.GetDirectoryName(sourcePath), "test.exe"); string pdbPath = Path.ChangeExtension(exePath, ".pdb"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/debug-", $"/out:{exePath}", sourcePath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == pdbPath) { throw new IOException(); } return File.Open(file, (FileMode)mode, (FileAccess)access, (FileShare)share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(0, csc.Run(outWriter)); System.IO.File.Delete(sourcePath); System.IO.File.Delete(exePath); System.IO.File.Delete(pdbPath); CleanupAllGeneratedFiles(sourcePath); } [Fact] public void IOFailure_OpenXmlFinal() { string sourcePath = MakeTrivialExe(); string xmlPath = Path.Combine(WorkingDirectory, "Test.xml"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/doc:" + xmlPath, sourcePath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == xmlPath) { throw new IOException(); } else { return File.Open(file, (FileMode)mode, (FileAccess)access, (FileShare)share); } }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = csc.Run(outWriter); var expectedOutput = string.Format("error CS0016: Could not write to output file '{0}' -- 'I/O error occurred.'", xmlPath); Assert.Equal(expectedOutput, outWriter.ToString().Trim()); Assert.NotEqual(0, exitCode); System.IO.File.Delete(xmlPath); System.IO.File.Delete(sourcePath); CleanupAllGeneratedFiles(sourcePath); } private string MakeTrivialExe(string directory = null) { return Temp.CreateFile(directory: directory, prefix: "", extension: ".cs").WriteAllText(@" class Program { public static void Main() { } } ").Path; } [Fact, WorkItem(546452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546452")] public void CS1691WRN_BadWarningNumber_AllErrorCodes() { const int jump = 200; for (int i = 0; i < 8000; i += (8000 / jump)) { int startErrorCode = (int)i * jump; int endErrorCode = startErrorCode + jump; string source = ComputeSourceText(startErrorCode, endErrorCode); // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied in a #pragma directive // (or via /nowarn /warnaserror flags on the command line). // Going forward, we won't generate any warning in such cases. This will make // maintenance of backwards compatibility easier (we no longer need to worry // about breaking existing projects / command lines if we deprecate / remove // an old warning code). Test(source, startErrorCode, endErrorCode); } } private static string ComputeSourceText(int startErrorCode, int endErrorCode) { string pragmaDisableWarnings = String.Empty; for (int errorCode = startErrorCode; errorCode < endErrorCode; errorCode++) { string pragmaDisableStr = @"#pragma warning disable " + errorCode.ToString() + @" "; pragmaDisableWarnings += pragmaDisableStr; } return pragmaDisableWarnings + @" public class C { public static void Main() { } }"; } private void Test(string source, int startErrorCode, int endErrorCode) { string sourcePath = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(source).Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", sourcePath }).Run(outWriter); Assert.Equal(0, exitCode); var cscOutput = outWriter.ToString().Trim(); for (int errorCode = startErrorCode; errorCode < endErrorCode; errorCode++) { Assert.True(cscOutput == string.Empty, "Failed at error code: " + errorCode); } CleanupAllGeneratedFiles(sourcePath); } [Fact] public void WriteXml() { var source = @" /// <summary> /// A subtype of <see cref=""object""/>. /// </summary> public class C { } "; var sourcePath = Temp.CreateFile(directory: WorkingDirectory, extension: ".cs").WriteAllText(source).Path; string xmlPath = Path.Combine(WorkingDirectory, "Test.xml"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/target:library", "/out:Test.dll", "/doc:" + xmlPath, sourcePath }); var writer = new StringWriter(CultureInfo.InvariantCulture); var exitCode = csc.Run(writer); if (exitCode != 0) { Console.WriteLine(writer.ToString()); Assert.Equal(0, exitCode); } var bytes = File.ReadAllBytes(xmlPath); var actual = new string(Encoding.UTF8.GetChars(bytes)); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> A subtype of <see cref=""T:System.Object""/>. </summary> </member> </members> </doc> "; Assert.Equal(expected.Trim(), actual.Trim()); System.IO.File.Delete(xmlPath); System.IO.File.Delete(sourcePath); CleanupAllGeneratedFiles(sourcePath); CleanupAllGeneratedFiles(xmlPath); } [WorkItem(546468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546468")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void CS2002WRN_FileAlreadyIncluded() { const string cs2002 = @"warning CS2002: Source file '{0}' specified multiple times"; TempDirectory tempParentDir = Temp.CreateDirectory(); TempDirectory tempDir = tempParentDir.CreateDirectory("tmpDir"); TempFile tempFile = tempDir.CreateFile("a.cs").WriteAllText(@"public class A { }"); // Simple case var commandLineArgs = new[] { "a.cs", "a.cs" }; // warning CS2002: Source file 'a.cs' specified multiple times string aWrnString = String.Format(cs2002, "a.cs"); TestCS2002(commandLineArgs, tempDir.Path, 0, aWrnString); // Multiple duplicates commandLineArgs = new[] { "a.cs", "a.cs", "a.cs" }; // warning CS2002: Source file 'a.cs' specified multiple times var warnings = new[] { aWrnString }; TestCS2002(commandLineArgs, tempDir.Path, 0, warnings); // Case-insensitive commandLineArgs = new[] { "a.cs", "A.cs" }; // warning CS2002: Source file 'A.cs' specified multiple times string AWrnString = String.Format(cs2002, "A.cs"); TestCS2002(commandLineArgs, tempDir.Path, 0, AWrnString); // Different extensions tempDir.CreateFile("a.csx"); commandLineArgs = new[] { "a.cs", "a.csx" }; // No errors or warnings TestCS2002(commandLineArgs, tempDir.Path, 0, String.Empty); // Absolute vs Relative commandLineArgs = new[] { @"tmpDir\a.cs", tempFile.Path }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times string tmpDiraString = String.Format(cs2002, @"tmpDir\a.cs"); TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); // Both relative commandLineArgs = new[] { @"tmpDir\..\tmpDir\a.cs", @"tmpDir\a.cs" }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); // With wild cards commandLineArgs = new[] { tempFile.Path, @"tmpDir\*.cs" }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); // "/recurse" scenarios commandLineArgs = new[] { @"/recurse:a.cs", @"tmpDir\a.cs" }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); commandLineArgs = new[] { @"/recurse:a.cs", @"/recurse:tmpDir\..\tmpDir\*.cs" }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); // Invalid file/path characters const string cs1504 = @"error CS1504: Source file '{0}' could not be opened -- {1}"; commandLineArgs = new[] { "/preferreduilang:en", tempFile.Path, "tmpDir\a.cs" }; // error CS1504: Source file '{0}' could not be opened: Illegal characters in path. var formattedcs1504Str = String.Format(cs1504, PathUtilities.CombineAbsoluteAndRelativePaths(tempParentDir.Path, "tmpDir\a.cs"), "Illegal characters in path."); TestCS2002(commandLineArgs, tempParentDir.Path, 1, formattedcs1504Str); commandLineArgs = new[] { tempFile.Path, @"tmpDi\r*a?.cs" }; var parseDiags = new[] { // error CS2021: File name 'tmpDi\r*a?.cs' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"tmpDi\r*a?.cs"), // error CS2001: Source file 'tmpDi\r*a?.cs' could not be found. Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments(@"tmpDi\r*a?.cs")}; TestCS2002(commandLineArgs, tempParentDir.Path, 1, (string[])null, parseDiags); char currentDrive = Directory.GetCurrentDirectory()[0]; commandLineArgs = new[] { tempFile.Path, currentDrive + @":a.cs" }; parseDiags = new[] { // error CS2021: File name 'e:a.cs' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + @":a.cs")}; TestCS2002(commandLineArgs, tempParentDir.Path, 1, (string[])null, parseDiags); commandLineArgs = new[] { "/preferreduilang:en", tempFile.Path, @":a.cs" }; // error CS1504: Source file '{0}' could not be opened: {1} var formattedcs1504 = String.Format(cs1504, PathUtilities.CombineAbsoluteAndRelativePaths(tempParentDir.Path, @":a.cs"), @"The given path's format is not supported."); TestCS2002(commandLineArgs, tempParentDir.Path, 1, formattedcs1504); CleanupAllGeneratedFiles(tempFile.Path); System.IO.Directory.Delete(tempParentDir.Path, true); } private void TestCS2002(string[] commandLineArgs, string baseDirectory, int expectedExitCode, string compileDiagnostic, params DiagnosticDescription[] parseDiagnostics) { TestCS2002(commandLineArgs, baseDirectory, expectedExitCode, new[] { compileDiagnostic }, parseDiagnostics); } private void TestCS2002(string[] commandLineArgs, string baseDirectory, int expectedExitCode, string[] compileDiagnostics, params DiagnosticDescription[] parseDiagnostics) { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var allCommandLineArgs = new[] { "/nologo", "/preferreduilang:en", "/t:library" }.Concat(commandLineArgs).ToArray(); // Verify command line parser diagnostics. DefaultParse(allCommandLineArgs, baseDirectory).Errors.Verify(parseDiagnostics); // Verify compile. int exitCode = CreateCSharpCompiler(null, baseDirectory, allCommandLineArgs).Run(outWriter); Assert.Equal(expectedExitCode, exitCode); if (parseDiagnostics.IsEmpty()) { // Verify compile diagnostics. string outString = String.Empty; for (int i = 0; i < compileDiagnostics.Length; i++) { if (i != 0) { outString += @" "; } outString += compileDiagnostics[i]; } Assert.Equal(outString, outWriter.ToString().Trim()); } else { Assert.Null(compileDiagnostics); } } [Fact] public void ErrorLineEnd() { var tree = SyntaxFactory.ParseSyntaxTree("class C public { }", path: "goo"); var comp = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/errorendlocation" }); var loc = new SourceLocation(tree.GetCompilationUnitRoot().FindToken(6)); var diag = new CSDiagnostic(new DiagnosticInfo(MessageProvider.Instance, (int)ErrorCode.ERR_MetadataNameTooLong), loc); var text = comp.DiagnosticFormatter.Format(diag); string stringStart = "goo(1,7,1,8)"; Assert.Equal(stringStart, text.Substring(0, stringStart.Length)); } [Fact] public void ReportAnalyzer() { var parsedArgs1 = DefaultParse(new[] { "a.cs", "/reportanalyzer" }, WorkingDirectory); Assert.True(parsedArgs1.ReportAnalyzer); var parsedArgs2 = DefaultParse(new[] { "a.cs", "" }, WorkingDirectory); Assert.False(parsedArgs2.ReportAnalyzer); } [Fact] public void ReportAnalyzerOutput() { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, srcDirectory, new[] { "/reportanalyzer", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, srcFile.Path }); var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); Assert.Contains(CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader, output, StringComparison.Ordinal); Assert.Contains("WarningDiagnosticAnalyzer (Warning01)", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] [WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")] public void SkipAnalyzersParse() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/SKIPANALYZERS+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers-", "/skipanalyzers+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers", "/skipanalyzers-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.SkipAnalyzers); } [Theory, CombinatorialData] [WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")] public void SkipAnalyzersSemantics(bool skipAnalyzers) { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var skipAnalyzersFlag = "/skipanalyzers" + (skipAnalyzers ? "+" : "-"); var csc = CreateCSharpCompiler(null, srcDirectory, new[] { skipAnalyzersFlag, "/reportanalyzer", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, srcFile.Path }); var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); if (skipAnalyzers) { Assert.DoesNotContain(CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader, output, StringComparison.Ordinal); Assert.DoesNotContain(new WarningDiagnosticAnalyzer().ToString(), output, StringComparison.Ordinal); } else { Assert.Contains(CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader, output, StringComparison.Ordinal); Assert.Contains(new WarningDiagnosticAnalyzer().ToString(), output, StringComparison.Ordinal); } CleanupAllGeneratedFiles(srcFile.Path); } [Fact] [WorkItem(24835, "https://github.com/dotnet/roslyn/issues/24835")] public void TestCompilationSuccessIfOnlySuppressedDiagnostics() { var srcFile = Temp.CreateFile().WriteAllText(@" #pragma warning disable Warning01 class C { } "); var errorLog = Temp.CreateFile(); var csc = CreateCSharpCompiler( null, workingDirectory: Path.GetDirectoryName(srcFile.Path), args: new[] { "/errorlog:" + errorLog.Path, "/warnaserror+", "/nologo", "/t:library", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new WarningDiagnosticAnalyzer())); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = csc.Run(outWriter); // Previously, the compiler would return error code 1 without printing any diagnostics Assert.Empty(outWriter.ToString()); Assert.Equal(0, exitCode); CleanupAllGeneratedFiles(srcFile.Path); CleanupAllGeneratedFiles(errorLog.Path); } [Fact] [WorkItem(1759, "https://github.com/dotnet/roslyn/issues/1759")] public void AnalyzerDiagnosticThrowsInGetMessage() { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/t:library", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerThatThrowsInGetMessage())); var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); // Verify that the diagnostic reported by AnalyzerThatThrowsInGetMessage is reported, though it doesn't have the message. Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.Id, output, StringComparison.Ordinal); // Verify that the analyzer exception diagnostic for the exception throw in AnalyzerThatThrowsInGetMessage is also reported. Assert.Contains(AnalyzerExecutor.AnalyzerExceptionDiagnosticId, output, StringComparison.Ordinal); Assert.Contains(nameof(NotImplementedException), output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] [WorkItem(3707, "https://github.com/dotnet/roslyn/issues/3707")] public void AnalyzerExceptionDiagnosticCanBeConfigured() { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/t:library", $"/warnaserror:{AnalyzerExecutor.AnalyzerExceptionDiagnosticId}", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerThatThrowsInGetMessage())); var exitCode = csc.Run(outWriter); Assert.NotEqual(0, exitCode); var output = outWriter.ToString(); // Verify that the analyzer exception diagnostic for the exception throw in AnalyzerThatThrowsInGetMessage is also reported. Assert.Contains(AnalyzerExecutor.AnalyzerExceptionDiagnosticId, output, StringComparison.Ordinal); Assert.Contains(nameof(NotImplementedException), output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] [WorkItem(4589, "https://github.com/dotnet/roslyn/issues/4589")] public void AnalyzerReportsMisformattedDiagnostic() { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/t:library", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerReportingMisformattedDiagnostic())); var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); // Verify that the diagnostic reported by AnalyzerReportingMisformattedDiagnostic is reported with the message format string, instead of the formatted message. Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.Id, output, StringComparison.Ordinal); Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.MessageFormat.ToString(CultureInfo.InvariantCulture), output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] public void ErrorPathsFromLineDirectives() { string sampleProgram = @" #line 10 "".."" //relative path using System* "; var syntaxTree = SyntaxFactory.ParseSyntaxTree(sampleProgram, path: "filename.cs"); var comp = CreateCSharpCompiler(null, WorkingDirectory, new string[] { }); var text = comp.DiagnosticFormatter.Format(syntaxTree.GetDiagnostics().First()); //Pull off the last segment of the current directory. var expectedPath = Path.GetDirectoryName(WorkingDirectory); //the end of the diagnostic's "file" portion should be signaled with the '(' of the line/col info. Assert.Equal('(', text[expectedPath.Length]); sampleProgram = @" #line 10 "".>"" //invalid path character using System* "; syntaxTree = SyntaxFactory.ParseSyntaxTree(sampleProgram, path: "filename.cs"); text = comp.DiagnosticFormatter.Format(syntaxTree.GetDiagnostics().First()); Assert.True(text.StartsWith(".>", StringComparison.Ordinal)); sampleProgram = @" #line 10 ""http://goo.bar/baz.aspx"" //URI using System* "; syntaxTree = SyntaxFactory.ParseSyntaxTree(sampleProgram, path: "filename.cs"); text = comp.DiagnosticFormatter.Format(syntaxTree.GetDiagnostics().First()); Assert.True(text.StartsWith("http://goo.bar/baz.aspx", StringComparison.Ordinal)); } [WorkItem(1119609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119609")] [Fact] public void PreferredUILang() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("CS2006", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("CS2006", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:zz" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("CS2038", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:en-zz" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("CS2038", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:en-US" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.DoesNotContain("CS2038", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:de" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.DoesNotContain("CS2038", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:de-AT" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.DoesNotContain("CS2038", outWriter.ToString(), StringComparison.Ordinal); } [WorkItem(531263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531263")] [Fact] public void EmptyFileName() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "" }).Run(outWriter); Assert.NotEqual(0, exitCode); // error CS2021: File name '' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Assert.Contains("CS2021", outWriter.ToString(), StringComparison.Ordinal); } [WorkItem(747219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/747219")] [Fact] public void NoInfoDiagnostics() { string filePath = Temp.CreateFile().WriteAllText(@" using System.Diagnostics; // Unused. ").Path; var cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/target:library", filePath }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(filePath); } [Fact] public void RuntimeMetadataVersion() { var parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_SwitchNeedsString, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion:" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_SwitchNeedsString, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion: " }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_SwitchNeedsString, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion:v4.0.30319" }, WorkingDirectory); Assert.Equal(0, parsedArgs.Errors.Length); Assert.Equal("v4.0.30319", parsedArgs.EmitOptions.RuntimeMetadataVersion); parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion:-_+@%#*^" }, WorkingDirectory); Assert.Equal(0, parsedArgs.Errors.Length); Assert.Equal("-_+@%#*^", parsedArgs.EmitOptions.RuntimeMetadataVersion); var comp = CreateEmptyCompilation(string.Empty); Assert.Equal("v4.0.30319", ModuleMetadata.CreateFromImage(comp.EmitToArray(new EmitOptions(runtimeMetadataVersion: "v4.0.30319"))).Module.MetadataVersion); comp = CreateEmptyCompilation(string.Empty); Assert.Equal("_+@%#*^", ModuleMetadata.CreateFromImage(comp.EmitToArray(new EmitOptions(runtimeMetadataVersion: "_+@%#*^"))).Module.MetadataVersion); } [WorkItem(715339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715339")] [ConditionalFact(typeof(WindowsOnly))] public void WRN_InvalidSearchPathDir() { var baseDir = Temp.CreateDirectory(); var sourceFile = baseDir.CreateFile("Source.cs"); var invalidPath = "::"; var nonExistentPath = "DoesNotExist"; // lib switch DefaultParse(new[] { "/lib:" + invalidPath, sourceFile.Path }, WorkingDirectory).Errors.Verify( // warning CS1668: Invalid search path '::' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("::", "/LIB option", "path is too long or invalid")); DefaultParse(new[] { "/lib:" + nonExistentPath, sourceFile.Path }, WorkingDirectory).Errors.Verify( // warning CS1668: Invalid search path 'DoesNotExist' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("DoesNotExist", "/LIB option", "directory does not exist")); // LIB environment variable DefaultParse(new[] { sourceFile.Path }, WorkingDirectory, additionalReferenceDirectories: invalidPath).Errors.Verify( // warning CS1668: Invalid search path '::' specified in 'LIB environment variable' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("::", "LIB environment variable", "path is too long or invalid")); DefaultParse(new[] { sourceFile.Path }, WorkingDirectory, additionalReferenceDirectories: nonExistentPath).Errors.Verify( // warning CS1668: Invalid search path 'DoesNotExist' specified in 'LIB environment variable' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("DoesNotExist", "LIB environment variable", "directory does not exist")); CleanupAllGeneratedFiles(sourceFile.Path); } [WorkItem(650083, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/650083")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/55730")] public void ReservedDeviceNameAsFileName() { var parsedArgs = DefaultParse(new[] { "com9.cs", "/t:library " }, WorkingDirectory); Assert.Equal(0, parsedArgs.Errors.Length); parsedArgs = DefaultParse(new[] { "a.cs", "/t:library ", "/appconfig:.\\aux.config" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/out:com1.dll " }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/doc:..\\lpt2.xml: " }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/debug+", "/pdb:.\\prn.pdb" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "@con.rsp" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_OpenResponseFile, parsedArgs.Errors.First().Code); } [Fact] public void ReservedDeviceNameAsFileName2() { string filePath = Temp.CreateFile().WriteAllText(@"class C {}").Path; // make sure reserved device names don't var cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/r:com2.dll", "/target:library", "/preferreduilang:en", filePath }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS0006: Metadata file 'com2.dll' could not be found", outWriter.ToString(), StringComparison.Ordinal); cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/link:..\\lpt8.dll", "/target:library", "/preferreduilang:en", filePath }); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = cmd.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS0006: Metadata file '..\\lpt8.dll' could not be found", outWriter.ToString(), StringComparison.Ordinal); cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/lib:aux", "/preferreduilang:en", filePath }); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = cmd.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("warning CS1668: Invalid search path 'aux' specified in '/LIB option' -- 'directory does not exist'", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(filePath); } [Fact] public void ParseFeatures() { var args = DefaultParse(new[] { "/features:Test", "a.vb" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal("Test", args.ParseOptions.Features.Single().Key); args = DefaultParse(new[] { "/features:Test", "a.vb", "/Features:Experiment" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.ParseOptions.Features.Count); Assert.True(args.ParseOptions.Features.ContainsKey("Test")); Assert.True(args.ParseOptions.Features.ContainsKey("Experiment")); args = DefaultParse(new[] { "/features:Test=false,Key=value", "a.vb" }, WorkingDirectory); args.Errors.Verify(); Assert.True(args.ParseOptions.Features.SetEquals(new Dictionary<string, string> { { "Test", "false" }, { "Key", "value" } })); args = DefaultParse(new[] { "/features:Test,", "a.vb" }, WorkingDirectory); args.Errors.Verify(); Assert.True(args.ParseOptions.Features.SetEquals(new Dictionary<string, string> { { "Test", "true" } })); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseAdditionalFile() { var args = DefaultParse(new[] { "/additionalfile:web.config", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles.Single().Path); args = DefaultParse(new[] { "/additionalfile:web.config", "a.cs", "/additionalfile:app.manifest" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { "/additionalfile:web.config", "a.cs", "/additionalfile:web.config" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { "/additionalfile:..\\web.config", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "..\\web.config"), args.AdditionalFiles.Single().Path); var baseDir = Temp.CreateDirectory(); baseDir.CreateFile("web1.config"); baseDir.CreateFile("web2.config"); baseDir.CreateFile("web3.config"); args = DefaultParse(new[] { "/additionalfile:web*.config", "a.cs" }, baseDir.Path); args.Errors.Verify(); Assert.Equal(3, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(baseDir.Path, "web1.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(baseDir.Path, "web2.config"), args.AdditionalFiles[1].Path); Assert.Equal(Path.Combine(baseDir.Path, "web3.config"), args.AdditionalFiles[2].Path); args = DefaultParse(new[] { "/additionalfile:web.config;app.manifest", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { "/additionalfile:web.config,app.manifest", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { "/additionalfile:web.config,app.manifest", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { @"/additionalfile:""web.config,app.manifest""", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(1, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config,app.manifest"), args.AdditionalFiles[0].Path); args = DefaultParse(new[] { "/additionalfile:web.config:app.manifest", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(1, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config:app.manifest"), args.AdditionalFiles[0].Path); args = DefaultParse(new[] { "/additionalfile", "a.cs" }, WorkingDirectory); args.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "additionalfile")); Assert.Equal(0, args.AdditionalFiles.Length); args = DefaultParse(new[] { "/additionalfile:", "a.cs" }, WorkingDirectory); args.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "additionalfile")); Assert.Equal(0, args.AdditionalFiles.Length); } [Fact] public void ParseEditorConfig() { var args = DefaultParse(new[] { "/analyzerconfig:.editorconfig", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths.Single()); args = DefaultParse(new[] { "/analyzerconfig:.editorconfig", "a.cs", "/analyzerconfig:subdir\\.editorconfig" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AnalyzerConfigPaths.Length); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[0]); Assert.Equal(Path.Combine(WorkingDirectory, "subdir\\.editorconfig"), args.AnalyzerConfigPaths[1]); args = DefaultParse(new[] { "/analyzerconfig:.editorconfig", "a.cs", "/analyzerconfig:.editorconfig" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AnalyzerConfigPaths.Length); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[0]); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[1]); args = DefaultParse(new[] { "/analyzerconfig:..\\.editorconfig", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "..\\.editorconfig"), args.AnalyzerConfigPaths.Single()); args = DefaultParse(new[] { "/analyzerconfig:.editorconfig;subdir\\.editorconfig", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AnalyzerConfigPaths.Length); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[0]); Assert.Equal(Path.Combine(WorkingDirectory, "subdir\\.editorconfig"), args.AnalyzerConfigPaths[1]); args = DefaultParse(new[] { "/analyzerconfig", "a.cs" }, WorkingDirectory); args.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<file list>' for 'analyzerconfig' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "analyzerconfig").WithLocation(1, 1)); Assert.Equal(0, args.AnalyzerConfigPaths.Length); args = DefaultParse(new[] { "/analyzerconfig:", "a.cs" }, WorkingDirectory); args.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<file list>' for 'analyzerconfig' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "analyzerconfig").WithLocation(1, 1)); Assert.Equal(0, args.AnalyzerConfigPaths.Length); } [Fact] public void NullablePublicOnly() { string source = @"namespace System.Runtime.CompilerServices { public sealed class NullableAttribute : Attribute { } // missing constructor } public class Program { private object? F = null; }"; string errorMessage = "error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'"; string filePath = Temp.CreateFile().WriteAllText(source).Path; int exitCode; string output; // No /feature (exitCode, output) = compileAndRun(featureOpt: null); Assert.Equal(1, exitCode); Assert.Contains(errorMessage, output, StringComparison.Ordinal); // /features:nullablePublicOnly (exitCode, output) = compileAndRun("/features:nullablePublicOnly"); Assert.Equal(0, exitCode); Assert.DoesNotContain(errorMessage, output, StringComparison.Ordinal); // /features:nullablePublicOnly=true (exitCode, output) = compileAndRun("/features:nullablePublicOnly=true"); Assert.Equal(0, exitCode); Assert.DoesNotContain(errorMessage, output, StringComparison.Ordinal); // /features:nullablePublicOnly=false (the value is ignored) (exitCode, output) = compileAndRun("/features:nullablePublicOnly=false"); Assert.Equal(0, exitCode); Assert.DoesNotContain(errorMessage, output, StringComparison.Ordinal); CleanupAllGeneratedFiles(filePath); (int, string) compileAndRun(string featureOpt) { var args = new[] { "/target:library", "/preferreduilang:en", "/langversion:8", "/nullable+", filePath }; if (featureOpt != null) args = args.Concat(featureOpt).ToArray(); var compiler = CreateCSharpCompiler(null, WorkingDirectory, args); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = compiler.Run(outWriter); return (exitCode, outWriter.ToString()); }; } // See also NullableContextTests.NullableAnalysisFlags_01(). [Fact] public void NullableAnalysisFlags() { string source = @"class Program { #nullable enable static object F1() => null; #nullable disable static object F2() => null; }"; string filePath = Temp.CreateFile().WriteAllText(source).Path; string fileName = Path.GetFileName(filePath); string[] expectedWarningsAll = new[] { fileName + "(4,27): warning CS8603: Possible null reference return." }; string[] expectedWarningsNone = Array.Empty<string>(); AssertEx.Equal(expectedWarningsAll, compileAndRun(featureOpt: null)); AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis")); AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=always")); AssertEx.Equal(expectedWarningsNone, compileAndRun("/features:run-nullable-analysis=never")); AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=ALWAYS")); // unrecognized value (incorrect case) ignored AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=NEVER")); // unrecognized value (incorrect case) ignored AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=true")); // unrecognized value ignored AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=false")); // unrecognized value ignored AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=unknown")); // unrecognized value ignored CleanupAllGeneratedFiles(filePath); string[] compileAndRun(string featureOpt) { var args = new[] { "/target:library", "/preferreduilang:en", "/nologo", filePath }; if (featureOpt != null) args = args.Concat(featureOpt).ToArray(); var compiler = CreateCSharpCompiler(null, WorkingDirectory, args); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = compiler.Run(outWriter); return outWriter.ToString().Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); }; } [Fact] public void Compiler_Uses_DriverCache() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); int sourceCallbackCount = 0; var generator = new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount++; }); }); // with no cache, we'll see the callback execute multiple times RunWithNoCache(); Assert.Equal(1, sourceCallbackCount); RunWithNoCache(); Assert.Equal(2, sourceCallbackCount); RunWithNoCache(); Assert.Equal(3, sourceCallbackCount); // now re-run with a cache GeneratorDriverCache cache = new GeneratorDriverCache(); sourceCallbackCount = 0; RunWithCache(); Assert.Equal(1, sourceCallbackCount); RunWithCache(); Assert.Equal(1, sourceCallbackCount); RunWithCache(); Assert.Equal(1, sourceCallbackCount); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); void RunWithNoCache() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview" }, generators: new[] { generator.AsSourceGenerator() }, analyzers: null); void RunWithCache() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); } [Fact] public void Compiler_Doesnt_Use_Cache_From_Other_Compilation() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); int sourceCallbackCount = 0; var generator = new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount++; }); }); // now re-run with a cache GeneratorDriverCache cache = new GeneratorDriverCache(); sourceCallbackCount = 0; RunWithCache("1.dll"); Assert.Equal(1, sourceCallbackCount); RunWithCache("1.dll"); Assert.Equal(1, sourceCallbackCount); // now emulate a new compilation, and check we were invoked, but only once RunWithCache("2.dll"); Assert.Equal(2, sourceCallbackCount); RunWithCache("2.dll"); Assert.Equal(2, sourceCallbackCount); // now re-run our first compilation RunWithCache("1.dll"); Assert.Equal(2, sourceCallbackCount); // a new one RunWithCache("3.dll"); Assert.Equal(3, sourceCallbackCount); // and another old one RunWithCache("2.dll"); Assert.Equal(3, sourceCallbackCount); RunWithCache("1.dll"); Assert.Equal(3, sourceCallbackCount); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); void RunWithCache(string outputPath) => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/out:" + outputPath }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); } [Fact] public void Compiler_Can_Disable_DriverCache() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); int sourceCallbackCount = 0; var generator = new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount++; }); }); // run with the cache GeneratorDriverCache cache = new GeneratorDriverCache(); sourceCallbackCount = 0; RunWithCache(); Assert.Equal(1, sourceCallbackCount); RunWithCache(); Assert.Equal(1, sourceCallbackCount); RunWithCache(); Assert.Equal(1, sourceCallbackCount); // now re-run with the cache disabled sourceCallbackCount = 0; RunWithCacheDisabled(); Assert.Equal(1, sourceCallbackCount); RunWithCacheDisabled(); Assert.Equal(2, sourceCallbackCount); RunWithCacheDisabled(); Assert.Equal(3, sourceCallbackCount); // now clear the cache as well as disabling, and verify we don't put any entries into it either cache = new GeneratorDriverCache(); sourceCallbackCount = 0; RunWithCacheDisabled(); Assert.Equal(1, sourceCallbackCount); Assert.Equal(0, cache.CacheSize); RunWithCacheDisabled(); Assert.Equal(2, sourceCallbackCount); Assert.Equal(0, cache.CacheSize); RunWithCacheDisabled(); Assert.Equal(3, sourceCallbackCount); Assert.Equal(0, cache.CacheSize); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); void RunWithCache() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); void RunWithCacheDisabled() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/features:disable-generator-cache" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); } [Fact] public void Adding_Or_Removing_A_Generator_Invalidates_Cache() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); int sourceCallbackCount = 0; int sourceCallbackCount2 = 0; var generator = new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount++; }); }); var generator2 = new PipelineCallbackGenerator2((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount2++; }); }); // run with the cache GeneratorDriverCache cache = new GeneratorDriverCache(); RunWithOneGenerator(); Assert.Equal(1, sourceCallbackCount); Assert.Equal(0, sourceCallbackCount2); RunWithOneGenerator(); Assert.Equal(1, sourceCallbackCount); Assert.Equal(0, sourceCallbackCount2); RunWithTwoGenerators(); Assert.Equal(2, sourceCallbackCount); Assert.Equal(1, sourceCallbackCount2); RunWithTwoGenerators(); Assert.Equal(2, sourceCallbackCount); Assert.Equal(1, sourceCallbackCount2); // this seems counterintuitive, but when the only thing to change is the generator, we end up back at the state of the project when // we just ran a single generator. Thus we already have an entry in the cache we can use (the one created by the original call to // RunWithOneGenerator above) meaning we can use the previously cached results and not run. RunWithOneGenerator(); Assert.Equal(2, sourceCallbackCount); Assert.Equal(1, sourceCallbackCount2); void RunWithOneGenerator() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); void RunWithTwoGenerators() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview" }, generators: new[] { generator.AsSourceGenerator(), generator2.AsSourceGenerator() }, driverCache: cache, analyzers: null); } private static int OccurrenceCount(string source, string word) { var n = 0; var index = source.IndexOf(word, StringComparison.Ordinal); while (index >= 0) { ++n; index = source.IndexOf(word, index + word.Length, StringComparison.Ordinal); } return n; } private string VerifyOutput(TempDirectory sourceDir, TempFile sourceFile, bool includeCurrentAssemblyAsAnalyzerReference = true, string[] additionalFlags = null, int expectedInfoCount = 0, int expectedWarningCount = 0, int expectedErrorCount = 0, int? expectedExitCode = null, bool errorlog = false, IEnumerable<ISourceGenerator> generators = null, GeneratorDriverCache driverCache = null, params DiagnosticAnalyzer[] analyzers) { var args = new[] { "/nologo", "/preferreduilang:en", "/t:library", sourceFile.Path }; if (includeCurrentAssemblyAsAnalyzerReference) { args = args.Append("/a:" + Assembly.GetExecutingAssembly().Location); } if (errorlog) { args = args.Append("/errorlog:errorlog"); } if (additionalFlags != null) { args = args.Append(additionalFlags); } var csc = CreateCSharpCompiler(null, sourceDir.Path, args, analyzers: analyzers.ToImmutableArrayOrEmpty(), generators: generators.ToImmutableArrayOrEmpty(), driverCache: driverCache); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = csc.Run(outWriter); var output = outWriter.ToString(); expectedExitCode ??= expectedErrorCount > 0 ? 1 : 0; Assert.True( expectedExitCode == exitCode, string.Format("Expected exit code to be '{0}' was '{1}'.{2} Output:{3}{4}", expectedExitCode, exitCode, Environment.NewLine, Environment.NewLine, output)); Assert.DoesNotContain("hidden", output, StringComparison.Ordinal); if (expectedInfoCount == 0) { Assert.DoesNotContain("info", output, StringComparison.Ordinal); } else { // Info diagnostics are only logged with /errorlog. Assert.True(errorlog); Assert.Equal(expectedInfoCount, OccurrenceCount(output, "info")); } if (expectedWarningCount == 0) { Assert.DoesNotContain("warning", output, StringComparison.Ordinal); } else { Assert.Equal(expectedWarningCount, OccurrenceCount(output, "warning")); } if (expectedErrorCount == 0) { Assert.DoesNotContain("error", output, StringComparison.Ordinal); } else { Assert.Equal(expectedErrorCount, OccurrenceCount(output, "error")); } return output; } [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [Fact] public void NoWarnAndWarnAsError_AnalyzerDriverWarnings() { // This assembly has an abstract MockAbstractDiagnosticAnalyzer type which should cause // compiler warning CS8032 to be produced when compilations created in this test try to load it. string source = @"using System;"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS8032 can be suppressed via /warn:0. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that compiler warning CS8032 can be individually suppressed via /nowarn:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:CS8032" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that compiler warning CS8032 can be promoted to an error via /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS8032 can be individually promoted to an error via /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:8032" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [Fact] public void NoWarnAndWarnAsError_HiddenDiagnostic() { // This assembly has a HiddenDiagnosticAnalyzer type which should produce custom hidden // diagnostics for #region directives present in the compilations created in this test. var source = @"using System; #region Region #endregion"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that /nowarn: has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warnaserror+ has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:8032" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that /warnaserror- has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warnaserror: promotes custom hidden diagnostic Hidden01 to an error. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Hidden01" }, expectedWarningCount: 1, expectedErrorCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal); // TEST: Verify that /warnaserror-: has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Hidden01", "/nowarn:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Hidden01", "/warnaserror:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/nowarn:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Hidden01", "/warnaserror-:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror:Hidden01" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that /warn:0 has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Hidden01", "/warn:0" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Hidden01", "/warnaserror-:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/warnaserror+:Hidden01" }, expectedWarningCount: 1, expectedErrorCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror+:Hidden01" }, expectedWarningCount: 1, expectedErrorCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/warnaserror+:Hidden01", "/nowarn:8032" }, expectedErrorCount: 1); Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Hidden01", "/warnaserror+", "/nowarn:8032" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Hidden01", "/warnaserror-" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/warnaserror-:Hidden01", "/nowarn:8032" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/warnaserror-" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror-:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [WorkItem(42166, "https://github.com/dotnet/roslyn/issues/42166")] [CombinatorialData, Theory] public void NoWarnAndWarnAsError_InfoDiagnostic(bool errorlog) { // NOTE: Info diagnostics are only logged on command line when /errorlog is specified. See https://github.com/dotnet/roslyn/issues/42166 for details. // This assembly has an InfoDiagnosticAnalyzer type which should produce custom info // diagnostics for the #pragma warning restore directives present in the compilations created in this test. var source = @"using System; #pragma warning restore"; var name = "a.cs"; string output; output = GetOutput(name, source, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 suppresses custom info diagnostic Info01. output = GetOutput(name, source, additionalFlags: new[] { "/warn:0" }, errorlog: errorlog); // TEST: Verify that custom info diagnostic Info01 can be individually suppressed via /nowarn:. output = GetOutput(name, source, additionalFlags: new[] { "/nowarn:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that custom info diagnostic Info01 can never be promoted to an error via /warnaserror+. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that custom info diagnostic Info01 is still reported as an info when /warnaserror- is used. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that custom info diagnostic Info01 can be individually promoted to an error via /warnaserror:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror:Info01" }, expectedWarningCount: 1, expectedErrorCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that custom info diagnostic Info01 is still reported as an info when passed to /warnaserror-:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify /nowarn overrides /warnaserror. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror:Info01", "/nowarn:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn overrides /warnaserror. output = GetOutput(name, source, additionalFlags: new[] { "/nowarn:Info01", "/warnaserror:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn overrides /warnaserror-. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/nowarn:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn overrides /warnaserror-. output = GetOutput(name, source, additionalFlags: new[] { "/nowarn:Info01", "/warnaserror-:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 has no impact on custom info diagnostic Info01. output = GetOutput(name, source, additionalFlags: new[] { "/warn:0", "/warnaserror:Info01" }, errorlog: errorlog); // TEST: Verify that /warn:0 has no impact on custom info diagnostic Info01. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror:Info01", "/warn:0" }); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+:Info01", "/warnaserror-:Info01" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/warnaserror+:Info01" }, expectedWarningCount: 1, expectedErrorCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-", "/warnaserror+:Info01" }, expectedWarningCount: 1, expectedErrorCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/warnaserror+", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+:Info01", "/warnaserror+", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+", "/warnaserror+:Info01", "/nowarn:8032" }, expectedErrorCount: 1, errorlog: errorlog); Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+:Info01", "/warnaserror-" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+", "/warnaserror-:Info01", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/warnaserror-" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-", "/warnaserror-:Info01" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); } private string GetOutput( string name, string source, bool includeCurrentAssemblyAsAnalyzerReference = true, string[] additionalFlags = null, int expectedInfoCount = 0, int expectedWarningCount = 0, int expectedErrorCount = 0, bool errorlog = false) { var dir = Temp.CreateDirectory(); var file = dir.CreateFile(name); file.WriteAllText(source); var output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference, additionalFlags, expectedInfoCount, expectedWarningCount, expectedErrorCount, null, errorlog); CleanupAllGeneratedFiles(file.Path); return output; } [WorkItem(11368, "https://github.com/dotnet/roslyn/issues/11368")] [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [WorkItem(998069, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/998069")] [WorkItem(998724, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/998724")] [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [Fact] public void NoWarnAndWarnAsError_WarningDiagnostic() { // This assembly has a WarningDiagnosticAnalyzer type which should produce custom warning // diagnostics for source types present in the compilations created in this test. string source = @" class C { static void Main() { int i; } } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, expectedWarningCount: 3); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be suppressed via /warn:0. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be individually suppressed via /nowarn:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that diagnostic ids are processed in case-sensitive fashion inside /nowarn:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:cs0168,warning01,700000" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be promoted to errors via /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/nowarn:8032" }, expectedErrorCount: 2); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be promoted to errors via /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:8032" }, expectedErrorCount: 2); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); // TEST: Verify that /warnaserror- keeps compiler warning CS0168 as well as custom warning diagnostic Warning01 as warnings. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that custom warning diagnostic Warning01 can be individually promoted to an error via /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Something,Warning01" }, expectedWarningCount: 2, expectedErrorCount: 1); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS0168 can be individually promoted to an error via /warnaserror+:. // This doesn't work correctly currently - promoting compiler warning CS0168 to an error causes us to no longer report any custom warning diagnostics as errors (Bug 998069). output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:CS0168" }, expectedWarningCount: 2, expectedErrorCount: 1); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that diagnostic ids are processed in case-sensitive fashion inside /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:cs0168,warning01,58000" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that custom warning diagnostic Warning01 as well as compiler warning CS0168 can be promoted to errors via /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:CS0168,Warning01" }, expectedWarningCount: 1, expectedErrorCount: 2); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror+" }); // TEST: Verify that /warn:0 overrides /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warn:0" }); // TEST: Verify that /warn:0 overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warn:0" }); // TEST: Verify that /warn:0 overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror-" }); // TEST: Verify that /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Something,CS0168,Warning01", "/nowarn:0168,Warning01,58000" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000", "/warnaserror:Something,CS0168,Warning01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Something,CS0168,Warning01", "/nowarn:0168,Warning01,58000" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000", "/warnaserror-:Something,CS0168,Warning01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:0168,Warning01,58000,8032" }); // TEST: Verify that /nowarn: overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000,8032", "/warnaserror+" }); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/nowarn:0168,Warning01,58000,8032" }); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000,8032", "/warnaserror-" }); // TEST: Verify that /warn:0 overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Something,CS0168,Warning01", "/warn:0" }); // TEST: Verify that /warn:0 overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror:Something,CS0168,Warning01" }); // TEST: Verify that last /warnaserror[+/-] flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-] flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warnaserror-" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Warning01", "/warnaserror+:Warning01" }, expectedWarningCount: 2, expectedErrorCount: 1); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Warning01", "/warnaserror-:Warning01" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Warning01,CS0168,58000,8032", "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warnaserror-:Warning01,CS0168,58000,8032" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Warning01,58000,8032", "/warnaserror-" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror+:Warning01" }, expectedWarningCount: 2, expectedErrorCount: 1); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Warning01,CS0168,58000", "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warnaserror+:Warning01,CS0168,58000" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Warning01,58000,8032", "/warnaserror-" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror-:Warning01,58000,8032" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [Fact] public void NoWarnAndWarnAsError_ErrorDiagnostic() { // This assembly has an ErrorDiagnosticAnalyzer type which should produce custom error // diagnostics for #pragma warning disable directives present in the compilations created in this test. string source = @"using System; #pragma warning disable"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); // TEST: Verify that custom error diagnostic Error01 can't be suppressed via /warn:0. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" }, expectedErrorCount: 1); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); // TEST: Verify that custom error diagnostic Error01 can be suppressed via /nowarn:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:Error01" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror+:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror+:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Error01", "/nowarn:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/nowarn:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror-" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Error01", "/nowarn:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror-:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that nothing bad happens when using /warnaserror[+/-] when custom error diagnostic Error01 is present. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-" }, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); // TEST: Verify that nothing bad happens if someone passes custom error diagnostic Error01 to /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Error01" }, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Error01" }, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Error01" }, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void ConsistentErrorMessageWhenProvidingNoKeyFile() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim()); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void ConsistentErrorMessageWhenProvidingEmptyKeyFile() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:\"\"", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim()); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void ConsistentErrorMessageWhenProvidingNoKeyFile_PublicSign() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:", "/publicsign", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim()); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void ConsistentErrorMessageWhenProvidingEmptyKeyFile_PublicSign() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:\"\"", "/publicsign", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim()); } [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [Fact] public void NoWarnAndWarnAsError_CompilerErrorDiagnostic() { string source = @"using System; class C { static void Main() { int i = new Exception(); } }"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); // TEST: Verify that compiler error CS0029 can't be suppressed via /warn:0. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warn:0" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); // TEST: Verify that compiler error CS0029 can't be suppressed via /nowarn:. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:29" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:CS0029" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); // TEST: Verify that nothing bad happens when using /warnaserror[+/-] when compiler error CS0029 is present. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror-" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); // TEST: Verify that nothing bad happens if someone passes compiler error CS0029 to /warnaserror[+/-]:. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror:0029" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror+:CS0029" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror-:29" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror-:CS0029" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [Fact] public void WarnAsError_LastOneWins1() { var arguments = DefaultParse(new[] { "/warnaserror-:3001", "/warnaserror" }, null); var options = arguments.CompilationOptions; var comp = CreateCompilation(@"[assembly: System.CLSCompliant(true)] public class C { public void M(ushort i) { } public static void Main(string[] args) {} }", options: options); comp.VerifyDiagnostics( // (4,26): warning CS3001: Argument type 'ushort' is not CLS-compliant // public void M(ushort i) Diagnostic(ErrorCode.WRN_CLS_BadArgType, "i") .WithArguments("ushort") .WithLocation(4, 26) .WithWarningAsError(true)); } [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [Fact] public void WarnAsError_LastOneWins2() { var arguments = DefaultParse(new[] { "/warnaserror", "/warnaserror-:3001" }, null); var options = arguments.CompilationOptions; var comp = CreateCompilation(@"[assembly: System.CLSCompliant(true)] public class C { public void M(ushort i) { } public static void Main(string[] args) {} }", options: options); comp.VerifyDiagnostics( // (4,26): warning CS3001: Argument type 'ushort' is not CLS-compliant // public void M(ushort i) Diagnostic(ErrorCode.WRN_CLS_BadArgType, "i") .WithArguments("ushort") .WithLocation(4, 26) .WithWarningAsError(false)); } [WorkItem(1091972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091972")] [WorkItem(444, "CodePlex")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void Bug1091972() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText( @" /// <summary>ABC...XYZ</summary> class C { static void Main() { var textStreamReader = new System.IO.StreamReader(typeof(C).Assembly.GetManifestResourceStream(""doc.xml"")); System.Console.WriteLine(textStreamReader.ReadToEnd()); } } "); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /doc:doc.xml /out:out.exe /resource:doc.xml \"{0}\"", src.ToString()), startFolder: dir.ToString()); Assert.Equal("", output.Trim()); Assert.True(File.Exists(Path.Combine(dir.ToString(), "doc.xml"))); var expected = @"<?xml version=""1.0""?> <doc> <assembly> <name>out</name> </assembly> <members> <member name=""T:C""> <summary>ABC...XYZ</summary> </member> </members> </doc>".Trim(); using (var reader = new StreamReader(Path.Combine(dir.ToString(), "doc.xml"))) { var content = reader.ReadToEnd(); Assert.Equal(expected, content.Trim()); } output = ProcessUtilities.RunAndGetOutput(Path.Combine(dir.ToString(), "out.exe"), startFolder: dir.ToString()); Assert.Equal(expected, output.Trim()); CleanupAllGeneratedFiles(src.Path); } [ConditionalFact(typeof(WindowsOnly))] public void CommandLineMisc() { CSharpCommandLineArguments args = null; string baseDirectory = @"c:\test"; Func<string, CSharpCommandLineArguments> parse = (x) => FullParse(x, baseDirectory); args = parse(@"/out:""a.exe"""); Assert.Equal(@"a.exe", args.OutputFileName); args = parse(@"/pdb:""a.pdb"""); Assert.Equal(Path.Combine(baseDirectory, @"a.pdb"), args.PdbPath); // The \ here causes " to be treated as a quote, not as an escaping construct args = parse(@"a\""b c""\d.cs"); Assert.Equal( new[] { @"c:\test\a""b", @"c:\test\c\d.cs" }, args.SourceFiles.Select(x => x.Path)); args = parse(@"a\\""b c""\d.cs"); Assert.Equal( new[] { @"c:\test\a\b c\d.cs" }, args.SourceFiles.Select(x => x.Path)); args = parse(@"/nostdlib /r:""a.dll"",""b.dll"" c.cs"); Assert.Equal( new[] { @"a.dll", @"b.dll" }, args.MetadataReferences.Select(x => x.Reference)); args = parse(@"/nostdlib /r:""a-s.dll"",""b-s.dll"" c.cs"); Assert.Equal( new[] { @"a-s.dll", @"b-s.dll" }, args.MetadataReferences.Select(x => x.Reference)); args = parse(@"/nostdlib /r:""a,;s.dll"",""b,;s.dll"" c.cs"); Assert.Equal( new[] { @"a,;s.dll", @"b,;s.dll" }, args.MetadataReferences.Select(x => x.Reference)); } [Fact] public void CommandLine_ScriptRunner1() { var args = ScriptParse(new[] { "--", "script.csx", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "--", "@script.csx", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "@script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "--", "-script.csx", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "-script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "script.csx", "--", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "--", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "script.csx", "a", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "a", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "script.csx", "a", "--", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "a", "--", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "-i", "script.csx", "a", "b", "c" }, baseDirectory: WorkingDirectory); Assert.True(args.InteractiveMode); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "a", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "-i", "--", "script.csx", "a", "b", "c" }, baseDirectory: WorkingDirectory); Assert.True(args.InteractiveMode); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "a", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "-i", "--", "--", "--" }, baseDirectory: WorkingDirectory); Assert.True(args.InteractiveMode); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "--") }, args.SourceFiles.Select(f => f.Path)); Assert.True(args.SourceFiles[0].IsScript); AssertEx.Equal(new[] { "--" }, args.ScriptArguments); // TODO: fails on Linux (https://github.com/dotnet/roslyn/issues/5904) // Result: C:\/script.csx //args = ScriptParse(new[] { "-i", "script.csx", "--", "--" }, baseDirectory: @"C:\"); //Assert.True(args.InteractiveMode); //AssertEx.Equal(new[] { @"C:\script.csx" }, args.SourceFiles.Select(f => f.Path)); //Assert.True(args.SourceFiles[0].IsScript); //AssertEx.Equal(new[] { "--" }, args.ScriptArguments); } [WorkItem(127403, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/127403")] [Fact] public void ParseSeparatedPaths_QuotedComma() { var paths = CSharpCommandLineParser.ParseSeparatedPaths(@"""a, b"""); Assert.Equal( new[] { @"a, b" }, paths); } [Fact] [CompilerTrait(CompilerFeature.Determinism)] public void PathMapParser() { var s = PathUtilities.DirectorySeparatorStr; var parsedArgs = DefaultParse(new[] { "/pathmap:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ImmutableArray.Create<KeyValuePair<string, string>>(), parsedArgs.PathMap); parsedArgs = DefaultParse(new[] { "/pathmap:K1=V1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("K1" + s, "V1" + s), parsedArgs.PathMap[0]); parsedArgs = DefaultParse(new[] { $"/pathmap:abc{s}=/", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("abc" + s, "/"), parsedArgs.PathMap[0]); parsedArgs = DefaultParse(new[] { "/pathmap:K1=V1,K2=V2", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("K1" + s, "V1" + s), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create("K2" + s, "V2" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { "/pathmap:,", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ImmutableArray.Create<KeyValuePair<string, string>>(), parsedArgs.PathMap); parsedArgs = DefaultParse(new[] { "/pathmap:,,", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:,,,", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:k=,=v", "a.cs" }, WorkingDirectory); Assert.Equal(2, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[1].Code); parsedArgs = DefaultParse(new[] { "/pathmap:k=v=bad", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:k=", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:=v", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:\"supporting spaces=is hard\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("supporting spaces" + s, "is hard" + s), parsedArgs.PathMap[0]); parsedArgs = DefaultParse(new[] { "/pathmap:\"K 1=V 1\",\"K 2=V 2\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("K 1" + s, "V 1" + s), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create("K 2" + s, "V 2" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { "/pathmap:\"K 1\"=\"V 1\",\"K 2\"=\"V 2\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("K 1" + s, "V 1" + s), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create("K 2" + s, "V 2" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { "/pathmap:\"a ==,,b\"=\"1,,== 2\",\"x ==,,y\"=\"3 4\",", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("a =,b" + s, "1,= 2" + s), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create("x =,y" + s, "3 4" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { @"/pathmap:C:\temp\=/_1/,C:\temp\a\=/_2/,C:\temp\a\b\=/_3/", "a.cs", @"a\b.cs", @"a\b\c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create(@"C:\temp\a\b\", "/_3/"), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create(@"C:\temp\a\", "/_2/"), parsedArgs.PathMap[1]); Assert.Equal(KeyValuePairUtil.Create(@"C:\temp\", "/_1/"), parsedArgs.PathMap[2]); } [Theory] [InlineData("", new string[0])] [InlineData(",", new[] { "", "" })] [InlineData(",,", new[] { "," })] [InlineData(",,,", new[] { ",", "" })] [InlineData(",,,,", new[] { ",," })] [InlineData("a,", new[] { "a", "" })] [InlineData("a,b", new[] { "a", "b" })] [InlineData(",,a,,,,,b,,", new[] { ",a,,", "b," })] public void SplitWithDoubledSeparatorEscaping(string str, string[] expected) { AssertEx.Equal(expected, CommandLineParser.SplitWithDoubledSeparatorEscaping(str, ',')); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] [CompilerTrait(CompilerFeature.Determinism)] public void PathMapPdbParser() { var dir = Path.Combine(WorkingDirectory, "a"); var parsedArgs = DefaultParse(new[] { $@"/pathmap:{dir}=b:\", "a.cs", @"/pdb:a\data.pdb", "/debug:full" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(dir, @"data.pdb"), parsedArgs.PdbPath); // This value is calculate during Emit phases and should be null even in the face of a pathmap targeting it. Assert.Null(parsedArgs.EmitOptions.PdbFilePath); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] [CompilerTrait(CompilerFeature.Determinism)] public void PathMapPdbEmit() { void AssertPdbEmit(TempDirectory dir, string pdbPath, string pePdbPath, params string[] extraArgs) { var source = @"class Program { static void Main() { } }"; var src = dir.CreateFile("a.cs").WriteAllText(source); var defaultArgs = new[] { "/nologo", "a.cs", "/out:a.exe", "/debug:full", $"/pdb:{pdbPath}" }; var isDeterministic = extraArgs.Contains("/deterministic"); var args = defaultArgs.Concat(extraArgs).ToArray(); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, args); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var exePath = Path.Combine(dir.Path, "a.exe"); Assert.True(File.Exists(exePath)); Assert.True(File.Exists(pdbPath)); using (var peStream = File.OpenRead(exePath)) { PdbValidation.ValidateDebugDirectory(peStream, null, pePdbPath, hashAlgorithm: default, hasEmbeddedPdb: false, isDeterministic); } } // Case with no mappings using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, pdbPath); } // Simple mapping using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, @"q:\a.pdb", $@"/pathmap:{dir.Path}=q:\"); } // Simple mapping deterministic using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, @"q:\a.pdb", $@"/pathmap:{dir.Path}=q:\", "/deterministic"); } // Partial mapping using (var dir = new DisposableDirectory(Temp)) { dir.CreateDirectory("pdb"); var pdbPath = Path.Combine(dir.Path, @"pdb\a.pdb"); AssertPdbEmit(dir, pdbPath, @"q:\pdb\a.pdb", $@"/pathmap:{dir.Path}=q:\"); } // Legacy feature flag using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, @"a.pdb", $@"/features:pdb-path-determinism"); } // Unix path map using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, @"/a.pdb", $@"/pathmap:{dir.Path}=/"); } // Multi-specified path map with mixed slashes using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, "/goo/a.pdb", $"/pathmap:{dir.Path}=/goo,{dir.Path}{PathUtilities.DirectorySeparatorChar}=/bar"); } } [CompilerTrait(CompilerFeature.Determinism)] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void DeterministicPdbsRegardlessOfBitness() { var dir = Temp.CreateDirectory(); var dir32 = dir.CreateDirectory("32"); var dir64 = dir.CreateDirectory("64"); var programExe32 = dir32.CreateFile("Program.exe"); var programPdb32 = dir32.CreateFile("Program.pdb"); var programExe64 = dir64.CreateFile("Program.exe"); var programPdb64 = dir64.CreateFile("Program.pdb"); var sourceFile = dir.CreateFile("Source.cs").WriteAllText(@" using System; using System.Linq; using System.Collections.Generic; namespace N { using I4 = System.Int32; class Program { public static IEnumerable<int> F() { I4 x = 1; yield return 1; yield return x; } public static void Main(string[] args) { dynamic x = 1; const int a = 1; F().ToArray(); Console.WriteLine(x + a); } } }"); var csc32src = $@" using System; using System.Reflection; class Runner {{ static int Main(string[] args) {{ var assembly = Assembly.LoadFrom(@""{s_CSharpCompilerExecutable}""); var program = assembly.GetType(""Microsoft.CodeAnalysis.CSharp.CommandLine.Program""); var main = program.GetMethod(""Main""); return (int)main.Invoke(null, new object[] {{ args }}); }} }} "; var csc32 = CreateCompilationWithMscorlib46(csc32src, options: TestOptions.ReleaseExe.WithPlatform(Platform.X86), assemblyName: "csc32"); var csc32exe = dir.CreateFile("csc32.exe").WriteAllBytes(csc32.EmitToArray()); dir.CopyFile(Path.ChangeExtension(s_CSharpCompilerExecutable, ".exe.config"), "csc32.exe.config"); dir.CopyFile(Path.Combine(Path.GetDirectoryName(s_CSharpCompilerExecutable), "csc.rsp")); var output = ProcessUtilities.RunAndGetOutput(csc32exe.Path, $@"/nologo /debug:full /deterministic /out:Program.exe /pathmap:""{dir32.Path}""=X:\ ""{sourceFile.Path}""", expectedRetCode: 0, startFolder: dir32.Path); Assert.Equal("", output); output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $@"/nologo /debug:full /deterministic /out:Program.exe /pathmap:""{dir64.Path}""=X:\ ""{sourceFile.Path}""", expectedRetCode: 0, startFolder: dir64.Path); Assert.Equal("", output); AssertEx.Equal(programExe32.ReadAllBytes(), programExe64.ReadAllBytes()); AssertEx.Equal(programPdb32.ReadAllBytes(), programPdb64.ReadAllBytes()); } [WorkItem(7588, "https://github.com/dotnet/roslyn/issues/7588")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void Version() { var folderName = Temp.CreateDirectory().ToString(); var argss = new[] { "/version", "a.cs /version /preferreduilang:en", "/version /nologo", "/version /help", }; foreach (var args in argss) { var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, args, startFolder: folderName); Assert.Equal(s_compilerVersion, output.Trim()); } } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void RefOut() { var dir = Temp.CreateDirectory(); var refDir = dir.CreateDirectory("ref"); var src = dir.CreateFile("a.cs"); src.WriteAllText(@" public class C { /// <summary>Main method</summary> public static void Main() { System.Console.Write(""Hello""); } /// <summary>Private method</summary> private static void PrivateMethod() { System.Console.Write(""Private""); } }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/out:a.exe", "/refout:ref/a.dll", "/doc:doc.xml", "/deterministic", "/langversion:7", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var exe = Path.Combine(dir.Path, "a.exe"); Assert.True(File.Exists(exe)); MetadataReaderUtils.VerifyPEMetadata(exe, new[] { "TypeDefinition:<Module>", "TypeDefinition:C" }, new[] { "MethodDefinition:Void C.Main()", "MethodDefinition:Void C.PrivateMethod()", "MethodDefinition:Void C..ctor()" }, new[] { "CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute" } ); var doc = Path.Combine(dir.Path, "doc.xml"); Assert.True(File.Exists(doc)); var content = File.ReadAllText(doc); var expectedDoc = @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""M:C.Main""> <summary>Main method</summary> </member> <member name=""M:C.PrivateMethod""> <summary>Private method</summary> </member> </members> </doc>"; Assert.Equal(expectedDoc, content.Trim()); var output = ProcessUtilities.RunAndGetOutput(exe, startFolder: dir.Path); Assert.Equal("Hello", output.Trim()); var refDll = Path.Combine(refDir.Path, "a.dll"); Assert.True(File.Exists(refDll)); // The types and members that are included needs further refinement. // See issue https://github.com/dotnet/roslyn/issues/17612 MetadataReaderUtils.VerifyPEMetadata(refDll, new[] { "TypeDefinition:<Module>", "TypeDefinition:C" }, new[] { "MethodDefinition:Void C.Main()", "MethodDefinition:Void C..ctor()" }, new[] { "CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute", "ReferenceAssemblyAttribute" } ); // Clean up temp files CleanupAllGeneratedFiles(dir.Path); CleanupAllGeneratedFiles(refDir.Path); } [Fact] public void RefOutWithError() { var dir = Temp.CreateDirectory(); dir.CreateDirectory("ref"); var src = dir.CreateFile("a.cs"); src.WriteAllText(@"class C { public static void Main() { error(); } }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/out:a.dll", "/refout:ref/a.dll", "/deterministic", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); var dll = Path.Combine(dir.Path, "a.dll"); Assert.False(File.Exists(dll)); var refDll = Path.Combine(dir.Path, Path.Combine("ref", "a.dll")); Assert.False(File.Exists(refDll)); Assert.Equal("a.cs(1,39): error CS0103: The name 'error' does not exist in the current context", outWriter.ToString().Trim()); // Clean up temp files CleanupAllGeneratedFiles(dir.Path); } [Fact] public void RefOnly() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText(@" using System; class C { /// <summary>Main method</summary> public static void Main() { error(); // semantic error in method body } private event Action E1 { add { } remove { } } private event Action E2; /// <summary>Private Class Field</summary> private int field; /// <summary>Private Struct</summary> private struct S { /// <summary>Private Struct Field</summary> private int field; } }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/out:a.dll", "/refonly", "/debug", "/deterministic", "/langversion:7", "/doc:doc.xml", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal("", outWriter.ToString()); Assert.Equal(0, exitCode); var refDll = Path.Combine(dir.Path, "a.dll"); Assert.True(File.Exists(refDll)); // The types and members that are included needs further refinement. // See issue https://github.com/dotnet/roslyn/issues/17612 MetadataReaderUtils.VerifyPEMetadata(refDll, new[] { "TypeDefinition:<Module>", "TypeDefinition:C", "TypeDefinition:S" }, new[] { "MethodDefinition:Void C.Main()", "MethodDefinition:Void C..ctor()" }, new[] { "CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute", "ReferenceAssemblyAttribute" } ); var pdb = Path.Combine(dir.Path, "a.pdb"); Assert.False(File.Exists(pdb)); var doc = Path.Combine(dir.Path, "doc.xml"); Assert.True(File.Exists(doc)); var content = File.ReadAllText(doc); var expectedDoc = @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""M:C.Main""> <summary>Main method</summary> </member> <member name=""F:C.field""> <summary>Private Class Field</summary> </member> <member name=""T:C.S""> <summary>Private Struct</summary> </member> <member name=""F:C.S.field""> <summary>Private Struct Field</summary> </member> </members> </doc>"; Assert.Equal(expectedDoc, content.Trim()); // Clean up temp files CleanupAllGeneratedFiles(dir.Path); } [Fact] public void CompilingCodeWithInvalidPreProcessorSymbolsShouldProvideDiagnostics() { var parsedArgs = DefaultParse(new[] { "/define:1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2029: Invalid name for a preprocessing symbol; '1' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("1").WithLocation(1, 1)); } [Fact] public void CompilingCodeWithInvalidLanguageVersionShouldProvideDiagnostics() { var parsedArgs = DefaultParse(new[] { "/langversion:1000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS1617: Invalid option '1000' for /langversion. Use '/langversion:?' to list supported values. Diagnostic(ErrorCode.ERR_BadCompatMode).WithArguments("1000").WithLocation(1, 1)); } [Fact, WorkItem(16913, "https://github.com/dotnet/roslyn/issues/16913")] public void CompilingCodeWithMultipleInvalidPreProcessorSymbolsShouldErrorOut() { var parsedArgs = DefaultParse(new[] { "/define:valid1,2invalid,valid3", "/define:4,5,valid6", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2029: Invalid value for '/define'; '2invalid' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("2invalid"), // warning CS2029: Invalid value for '/define'; '4' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("4"), // warning CS2029: Invalid value for '/define'; '5' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("5")); } [WorkItem(406649, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=406649")] [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void MissingCompilerAssembly() { var dir = Temp.CreateDirectory(); var cscPath = dir.CopyFile(s_CSharpCompilerExecutable).Path; dir.CopyFile(typeof(Compilation).Assembly.Location); // Missing Microsoft.CodeAnalysis.CSharp.dll. var result = ProcessUtilities.Run(cscPath, arguments: "/nologo /t:library unknown.cs", workingDirectory: dir.Path); Assert.Equal(1, result.ExitCode); Assert.Equal( $"Could not load file or assembly '{typeof(CSharpCompilation).Assembly.FullName}' or one of its dependencies. The system cannot find the file specified.", result.Output.Trim()); // Missing System.Collections.Immutable.dll. dir.CopyFile(typeof(CSharpCompilation).Assembly.Location); result = ProcessUtilities.Run(cscPath, arguments: "/nologo /t:library unknown.cs", workingDirectory: dir.Path); Assert.Equal(1, result.ExitCode); Assert.Equal( $"Could not load file or assembly '{typeof(ImmutableArray).Assembly.FullName}' or one of its dependencies. The system cannot find the file specified.", result.Output.Trim()); } #if NET472 [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void LoadinganalyzerNetStandard13() { var analyzerFileName = "AnalyzerNS13.dll"; var srcFileName = "src.cs"; var analyzerDir = Temp.CreateDirectory(); var analyzerFile = analyzerDir.CreateFile(analyzerFileName).WriteAllBytes(CreateCSharpAnalyzerNetStandard13(Path.GetFileNameWithoutExtension(analyzerFileName))); var srcFile = analyzerDir.CreateFile(srcFileName).WriteAllText("public class C { }"); var result = ProcessUtilities.Run(s_CSharpCompilerExecutable, arguments: $"/nologo /t:library /analyzer:{analyzerFileName} {srcFileName}", workingDirectory: analyzerDir.Path); var outputWithoutPaths = Regex.Replace(result.Output, " in .*", ""); AssertEx.AssertEqualToleratingWhitespaceDifferences( $@"warning AD0001: Analyzer 'TestAnalyzer' threw an exception of type 'System.NotImplementedException' with message '28'. System.NotImplementedException: 28 at TestAnalyzer.get_SupportedDiagnostics() at Microsoft.CodeAnalysis.Diagnostics.AnalyzerManager.AnalyzerExecutionContext.<>c__DisplayClass20_0.<ComputeDiagnosticDescriptors>b__0(Object _) at Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.ExecuteAndCatchIfThrows_NoLock[TArg](DiagnosticAnalyzer analyzer, Action`1 analyze, TArg argument, Nullable`1 info) -----", outputWithoutPaths); Assert.Equal(0, result.ExitCode); } #endif private static ImmutableArray<byte> CreateCSharpAnalyzerNetStandard13(string analyzerAssemblyName) { var minSystemCollectionsImmutableSource = @" [assembly: System.Reflection.AssemblyVersion(""1.2.3.0"")] namespace System.Collections.Immutable { public struct ImmutableArray<T> { } } "; var minCodeAnalysisSource = @" using System; [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] namespace Microsoft.CodeAnalysis.Diagnostics { [AttributeUsage(AttributeTargets.Class)] public sealed class DiagnosticAnalyzerAttribute : Attribute { public DiagnosticAnalyzerAttribute(string firstLanguage, params string[] additionalLanguages) {} } public abstract class DiagnosticAnalyzer { public abstract System.Collections.Immutable.ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } public abstract void Initialize(AnalysisContext context); } public abstract class AnalysisContext { } } namespace Microsoft.CodeAnalysis { public sealed class DiagnosticDescriptor { } } "; var minSystemCollectionsImmutableImage = CSharpCompilation.Create( "System.Collections.Immutable", new[] { SyntaxFactory.ParseSyntaxTree(minSystemCollectionsImmutableSource) }, new MetadataReference[] { NetStandard13.SystemRuntime }, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, cryptoPublicKey: TestResources.TestKeys.PublicKey_b03f5f7f11d50a3a)).EmitToArray(); var minSystemCollectionsImmutableRef = MetadataReference.CreateFromImage(minSystemCollectionsImmutableImage); var minCodeAnalysisImage = CSharpCompilation.Create( "Microsoft.CodeAnalysis", new[] { SyntaxFactory.ParseSyntaxTree(minCodeAnalysisSource) }, new MetadataReference[] { NetStandard13.SystemRuntime, minSystemCollectionsImmutableRef }, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, cryptoPublicKey: TestResources.TestKeys.PublicKey_31bf3856ad364e35)).EmitToArray(); var minCodeAnalysisRef = MetadataReference.CreateFromImage(minCodeAnalysisImage); var analyzerSource = @" using System; using System.Collections.ObjectModel; using System.Collections.Immutable; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Net.Http; using System.Net.Security; using System.Net.Sockets; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security.AccessControl; using System.Security.Cryptography; using System.Security.Principal; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; using System.Xml.XPath; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.Win32.SafeHandles; [DiagnosticAnalyzer(""C#"")] public class TestAnalyzer : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => throw new NotImplementedException(new[] { typeof(Win32Exception), // Microsoft.Win32.Primitives typeof(AppContext), // System.AppContext typeof(Console), // System.Console typeof(ValueTuple), // System.ValueTuple typeof(FileVersionInfo), // System.Diagnostics.FileVersionInfo typeof(Process), // System.Diagnostics.Process typeof(ChineseLunisolarCalendar), // System.Globalization.Calendars typeof(ZipArchive), // System.IO.Compression typeof(ZipFile), // System.IO.Compression.ZipFile typeof(FileOptions), // System.IO.FileSystem typeof(FileAttributes), // System.IO.FileSystem.Primitives typeof(HttpClient), // System.Net.Http typeof(AuthenticatedStream), // System.Net.Security typeof(IOControlCode), // System.Net.Sockets typeof(RuntimeInformation), // System.Runtime.InteropServices.RuntimeInformation typeof(SerializationException), // System.Runtime.Serialization.Primitives typeof(GenericIdentity), // System.Security.Claims typeof(Aes), // System.Security.Cryptography.Algorithms typeof(CspParameters), // System.Security.Cryptography.Csp typeof(AsnEncodedData), // System.Security.Cryptography.Encoding typeof(AsymmetricAlgorithm), // System.Security.Cryptography.Primitives typeof(SafeX509ChainHandle), // System.Security.Cryptography.X509Certificates typeof(IXmlLineInfo), // System.Xml.ReaderWriter typeof(XmlNode), // System.Xml.XmlDocument typeof(XPathDocument), // System.Xml.XPath typeof(XDocumentExtensions), // System.Xml.XPath.XDocument typeof(CodePagesEncodingProvider),// System.Text.Encoding.CodePages typeof(ValueTask<>), // System.Threading.Tasks.Extensions // csc doesn't ship with facades for the following assemblies. // Analyzers can't use them unless they carry the facade with them. // typeof(SafePipeHandle), // System.IO.Pipes // typeof(StackFrame), // System.Diagnostics.StackTrace // typeof(BindingFlags), // System.Reflection.TypeExtensions // typeof(AccessControlActions), // System.Security.AccessControl // typeof(SafeAccessTokenHandle), // System.Security.Principal.Windows // typeof(Thread), // System.Threading.Thread }.Length.ToString()); public override void Initialize(AnalysisContext context) { } }"; var references = new MetadataReference[] { minCodeAnalysisRef, minSystemCollectionsImmutableRef }; references = references.Concat(NetStandard13.All).ToArray(); var analyzerImage = CSharpCompilation.Create( analyzerAssemblyName, new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree(analyzerSource) }, references: references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)).EmitToArray(); return analyzerImage; } [WorkItem(406649, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=484417")] [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void MicrosoftDiaSymReaderNativeAltLoadPath() { var dir = Temp.CreateDirectory(); var cscDir = Path.GetDirectoryName(s_CSharpCompilerExecutable); // copy csc and dependencies except for DSRN: foreach (var filePath in Directory.EnumerateFiles(cscDir)) { var fileName = Path.GetFileName(filePath); if (fileName.StartsWith("csc") || fileName.StartsWith("System.") || fileName.StartsWith("Microsoft.") && !fileName.StartsWith("Microsoft.DiaSymReader.Native")) { dir.CopyFile(filePath); } } dir.CreateFile("Source.cs").WriteAllText("class C { void F() { } }"); var cscCopy = Path.Combine(dir.Path, "csc.exe"); var arguments = "/nologo /t:library /debug:full Source.cs"; // env variable not set (deterministic) -- DSRN is required: var result = ProcessUtilities.Run(cscCopy, arguments + " /deterministic", workingDirectory: dir.Path); AssertEx.AssertEqualToleratingWhitespaceDifferences( "error CS0041: Unexpected error writing debug information -- 'Unable to load DLL 'Microsoft.DiaSymReader.Native.amd64.dll': " + "The specified module could not be found. (Exception from HRESULT: 0x8007007E)'", result.Output.Trim()); // env variable not set (non-deterministic) -- globally registered SymReader is picked up: result = ProcessUtilities.Run(cscCopy, arguments, workingDirectory: dir.Path); AssertEx.AssertEqualToleratingWhitespaceDifferences("", result.Output.Trim()); // env variable set: result = ProcessUtilities.Run( cscCopy, arguments + " /deterministic", workingDirectory: dir.Path, additionalEnvironmentVars: new[] { KeyValuePairUtil.Create("MICROSOFT_DIASYMREADER_NATIVE_ALT_LOAD_PATH", cscDir) }); Assert.Equal("", result.Output.Trim()); } [ConditionalFact(typeof(WindowsOnly))] [WorkItem(21935, "https://github.com/dotnet/roslyn/issues/21935")] public void PdbPathNotEmittedWithoutPdb() { var dir = Temp.CreateDirectory(); var source = @"class Program { static void Main() { } }"; var src = dir.CreateFile("a.cs").WriteAllText(source); var args = new[] { "/nologo", "a.cs", "/out:a.exe", "/debug-" }; var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, args); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var exePath = Path.Combine(dir.Path, "a.exe"); Assert.True(File.Exists(exePath)); using (var peStream = File.OpenRead(exePath)) using (var peReader = new PEReader(peStream)) { var debugDirectory = peReader.PEHeaders.PEHeader.DebugTableDirectory; Assert.Equal(0, debugDirectory.Size); Assert.Equal(0, debugDirectory.RelativeVirtualAddress); } } [Fact] public void StrongNameProviderWithCustomTempPath() { var tempDir = Temp.CreateDirectory(); var workingDir = Temp.CreateDirectory(); workingDir.CreateFile("a.cs"); var buildPaths = new BuildPaths(clientDir: "", workingDir: workingDir.Path, sdkDir: null, tempDir: tempDir.Path); var csc = new MockCSharpCompiler(null, buildPaths, args: new[] { "/features:UseLegacyStrongNameProvider", "/nostdlib", "a.cs" }); var comp = csc.CreateCompilation(new StringWriter(), new TouchedFileLogger(), errorLogger: null); Assert.True(!comp.SignUsingBuilder); } public class QuotedArgumentTests : CommandLineTestBase { private static readonly string s_rootPath = ExecutionConditionUtil.IsWindows ? @"c:\" : "/"; private void VerifyQuotedValid<T>(string name, string value, T expected, Func<CSharpCommandLineArguments, T> getValue) { var args = DefaultParse(new[] { $"/{name}:{value}", "a.cs" }, s_rootPath); Assert.Equal(0, args.Errors.Length); Assert.Equal(expected, getValue(args)); args = DefaultParse(new[] { $@"/{name}:""{value}""", "a.cs" }, s_rootPath); Assert.Equal(0, args.Errors.Length); Assert.Equal(expected, getValue(args)); } private void VerifyQuotedInvalid<T>(string name, string value, T expected, Func<CSharpCommandLineArguments, T> getValue) { var args = DefaultParse(new[] { $"/{name}:{value}", "a.cs" }, s_rootPath); Assert.Equal(0, args.Errors.Length); Assert.Equal(expected, getValue(args)); args = DefaultParse(new[] { $@"/{name}:""{value}""", "a.cs" }, s_rootPath); Assert.True(args.Errors.Length > 0); } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void DebugFlag() { var platformPdbKind = PathUtilities.IsUnixLikePlatform ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb; var list = new List<Tuple<string, DebugInformationFormat>>() { Tuple.Create("portable", DebugInformationFormat.PortablePdb), Tuple.Create("full", platformPdbKind), Tuple.Create("pdbonly", platformPdbKind), Tuple.Create("embedded", DebugInformationFormat.Embedded) }; foreach (var tuple in list) { VerifyQuotedValid("debug", tuple.Item1, tuple.Item2, x => x.EmitOptions.DebugInformationFormat); } } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30328")] public void CodePage() { VerifyQuotedValid("codepage", "1252", 1252, x => x.Encoding.CodePage); } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void Target() { var list = new List<Tuple<string, OutputKind>>() { Tuple.Create("exe", OutputKind.ConsoleApplication), Tuple.Create("winexe", OutputKind.WindowsApplication), Tuple.Create("library", OutputKind.DynamicallyLinkedLibrary), Tuple.Create("module", OutputKind.NetModule), Tuple.Create("appcontainerexe", OutputKind.WindowsRuntimeApplication), Tuple.Create("winmdobj", OutputKind.WindowsRuntimeMetadata) }; foreach (var tuple in list) { VerifyQuotedInvalid("target", tuple.Item1, tuple.Item2, x => x.CompilationOptions.OutputKind); } } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void PlatformFlag() { var list = new List<Tuple<string, Platform>>() { Tuple.Create("x86", Platform.X86), Tuple.Create("x64", Platform.X64), Tuple.Create("itanium", Platform.Itanium), Tuple.Create("anycpu", Platform.AnyCpu), Tuple.Create("anycpu32bitpreferred",Platform.AnyCpu32BitPreferred), Tuple.Create("arm", Platform.Arm) }; foreach (var tuple in list) { VerifyQuotedValid("platform", tuple.Item1, tuple.Item2, x => x.CompilationOptions.Platform); } } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void WarnFlag() { VerifyQuotedValid("warn", "1", 1, x => x.CompilationOptions.WarningLevel); } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void LangVersionFlag() { VerifyQuotedValid("langversion", "2", LanguageVersion.CSharp2, x => x.ParseOptions.LanguageVersion); } } [Fact] [WorkItem(23525, "https://github.com/dotnet/roslyn/issues/23525")] public void InvalidPathCharacterInPathMap() { string filePath = Temp.CreateFile().WriteAllText("").Path; var compiler = CreateCSharpCompiler(null, WorkingDirectory, new[] { filePath, "/debug:embedded", "/pathmap:test\\=\"", "/target:library", "/preferreduilang:en" }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = compiler.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS8101: The pathmap option was incorrectly formatted.", outWriter.ToString(), StringComparison.Ordinal); } [WorkItem(23525, "https://github.com/dotnet/roslyn/issues/23525")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void InvalidPathCharacterInPdbPath() { string filePath = Temp.CreateFile().WriteAllText("").Path; var compiler = CreateCSharpCompiler(null, WorkingDirectory, new[] { filePath, "/debug:embedded", "/pdb:test\\?.pdb", "/target:library", "/preferreduilang:en" }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = compiler.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS2021: File name 'test\\?.pdb' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long", outWriter.ToString(), StringComparison.Ordinal); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [ConditionalFact(typeof(IsEnglishLocal))] public void TestSuppression_CompilerParserWarningAsError() { string source = @" class C { long M(int i) { // warning CS0078 : The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity return 0l; } } "; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that parser warning CS0078 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("warning CS0078", output, StringComparison.Ordinal); // Verify that parser warning CS0078 is reported as error for /warnaserror. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("error CS0078", output, StringComparison.Ordinal); // Verify that parser warning CS0078 is suppressed with diagnostic suppressor even with /warnaserror // and info diagnostic is logged with programmatic suppression information. var suppressor = new DiagnosticSuppressorForId("CS0078"); output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, expectedErrorCount: 0, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, analyzers: suppressor); Assert.DoesNotContain($"error CS0078", output, StringComparison.Ordinal); Assert.DoesNotContain($"warning CS0078", output, StringComparison.Ordinal); // Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.WRN_LowercaseEllSuffix, "l"), Location.None).GetMessage(CultureInfo.InvariantCulture), suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [ConditionalFact(typeof(IsEnglishLocal))] public void TestSuppression_CompilerSyntaxWarning() { // warning CS1522: Empty switch block // NOTE: Empty switch block warning is reported by the C# language parser string source = @" class C { void M(int i) { switch (i) { } } }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that compiler warning CS1522 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("warning CS1522", output, StringComparison.Ordinal); // Verify that compiler warning CS1522 is suppressed with diagnostic suppressor // and info diagnostic is logged with programmatic suppression information. var suppressor = new DiagnosticSuppressorForId("CS1522"); // Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.WRN_EmptySwitch), Location.None).GetMessage(CultureInfo.InvariantCulture), suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification); output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: suppressor, errorlog: true); Assert.DoesNotContain($"warning CS1522", output, StringComparison.Ordinal); Assert.Contains($"info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); // Verify that compiler warning CS1522 is reported as error for /warnaserror. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("error CS1522", output, StringComparison.Ordinal); // Verify that compiler warning CS1522 is suppressed with diagnostic suppressor even with /warnaserror // and info diagnostic is logged with programmatic suppression information. output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, expectedErrorCount: 0, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, analyzers: suppressor); Assert.DoesNotContain($"error CS1522", output, StringComparison.Ordinal); Assert.DoesNotContain($"warning CS1522", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [ConditionalFact(typeof(IsEnglishLocal))] public void TestSuppression_CompilerSemanticWarning() { string source = @" class C { // warning CS0169: The field 'C.f' is never used private readonly int f; }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that compiler warning CS0169 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("warning CS0169", output, StringComparison.Ordinal); // Verify that compiler warning CS0169 is suppressed with diagnostic suppressor // and info diagnostic is logged with programmatic suppression information. var suppressor = new DiagnosticSuppressorForId("CS0169"); // Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.WRN_UnreferencedField, "C.f"), Location.None).GetMessage(CultureInfo.InvariantCulture), suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification); output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: suppressor, errorlog: true); Assert.DoesNotContain($"warning CS0169", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); // Verify that compiler warning CS0169 is reported as error for /warnaserror. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("error CS0169", output, StringComparison.Ordinal); // Verify that compiler warning CS0169 is suppressed with diagnostic suppressor even with /warnaserror // and info diagnostic is logged with programmatic suppression information. output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, expectedErrorCount: 0, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, analyzers: suppressor); Assert.DoesNotContain($"error CS0169", output, StringComparison.Ordinal); Assert.DoesNotContain($"warning CS0169", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [Fact] public void TestNoSuppression_CompilerSyntaxError() { // error CS1001: Identifier expected string source = @" class { }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that compiler syntax error CS1001 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("error CS1001", output, StringComparison.Ordinal); // Verify that compiler syntax error CS1001 cannot be suppressed with diagnostic suppressor. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: new DiagnosticSuppressorForId("CS1001")); Assert.Contains("error CS1001", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [Fact] public void TestNoSuppression_CompilerSemanticError() { // error CS0246: The type or namespace name 'UndefinedType' could not be found (are you missing a using directive or an assembly reference?) string source = @" class C { void M(UndefinedType x) { } }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that compiler error CS0246 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("error CS0246", output, StringComparison.Ordinal); // Verify that compiler error CS0246 cannot be suppressed with diagnostic suppressor. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: new DiagnosticSuppressorForId("CS0246")); Assert.Contains("error CS0246", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [ConditionalFact(typeof(IsEnglishLocal))] public void TestSuppression_AnalyzerWarning() { string source = @" class C { }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that analyzer warning is reported. var analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Warning, configurable: true); var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzer); Assert.Contains($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); // Verify that analyzer warning is suppressed with diagnostic suppressor // and info diagnostic is logged with programmatic suppression information. var suppressor = new DiagnosticSuppressorForId(analyzer.Descriptor.Id); // Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, analyzer.Descriptor.MessageFormat, suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification); var analyzerAndSuppressor = new DiagnosticAnalyzer[] { analyzer, suppressor }; output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, analyzers: analyzerAndSuppressor); Assert.DoesNotContain($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); // Verify that analyzer warning is reported as error for /warnaserror. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzer); Assert.Contains($"error {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); // Verify that analyzer warning is suppressed with diagnostic suppressor even with /warnaserror // and info diagnostic is logged with programmatic suppression information. output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, analyzers: analyzerAndSuppressor); Assert.DoesNotContain($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); // Verify that "NotConfigurable" analyzer warning cannot be suppressed with diagnostic suppressor. analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Warning, configurable: false); suppressor = new DiagnosticSuppressorForId(analyzer.Descriptor.Id); analyzerAndSuppressor = new DiagnosticAnalyzer[] { analyzer, suppressor }; output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzerAndSuppressor); Assert.Contains($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [Fact] public void TestNoSuppression_AnalyzerError() { string source = @" class C { }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that analyzer error is reported. var analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Error, configurable: true); var output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzer); Assert.Contains($"error {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); // Verify that analyzer error cannot be suppressed with diagnostic suppressor. var suppressor = new DiagnosticSuppressorForId(analyzer.Descriptor.Id); var analyzerAndSuppressor = new DiagnosticAnalyzer[] { analyzer, suppressor }; output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzerAndSuppressor); Assert.Contains($"error {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(38674, "https://github.com/dotnet/roslyn/issues/38674")] [InlineData(DiagnosticSeverity.Warning, false)] [InlineData(DiagnosticSeverity.Info, true)] [InlineData(DiagnosticSeverity.Info, false)] [InlineData(DiagnosticSeverity.Hidden, false)] [Theory] public void TestCategoryBasedBulkAnalyzerDiagnosticConfiguration(DiagnosticSeverity defaultSeverity, bool errorlog) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity); var diagnosticId = analyzer.Descriptor.Id; var category = analyzer.Descriptor.Category; // Verify category based configuration without any diagnostic ID configuration is respected. var analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error); // Verify category based configuration does not get applied for suppressed diagnostic. TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress, noWarn: true); // Verify category based configuration does not get applied for diagnostic configured in ruleset. var rulesetText = $@"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis""> <Rule Id=""{diagnosticId}"" Action=""Warning"" /> </Rules> </RuleSet>"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn, rulesetText: rulesetText); // Verify category based configuration before diagnostic ID configuration is not respected. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = error dotnet_diagnostic.{diagnosticId}.severity = warning"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify category based configuration after diagnostic ID configuration is not respected. analyzerConfigText = $@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = warning dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify global config based configuration before diagnostic ID configuration is not respected. analyzerConfigText = $@" is_global = true dotnet_analyzer_diagnostic.category-{category}.severity = error dotnet_diagnostic.{diagnosticId}.severity = warning"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify global config based configuration after diagnostic ID configuration is not respected. analyzerConfigText = $@" is_global = true dotnet_diagnostic.{diagnosticId}.severity = warning dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify disabled by default analyzer is not enabled by category based configuration. analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: false, defaultSeverity); analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); // Verify disabled by default analyzer is not enabled by category based configuration in global config analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: false, defaultSeverity); analyzerConfigText = $@" is_global=true dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); if (defaultSeverity == DiagnosticSeverity.Hidden || defaultSeverity == DiagnosticSeverity.Info && !errorlog) { // Verify analyzer with Hidden severity OR Info severity + no /errorlog is not executed. analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: true); TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText: string.Empty, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); // Verify that bulk configuration 'none' entry does not enable this analyzer. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = none"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); // Verify that bulk configuration 'none' entry does not enable this analyzer via global config analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = none"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); } } [WorkItem(38674, "https://github.com/dotnet/roslyn/issues/38674")] [InlineData(DiagnosticSeverity.Warning, false)] [InlineData(DiagnosticSeverity.Info, true)] [InlineData(DiagnosticSeverity.Info, false)] [InlineData(DiagnosticSeverity.Hidden, false)] [Theory] public void TestBulkAnalyzerDiagnosticConfiguration(DiagnosticSeverity defaultSeverity, bool errorlog) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity); var diagnosticId = analyzer.Descriptor.Id; // Verify bulk configuration without any diagnostic ID configuration is respected. var analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error); // Verify bulk configuration does not get applied for suppressed diagnostic. TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress, noWarn: true); // Verify bulk configuration does not get applied for diagnostic configured in ruleset. var rulesetText = $@"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis""> <Rule Id=""{diagnosticId}"" Action=""Warning"" /> </Rules> </RuleSet>"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn, rulesetText: rulesetText); // Verify bulk configuration before diagnostic ID configuration is not respected. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = error dotnet_diagnostic.{diagnosticId}.severity = warning"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify bulk configuration after diagnostic ID configuration is not respected. analyzerConfigText = $@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = warning dotnet_analyzer_diagnostic.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify disabled by default analyzer is not enabled by bulk configuration. analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: false, defaultSeverity); analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); if (defaultSeverity == DiagnosticSeverity.Hidden || defaultSeverity == DiagnosticSeverity.Info && !errorlog) { // Verify analyzer with Hidden severity OR Info severity + no /errorlog is not executed. analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: true); TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText: string.Empty, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); // Verify that bulk configuration 'none' entry does not enable this analyzer. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = none"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); } } [WorkItem(38674, "https://github.com/dotnet/roslyn/issues/38674")] [InlineData(DiagnosticSeverity.Warning, false)] [InlineData(DiagnosticSeverity.Info, true)] [InlineData(DiagnosticSeverity.Info, false)] [InlineData(DiagnosticSeverity.Hidden, false)] [Theory] public void TestMixedCategoryBasedAndBulkAnalyzerDiagnosticConfiguration(DiagnosticSeverity defaultSeverity, bool errorlog) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity); var diagnosticId = analyzer.Descriptor.Id; var category = analyzer.Descriptor.Category; // Verify category based configuration before bulk analyzer diagnostic configuration is respected. var analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = error dotnet_analyzer_diagnostic.severity = warning"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error); // Verify category based configuration after bulk analyzer diagnostic configuration is respected. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = warning dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error); // Verify neither category based nor bulk diagnostic configuration is respected when specific diagnostic ID is configured in analyzer config. analyzerConfigText = $@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = warning dotnet_analyzer_diagnostic.category-{category}.severity = none dotnet_analyzer_diagnostic.severity = suggestion"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify neither category based nor bulk diagnostic configuration is respected when specific diagnostic ID is configured in ruleset. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = none dotnet_analyzer_diagnostic.severity = suggestion"; var rulesetText = $@"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis""> <Rule Id=""{diagnosticId}"" Action=""Warning"" /> </Rules> </RuleSet>"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn, rulesetText); } private void TestBulkAnalyzerConfigurationCore( NamedTypeAnalyzerWithConfigurableEnabledByDefault analyzer, string analyzerConfigText, bool errorlog, ReportDiagnostic expectedDiagnosticSeverity, string rulesetText = null, bool noWarn = false) { var diagnosticId = analyzer.Descriptor.Id; var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(analyzerConfigText); var arguments = new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path }; if (noWarn) { arguments = arguments.Append($"/nowarn:{diagnosticId}"); } if (errorlog) { arguments = arguments.Append($"/errorlog:errorlog"); } if (rulesetText != null) { var rulesetFile = CreateRuleSetFile(rulesetText); arguments = arguments.Append($"/ruleset:{rulesetFile.Path}"); } var cmd = CreateCSharpCompiler(null, dir.Path, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var expectedErrorCode = expectedDiagnosticSeverity == ReportDiagnostic.Error ? 1 : 0; Assert.Equal(expectedErrorCode, exitCode); var prefix = expectedDiagnosticSeverity switch { ReportDiagnostic.Error => "error", ReportDiagnostic.Warn => "warning", ReportDiagnostic.Info => errorlog ? "info" : null, ReportDiagnostic.Hidden => null, ReportDiagnostic.Suppress => null, _ => throw ExceptionUtilities.UnexpectedValue(expectedDiagnosticSeverity) }; if (prefix == null) { Assert.DoesNotContain(diagnosticId, outWriter.ToString()); } else { Assert.Contains($"{prefix} {diagnosticId}: {analyzer.Descriptor.MessageFormat}", outWriter.ToString()); } } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void CompilerWarnAsErrorDoesNotEmit(bool warnAsError) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { int _f; // CS0169: unused field }"); var docName = "temp.xml"; var pdbName = "temp.pdb"; var additionalArgs = new[] { $"/doc:{docName}", $"/pdb:{pdbName}", "/debug" }; if (warnAsError) { additionalArgs = additionalArgs.Append("/warnaserror").AsArray(); } var expectedErrorCount = warnAsError ? 1 : 0; var expectedWarningCount = !warnAsError ? 1 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectedErrorCount, expectedWarningCount: expectedWarningCount); var expectedOutput = warnAsError ? "error CS0169" : "warning CS0169"; Assert.Contains(expectedOutput, output); string binaryPath = Path.Combine(dir.Path, "temp.dll"); Assert.True(File.Exists(binaryPath) == !warnAsError); string pdbPath = Path.Combine(dir.Path, pdbName); Assert.True(File.Exists(pdbPath) == !warnAsError); string xmlDocFilePath = Path.Combine(dir.Path, docName); Assert.True(File.Exists(xmlDocFilePath) == !warnAsError); } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void AnalyzerConfigSeverityEscalationToErrorDoesNotEmit(bool analyzerConfigSetToError) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { int _f; // CS0169: unused field }"); var docName = "temp.xml"; var pdbName = "temp.pdb"; var additionalArgs = new[] { $"/doc:{docName}", $"/pdb:{pdbName}", "/debug" }; if (analyzerConfigSetToError) { var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.cs0169.severity = error"); additionalArgs = additionalArgs.Append("/analyzerconfig:" + analyzerConfig.Path).ToArray(); } var expectedErrorCount = analyzerConfigSetToError ? 1 : 0; var expectedWarningCount = !analyzerConfigSetToError ? 1 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectedErrorCount, expectedWarningCount: expectedWarningCount); var expectedOutput = analyzerConfigSetToError ? "error CS0169" : "warning CS0169"; Assert.Contains(expectedOutput, output); string binaryPath = Path.Combine(dir.Path, "temp.dll"); Assert.True(File.Exists(binaryPath) == !analyzerConfigSetToError); string pdbPath = Path.Combine(dir.Path, pdbName); Assert.True(File.Exists(pdbPath) == !analyzerConfigSetToError); string xmlDocFilePath = Path.Combine(dir.Path, docName); Assert.True(File.Exists(xmlDocFilePath) == !analyzerConfigSetToError); } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void RulesetSeverityEscalationToErrorDoesNotEmit(bool rulesetSetToError) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { int _f; // CS0169: unused field }"); var docName = "temp.xml"; var pdbName = "temp.pdb"; var additionalArgs = new[] { $"/doc:{docName}", $"/pdb:{pdbName}", "/debug" }; if (rulesetSetToError) { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis""> <Rule Id=""CS0169"" Action=""Error"" /> </Rules> </RuleSet> "; var rulesetFile = CreateRuleSetFile(source); additionalArgs = additionalArgs.Append("/ruleset:" + rulesetFile.Path).ToArray(); } var expectedErrorCount = rulesetSetToError ? 1 : 0; var expectedWarningCount = !rulesetSetToError ? 1 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectedErrorCount, expectedWarningCount: expectedWarningCount); var expectedOutput = rulesetSetToError ? "error CS0169" : "warning CS0169"; Assert.Contains(expectedOutput, output); string binaryPath = Path.Combine(dir.Path, "temp.dll"); Assert.True(File.Exists(binaryPath) == !rulesetSetToError); string pdbPath = Path.Combine(dir.Path, pdbName); Assert.True(File.Exists(pdbPath) == !rulesetSetToError); string xmlDocFilePath = Path.Combine(dir.Path, docName); Assert.True(File.Exists(xmlDocFilePath) == !rulesetSetToError); } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void AnalyzerWarnAsErrorDoesNotEmit(bool warnAsError) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText("class C { }"); var additionalArgs = warnAsError ? new[] { "/warnaserror" } : null; var expectedErrorCount = warnAsError ? 1 : 0; var expectedWarningCount = !warnAsError ? 1 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectedErrorCount, expectedWarningCount: expectedWarningCount, analyzers: new[] { new WarningDiagnosticAnalyzer() }); var expectedDiagnosticSeverity = warnAsError ? "error" : "warning"; Assert.Contains($"{expectedDiagnosticSeverity} {WarningDiagnosticAnalyzer.Warning01.Id}", output); string binaryPath = Path.Combine(dir.Path, "temp.dll"); Assert.True(File.Exists(binaryPath) == !warnAsError); } // Currently, configuring no location diagnostics through editorconfig is not supported. [Theory(Skip = "https://github.com/dotnet/roslyn/issues/38042")] [CombinatorialData] public void AnalyzerConfigRespectedForNoLocationDiagnostic(ReportDiagnostic reportDiagnostic, bool isEnabledByDefault, bool noWarn, bool errorlog) { var analyzer = new AnalyzerWithNoLocationDiagnostics(isEnabledByDefault); TestAnalyzerConfigRespectedCore(analyzer, analyzer.Descriptor, reportDiagnostic, noWarn, errorlog); } [WorkItem(37876, "https://github.com/dotnet/roslyn/issues/37876")] [Theory] [CombinatorialData] public void AnalyzerConfigRespectedForDisabledByDefaultDiagnostic(ReportDiagnostic analyzerConfigSeverity, bool isEnabledByDefault, bool noWarn, bool errorlog) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault, defaultSeverity: DiagnosticSeverity.Warning); TestAnalyzerConfigRespectedCore(analyzer, analyzer.Descriptor, analyzerConfigSeverity, noWarn, errorlog); } private void TestAnalyzerConfigRespectedCore(DiagnosticAnalyzer analyzer, DiagnosticDescriptor descriptor, ReportDiagnostic analyzerConfigSeverity, bool noWarn, bool errorlog) { if (analyzerConfigSeverity == ReportDiagnostic.Default) { // "dotnet_diagnostic.ID.severity = default" is not supported. return; } var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText($@" [*.cs] dotnet_diagnostic.{descriptor.Id}.severity = {analyzerConfigSeverity.ToAnalyzerConfigString()}"); var arguments = new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path }; if (noWarn) { arguments = arguments.Append($"/nowarn:{descriptor.Id}"); } if (errorlog) { arguments = arguments.Append($"/errorlog:errorlog"); } var cmd = CreateCSharpCompiler(null, dir.Path, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var expectedErrorCode = !noWarn && analyzerConfigSeverity == ReportDiagnostic.Error ? 1 : 0; Assert.Equal(expectedErrorCode, exitCode); // NOTE: Info diagnostics are only logged on command line when /errorlog is specified. See https://github.com/dotnet/roslyn/issues/42166 for details. if (!noWarn && (analyzerConfigSeverity == ReportDiagnostic.Error || analyzerConfigSeverity == ReportDiagnostic.Warn || (analyzerConfigSeverity == ReportDiagnostic.Info && errorlog))) { var prefix = analyzerConfigSeverity == ReportDiagnostic.Error ? "error" : analyzerConfigSeverity == ReportDiagnostic.Warn ? "warning" : "info"; Assert.Contains($"{prefix} {descriptor.Id}: {descriptor.MessageFormat}", outWriter.ToString()); } else { Assert.DoesNotContain(descriptor.Id.ToString(), outWriter.ToString()); } } [Fact] [WorkItem(3705, "https://github.com/dotnet/roslyn/issues/3705")] public void IsUserConfiguredGeneratedCodeInAnalyzerConfig() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M(C? c) { _ = c.ToString(); // warning CS8602: Dereference of a possibly null reference. } }"); var output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable" }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning CS8602: Dereference of a possibly null reference. Assert.Contains("warning CS8602", output, StringComparison.Ordinal); // generated_code = true var analyzerConfigFile = dir.CreateFile(".editorconfig"); var analyzerConfig = analyzerConfigFile.WriteAllText(@" [*.cs] generated_code = true"); output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable", "/analyzerconfig:" + analyzerConfig.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.DoesNotContain("warning CS8602", output, StringComparison.Ordinal); // warning CS8669: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. Auto-generated code requires an explicit '#nullable' directive in source. Assert.Contains("warning CS8669", output, StringComparison.Ordinal); // generated_code = false analyzerConfig = analyzerConfigFile.WriteAllText(@" [*.cs] generated_code = false"); output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable", "/analyzerconfig:" + analyzerConfig.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning CS8602: Dereference of a possibly null reference. Assert.Contains("warning CS8602", output, StringComparison.Ordinal); // generated_code = auto analyzerConfig = analyzerConfigFile.WriteAllText(@" [*.cs] generated_code = auto"); output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable", "/analyzerconfig:" + analyzerConfig.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning CS8602: Dereference of a possibly null reference. Assert.Contains("warning CS8602", output, StringComparison.Ordinal); } [WorkItem(42166, "https://github.com/dotnet/roslyn/issues/42166")] [CombinatorialData, Theory] public void TestAnalyzerFilteringBasedOnSeverity(DiagnosticSeverity defaultSeverity, bool errorlog) { // This test verifies that analyzer execution is skipped at build time for the following: // 1. Analyzer reporting Hidden diagnostics // 2. Analyzer reporting Info diagnostics, when /errorlog is not specified var analyzerShouldBeSkipped = defaultSeverity == DiagnosticSeverity.Hidden || defaultSeverity == DiagnosticSeverity.Info && !errorlog; // We use an analyzer that throws an exception on every analyzer callback. // So an AD0001 analyzer exception diagnostic is reported if analyzer executed, otherwise not. var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: true); var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); var args = new[] { "/nologo", "/t:library", "/preferreduilang:en", src.Path }; if (errorlog) args = args.Append("/errorlog:errorlog"); var cmd = CreateCSharpCompiler(null, dir.Path, args, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); if (analyzerShouldBeSkipped) { Assert.Empty(output); } else { Assert.Contains("warning AD0001: Analyzer 'Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers+NamedTypeAnalyzerWithConfigurableEnabledByDefault' threw an exception of type 'System.NotImplementedException'", output, StringComparison.Ordinal); } } [WorkItem(47017, "https://github.com/dotnet/roslyn/issues/47017")] [CombinatorialData, Theory] public void TestWarnAsErrorMinusDoesNotEnableDisabledByDefaultAnalyzers(DiagnosticSeverity defaultSeverity, bool isEnabledByDefault) { // This test verifies that '/warnaserror-:DiagnosticId' does not affect if analyzers are executed or skipped.. // Setup the analyzer to always throw an exception on analyzer callbacks for cases where we expect analyzer execution to be skipped: // 1. Disabled by default analyzer, i.e. 'isEnabledByDefault == false'. // 2. Default severity Hidden/Info: We only execute analyzers reporting Warning/Error severity diagnostics on command line builds. var analyzerShouldBeSkipped = !isEnabledByDefault || defaultSeverity == DiagnosticSeverity.Hidden || defaultSeverity == DiagnosticSeverity.Info; var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault, defaultSeverity, throwOnAllNamedTypes: analyzerShouldBeSkipped); var diagnosticId = analyzer.Descriptor.Id; var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); // Verify '/warnaserror-:DiagnosticId' behavior. var args = new[] { "/warnaserror+", $"/warnaserror-:{diagnosticId}", "/nologo", "/t:library", "/preferreduilang:en", src.Path }; var cmd = CreateCSharpCompiler(null, dir.Path, args, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var expectedExitCode = !analyzerShouldBeSkipped && defaultSeverity == DiagnosticSeverity.Error ? 1 : 0; Assert.Equal(expectedExitCode, exitCode); var output = outWriter.ToString(); if (analyzerShouldBeSkipped) { Assert.Empty(output); } else { var prefix = defaultSeverity == DiagnosticSeverity.Warning ? "warning" : "error"; Assert.Contains($"{prefix} {diagnosticId}: {analyzer.Descriptor.MessageFormat}", output); } } [WorkItem(49446, "https://github.com/dotnet/roslyn/issues/49446")] [Theory] // Verify '/warnaserror-:ID' prevents escalation to 'Error' when config file bumps severity to 'Warning' [InlineData(false, DiagnosticSeverity.Info, DiagnosticSeverity.Warning, DiagnosticSeverity.Error)] [InlineData(true, DiagnosticSeverity.Info, DiagnosticSeverity.Warning, DiagnosticSeverity.Warning)] // Verify '/warnaserror-:ID' prevents escalation to 'Error' when default severity is 'Warning' and no config file setting is specified. [InlineData(false, DiagnosticSeverity.Warning, null, DiagnosticSeverity.Error)] [InlineData(true, DiagnosticSeverity.Warning, null, DiagnosticSeverity.Warning)] // Verify '/warnaserror-:ID' prevents escalation to 'Error' when default severity is 'Warning' and config file bumps severity to 'Error' [InlineData(false, DiagnosticSeverity.Warning, DiagnosticSeverity.Error, DiagnosticSeverity.Error)] [InlineData(true, DiagnosticSeverity.Warning, DiagnosticSeverity.Error, DiagnosticSeverity.Warning)] // Verify '/warnaserror-:ID' has no effect when default severity is 'Info' and config file bumps severity to 'Error' [InlineData(false, DiagnosticSeverity.Info, DiagnosticSeverity.Error, DiagnosticSeverity.Error)] [InlineData(true, DiagnosticSeverity.Info, DiagnosticSeverity.Error, DiagnosticSeverity.Error)] public void TestWarnAsErrorMinusDoesNotNullifyEditorConfig( bool warnAsErrorMinus, DiagnosticSeverity defaultSeverity, DiagnosticSeverity? severityInConfigFile, DiagnosticSeverity expectedEffectiveSeverity) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: false); var diagnosticId = analyzer.Descriptor.Id; var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); var additionalFlags = new[] { "/warnaserror+" }; if (severityInConfigFile.HasValue) { var severityString = DiagnosticDescriptor.MapSeverityToReport(severityInConfigFile.Value).ToAnalyzerConfigString(); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText($@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = {severityString}"); additionalFlags = additionalFlags.Append($"/analyzerconfig:{analyzerConfig.Path}").ToArray(); } if (warnAsErrorMinus) { additionalFlags = additionalFlags.Append($"/warnaserror-:{diagnosticId}").ToArray(); } int expectedWarningCount = 0, expectedErrorCount = 0; switch (expectedEffectiveSeverity) { case DiagnosticSeverity.Warning: expectedWarningCount = 1; break; case DiagnosticSeverity.Error: expectedErrorCount = 1; break; default: throw ExceptionUtilities.UnexpectedValue(expectedEffectiveSeverity); } VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, expectedWarningCount: expectedWarningCount, expectedErrorCount: expectedErrorCount, additionalFlags: additionalFlags, analyzers: new[] { analyzer }); } [Fact] public void SourceGenerators_EmbeddedSources() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/debug:embedded", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); ValidateEmbeddedSources_Portable(new Dictionary<string, string> { { Path.Combine(dir.Path, generatorPrefix, $"generatedSource.cs"), generatedSource } }, dir, true); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Theory, CombinatorialData] [WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")] public void TestSourceGeneratorsWithAnalyzers(bool includeCurrentAssemblyAsAnalyzerReference, bool skipAnalyzers) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); // 'skipAnalyzers' should have no impact on source generator execution, but should prevent analyzer execution. var skipAnalyzersFlag = "/skipAnalyzers" + (skipAnalyzers ? "+" : "-"); // Verify analyzers were executed only if both the following conditions were satisfied: // 1. Current assembly was added as an analyzer reference, i.e. "includeCurrentAssemblyAsAnalyzerReference = true" and // 2. We did not explicitly request skipping analyzers, i.e. "skipAnalyzers = false". var expectedAnalyzerExecution = includeCurrentAssemblyAsAnalyzerReference && !skipAnalyzers; // 'WarningDiagnosticAnalyzer' generates a warning for each named type. // We expect two warnings for this test: type "C" defined in source and the source generator defined type. // Additionally, we also have an analyzer that generates "warning CS8032: An instance of analyzer cannot be created" var expectedWarningCount = expectedAnalyzerExecution ? 3 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference, expectedWarningCount: expectedWarningCount, additionalFlags: new[] { "/debug:embedded", "/out:embed.exe", skipAnalyzersFlag }, generators: new[] { generator }); // Verify source generator was executed, regardless of the value of 'skipAnalyzers'. var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); ValidateEmbeddedSources_Portable(new Dictionary<string, string> { { Path.Combine(dir.Path, generatorPrefix, "generatedSource.cs"), generatedSource } }, dir, true); if (expectedAnalyzerExecution) { Assert.Contains("warning Warning01", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); } else { Assert.Empty(output); } // Clean up temp files CleanupAllGeneratedFiles(src.Path); } [Theory] [InlineData("partial class D {}", "file1.cs", "partial class E {}", "file2.cs")] // different files, different names [InlineData("partial class D {}", "file1.cs", "partial class E {}", "file1.cs")] // different files, same names [InlineData("partial class D {}", "file1.cs", "partial class D {}", "file2.cs")] // same files, different names [InlineData("partial class D {}", "file1.cs", "partial class D {}", "file1.cs")] // same files, same names [InlineData("partial class D {}", "file1.cs", "", "file2.cs")] // empty second file public void SourceGenerators_EmbeddedSources_MultipleFiles(string source1, string source1Name, string source2, string source2Name) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generator = new SingleFileTestGenerator(source1, source1Name); var generator2 = new SingleFileTestGenerator2(source2, source2Name); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/debug:embedded", "/out:embed.exe" }, generators: new[] { generator, generator2 }, analyzers: null); var generator1Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); var generator2Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator2); ValidateEmbeddedSources_Portable(new Dictionary<string, string> { { Path.Combine(dir.Path, generator1Prefix, source1Name), source1}, { Path.Combine(dir.Path, generator2Prefix, source2Name), source2}, }, dir, true); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_WriteGeneratedSources() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource } } } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_OverwriteGeneratedSources() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generatedSource1 = "class D { } class E { }"; var generator1 = new SingleFileTestGenerator(generatedSource1, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator1 }, analyzers: null); var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator1); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource1 } } } }); var generatedSource2 = "public class D { }"; var generator2 = new SingleFileTestGenerator(generatedSource2, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator2 }, analyzers: null); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource2 } } } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Theory] [InlineData("partial class D {}", "file1.cs", "partial class E {}", "file2.cs")] // different files, different names [InlineData("partial class D {}", "file1.cs", "partial class E {}", "file1.cs")] // different files, same names [InlineData("partial class D {}", "file1.cs", "partial class D {}", "file2.cs")] // same files, different names [InlineData("partial class D {}", "file1.cs", "partial class D {}", "file1.cs")] // same files, same names [InlineData("partial class D {}", "file1.cs", "", "file2.cs")] // empty second file public void SourceGenerators_WriteGeneratedSources_MultipleFiles(string source1, string source1Name, string source2, string source2Name) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generator = new SingleFileTestGenerator(source1, source1Name); var generator2 = new SingleFileTestGenerator2(source2, source2Name); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator, generator2 }, analyzers: null); var generator1Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); var generator2Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator2); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generator1Prefix), new() { { source1Name, source1 } } }, { Path.Combine(generatedDir.Path, generator2Prefix), new() { { source2Name, source2 } } } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [ConditionalFact(typeof(DesktopClrOnly))] //CoreCLR doesn't support SxS loading [WorkItem(47990, "https://github.com/dotnet/roslyn/issues/47990")] public void SourceGenerators_SxS_AssemblyLoading() { // compile the generators var dir = Temp.CreateDirectory(); var snk = Temp.CreateFile("TestKeyPair_", ".snk", dir.Path).WriteAllBytes(TestResources.General.snKey); var src = dir.CreateFile("generator.cs"); var virtualSnProvider = new DesktopStrongNameProvider(ImmutableArray.Create(dir.Path)); string createGenerator(string version) { var generatorSource = $@" using Microsoft.CodeAnalysis; [assembly:System.Reflection.AssemblyVersion(""{version}"")] [Generator] public class TestGenerator : ISourceGenerator {{ public void Execute(GeneratorExecutionContext context) {{ context.AddSource(""generatedSource.cs"", ""//from version {version}""); }} public void Initialize(GeneratorInitializationContext context) {{ }} }}"; var path = Path.Combine(dir.Path, Guid.NewGuid().ToString() + ".dll"); var comp = CreateEmptyCompilation(source: generatorSource, references: TargetFrameworkUtil.NetStandard20References.Add(MetadataReference.CreateFromAssemblyInternal(typeof(ISourceGenerator).Assembly)), options: TestOptions.DebugDll.WithCryptoKeyFile(Path.GetFileName(snk.Path)).WithStrongNameProvider(virtualSnProvider), assemblyName: "generator"); comp.VerifyDiagnostics(); comp.Emit(path); return path; } var gen1 = createGenerator("1.0.0.0"); var gen2 = createGenerator("2.0.0.0"); var generatedDir = dir.CreateDirectory("generated"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/analyzer:" + gen1, "/analyzer:" + gen2 }.ToArray()); // This is wrong! Both generators are writing the same file out, over the top of each other // See https://github.com/dotnet/roslyn/issues/47990 ValidateWrittenSources(new() { // { Path.Combine(generatedDir.Path, "generator", "TestGenerator"), new() { { "generatedSource.cs", "//from version 1.0.0.0" } } }, { Path.Combine(generatedDir.Path, "generator", "TestGenerator"), new() { { "generatedSource.cs", "//from version 2.0.0.0" } } } }); } [Fact] public void SourceGenerators_DoNotWriteGeneratedSources_When_No_Directory_Supplied() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); ValidateWrittenSources(new() { { generatedDir.Path, new() } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_Error_When_GeneratedDir_NotExist() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDirPath = Path.Combine(dir.Path, "noexist"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); var output = VerifyOutput(dir, src, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDirPath, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); Assert.Contains("CS0016:", output); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_GeneratedDir_Has_Spaces() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated files"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource } } } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void ParseGeneratedFilesOut() { string root = PathUtilities.IsUnixLikePlatform ? "/" : "c:\\"; string baseDirectory = Path.Combine(root, "abc", "def"); var parsedArgs = DefaultParse(new[] { @"/generatedfilesout:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/generatedfilesout:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/generatedfilesout:")); Assert.Null(parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/generatedfilesout:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/generatedfilesout:\"\"")); Assert.Null(parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:outdir", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "outdir"), parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:""outdir""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "outdir"), parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:out dir", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "out dir"), parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:""out dir""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "out dir"), parsedArgs.GeneratedFilesOutputDirectory); var absPath = Path.Combine(root, "outdir"); parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:{absPath}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:""{absPath}""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory); absPath = Path.Combine(root, "generated files"); parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:{absPath}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:""{absPath}""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory); } [Fact] public void SourceGenerators_Error_When_NoDirectoryArgumentGiven() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var output = VerifyOutput(dir, src, expectedErrorCount: 2, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:", "/langversion:preview", "/out:embed.exe" }); Assert.Contains("error CS2006: Command-line syntax error: Missing '<text>' for '/generatedfilesout:' option", output); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_ReportedWrittenFiles_To_TouchedFilesLogger() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, $"/touchedfiles:{dir.Path}/touched", "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); var touchedFiles = Directory.GetFiles(dir.Path, "touched*"); Assert.Equal(2, touchedFiles.Length); string[] writtenText = File.ReadAllLines(Path.Combine(dir.Path, "touched.write")); Assert.Equal(2, writtenText.Length); Assert.EndsWith("EMBED.EXE", writtenText[0], StringComparison.OrdinalIgnoreCase); Assert.EndsWith("GENERATEDSOURCE.CS", writtenText[1], StringComparison.OrdinalIgnoreCase); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44087")] public void SourceGeneratorsAndAnalyzerConfig() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] key = value"); var generator = new SingleFileTestGenerator("public class D {}", "generated.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzerconfig:" + analyzerConfig.Path }, generators: new[] { generator }, analyzers: null); } [Fact] public void SourceGeneratorsCanReadAnalyzerConfig() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var analyzerConfig1 = dir.CreateFile(".globaleditorconfig").WriteAllText(@" is_global = true key1 = value1 [*.cs] key2 = value2 [*.vb] key3 = value3"); var analyzerConfig2 = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] key4 = value4 [*.vb] key5 = value5"); var subDir = dir.CreateDirectory("subDir"); var analyzerConfig3 = subDir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] key6 = value6 [*.vb] key7 = value7"); var generator = new CallbackGenerator((ic) => { }, (gc) => { // can get the global options var globalOptions = gc.AnalyzerConfigOptions.GlobalOptions; Assert.True(globalOptions.TryGetValue("key1", out var keyValue)); Assert.Equal("value1", keyValue); Assert.False(globalOptions.TryGetValue("key2", out _)); Assert.False(globalOptions.TryGetValue("key3", out _)); Assert.False(globalOptions.TryGetValue("key4", out _)); Assert.False(globalOptions.TryGetValue("key5", out _)); Assert.False(globalOptions.TryGetValue("key6", out _)); Assert.False(globalOptions.TryGetValue("key7", out _)); // can get the options for class C var classOptions = gc.AnalyzerConfigOptions.GetOptions(gc.Compilation.SyntaxTrees.First()); Assert.True(classOptions.TryGetValue("key1", out keyValue)); Assert.Equal("value1", keyValue); Assert.False(classOptions.TryGetValue("key2", out _)); Assert.False(classOptions.TryGetValue("key3", out _)); Assert.True(classOptions.TryGetValue("key4", out keyValue)); Assert.Equal("value4", keyValue); Assert.False(classOptions.TryGetValue("key5", out _)); Assert.False(classOptions.TryGetValue("key6", out _)); Assert.False(classOptions.TryGetValue("key7", out _)); }); var args = new[] { "/analyzerconfig:" + analyzerConfig1.Path, "/analyzerconfig:" + analyzerConfig2.Path, "/analyzerconfig:" + analyzerConfig3.Path, "/t:library", src.Path }; var cmd = CreateCSharpCompiler(null, dir.Path, args, generators: ImmutableArray.Create<ISourceGenerator>(generator)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); // test for both the original tree and the generated one var provider = cmd.AnalyzerOptions.AnalyzerConfigOptionsProvider; // get the global options var globalOptions = provider.GlobalOptions; Assert.True(globalOptions.TryGetValue("key1", out var keyValue)); Assert.Equal("value1", keyValue); Assert.False(globalOptions.TryGetValue("key2", out _)); Assert.False(globalOptions.TryGetValue("key3", out _)); Assert.False(globalOptions.TryGetValue("key4", out _)); Assert.False(globalOptions.TryGetValue("key5", out _)); Assert.False(globalOptions.TryGetValue("key6", out _)); Assert.False(globalOptions.TryGetValue("key7", out _)); // get the options for class C var classOptions = provider.GetOptions(cmd.Compilation.SyntaxTrees.First()); Assert.True(classOptions.TryGetValue("key1", out keyValue)); Assert.Equal("value1", keyValue); Assert.False(classOptions.TryGetValue("key2", out _)); Assert.False(classOptions.TryGetValue("key3", out _)); Assert.True(classOptions.TryGetValue("key4", out keyValue)); Assert.Equal("value4", keyValue); Assert.False(classOptions.TryGetValue("key5", out _)); Assert.False(classOptions.TryGetValue("key6", out _)); Assert.False(classOptions.TryGetValue("key7", out _)); // get the options for generated class D var generatedOptions = provider.GetOptions(cmd.Compilation.SyntaxTrees.Last()); Assert.True(generatedOptions.TryGetValue("key1", out keyValue)); Assert.Equal("value1", keyValue); Assert.False(generatedOptions.TryGetValue("key2", out _)); Assert.False(generatedOptions.TryGetValue("key3", out _)); Assert.True(classOptions.TryGetValue("key4", out keyValue)); Assert.Equal("value4", keyValue); Assert.False(generatedOptions.TryGetValue("key5", out _)); Assert.False(generatedOptions.TryGetValue("key6", out _)); Assert.False(generatedOptions.TryGetValue("key7", out _)); } [Theory] [CombinatorialData] public void SourceGeneratorsRunRegardlessOfLanguageVersion(LanguageVersion version) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@"class C {}"); var generator = new CallbackGenerator(i => { }, e => throw null); var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:" + version.ToDisplayString() }, generators: new[] { generator }, expectedWarningCount: 1, expectedErrorCount: 1, expectedExitCode: 0); Assert.Contains("CS8785: Generator 'CallbackGenerator' failed to generate source.", output); } [DiagnosticAnalyzer(LanguageNames.CSharp)] private sealed class FieldAnalyzer : DiagnosticAnalyzer { private static readonly DiagnosticDescriptor _rule = new DiagnosticDescriptor("Id", "Title", "Message", "Category", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(_rule); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeFieldDeclaration, SyntaxKind.FieldDeclaration); } private static void AnalyzeFieldDeclaration(SyntaxNodeAnalysisContext context) { } } [Fact] [WorkItem(44000, "https://github.com/dotnet/roslyn/issues/44000")] public void TupleField_ForceComplete() { var source = @"namespace System { public struct ValueTuple<T1> { public T1 Item1; public ValueTuple(T1 item1) { Item1 = item1; } } }"; var srcFile = Temp.CreateFile().WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler( null, WorkingDirectory, new[] { "/nologo", "/t:library", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new FieldAnalyzer())); // at least one analyzer required var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); Assert.Empty(output); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] public void GlobalAnalyzerConfigsAllowedInSameDir() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var configText = @" is_global = true "; var analyzerConfig1 = dir.CreateFile("analyzerconfig1").WriteAllText(configText); var analyzerConfig2 = dir.CreateFile("analyzerconfig2").WriteAllText(configText); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig1.Path, "/analyzerconfig:" + analyzerConfig2.Path, src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); } [Fact] public void GlobalAnalyzerConfigMultipleSetKeys() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var analyzerConfigFile = dir.CreateFile(".globalconfig"); var analyzerConfig = analyzerConfigFile.WriteAllText(@" is_global = true global_level = 100 option1 = abc"); var analyzerConfigFile2 = dir.CreateFile(".globalconfig2"); var analyzerConfig2 = analyzerConfigFile2.WriteAllText(@" is_global = true global_level = 100 option1 = def"); var output = VerifyOutput(dir, src, additionalFlags: new[] { "/analyzerconfig:" + analyzerConfig.Path + "," + analyzerConfig2.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning MultipleGlobalAnalyzerKeys: Multiple global analyzer config files set the same key 'option1' in section 'Global Section'. It has been unset. Key was set by the following files: ... Assert.Contains("MultipleGlobalAnalyzerKeys:", output, StringComparison.Ordinal); Assert.Contains("'option1'", output, StringComparison.Ordinal); Assert.Contains("'Global Section'", output, StringComparison.Ordinal); analyzerConfig = analyzerConfigFile.WriteAllText(@" is_global = true global_level = 100 [/file.cs] option1 = abc"); analyzerConfig2 = analyzerConfigFile2.WriteAllText(@" is_global = true global_level = 100 [/file.cs] option1 = def"); output = VerifyOutput(dir, src, additionalFlags: new[] { "/analyzerconfig:" + analyzerConfig.Path + "," + analyzerConfig2.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning MultipleGlobalAnalyzerKeys: Multiple global analyzer config files set the same key 'option1' in section 'file.cs'. It has been unset. Key was set by the following files: ... Assert.Contains("MultipleGlobalAnalyzerKeys:", output, StringComparison.Ordinal); Assert.Contains("'option1'", output, StringComparison.Ordinal); Assert.Contains("'/file.cs'", output, StringComparison.Ordinal); } [Fact] public void GlobalAnalyzerConfigWithOptions() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { }"); var additionalFile = dir.CreateFile("file.txt"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] key1 = value1 [*.txt] key2 = value2"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText(@" is_global = true key3 = value3"); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/analyzerconfig:" + analyzerConfig.Path, "/analyzerconfig:" + globalConfig.Path, "/analyzer:" + Assembly.GetExecutingAssembly().Location, "/nowarn:8032,Warning01", "/additionalfile:" + additionalFile.Path, src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal("", outWriter.ToString()); Assert.Equal(0, exitCode); var comp = cmd.Compilation; var tree = comp.SyntaxTrees.Single(); var provider = cmd.AnalyzerOptions.AnalyzerConfigOptionsProvider; var options = provider.GetOptions(tree); Assert.NotNull(options); Assert.True(options.TryGetValue("key1", out string val)); Assert.Equal("value1", val); Assert.False(options.TryGetValue("key2", out _)); Assert.True(options.TryGetValue("key3", out val)); Assert.Equal("value3", val); options = provider.GetOptions(cmd.AnalyzerOptions.AdditionalFiles.Single()); Assert.NotNull(options); Assert.False(options.TryGetValue("key1", out _)); Assert.True(options.TryGetValue("key2", out val)); Assert.Equal("value2", val); Assert.True(options.TryGetValue("key3", out val)); Assert.Equal("value3", val); options = provider.GlobalOptions; Assert.NotNull(options); Assert.False(options.TryGetValue("key1", out _)); Assert.False(options.TryGetValue("key2", out _)); Assert.True(options.TryGetValue("key3", out val)); Assert.Equal("value3", val); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")] public void GlobalAnalyzerConfigDiagnosticOptionsCanBeOverridenByCommandLine() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M() { label1:; } }"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText(@" is_global = true dotnet_diagnostic.CS0164.severity = error; "); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.CS0164.severity = warning; "); var none = Array.Empty<TempFile>(); var globalOnly = new[] { globalConfig }; var globalAndSpecific = new[] { globalConfig, analyzerConfig }; // by default a warning, which can be suppressed via cmdline verify(configs: none, expectedWarnings: 1); verify(configs: none, noWarn: "CS0164", expectedWarnings: 0); // the global analyzer config ups the warning to an error, but the cmdline setting overrides it verify(configs: globalOnly, expectedErrors: 1); verify(configs: globalOnly, noWarn: "CS0164", expectedWarnings: 0); verify(configs: globalOnly, noWarn: "164", expectedWarnings: 0); // cmdline can be shortened, but still works // the editor config downgrades the error back to warning, but the cmdline setting overrides it verify(configs: globalAndSpecific, expectedWarnings: 1); verify(configs: globalAndSpecific, noWarn: "CS0164", expectedWarnings: 0); void verify(TempFile[] configs, int expectedWarnings = 0, int expectedErrors = 0, string noWarn = "0") => VerifyOutput(dir, src, expectedErrorCount: expectedErrors, expectedWarningCount: expectedWarnings, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: null, additionalFlags: configs.SelectAsArray(c => "/analyzerconfig:" + c.Path) .Add("/noWarn:" + noWarn).ToArray()); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")] public void GlobalAnalyzerConfigSpecificDiagnosticOptionsOverrideGeneralCommandLineOptions() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M() { label1:; } }"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText($@" is_global = true dotnet_diagnostic.CS0164.severity = none; "); VerifyOutput(dir, src, additionalFlags: new[] { "/warnaserror+", "/analyzerconfig:" + globalConfig.Path }, includeCurrentAssemblyAsAnalyzerReference: false); } [Theory, CombinatorialData] [WorkItem(43051, "https://github.com/dotnet/roslyn/issues/43051")] public void WarnAsErrorIsRespectedForForWarningsConfiguredInRulesetOrGlobalConfig(bool useGlobalConfig) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M() { label1:; } }"); var additionalFlags = new[] { "/warnaserror+" }; if (useGlobalConfig) { var globalConfig = dir.CreateFile(".globalconfig").WriteAllText($@" is_global = true dotnet_diagnostic.CS0164.severity = warning; "); additionalFlags = additionalFlags.Append("/analyzerconfig:" + globalConfig.Path).ToArray(); } else { string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""15.0""> <Rules AnalyzerId=""Compiler"" RuleNamespace=""Compiler""> <Rule Id=""CS0164"" Action=""Warning"" /> </Rules> </RuleSet> "; _ = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); additionalFlags = additionalFlags.Append("/ruleset:Rules.ruleset").ToArray(); } VerifyOutput(dir, src, additionalFlags: additionalFlags, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")] public void GlobalAnalyzerConfigSectionsDoNotOverrideCommandLine() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M() { label1:; } }"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText($@" is_global = true [{PathUtilities.NormalizeWithForwardSlash(src.Path)}] dotnet_diagnostic.CS0164.severity = error; "); VerifyOutput(dir, src, additionalFlags: new[] { "/nowarn:0164", "/analyzerconfig:" + globalConfig.Path }, expectedErrorCount: 0, includeCurrentAssemblyAsAnalyzerReference: false); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")] public void GlobalAnalyzerConfigCanSetDiagnosticWithNoLocation() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { }"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText(@" is_global = true dotnet_diagnostic.Warning01.severity = error; "); VerifyOutput(dir, src, additionalFlags: new[] { "/analyzerconfig:" + globalConfig.Path }, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: new WarningDiagnosticAnalyzer()); VerifyOutput(dir, src, additionalFlags: new[] { "/nowarn:Warning01", "/analyzerconfig:" + globalConfig.Path }, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: new WarningDiagnosticAnalyzer()); } [Theory, CombinatorialData] public void TestAdditionalFileAnalyzer(bool registerFromInitialize) { var srcDirectory = Temp.CreateDirectory(); var source = "class C { }"; var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); var additionalText = "Additional Text"; var additionalFile = srcDirectory.CreateFile("b.txt"); additionalFile.WriteAllText(additionalText); var diagnosticSpan = new TextSpan(2, 2); var analyzer = new AdditionalFileAnalyzer(registerFromInitialize, diagnosticSpan); var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/additionalfile:" + additionalFile.Path }, analyzers: analyzer); Assert.Contains("b.txt(1,3): warning ID0001", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcDirectory.Path); } [Theory] // "/warnaserror" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/warnaserror", /*expectError*/true, /*expectWarning*/false)] // "/warnaserror:CS0169" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror:CS0169", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror:CS0169", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/warnaserror:CS0169", /*expectError*/true, /*expectWarning*/false)] // "/nowarn" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/nowarn:CS0169", /*expectError*/false, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/nowarn:CS0169", /*expectError*/false, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/nowarn:CS0169", /*expectError*/false, /*expectWarning*/false)] // Neither "/nowarn" nor "/warnaserror" tests [InlineData(/*analyzerConfigSeverity*/"warning", /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)] [InlineData(/*analyzerConfigSeverity*/"error", /*additionalArg*/null, /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)] [WorkItem(43051, "https://github.com/dotnet/roslyn/issues/43051")] public void TestCompilationOptionsOverrideAnalyzerConfig_CompilerWarning(string analyzerConfigSeverity, string additionalArg, bool expectError, bool expectWarning) { var src = @" class C { int _f; // CS0169: unused field }"; TestCompilationOptionsOverrideAnalyzerConfigCore(src, diagnosticId: "CS0169", analyzerConfigSeverity, additionalArg, expectError, expectWarning); } [Theory] // "/warnaserror" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/warnaserror", /*expectError*/true, /*expectWarning*/false)] // "/warnaserror:DiagnosticId" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/warnaserror:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/true, /*expectWarning*/false)] // "/nowarn" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/nowarn:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/false, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/nowarn:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/false, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/nowarn:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/false, /*expectWarning*/false)] // Neither "/nowarn" nor "/warnaserror" tests [InlineData(/*analyzerConfigSeverity*/"warning", /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)] [InlineData(/*analyzerConfigSeverity*/"error", /*additionalArg*/null, /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)] [WorkItem(43051, "https://github.com/dotnet/roslyn/issues/43051")] public void TestCompilationOptionsOverrideAnalyzerConfig_AnalyzerWarning(string analyzerConfigSeverity, string additionalArg, bool expectError, bool expectWarning) { var analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Warning, configurable: true); var src = @"class C { }"; TestCompilationOptionsOverrideAnalyzerConfigCore(src, CompilationAnalyzerWithSeverity.DiagnosticId, analyzerConfigSeverity, additionalArg, expectError, expectWarning, analyzer); } private void TestCompilationOptionsOverrideAnalyzerConfigCore( string source, string diagnosticId, string analyzerConfigSeverity, string additionalArg, bool expectError, bool expectWarning, params DiagnosticAnalyzer[] analyzers) { Assert.True(!expectError || !expectWarning); var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(source); var additionalArgs = Array.Empty<string>(); if (analyzerConfigSeverity != null) { var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText($@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = {analyzerConfigSeverity}"); additionalArgs = additionalArgs.Append("/analyzerconfig:" + analyzerConfig.Path).ToArray(); } if (!string.IsNullOrEmpty(additionalArg)) { additionalArgs = additionalArgs.Append(additionalArg); } var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectError ? 1 : 0, expectedWarningCount: expectWarning ? 1 : 0, analyzers: analyzers); if (expectError) { Assert.Contains($"error {diagnosticId}", output); } else if (expectWarning) { Assert.Contains($"warning {diagnosticId}", output); } else { Assert.DoesNotContain(diagnosticId, output); } } [ConditionalFact(typeof(CoreClrOnly), Reason = "Can't load a coreclr targeting generator on net framework / mono")] public void TestGeneratorsCantTargetNetFramework() { var directory = Temp.CreateDirectory(); var src = directory.CreateFile("test.cs").WriteAllText(@" class C { }"); // core var coreGenerator = emitGenerator(".NETCoreApp,Version=v5.0"); VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + coreGenerator }); // netstandard var nsGenerator = emitGenerator(".NETStandard,Version=v2.0"); VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + nsGenerator }); // no target var ntGenerator = emitGenerator(targetFramework: null); VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + ntGenerator }); // framework var frameworkGenerator = emitGenerator(".NETFramework,Version=v4.7.2"); var output = VerifyOutput(directory, src, expectedWarningCount: 2, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + frameworkGenerator }); Assert.Contains("CS8850", output); // ref's net fx Assert.Contains("CS8033", output); // no analyzers in assembly // framework, suppressed output = VerifyOutput(directory, src, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:CS8850", "/analyzer:" + frameworkGenerator }); Assert.Contains("CS8033", output); VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:CS8850,CS8033", "/analyzer:" + frameworkGenerator }); string emitGenerator(string targetFramework) { string targetFrameworkAttributeText = targetFramework is object ? $"[assembly: System.Runtime.Versioning.TargetFramework(\"{targetFramework}\")]" : string.Empty; string generatorSource = $@" using Microsoft.CodeAnalysis; {targetFrameworkAttributeText} [Generator] public class Generator : ISourceGenerator {{ public void Execute(GeneratorExecutionContext context) {{ }} public void Initialize(GeneratorInitializationContext context) {{ }} }}"; var directory = Temp.CreateDirectory(); var generatorPath = Path.Combine(directory.Path, "generator.dll"); var compilation = CSharpCompilation.Create($"generator", new[] { CSharpSyntaxTree.ParseText(generatorSource) }, TargetFrameworkUtil.GetReferences(TargetFramework.Standard, new[] { MetadataReference.CreateFromAssemblyInternal(typeof(ISourceGenerator).Assembly) }), new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); compilation.VerifyDiagnostics(); var result = compilation.Emit(generatorPath); Assert.True(result.Success); return generatorPath; } } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal abstract class CompilationStartedAnalyzer : DiagnosticAnalyzer { public abstract override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } public abstract void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context); public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction(CreateAnalyzerWithinCompilation); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal class HiddenDiagnosticAnalyzer : CompilationStartedAnalyzer { internal static readonly DiagnosticDescriptor Hidden01 = new DiagnosticDescriptor("Hidden01", "", "Throwing a diagnostic for #region", "", DiagnosticSeverity.Hidden, isEnabledByDefault: true); internal static readonly DiagnosticDescriptor Hidden02 = new DiagnosticDescriptor("Hidden02", "", "Throwing a diagnostic for something else", "", DiagnosticSeverity.Hidden, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Hidden01, Hidden02); } } private void AnalyzeNode(SyntaxNodeAnalysisContext context) { context.ReportDiagnostic(Diagnostic.Create(Hidden01, context.Node.GetLocation())); } public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.RegionDirectiveTrivia); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal class InfoDiagnosticAnalyzer : CompilationStartedAnalyzer { internal static readonly DiagnosticDescriptor Info01 = new DiagnosticDescriptor("Info01", "", "Throwing a diagnostic for #pragma restore", "", DiagnosticSeverity.Info, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Info01); } } private void AnalyzeNode(SyntaxNodeAnalysisContext context) { if ((context.Node as PragmaWarningDirectiveTriviaSyntax).DisableOrRestoreKeyword.IsKind(SyntaxKind.RestoreKeyword)) { context.ReportDiagnostic(Diagnostic.Create(Info01, context.Node.GetLocation())); } } public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.PragmaWarningDirectiveTrivia); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal class WarningDiagnosticAnalyzer : CompilationStartedAnalyzer { internal static readonly DiagnosticDescriptor Warning01 = new DiagnosticDescriptor("Warning01", "", "Throwing a diagnostic for types declared", "", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Warning01); } } public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSymbolAction( (symbolContext) => { symbolContext.ReportDiagnostic(Diagnostic.Create(Warning01, symbolContext.Symbol.Locations.First())); }, SymbolKind.NamedType); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal class ErrorDiagnosticAnalyzer : CompilationStartedAnalyzer { internal static readonly DiagnosticDescriptor Error01 = new DiagnosticDescriptor("Error01", "", "Throwing a diagnostic for #pragma disable", "", DiagnosticSeverity.Error, isEnabledByDefault: true); internal static readonly DiagnosticDescriptor Error02 = new DiagnosticDescriptor("Error02", "", "Throwing a diagnostic for something else", "", DiagnosticSeverity.Error, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Error01, Error02); } } public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSyntaxNodeAction( (nodeContext) => { if ((nodeContext.Node as PragmaWarningDirectiveTriviaSyntax).DisableOrRestoreKeyword.IsKind(SyntaxKind.DisableKeyword)) { nodeContext.ReportDiagnostic(Diagnostic.Create(Error01, nodeContext.Node.GetLocation())); } }, SyntaxKind.PragmaWarningDirectiveTrivia ); } } }
1
dotnet/roslyn
56,223
Rework our netstandard1.3 test references
The `netstandard1.3` test references were being provided by our MS.CA.Test.Resources.Proprietary package. The contents of this package get included in the output directory of every single unit test DLL that we build (which contributes to build output size). The references themselves though were only used in a very small number of tests. This change upgrades to a version of MS.CA.Test.Resources.Proprietary that has the `netstandard1.3` references removed and adds the `netstandard1.3` references to only the projects that needs them
jaredpar
"2021-09-07T20:35:04Z"
"2021-09-07T23:50:57Z"
0240973369997c88a2c2f1aaa22c14182ac17e9f
5dbd783367d7f6b105726b84558cc1809aa198ce
Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our MS.CA.Test.Resources.Proprietary package. The contents of this package get included in the output directory of every single unit test DLL that we build (which contributes to build output size). The references themselves though were only used in a very small number of tests. This change upgrades to a version of MS.CA.Test.Resources.Proprietary that has the `netstandard1.3` references removed and adds the `netstandard1.3` references to only the projects that needs them
./src/Compilers/CSharp/Test/CommandLine/Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests</RootNamespace> <TargetFrameworks>net5.0;net472</TargetFrameworks> <GenerateMicrosoftCodeAnalysisCommitHashAttribute>true</GenerateMicrosoftCodeAnalysisCommitHashAttribute> </PropertyGroup> <ItemGroup> <Compile Include="..\..\..\Test\Resources\Core\ResourceLoader.cs" Link="ResourceLoader.cs" /> </ItemGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\..\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\Test\Utilities\CSharp\Microsoft.CodeAnalysis.CSharp.Test.Utilities.csproj" /> <ProjectReference Include="..\..\csc\csc.csproj" ReferenceOutputAssembly="false" OutputItemType="RoslynReferenceToDependencyDirectory" /> <ProjectReference Include="..\..\..\..\Interactive\csi\csi.csproj" ReferenceOutputAssembly="false" OutputItemType="CsiReferenceToDependencyDirectory" /> <ProjectReference Include="..\..\..\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\..\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="..\..\csc\csc.rsp" LogicalName="csc.rsp" /> </ItemGroup> <ItemGroup> <PackageReference Include="Xunit.Combinatorial" Version="$(XunitCombinatorialVersion)" /> </ItemGroup> <ItemGroup> <Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" /> </ItemGroup> <Target Name="CopyCsiReferencedProjectToDependenciesDirectory" Condition="'@(CsiReferenceToDependencyDirectory)' != ''" AfterTargets="ResolveProjectReferences"> <PropertyGroup> <_CsiReferenceOutputPath>@(CsiReferenceToDependencyDirectory->'%(RootDir)%(Directory)*.*')</_CsiReferenceOutputPath> </PropertyGroup> <ItemGroup> <_CsiReferenceContent Include="$(_CsiReferenceOutputPath)" /> <Content Include="@(_CsiReferenceContent)" Link="dependency\csi\%(_CsiReferenceContent.Filename)%(_CsiReferenceContent.Extension)" CopyToOutputDirectory="PreserveNewest" /> </ItemGroup> </Target> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests</RootNamespace> <TargetFrameworks>net5.0;net472</TargetFrameworks> <GenerateMicrosoftCodeAnalysisCommitHashAttribute>true</GenerateMicrosoftCodeAnalysisCommitHashAttribute> </PropertyGroup> <ItemGroup> <Compile Include="..\..\..\Test\Resources\Core\ResourceLoader.cs" Link="ResourceLoader.cs" /> </ItemGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\..\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\Test\Utilities\CSharp\Microsoft.CodeAnalysis.CSharp.Test.Utilities.csproj" /> <ProjectReference Include="..\..\csc\csc.csproj" ReferenceOutputAssembly="false" OutputItemType="RoslynReferenceToDependencyDirectory" /> <ProjectReference Include="..\..\..\..\Interactive\csi\csi.csproj" ReferenceOutputAssembly="false" OutputItemType="CsiReferenceToDependencyDirectory" /> <ProjectReference Include="..\..\..\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\..\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" /> <PackageReference Include="Basic.Reference.Assemblies.NetStandard13" Version="$(BasicReferenceAssembliesNetStandard13Version)" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="..\..\csc\csc.rsp" LogicalName="csc.rsp" /> </ItemGroup> <ItemGroup> <PackageReference Include="Xunit.Combinatorial" Version="$(XunitCombinatorialVersion)" /> </ItemGroup> <ItemGroup> <Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" /> </ItemGroup> <Target Name="CopyCsiReferencedProjectToDependenciesDirectory" Condition="'@(CsiReferenceToDependencyDirectory)' != ''" AfterTargets="ResolveProjectReferences"> <PropertyGroup> <_CsiReferenceOutputPath>@(CsiReferenceToDependencyDirectory->'%(RootDir)%(Directory)*.*')</_CsiReferenceOutputPath> </PropertyGroup> <ItemGroup> <_CsiReferenceContent Include="$(_CsiReferenceOutputPath)" /> <Content Include="@(_CsiReferenceContent)" Link="dependency\csi\%(_CsiReferenceContent.Filename)%(_CsiReferenceContent.Extension)" CopyToOutputDirectory="PreserveNewest" /> </ItemGroup> </Target> </Project>
1
dotnet/roslyn
56,223
Rework our netstandard1.3 test references
The `netstandard1.3` test references were being provided by our MS.CA.Test.Resources.Proprietary package. The contents of this package get included in the output directory of every single unit test DLL that we build (which contributes to build output size). The references themselves though were only used in a very small number of tests. This change upgrades to a version of MS.CA.Test.Resources.Proprietary that has the `netstandard1.3` references removed and adds the `netstandard1.3` references to only the projects that needs them
jaredpar
"2021-09-07T20:35:04Z"
"2021-09-07T23:50:57Z"
0240973369997c88a2c2f1aaa22c14182ac17e9f
5dbd783367d7f6b105726b84558cc1809aa198ce
Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our MS.CA.Test.Resources.Proprietary package. The contents of this package get included in the output directory of every single unit test DLL that we build (which contributes to build output size). The references themselves though were only used in a very small number of tests. This change upgrades to a version of MS.CA.Test.Resources.Proprietary that has the `netstandard1.3` references removed and adds the `netstandard1.3` references to only the projects that needs them
./src/Compilers/Test/Core/Mocks/TestReferences.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Resources.Proprietary; using Roslyn.Test.Utilities; public static class TestReferences { public static class MetadataTests { public static class NetModule01 { private static readonly Lazy<PortableExecutableReference> s_appCS = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.MetadataTests.NetModule01.AppCS).GetReference(display: "AppCS"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference AppCS => s_appCS.Value; private static readonly Lazy<PortableExecutableReference> s_moduleCS00 = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.MetadataTests.NetModule01.ModuleCS00).GetReference(display: "ModuleCS00.mod"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference ModuleCS00 => s_moduleCS00.Value; private static readonly Lazy<PortableExecutableReference> s_moduleCS01 = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.MetadataTests.NetModule01.ModuleCS01).GetReference(display: "ModuleCS01.mod"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference ModuleCS01 => s_moduleCS01.Value; private static readonly Lazy<PortableExecutableReference> s_moduleVB01 = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.MetadataTests.NetModule01.ModuleVB01).GetReference(display: "ModuleVB01.mod"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference ModuleVB01 => s_moduleVB01.Value; } public static class InterfaceAndClass { private static readonly Lazy<PortableExecutableReference> s_CSClasses01 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.MetadataTests.InterfaceAndClass.CSClasses01).GetReference(display: "CSClasses01.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference CSClasses01 => s_CSClasses01.Value; private static readonly Lazy<PortableExecutableReference> s_CSInterfaces01 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.MetadataTests.InterfaceAndClass.CSInterfaces01).GetReference(display: "CSInterfaces01.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference CSInterfaces01 => s_CSInterfaces01.Value; private static readonly Lazy<PortableExecutableReference> s_VBClasses01 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.MetadataTests.InterfaceAndClass.VBClasses01).GetReference(display: "VBClasses01.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference VBClasses01 => s_VBClasses01.Value; private static readonly Lazy<PortableExecutableReference> s_VBClasses02 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.MetadataTests.InterfaceAndClass.VBClasses02).GetReference(display: "VBClasses02.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference VBClasses02 => s_VBClasses02.Value; private static readonly Lazy<PortableExecutableReference> s_VBInterfaces01 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.MetadataTests.InterfaceAndClass.VBInterfaces01).GetReference(display: "VBInterfaces01.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference VBInterfaces01 => s_VBInterfaces01.Value; } } public static class NetFx { public static class Minimal { private static readonly Lazy<PortableExecutableReference> s_mincorlib = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.NetFX.Minimal.mincorlib).GetReference(display: "mincorlib.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference mincorlib => s_mincorlib.Value; private static readonly Lazy<PortableExecutableReference> s_minasync = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.NetFX.Minimal.minasync).GetReference(display: "minasync.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference minasync => s_minasync.Value; private static readonly Lazy<PortableExecutableReference> s_minasynccorlib = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.NetFX.Minimal.minasynccorlib).GetReference(display: "minasynccorlib.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference minasynccorlib => s_minasynccorlib.Value; } public static class ValueTuple { private static readonly Lazy<PortableExecutableReference> s_tuplelib = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.NetFX.ValueTuple.tuplelib).GetReference(display: "System.ValueTuple.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference tuplelib => s_tuplelib.Value; } public static class silverlight_v5_0_5_0 { private static readonly Lazy<PortableExecutableReference> s_system = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(ProprietaryTestResources.silverlight_v5_0_5_0.System_v5_0_5_0_silverlight).GetReference(display: "System.v5.0.5.0_silverlight.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference System => s_system.Value; } } public static class NetStandard13 { private static readonly Lazy<PortableExecutableReference> s_systemRuntime = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(ProprietaryTestResources.netstandard13.System_Runtime).GetReference(display: @"System.Runtime.dll (netstandard13 ref)"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference SystemRuntime => s_systemRuntime.Value; } public static class DiagnosticTests { public static class ErrTestLib01 { private static readonly Lazy<PortableExecutableReference> s_errTestLib01 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.DiagnosticTests.ErrTestLib01).GetReference(display: "ErrTestLib01.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_errTestLib01.Value; } public static class ErrTestLib02 { private static readonly Lazy<PortableExecutableReference> s_errTestLib02 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.DiagnosticTests.ErrTestLib02).GetReference(display: "ErrTestLib02.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_errTestLib02.Value; } public static class ErrTestLib11 { private static readonly Lazy<PortableExecutableReference> s_errTestLib11 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.DiagnosticTests.ErrTestLib11).GetReference(display: "ErrTestLib11.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_errTestLib11.Value; } public static class ErrTestMod01 { private static readonly Lazy<PortableExecutableReference> s_errTestMod01 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.DiagnosticTests.ErrTestMod01).GetReference(display: "ErrTestMod01.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_errTestMod01.Value; } public static class ErrTestMod02 { private static readonly Lazy<PortableExecutableReference> s_errTestMod02 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.DiagnosticTests.ErrTestMod02).GetReference(display: "ErrTestMod02.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_errTestMod02.Value; } public static class badresfile { private static readonly Lazy<PortableExecutableReference> s_badresfile = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.DiagnosticTests.badresfile).GetReference(display: "badresfile.res"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference res => s_badresfile.Value; } } public static class SymbolsTests { private static readonly Lazy<PortableExecutableReference> s_mdTestLib1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.MDTestLib1).GetReference(display: "MDTestLib1.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference MDTestLib1 => s_mdTestLib1.Value; private static readonly Lazy<PortableExecutableReference> s_mdTestLib2 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.MDTestLib2).GetReference(display: "MDTestLib2.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference MDTestLib2 => s_mdTestLib2.Value; private static readonly Lazy<PortableExecutableReference> s_VBConversions = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.VBConversions).GetReference(display: "VBConversions.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference VBConversions => s_VBConversions.Value; private static readonly Lazy<PortableExecutableReference> s_withSpaces = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.With_Spaces).GetReference(display: "With Spaces.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference WithSpaces => s_withSpaces.Value; private static readonly Lazy<PortableExecutableReference> s_withSpacesModule = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.General.With_SpacesModule).GetReference(display: "With Spaces.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference WithSpacesModule => s_withSpacesModule.Value; private static readonly Lazy<PortableExecutableReference> s_inheritIComparable = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.InheritIComparable).GetReference(display: "InheritIComparable.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference InheritIComparable => s_inheritIComparable.Value; private static readonly Lazy<PortableExecutableReference> s_bigVisitor = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.BigVisitor).GetReference(display: "BigVisitor.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference BigVisitor => s_bigVisitor.Value; private static readonly Lazy<PortableExecutableReference> s_properties = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.Properties).GetReference(display: "Properties.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Properties => s_properties.Value; private static readonly Lazy<PortableExecutableReference> s_propertiesWithByRef = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.PropertiesWithByRef).GetReference(display: "PropertiesWithByRef.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference PropertiesWithByRef => s_propertiesWithByRef.Value; private static readonly Lazy<PortableExecutableReference> s_indexers = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.Indexers).GetReference(display: "Indexers.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Indexers => s_indexers.Value; private static readonly Lazy<PortableExecutableReference> s_events = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.Events).GetReference(display: "Events.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Events => s_events.Value; public static class netModule { private static readonly Lazy<PortableExecutableReference> s_netModule1 = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.netModule1).GetReference(display: "netModule1.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference netModule1 => s_netModule1.Value; private static readonly Lazy<PortableExecutableReference> s_netModule2 = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.netModule2).GetReference(display: "netModule2.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference netModule2 => s_netModule2.Value; private static readonly Lazy<PortableExecutableReference> s_crossRefModule1 = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.CrossRefModule1).GetReference(display: "CrossRefModule1.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference CrossRefModule1 => s_crossRefModule1.Value; private static readonly Lazy<PortableExecutableReference> s_crossRefModule2 = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.CrossRefModule2).GetReference(display: "CrossRefModule2.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference CrossRefModule2 => s_crossRefModule2.Value; private static readonly Lazy<PortableExecutableReference> s_crossRefLib = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.Create( ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.CrossRefLib), ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.CrossRefModule1), ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.CrossRefModule2)).GetReference(display: "CrossRefLib.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference CrossRefLib => s_crossRefLib.Value; private static readonly Lazy<PortableExecutableReference> s_hash_module = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.hash_module).GetReference(display: "hash_module.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference hash_module => s_hash_module.Value; private static readonly Lazy<PortableExecutableReference> s_x64COFF = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.x64COFF).GetReference(display: "x64COFF.obj"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference x64COFF => s_x64COFF.Value; } public static class V1 { public static class MTTestLib1 { private static readonly Lazy<PortableExecutableReference> s_v1MTTestLib1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.V1.MTTestLib1).GetReference(display: "MTTestLib1.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_v1MTTestLib1.Value; } public static class MTTestModule1 { private static readonly Lazy<PortableExecutableReference> s_v1MTTestLib1 = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.V1.MTTestModule1).GetReference(display: "MTTestModule1.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference netmodule => s_v1MTTestLib1.Value; } public static class MTTestLib2 { private static readonly Lazy<PortableExecutableReference> s_v1MTTestLib2 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.V1.MTTestLib2).GetReference(display: "MTTestLib2.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_v1MTTestLib2.Value; } public static class MTTestModule2 { private static readonly Lazy<PortableExecutableReference> s_v1MTTestLib1 = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.V1.MTTestModule2).GetReference(display: "MTTestModule2.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference netmodule => s_v1MTTestLib1.Value; } } public static class V2 { public static class MTTestLib1 { private static readonly Lazy<PortableExecutableReference> s_v2MTTestLib1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.V2.MTTestLib1).GetReference(display: "MTTestLib1.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_v2MTTestLib1.Value; } public static class MTTestModule1 { private static readonly Lazy<PortableExecutableReference> s_v1MTTestLib1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.V2.MTTestModule1).GetReference(display: "MTTestModule1.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference netmodule => s_v1MTTestLib1.Value; } public static class MTTestLib3 { private static readonly Lazy<PortableExecutableReference> s_v2MTTestLib3 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.V2.MTTestLib3).GetReference(display: "MTTestLib3.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_v2MTTestLib3.Value; } public static class MTTestModule3 { private static readonly Lazy<PortableExecutableReference> s_v1MTTestLib1 = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.V2.MTTestModule3).GetReference(display: "MTTestModule3.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference netmodule => s_v1MTTestLib1.Value; } } public static class V3 { public static class MTTestLib1 { private static readonly Lazy<PortableExecutableReference> s_v3MTTestLib1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.V3.MTTestLib1).GetReference(display: "MTTestLib1.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_v3MTTestLib1.Value; } public static class MTTestModule1 { private static readonly Lazy<PortableExecutableReference> s_v1MTTestLib1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.V3.MTTestModule1).GetReference(display: "MTTestModule1.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference netmodule => s_v1MTTestLib1.Value; } public static class MTTestLib4 { private static readonly Lazy<PortableExecutableReference> s_v3MTTestLib4 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.V3.MTTestLib4).GetReference(display: "MTTestLib4.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_v3MTTestLib4.Value; } public static class MTTestModule4 { private static readonly Lazy<PortableExecutableReference> s_v1MTTestLib1 = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.V3.MTTestModule4).GetReference(display: "MTTestModule4.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference netmodule => s_v1MTTestLib1.Value; } } public static class MultiModule { private static readonly Lazy<PortableExecutableReference> s_assembly = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.Create( ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.MultiModule.MultiModuleDll), ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.MultiModule.mod2), ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.MultiModule.mod3)).GetReference(display: "MultiModule.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Assembly => s_assembly.Value; private static readonly Lazy<PortableExecutableReference> s_mod2 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.MultiModule.mod2).GetReference(display: "mod2.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference mod2 => s_mod2.Value; private static readonly Lazy<PortableExecutableReference> s_mod3 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.MultiModule.mod3).GetReference(display: "mod3.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference mod3 => s_mod3.Value; private static readonly Lazy<PortableExecutableReference> s_consumer = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.MultiModule.Consumer).GetReference(display: "Consumer.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Consumer => s_consumer.Value; } public static class DifferByCase { private static readonly Lazy<PortableExecutableReference> s_typeAndNamespaceDifferByCase = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.DifferByCase.TypeAndNamespaceDifferByCase).GetReference(display: "TypeAndNamespaceDifferByCase.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference TypeAndNamespaceDifferByCase => s_typeAndNamespaceDifferByCase.Value; private static readonly Lazy<PortableExecutableReference> s_differByCaseConsumer = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.DifferByCase.Consumer).GetReference(display: "Consumer.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Consumer => s_differByCaseConsumer.Value; private static readonly Lazy<PortableExecutableReference> s_csharpCaseSen = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.DifferByCase.Consumer).GetReference(display: "CsharpCaseSen.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference CsharpCaseSen => s_csharpCaseSen.Value; private static readonly Lazy<PortableExecutableReference> s_csharpDifferCaseOverloads = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.DifferByCase.CSharpDifferCaseOverloads).GetReference(display: "CSharpDifferCaseOverloads.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference CsharpDifferCaseOverloads => s_csharpDifferCaseOverloads.Value; } public static class CorLibrary { public static class GuidTest2 { private static readonly Lazy<PortableExecutableReference> s_exe = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.CorLibrary.GuidTest2).GetReference(display: "GuidTest2.exe"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference exe => s_exe.Value; } private static readonly Lazy<PortableExecutableReference> s_noMsCorLibRef = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.CorLibrary.NoMsCorLibRef).GetReference(display: "NoMsCorLibRef.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference NoMsCorLibRef => s_noMsCorLibRef.Value; public static class FakeMsCorLib { private static readonly Lazy<PortableExecutableReference> s_dll = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.CorLibrary.FakeMsCorLib).GetReference(display: "FakeMsCorLib.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_dll.Value; } } public static class CustomModifiers { public static class Modifiers { private static readonly Lazy<PortableExecutableReference> s_dll = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.CustomModifiers.Modifiers).GetReference(display: "Modifiers.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_dll.Value; private static readonly Lazy<PortableExecutableReference> s_module = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.CustomModifiers.ModifiersModule).GetReference(display: "Modifiers.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference netmodule => s_module.Value; } private static readonly Lazy<PortableExecutableReference> s_modoptTests = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.CustomModifiers.ModoptTests).GetReference(display: "ModoptTests.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference ModoptTests => s_modoptTests.Value; public static class CppCli { private static readonly Lazy<PortableExecutableReference> s_dll = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.CustomModifiers.CppCli).GetReference(display: "CppCli.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_dll.Value; } public static class GenericMethodWithModifiers { private static readonly Lazy<PortableExecutableReference> s_dll = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.CustomModifiers.GenericMethodWithModifiers).GetReference(display: "GenericMethodWithModifiers.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_dll.Value; } } public static class Cyclic { public static class Cyclic1 { private static readonly Lazy<PortableExecutableReference> s_cyclic1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Cyclic.Cyclic1).GetReference(display: "Cyclic1.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_cyclic1.Value; } public static class Cyclic2 { private static readonly Lazy<PortableExecutableReference> s_cyclic2 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Cyclic.Cyclic2).GetReference(display: "Cyclic2.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_cyclic2.Value; } } public static class CyclicInheritance { private static readonly Lazy<PortableExecutableReference> s_class1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.CyclicInheritance.Class1).GetReference(display: "Class1.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Class1 => s_class1.Value; private static readonly Lazy<PortableExecutableReference> s_class2 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.CyclicInheritance.Class2).GetReference(display: "Class2.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Class2 => s_class2.Value; private static readonly Lazy<PortableExecutableReference> s_class3 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.CyclicInheritance.Class3).GetReference(display: "Class3.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Class3 => s_class3.Value; } private static readonly Lazy<PortableExecutableReference> s_cycledStructs = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.CyclicStructure.cycledstructs).GetReference(display: "cycledstructs.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference CycledStructs => s_cycledStructs.Value; public static class RetargetingCycle { public static class V1 { public static class ClassA { private static readonly Lazy<PortableExecutableReference> s_classA = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.RetargetingCycle.RetV1.ClassA).GetReference(display: "ClassA.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_classA.Value; } public static class ClassB { private static readonly Lazy<PortableExecutableReference> s_classB = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.RetargetingCycle.RetV1.ClassB).GetReference(display: "ClassB.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference netmodule => s_classB.Value; } } public static class V2 { public static class ClassA { private static readonly Lazy<PortableExecutableReference> s_classA = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.RetargetingCycle.RetV2.ClassA).GetReference(display: "ClassA.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_classA.Value; } public static class ClassB { private static readonly Lazy<PortableExecutableReference> s_classB = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.RetargetingCycle.RetV2.ClassB).GetReference(display: "ClassB.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_classB.Value; } } } public static class Methods { private static readonly Lazy<PortableExecutableReference> s_CSMethods = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Methods.CSMethods).GetReference(display: "CSMethods.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference CSMethods => s_CSMethods.Value; private static readonly Lazy<PortableExecutableReference> s_VBMethods = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Methods.VBMethods).GetReference(display: "VBMethods.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference VBMethods => s_VBMethods.Value; private static readonly Lazy<PortableExecutableReference> s_ILMethods = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Methods.ILMethods).GetReference(display: "ILMethods.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference ILMethods => s_ILMethods.Value; private static readonly Lazy<PortableExecutableReference> s_byRefReturn = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Methods.ByRefReturn).GetReference(display: "ByRefReturn.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference ByRefReturn => s_byRefReturn.Value; } public static class Fields { public static class CSFields { private static readonly Lazy<PortableExecutableReference> s_CSFields = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Fields.CSFields).GetReference(display: "CSFields.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_CSFields.Value; } public static class VBFields { private static readonly Lazy<PortableExecutableReference> s_VBFields = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Fields.VBFields).GetReference(display: "VBFields.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_VBFields.Value; } private static readonly Lazy<PortableExecutableReference> s_constantFields = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Fields.ConstantFields).GetReference(display: "ConstantFields.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference ConstantFields => s_constantFields.Value; } public static class MissingTypes { private static readonly Lazy<PortableExecutableReference> s_MDMissingType = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.MissingTypes.MDMissingType).GetReference(display: "MDMissingType.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference MDMissingType => s_MDMissingType.Value; private static readonly Lazy<PortableExecutableReference> s_MDMissingTypeLib = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.MissingTypes.MDMissingTypeLib).GetReference(display: "MDMissingTypeLib.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference MDMissingTypeLib => s_MDMissingTypeLib.Value; private static readonly Lazy<PortableExecutableReference> s_missingTypesEquality1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.MissingTypes.MissingTypesEquality1).GetReference(display: "MissingTypesEquality1.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference MissingTypesEquality1 => s_missingTypesEquality1.Value; private static readonly Lazy<PortableExecutableReference> s_missingTypesEquality2 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.MissingTypes.MissingTypesEquality2).GetReference(display: "MissingTypesEquality2.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference MissingTypesEquality2 => s_missingTypesEquality2.Value; private static readonly Lazy<PortableExecutableReference> s_CL2 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.MissingTypes.CL2).GetReference(display: "CL2.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference CL2 => s_CL2.Value; private static readonly Lazy<PortableExecutableReference> s_CL3 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.MissingTypes.CL3).GetReference(display: "CL3.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference CL3 => s_CL3.Value; } public static class TypeForwarders { public static class TypeForwarder { private static readonly Lazy<PortableExecutableReference> s_typeForwarder2 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.TypeForwarders.TypeForwarder).GetReference(display: "TypeForwarder.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_typeForwarder2.Value; } public static class TypeForwarderLib { private static readonly Lazy<PortableExecutableReference> s_typeForwarderLib2 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.TypeForwarders.TypeForwarderLib).GetReference(display: "TypeForwarderLib.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_typeForwarderLib2.Value; } public static class TypeForwarderBase { private static readonly Lazy<PortableExecutableReference> s_typeForwarderBase2 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.TypeForwarders.TypeForwarderBase).GetReference(display: "TypeForwarderBase.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_typeForwarderBase2.Value; } } public static class MultiTargeting { private static readonly Lazy<PortableExecutableReference> s_source1Module = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.MultiTargeting.Source1Module).GetReference(display: "Source1Module.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Source1Module => s_source1Module.Value; private static readonly Lazy<PortableExecutableReference> s_source3Module = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.MultiTargeting.Source3Module).GetReference(display: "Source3Module.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Source3Module => s_source3Module.Value; private static readonly Lazy<PortableExecutableReference> s_source4Module = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.MultiTargeting.Source4Module).GetReference(display: "Source4Module.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Source4Module => s_source4Module.Value; private static readonly Lazy<PortableExecutableReference> s_source5Module = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.MultiTargeting.Source5Module).GetReference(display: "Source5Module.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Source5Module => s_source5Module.Value; private static readonly Lazy<PortableExecutableReference> s_source7Module = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.MultiTargeting.Source7Module).GetReference(display: "Source7Module.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Source7Module => s_source7Module.Value; } public static class NoPia { private static readonly Lazy<PortableExecutableReference> s_stdOle = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(ProprietaryTestResources.ProprietaryPias.stdole).GetReference(display: "stdole.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference StdOle => s_stdOle.Value; private static readonly Lazy<PortableExecutableReference> s_pia1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.Pia1).GetReference(display: "Pia1.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Pia1 => s_pia1.Value; private static readonly Lazy<PortableExecutableReference> s_pia1Copy = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.Pia1Copy).GetReference(display: "Pia1Copy.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Pia1Copy => s_pia1Copy.Value; private static readonly Lazy<PortableExecutableReference> s_pia2 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.Pia2).GetReference(display: "Pia2.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Pia2 => s_pia2.Value; private static readonly Lazy<PortableExecutableReference> s_pia3 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.Pia3).GetReference(display: "Pia3.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Pia3 => s_pia3.Value; private static readonly Lazy<PortableExecutableReference> s_pia4 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.Pia4).GetReference(display: "Pia4.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Pia4 => s_pia4.Value; private static readonly Lazy<PortableExecutableReference> s_pia5 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.Pia5).GetReference(display: "Pia5.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Pia5 => s_pia5.Value; private static readonly Lazy<PortableExecutableReference> s_generalPia = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.GeneralPia).GetReference(display: "GeneralPia.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference GeneralPia => s_generalPia.Value; private static readonly Lazy<PortableExecutableReference> s_generalPiaCopy = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.GeneralPiaCopy).GetReference(display: "GeneralPiaCopy.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference GeneralPiaCopy => s_generalPiaCopy.Value; private static readonly Lazy<PortableExecutableReference> s_noPIAGenericsAsm1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.NoPIAGenerics1_Asm1).GetReference(display: "NoPIAGenerics1-Asm1.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference NoPIAGenericsAsm1 => s_noPIAGenericsAsm1.Value; private static readonly Lazy<PortableExecutableReference> s_externalAsm1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.ExternalAsm1).GetReference(display: "ExternalAsm1.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference ExternalAsm1 => s_externalAsm1.Value; private static readonly Lazy<PortableExecutableReference> s_library1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.Library1).GetReference(display: "Library1.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Library1 => s_library1.Value; private static readonly Lazy<PortableExecutableReference> s_library2 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.Library2).GetReference(display: "Library2.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Library2 => s_library2.Value; private static readonly Lazy<PortableExecutableReference> s_localTypes1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.LocalTypes1).GetReference(display: "LocalTypes1.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference LocalTypes1 => s_localTypes1.Value; private static readonly Lazy<PortableExecutableReference> s_localTypes2 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.LocalTypes2).GetReference(display: "LocalTypes2.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference LocalTypes2 => s_localTypes2.Value; private static readonly Lazy<PortableExecutableReference> s_localTypes3 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.LocalTypes3).GetReference(display: "LocalTypes3.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference LocalTypes3 => s_localTypes3.Value; private static readonly Lazy<PortableExecutableReference> s_A = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.A).GetReference(display: "A.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference A => s_A.Value; private static readonly Lazy<PortableExecutableReference> s_B = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.B).GetReference(display: "B.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference B => s_B.Value; private static readonly Lazy<PortableExecutableReference> s_C = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.C).GetReference(display: "C.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference C => s_C.Value; private static readonly Lazy<PortableExecutableReference> s_D = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.D).GetReference(display: "D.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference D => s_D.Value; public static class Microsoft { public static class VisualStudio { private static readonly Lazy<PortableExecutableReference> s_missingPIAAttributes = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.MissingPIAAttributes).GetReference(display: "MicrosoftPIAAttributes.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference MissingPIAAttributes => s_missingPIAAttributes.Value; } } } public static class Interface { private static readonly Lazy<PortableExecutableReference> s_staticMethodInInterface = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Interface.StaticMethodInInterface).GetReference(display: "StaticMethodInInterface.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference StaticMethodInInterface => s_staticMethodInInterface.Value; private static readonly Lazy<PortableExecutableReference> s_MDInterfaceMapping = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Interface.MDInterfaceMapping).GetReference(display: "MDInterfaceMapping.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference MDInterfaceMapping => s_MDInterfaceMapping.Value; } public static class MetadataCache { private static readonly Lazy<PortableExecutableReference> s_MDTestLib1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.MDTestLib1).GetReference(display: "MDTestLib1.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference MDTestLib1 => s_MDTestLib1.Value; private static readonly Lazy<PortableExecutableReference> s_netModule1 = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.netModule1).GetReference(display: "netModule1.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference netModule1 => s_netModule1.Value; } public static class ExplicitInterfaceImplementation { public static class Methods { private static readonly Lazy<PortableExecutableReference> s_CSharp = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.CSharpExplicitInterfaceImplementation).GetReference(display: "CSharpExplicitInterfaceImplementation.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference CSharp => s_CSharp.Value; private static readonly Lazy<PortableExecutableReference> s_IL = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.ILExplicitInterfaceImplementation).GetReference(display: "ILExplicitInterfaceImplementation.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference IL => s_IL.Value; } public static class Properties { private static readonly Lazy<PortableExecutableReference> s_CSharp = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.CSharpExplicitInterfaceImplementationProperties).GetReference(display: "CSharpExplicitInterfaceImplementationProperties.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference CSharp => s_CSharp.Value; private static readonly Lazy<PortableExecutableReference> s_IL = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.ILExplicitInterfaceImplementationProperties).GetReference(display: "ILExplicitInterfaceImplementationProperties.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference IL => s_IL.Value; } public static class Events { private static readonly Lazy<PortableExecutableReference> s_CSharp = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.CSharpExplicitInterfaceImplementationEvents).GetReference(display: "CSharpExplicitInterfaceImplementationEvents.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference CSharp => s_CSharp.Value; } } private static readonly Lazy<PortableExecutableReference> s_regress40025 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.Regress40025DLL).GetReference(display: "Regress40025DLL.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Regress40025 => s_regress40025.Value; public static class WithEvents { private static readonly Lazy<PortableExecutableReference> s_simpleWithEvents = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.WithEvents.SimpleWithEvents).GetReference(display: "SimpleWithEvents.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference SimpleWithEvents => s_simpleWithEvents.Value; } public static class DelegateImplementation { private static readonly Lazy<PortableExecutableReference> s_delegatesWithoutInvoke = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.DelegatesWithoutInvoke).GetReference(display: "DelegatesWithoutInvoke.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference DelegatesWithoutInvoke => s_delegatesWithoutInvoke.Value; private static readonly Lazy<PortableExecutableReference> s_delegateByRefParamArray = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.DelegateByRefParamArray).GetReference(display: "DelegateByRefParamArray.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference DelegateByRefParamArray => s_delegateByRefParamArray.Value; } public static class Metadata { private static readonly Lazy<PortableExecutableReference> s_invalidCharactersInAssemblyName2 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Metadata.InvalidCharactersInAssemblyName).GetReference(display: "InvalidCharactersInAssemblyName.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference InvalidCharactersInAssemblyName => s_invalidCharactersInAssemblyName2.Value; private static readonly Lazy<PortableExecutableReference> s_MDTestAttributeDefLib = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Metadata.MDTestAttributeDefLib).GetReference(display: "MDTestAttributeDefLib.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference MDTestAttributeDefLib => s_MDTestAttributeDefLib.Value; private static readonly Lazy<PortableExecutableReference> s_MDTestAttributeApplicationLib = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Metadata.MDTestAttributeApplicationLib).GetReference(display: "MDTestAttributeApplicationLib.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference MDTestAttributeApplicationLib => s_MDTestAttributeApplicationLib.Value; private static readonly Lazy<PortableExecutableReference> s_attributeInterop01 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeInterop01).GetReference(display: "AttributeInterop01.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference AttributeInterop01 => s_attributeInterop01.Value; private static readonly Lazy<PortableExecutableReference> s_attributeInterop02 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeInterop02).GetReference(display: "AttributeInterop02.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference AttributeInterop02 => s_attributeInterop02.Value; private static readonly Lazy<PortableExecutableReference> s_attributeTestLib01 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestLib01).GetReference(display: "AttributeTestLib01.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference AttributeTestLib01 => s_attributeTestLib01.Value; private static readonly Lazy<PortableExecutableReference> s_attributeTestDef01 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01).GetReference(display: "AttributeTestDef01.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference AttributeTestDef01 => s_attributeTestDef01.Value; private static readonly Lazy<PortableExecutableReference> s_dynamicAttributeLib = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Metadata.DynamicAttribute).GetReference(display: "DynamicAttribute.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference DynamicAttributeLib => s_dynamicAttributeLib.Value; } public static class UseSiteErrors { private static readonly Lazy<PortableExecutableReference> s_unavailable = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.Unavailable).GetReference(display: "Unavailable.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Unavailable => s_unavailable.Value; private static readonly Lazy<PortableExecutableReference> s_CSharp = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.CSharpErrors).GetReference(display: "CSharpErrors.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference CSharp => s_CSharp.Value; private static readonly Lazy<PortableExecutableReference> s_IL = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.ILErrors).GetReference(display: "ILErrors.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference IL => s_IL.Value; } public static class Versioning { private static readonly Lazy<PortableExecutableReference> s_AR_SA = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.Culture_AR_SA).GetReference(display: "AR-SA"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference AR_SA => s_AR_SA.Value; private static readonly Lazy<PortableExecutableReference> s_EN_US = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.Culture_EN_US).GetReference(display: "EN-US"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference EN_US => s_EN_US.Value; private static readonly Lazy<PortableExecutableReference> s_C1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.C1).GetReference(display: "C1"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference C1 => s_C1.Value; private static readonly Lazy<PortableExecutableReference> s_C2 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.C2).GetReference(display: "C2"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference C2 => s_C2.Value; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Resources.Proprietary; using Roslyn.Test.Utilities; public static class TestReferences { public static class MetadataTests { public static class NetModule01 { private static readonly Lazy<PortableExecutableReference> s_appCS = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.MetadataTests.NetModule01.AppCS).GetReference(display: "AppCS"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference AppCS => s_appCS.Value; private static readonly Lazy<PortableExecutableReference> s_moduleCS00 = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.MetadataTests.NetModule01.ModuleCS00).GetReference(display: "ModuleCS00.mod"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference ModuleCS00 => s_moduleCS00.Value; private static readonly Lazy<PortableExecutableReference> s_moduleCS01 = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.MetadataTests.NetModule01.ModuleCS01).GetReference(display: "ModuleCS01.mod"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference ModuleCS01 => s_moduleCS01.Value; private static readonly Lazy<PortableExecutableReference> s_moduleVB01 = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.MetadataTests.NetModule01.ModuleVB01).GetReference(display: "ModuleVB01.mod"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference ModuleVB01 => s_moduleVB01.Value; } public static class InterfaceAndClass { private static readonly Lazy<PortableExecutableReference> s_CSClasses01 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.MetadataTests.InterfaceAndClass.CSClasses01).GetReference(display: "CSClasses01.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference CSClasses01 => s_CSClasses01.Value; private static readonly Lazy<PortableExecutableReference> s_CSInterfaces01 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.MetadataTests.InterfaceAndClass.CSInterfaces01).GetReference(display: "CSInterfaces01.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference CSInterfaces01 => s_CSInterfaces01.Value; private static readonly Lazy<PortableExecutableReference> s_VBClasses01 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.MetadataTests.InterfaceAndClass.VBClasses01).GetReference(display: "VBClasses01.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference VBClasses01 => s_VBClasses01.Value; private static readonly Lazy<PortableExecutableReference> s_VBClasses02 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.MetadataTests.InterfaceAndClass.VBClasses02).GetReference(display: "VBClasses02.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference VBClasses02 => s_VBClasses02.Value; private static readonly Lazy<PortableExecutableReference> s_VBInterfaces01 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.MetadataTests.InterfaceAndClass.VBInterfaces01).GetReference(display: "VBInterfaces01.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference VBInterfaces01 => s_VBInterfaces01.Value; } } public static class NetFx { public static class Minimal { private static readonly Lazy<PortableExecutableReference> s_mincorlib = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.NetFX.Minimal.mincorlib).GetReference(display: "mincorlib.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference mincorlib => s_mincorlib.Value; private static readonly Lazy<PortableExecutableReference> s_minasync = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.NetFX.Minimal.minasync).GetReference(display: "minasync.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference minasync => s_minasync.Value; private static readonly Lazy<PortableExecutableReference> s_minasynccorlib = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.NetFX.Minimal.minasynccorlib).GetReference(display: "minasynccorlib.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference minasynccorlib => s_minasynccorlib.Value; } public static class ValueTuple { private static readonly Lazy<PortableExecutableReference> s_tuplelib = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.NetFX.ValueTuple.tuplelib).GetReference(display: "System.ValueTuple.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference tuplelib => s_tuplelib.Value; } public static class silverlight_v5_0_5_0 { private static readonly Lazy<PortableExecutableReference> s_system = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(ProprietaryTestResources.silverlight_v5_0_5_0.System_v5_0_5_0_silverlight).GetReference(display: "System.v5.0.5.0_silverlight.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference System => s_system.Value; } } public static class DiagnosticTests { public static class ErrTestLib01 { private static readonly Lazy<PortableExecutableReference> s_errTestLib01 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.DiagnosticTests.ErrTestLib01).GetReference(display: "ErrTestLib01.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_errTestLib01.Value; } public static class ErrTestLib02 { private static readonly Lazy<PortableExecutableReference> s_errTestLib02 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.DiagnosticTests.ErrTestLib02).GetReference(display: "ErrTestLib02.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_errTestLib02.Value; } public static class ErrTestLib11 { private static readonly Lazy<PortableExecutableReference> s_errTestLib11 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.DiagnosticTests.ErrTestLib11).GetReference(display: "ErrTestLib11.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_errTestLib11.Value; } public static class ErrTestMod01 { private static readonly Lazy<PortableExecutableReference> s_errTestMod01 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.DiagnosticTests.ErrTestMod01).GetReference(display: "ErrTestMod01.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_errTestMod01.Value; } public static class ErrTestMod02 { private static readonly Lazy<PortableExecutableReference> s_errTestMod02 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.DiagnosticTests.ErrTestMod02).GetReference(display: "ErrTestMod02.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_errTestMod02.Value; } public static class badresfile { private static readonly Lazy<PortableExecutableReference> s_badresfile = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.DiagnosticTests.badresfile).GetReference(display: "badresfile.res"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference res => s_badresfile.Value; } } public static class SymbolsTests { private static readonly Lazy<PortableExecutableReference> s_mdTestLib1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.MDTestLib1).GetReference(display: "MDTestLib1.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference MDTestLib1 => s_mdTestLib1.Value; private static readonly Lazy<PortableExecutableReference> s_mdTestLib2 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.MDTestLib2).GetReference(display: "MDTestLib2.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference MDTestLib2 => s_mdTestLib2.Value; private static readonly Lazy<PortableExecutableReference> s_VBConversions = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.VBConversions).GetReference(display: "VBConversions.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference VBConversions => s_VBConversions.Value; private static readonly Lazy<PortableExecutableReference> s_withSpaces = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.With_Spaces).GetReference(display: "With Spaces.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference WithSpaces => s_withSpaces.Value; private static readonly Lazy<PortableExecutableReference> s_withSpacesModule = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.General.With_SpacesModule).GetReference(display: "With Spaces.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference WithSpacesModule => s_withSpacesModule.Value; private static readonly Lazy<PortableExecutableReference> s_inheritIComparable = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.InheritIComparable).GetReference(display: "InheritIComparable.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference InheritIComparable => s_inheritIComparable.Value; private static readonly Lazy<PortableExecutableReference> s_bigVisitor = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.BigVisitor).GetReference(display: "BigVisitor.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference BigVisitor => s_bigVisitor.Value; private static readonly Lazy<PortableExecutableReference> s_properties = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.Properties).GetReference(display: "Properties.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Properties => s_properties.Value; private static readonly Lazy<PortableExecutableReference> s_propertiesWithByRef = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.PropertiesWithByRef).GetReference(display: "PropertiesWithByRef.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference PropertiesWithByRef => s_propertiesWithByRef.Value; private static readonly Lazy<PortableExecutableReference> s_indexers = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.Indexers).GetReference(display: "Indexers.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Indexers => s_indexers.Value; private static readonly Lazy<PortableExecutableReference> s_events = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.Events).GetReference(display: "Events.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Events => s_events.Value; public static class netModule { private static readonly Lazy<PortableExecutableReference> s_netModule1 = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.netModule1).GetReference(display: "netModule1.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference netModule1 => s_netModule1.Value; private static readonly Lazy<PortableExecutableReference> s_netModule2 = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.netModule2).GetReference(display: "netModule2.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference netModule2 => s_netModule2.Value; private static readonly Lazy<PortableExecutableReference> s_crossRefModule1 = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.CrossRefModule1).GetReference(display: "CrossRefModule1.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference CrossRefModule1 => s_crossRefModule1.Value; private static readonly Lazy<PortableExecutableReference> s_crossRefModule2 = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.CrossRefModule2).GetReference(display: "CrossRefModule2.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference CrossRefModule2 => s_crossRefModule2.Value; private static readonly Lazy<PortableExecutableReference> s_crossRefLib = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.Create( ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.CrossRefLib), ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.CrossRefModule1), ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.CrossRefModule2)).GetReference(display: "CrossRefLib.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference CrossRefLib => s_crossRefLib.Value; private static readonly Lazy<PortableExecutableReference> s_hash_module = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.hash_module).GetReference(display: "hash_module.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference hash_module => s_hash_module.Value; private static readonly Lazy<PortableExecutableReference> s_x64COFF = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.x64COFF).GetReference(display: "x64COFF.obj"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference x64COFF => s_x64COFF.Value; } public static class V1 { public static class MTTestLib1 { private static readonly Lazy<PortableExecutableReference> s_v1MTTestLib1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.V1.MTTestLib1).GetReference(display: "MTTestLib1.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_v1MTTestLib1.Value; } public static class MTTestModule1 { private static readonly Lazy<PortableExecutableReference> s_v1MTTestLib1 = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.V1.MTTestModule1).GetReference(display: "MTTestModule1.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference netmodule => s_v1MTTestLib1.Value; } public static class MTTestLib2 { private static readonly Lazy<PortableExecutableReference> s_v1MTTestLib2 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.V1.MTTestLib2).GetReference(display: "MTTestLib2.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_v1MTTestLib2.Value; } public static class MTTestModule2 { private static readonly Lazy<PortableExecutableReference> s_v1MTTestLib1 = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.V1.MTTestModule2).GetReference(display: "MTTestModule2.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference netmodule => s_v1MTTestLib1.Value; } } public static class V2 { public static class MTTestLib1 { private static readonly Lazy<PortableExecutableReference> s_v2MTTestLib1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.V2.MTTestLib1).GetReference(display: "MTTestLib1.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_v2MTTestLib1.Value; } public static class MTTestModule1 { private static readonly Lazy<PortableExecutableReference> s_v1MTTestLib1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.V2.MTTestModule1).GetReference(display: "MTTestModule1.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference netmodule => s_v1MTTestLib1.Value; } public static class MTTestLib3 { private static readonly Lazy<PortableExecutableReference> s_v2MTTestLib3 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.V2.MTTestLib3).GetReference(display: "MTTestLib3.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_v2MTTestLib3.Value; } public static class MTTestModule3 { private static readonly Lazy<PortableExecutableReference> s_v1MTTestLib1 = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.V2.MTTestModule3).GetReference(display: "MTTestModule3.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference netmodule => s_v1MTTestLib1.Value; } } public static class V3 { public static class MTTestLib1 { private static readonly Lazy<PortableExecutableReference> s_v3MTTestLib1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.V3.MTTestLib1).GetReference(display: "MTTestLib1.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_v3MTTestLib1.Value; } public static class MTTestModule1 { private static readonly Lazy<PortableExecutableReference> s_v1MTTestLib1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.V3.MTTestModule1).GetReference(display: "MTTestModule1.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference netmodule => s_v1MTTestLib1.Value; } public static class MTTestLib4 { private static readonly Lazy<PortableExecutableReference> s_v3MTTestLib4 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.V3.MTTestLib4).GetReference(display: "MTTestLib4.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_v3MTTestLib4.Value; } public static class MTTestModule4 { private static readonly Lazy<PortableExecutableReference> s_v1MTTestLib1 = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.V3.MTTestModule4).GetReference(display: "MTTestModule4.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference netmodule => s_v1MTTestLib1.Value; } } public static class MultiModule { private static readonly Lazy<PortableExecutableReference> s_assembly = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.Create( ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.MultiModule.MultiModuleDll), ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.MultiModule.mod2), ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.MultiModule.mod3)).GetReference(display: "MultiModule.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Assembly => s_assembly.Value; private static readonly Lazy<PortableExecutableReference> s_mod2 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.MultiModule.mod2).GetReference(display: "mod2.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference mod2 => s_mod2.Value; private static readonly Lazy<PortableExecutableReference> s_mod3 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.MultiModule.mod3).GetReference(display: "mod3.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference mod3 => s_mod3.Value; private static readonly Lazy<PortableExecutableReference> s_consumer = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.MultiModule.Consumer).GetReference(display: "Consumer.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Consumer => s_consumer.Value; } public static class DifferByCase { private static readonly Lazy<PortableExecutableReference> s_typeAndNamespaceDifferByCase = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.DifferByCase.TypeAndNamespaceDifferByCase).GetReference(display: "TypeAndNamespaceDifferByCase.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference TypeAndNamespaceDifferByCase => s_typeAndNamespaceDifferByCase.Value; private static readonly Lazy<PortableExecutableReference> s_differByCaseConsumer = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.DifferByCase.Consumer).GetReference(display: "Consumer.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Consumer => s_differByCaseConsumer.Value; private static readonly Lazy<PortableExecutableReference> s_csharpCaseSen = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.DifferByCase.Consumer).GetReference(display: "CsharpCaseSen.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference CsharpCaseSen => s_csharpCaseSen.Value; private static readonly Lazy<PortableExecutableReference> s_csharpDifferCaseOverloads = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.DifferByCase.CSharpDifferCaseOverloads).GetReference(display: "CSharpDifferCaseOverloads.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference CsharpDifferCaseOverloads => s_csharpDifferCaseOverloads.Value; } public static class CorLibrary { public static class GuidTest2 { private static readonly Lazy<PortableExecutableReference> s_exe = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.CorLibrary.GuidTest2).GetReference(display: "GuidTest2.exe"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference exe => s_exe.Value; } private static readonly Lazy<PortableExecutableReference> s_noMsCorLibRef = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.CorLibrary.NoMsCorLibRef).GetReference(display: "NoMsCorLibRef.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference NoMsCorLibRef => s_noMsCorLibRef.Value; public static class FakeMsCorLib { private static readonly Lazy<PortableExecutableReference> s_dll = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.CorLibrary.FakeMsCorLib).GetReference(display: "FakeMsCorLib.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_dll.Value; } } public static class CustomModifiers { public static class Modifiers { private static readonly Lazy<PortableExecutableReference> s_dll = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.CustomModifiers.Modifiers).GetReference(display: "Modifiers.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_dll.Value; private static readonly Lazy<PortableExecutableReference> s_module = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.CustomModifiers.ModifiersModule).GetReference(display: "Modifiers.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference netmodule => s_module.Value; } private static readonly Lazy<PortableExecutableReference> s_modoptTests = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.CustomModifiers.ModoptTests).GetReference(display: "ModoptTests.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference ModoptTests => s_modoptTests.Value; public static class CppCli { private static readonly Lazy<PortableExecutableReference> s_dll = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.CustomModifiers.CppCli).GetReference(display: "CppCli.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_dll.Value; } public static class GenericMethodWithModifiers { private static readonly Lazy<PortableExecutableReference> s_dll = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.CustomModifiers.GenericMethodWithModifiers).GetReference(display: "GenericMethodWithModifiers.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_dll.Value; } } public static class Cyclic { public static class Cyclic1 { private static readonly Lazy<PortableExecutableReference> s_cyclic1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Cyclic.Cyclic1).GetReference(display: "Cyclic1.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_cyclic1.Value; } public static class Cyclic2 { private static readonly Lazy<PortableExecutableReference> s_cyclic2 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Cyclic.Cyclic2).GetReference(display: "Cyclic2.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_cyclic2.Value; } } public static class CyclicInheritance { private static readonly Lazy<PortableExecutableReference> s_class1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.CyclicInheritance.Class1).GetReference(display: "Class1.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Class1 => s_class1.Value; private static readonly Lazy<PortableExecutableReference> s_class2 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.CyclicInheritance.Class2).GetReference(display: "Class2.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Class2 => s_class2.Value; private static readonly Lazy<PortableExecutableReference> s_class3 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.CyclicInheritance.Class3).GetReference(display: "Class3.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Class3 => s_class3.Value; } private static readonly Lazy<PortableExecutableReference> s_cycledStructs = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.CyclicStructure.cycledstructs).GetReference(display: "cycledstructs.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference CycledStructs => s_cycledStructs.Value; public static class RetargetingCycle { public static class V1 { public static class ClassA { private static readonly Lazy<PortableExecutableReference> s_classA = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.RetargetingCycle.RetV1.ClassA).GetReference(display: "ClassA.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_classA.Value; } public static class ClassB { private static readonly Lazy<PortableExecutableReference> s_classB = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.RetargetingCycle.RetV1.ClassB).GetReference(display: "ClassB.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference netmodule => s_classB.Value; } } public static class V2 { public static class ClassA { private static readonly Lazy<PortableExecutableReference> s_classA = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.RetargetingCycle.RetV2.ClassA).GetReference(display: "ClassA.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_classA.Value; } public static class ClassB { private static readonly Lazy<PortableExecutableReference> s_classB = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.RetargetingCycle.RetV2.ClassB).GetReference(display: "ClassB.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_classB.Value; } } } public static class Methods { private static readonly Lazy<PortableExecutableReference> s_CSMethods = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Methods.CSMethods).GetReference(display: "CSMethods.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference CSMethods => s_CSMethods.Value; private static readonly Lazy<PortableExecutableReference> s_VBMethods = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Methods.VBMethods).GetReference(display: "VBMethods.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference VBMethods => s_VBMethods.Value; private static readonly Lazy<PortableExecutableReference> s_ILMethods = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Methods.ILMethods).GetReference(display: "ILMethods.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference ILMethods => s_ILMethods.Value; private static readonly Lazy<PortableExecutableReference> s_byRefReturn = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Methods.ByRefReturn).GetReference(display: "ByRefReturn.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference ByRefReturn => s_byRefReturn.Value; } public static class Fields { public static class CSFields { private static readonly Lazy<PortableExecutableReference> s_CSFields = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Fields.CSFields).GetReference(display: "CSFields.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_CSFields.Value; } public static class VBFields { private static readonly Lazy<PortableExecutableReference> s_VBFields = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Fields.VBFields).GetReference(display: "VBFields.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_VBFields.Value; } private static readonly Lazy<PortableExecutableReference> s_constantFields = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Fields.ConstantFields).GetReference(display: "ConstantFields.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference ConstantFields => s_constantFields.Value; } public static class MissingTypes { private static readonly Lazy<PortableExecutableReference> s_MDMissingType = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.MissingTypes.MDMissingType).GetReference(display: "MDMissingType.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference MDMissingType => s_MDMissingType.Value; private static readonly Lazy<PortableExecutableReference> s_MDMissingTypeLib = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.MissingTypes.MDMissingTypeLib).GetReference(display: "MDMissingTypeLib.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference MDMissingTypeLib => s_MDMissingTypeLib.Value; private static readonly Lazy<PortableExecutableReference> s_missingTypesEquality1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.MissingTypes.MissingTypesEquality1).GetReference(display: "MissingTypesEquality1.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference MissingTypesEquality1 => s_missingTypesEquality1.Value; private static readonly Lazy<PortableExecutableReference> s_missingTypesEquality2 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.MissingTypes.MissingTypesEquality2).GetReference(display: "MissingTypesEquality2.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference MissingTypesEquality2 => s_missingTypesEquality2.Value; private static readonly Lazy<PortableExecutableReference> s_CL2 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.MissingTypes.CL2).GetReference(display: "CL2.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference CL2 => s_CL2.Value; private static readonly Lazy<PortableExecutableReference> s_CL3 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.MissingTypes.CL3).GetReference(display: "CL3.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference CL3 => s_CL3.Value; } public static class TypeForwarders { public static class TypeForwarder { private static readonly Lazy<PortableExecutableReference> s_typeForwarder2 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.TypeForwarders.TypeForwarder).GetReference(display: "TypeForwarder.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_typeForwarder2.Value; } public static class TypeForwarderLib { private static readonly Lazy<PortableExecutableReference> s_typeForwarderLib2 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.TypeForwarders.TypeForwarderLib).GetReference(display: "TypeForwarderLib.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_typeForwarderLib2.Value; } public static class TypeForwarderBase { private static readonly Lazy<PortableExecutableReference> s_typeForwarderBase2 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.TypeForwarders.TypeForwarderBase).GetReference(display: "TypeForwarderBase.Dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference dll => s_typeForwarderBase2.Value; } } public static class MultiTargeting { private static readonly Lazy<PortableExecutableReference> s_source1Module = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.MultiTargeting.Source1Module).GetReference(display: "Source1Module.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Source1Module => s_source1Module.Value; private static readonly Lazy<PortableExecutableReference> s_source3Module = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.MultiTargeting.Source3Module).GetReference(display: "Source3Module.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Source3Module => s_source3Module.Value; private static readonly Lazy<PortableExecutableReference> s_source4Module = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.MultiTargeting.Source4Module).GetReference(display: "Source4Module.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Source4Module => s_source4Module.Value; private static readonly Lazy<PortableExecutableReference> s_source5Module = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.MultiTargeting.Source5Module).GetReference(display: "Source5Module.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Source5Module => s_source5Module.Value; private static readonly Lazy<PortableExecutableReference> s_source7Module = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.MultiTargeting.Source7Module).GetReference(display: "Source7Module.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Source7Module => s_source7Module.Value; } public static class NoPia { private static readonly Lazy<PortableExecutableReference> s_stdOle = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(ProprietaryTestResources.ProprietaryPias.stdole).GetReference(display: "stdole.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference StdOle => s_stdOle.Value; private static readonly Lazy<PortableExecutableReference> s_pia1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.Pia1).GetReference(display: "Pia1.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Pia1 => s_pia1.Value; private static readonly Lazy<PortableExecutableReference> s_pia1Copy = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.Pia1Copy).GetReference(display: "Pia1Copy.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Pia1Copy => s_pia1Copy.Value; private static readonly Lazy<PortableExecutableReference> s_pia2 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.Pia2).GetReference(display: "Pia2.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Pia2 => s_pia2.Value; private static readonly Lazy<PortableExecutableReference> s_pia3 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.Pia3).GetReference(display: "Pia3.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Pia3 => s_pia3.Value; private static readonly Lazy<PortableExecutableReference> s_pia4 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.Pia4).GetReference(display: "Pia4.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Pia4 => s_pia4.Value; private static readonly Lazy<PortableExecutableReference> s_pia5 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.Pia5).GetReference(display: "Pia5.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Pia5 => s_pia5.Value; private static readonly Lazy<PortableExecutableReference> s_generalPia = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.GeneralPia).GetReference(display: "GeneralPia.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference GeneralPia => s_generalPia.Value; private static readonly Lazy<PortableExecutableReference> s_generalPiaCopy = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.GeneralPiaCopy).GetReference(display: "GeneralPiaCopy.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference GeneralPiaCopy => s_generalPiaCopy.Value; private static readonly Lazy<PortableExecutableReference> s_noPIAGenericsAsm1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.NoPIAGenerics1_Asm1).GetReference(display: "NoPIAGenerics1-Asm1.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference NoPIAGenericsAsm1 => s_noPIAGenericsAsm1.Value; private static readonly Lazy<PortableExecutableReference> s_externalAsm1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.ExternalAsm1).GetReference(display: "ExternalAsm1.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference ExternalAsm1 => s_externalAsm1.Value; private static readonly Lazy<PortableExecutableReference> s_library1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.Library1).GetReference(display: "Library1.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Library1 => s_library1.Value; private static readonly Lazy<PortableExecutableReference> s_library2 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.Library2).GetReference(display: "Library2.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Library2 => s_library2.Value; private static readonly Lazy<PortableExecutableReference> s_localTypes1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.LocalTypes1).GetReference(display: "LocalTypes1.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference LocalTypes1 => s_localTypes1.Value; private static readonly Lazy<PortableExecutableReference> s_localTypes2 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.LocalTypes2).GetReference(display: "LocalTypes2.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference LocalTypes2 => s_localTypes2.Value; private static readonly Lazy<PortableExecutableReference> s_localTypes3 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.LocalTypes3).GetReference(display: "LocalTypes3.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference LocalTypes3 => s_localTypes3.Value; private static readonly Lazy<PortableExecutableReference> s_A = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.A).GetReference(display: "A.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference A => s_A.Value; private static readonly Lazy<PortableExecutableReference> s_B = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.B).GetReference(display: "B.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference B => s_B.Value; private static readonly Lazy<PortableExecutableReference> s_C = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.C).GetReference(display: "C.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference C => s_C.Value; private static readonly Lazy<PortableExecutableReference> s_D = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.D).GetReference(display: "D.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference D => s_D.Value; public static class Microsoft { public static class VisualStudio { private static readonly Lazy<PortableExecutableReference> s_missingPIAAttributes = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.MissingPIAAttributes).GetReference(display: "MicrosoftPIAAttributes.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference MissingPIAAttributes => s_missingPIAAttributes.Value; } } } public static class Interface { private static readonly Lazy<PortableExecutableReference> s_staticMethodInInterface = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Interface.StaticMethodInInterface).GetReference(display: "StaticMethodInInterface.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference StaticMethodInInterface => s_staticMethodInInterface.Value; private static readonly Lazy<PortableExecutableReference> s_MDInterfaceMapping = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Interface.MDInterfaceMapping).GetReference(display: "MDInterfaceMapping.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference MDInterfaceMapping => s_MDInterfaceMapping.Value; } public static class MetadataCache { private static readonly Lazy<PortableExecutableReference> s_MDTestLib1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.MDTestLib1).GetReference(display: "MDTestLib1.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference MDTestLib1 => s_MDTestLib1.Value; private static readonly Lazy<PortableExecutableReference> s_netModule1 = new Lazy<PortableExecutableReference>( () => ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.netModule1).GetReference(display: "netModule1.netmodule"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference netModule1 => s_netModule1.Value; } public static class ExplicitInterfaceImplementation { public static class Methods { private static readonly Lazy<PortableExecutableReference> s_CSharp = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.CSharpExplicitInterfaceImplementation).GetReference(display: "CSharpExplicitInterfaceImplementation.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference CSharp => s_CSharp.Value; private static readonly Lazy<PortableExecutableReference> s_IL = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.ILExplicitInterfaceImplementation).GetReference(display: "ILExplicitInterfaceImplementation.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference IL => s_IL.Value; } public static class Properties { private static readonly Lazy<PortableExecutableReference> s_CSharp = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.CSharpExplicitInterfaceImplementationProperties).GetReference(display: "CSharpExplicitInterfaceImplementationProperties.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference CSharp => s_CSharp.Value; private static readonly Lazy<PortableExecutableReference> s_IL = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.ILExplicitInterfaceImplementationProperties).GetReference(display: "ILExplicitInterfaceImplementationProperties.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference IL => s_IL.Value; } public static class Events { private static readonly Lazy<PortableExecutableReference> s_CSharp = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.CSharpExplicitInterfaceImplementationEvents).GetReference(display: "CSharpExplicitInterfaceImplementationEvents.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference CSharp => s_CSharp.Value; } } private static readonly Lazy<PortableExecutableReference> s_regress40025 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.Regress40025DLL).GetReference(display: "Regress40025DLL.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Regress40025 => s_regress40025.Value; public static class WithEvents { private static readonly Lazy<PortableExecutableReference> s_simpleWithEvents = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.WithEvents.SimpleWithEvents).GetReference(display: "SimpleWithEvents.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference SimpleWithEvents => s_simpleWithEvents.Value; } public static class DelegateImplementation { private static readonly Lazy<PortableExecutableReference> s_delegatesWithoutInvoke = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.DelegatesWithoutInvoke).GetReference(display: "DelegatesWithoutInvoke.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference DelegatesWithoutInvoke => s_delegatesWithoutInvoke.Value; private static readonly Lazy<PortableExecutableReference> s_delegateByRefParamArray = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.DelegateByRefParamArray).GetReference(display: "DelegateByRefParamArray.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference DelegateByRefParamArray => s_delegateByRefParamArray.Value; } public static class Metadata { private static readonly Lazy<PortableExecutableReference> s_invalidCharactersInAssemblyName2 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Metadata.InvalidCharactersInAssemblyName).GetReference(display: "InvalidCharactersInAssemblyName.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference InvalidCharactersInAssemblyName => s_invalidCharactersInAssemblyName2.Value; private static readonly Lazy<PortableExecutableReference> s_MDTestAttributeDefLib = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Metadata.MDTestAttributeDefLib).GetReference(display: "MDTestAttributeDefLib.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference MDTestAttributeDefLib => s_MDTestAttributeDefLib.Value; private static readonly Lazy<PortableExecutableReference> s_MDTestAttributeApplicationLib = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Metadata.MDTestAttributeApplicationLib).GetReference(display: "MDTestAttributeApplicationLib.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference MDTestAttributeApplicationLib => s_MDTestAttributeApplicationLib.Value; private static readonly Lazy<PortableExecutableReference> s_attributeInterop01 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeInterop01).GetReference(display: "AttributeInterop01.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference AttributeInterop01 => s_attributeInterop01.Value; private static readonly Lazy<PortableExecutableReference> s_attributeInterop02 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeInterop02).GetReference(display: "AttributeInterop02.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference AttributeInterop02 => s_attributeInterop02.Value; private static readonly Lazy<PortableExecutableReference> s_attributeTestLib01 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestLib01).GetReference(display: "AttributeTestLib01.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference AttributeTestLib01 => s_attributeTestLib01.Value; private static readonly Lazy<PortableExecutableReference> s_attributeTestDef01 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01).GetReference(display: "AttributeTestDef01.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference AttributeTestDef01 => s_attributeTestDef01.Value; private static readonly Lazy<PortableExecutableReference> s_dynamicAttributeLib = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.Metadata.DynamicAttribute).GetReference(display: "DynamicAttribute.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference DynamicAttributeLib => s_dynamicAttributeLib.Value; } public static class UseSiteErrors { private static readonly Lazy<PortableExecutableReference> s_unavailable = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.Unavailable).GetReference(display: "Unavailable.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference Unavailable => s_unavailable.Value; private static readonly Lazy<PortableExecutableReference> s_CSharp = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.CSharpErrors).GetReference(display: "CSharpErrors.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference CSharp => s_CSharp.Value; private static readonly Lazy<PortableExecutableReference> s_IL = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.ILErrors).GetReference(display: "ILErrors.dll"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference IL => s_IL.Value; } public static class Versioning { private static readonly Lazy<PortableExecutableReference> s_AR_SA = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.Culture_AR_SA).GetReference(display: "AR-SA"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference AR_SA => s_AR_SA.Value; private static readonly Lazy<PortableExecutableReference> s_EN_US = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.Culture_EN_US).GetReference(display: "EN-US"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference EN_US => s_EN_US.Value; private static readonly Lazy<PortableExecutableReference> s_C1 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.C1).GetReference(display: "C1"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference C1 => s_C1.Value; private static readonly Lazy<PortableExecutableReference> s_C2 = new Lazy<PortableExecutableReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.C2).GetReference(display: "C2"), LazyThreadSafetyMode.PublicationOnly); public static PortableExecutableReference C2 => s_C2.Value; } } }
1
dotnet/roslyn
56,223
Rework our netstandard1.3 test references
The `netstandard1.3` test references were being provided by our MS.CA.Test.Resources.Proprietary package. The contents of this package get included in the output directory of every single unit test DLL that we build (which contributes to build output size). The references themselves though were only used in a very small number of tests. This change upgrades to a version of MS.CA.Test.Resources.Proprietary that has the `netstandard1.3` references removed and adds the `netstandard1.3` references to only the projects that needs them
jaredpar
"2021-09-07T20:35:04Z"
"2021-09-07T23:50:57Z"
0240973369997c88a2c2f1aaa22c14182ac17e9f
5dbd783367d7f6b105726b84558cc1809aa198ce
Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our MS.CA.Test.Resources.Proprietary package. The contents of this package get included in the output directory of every single unit test DLL that we build (which contributes to build output size). The references themselves though were only used in a very small number of tests. This change upgrades to a version of MS.CA.Test.Resources.Proprietary that has the `netstandard1.3` references removed and adds the `netstandard1.3` references to only the projects that needs them
./src/Compilers/Test/Core/Platform/Desktop/TestHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #if NET472 using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Resources.Proprietary; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.Win32; using Basic.Reference.Assemblies; namespace Roslyn.Test.Utilities { public static class DesktopTestHelpers { public static IEnumerable<Type> GetAllTypesImplementingGivenInterface(Assembly assembly, Type interfaceType) { if (assembly == null || interfaceType == null || !interfaceType.IsInterface) { throw new ArgumentException("interfaceType is not an interface.", nameof(interfaceType)); } return assembly.GetTypes().Where((t) => { // simplest way to get types that implement mef type // we might need to actually check whether type export the interface type later if (t.IsAbstract) { return false; } var candidate = t.GetInterface(interfaceType.ToString()); return candidate != null && candidate.Equals(interfaceType); }).ToList(); } public static IEnumerable<Type> GetAllTypesSubclassingType(Assembly assembly, Type type) { if (assembly == null || type == null) { throw new ArgumentException("Invalid arguments"); } return (from t in assembly.GetTypes() where !t.IsAbstract where type.IsAssignableFrom(t) select t).ToList(); } public static TempFile CreateCSharpAnalyzerAssemblyWithTestAnalyzer(TempDirectory dir, string assemblyName) { var analyzerSource = @" using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; [DiagnosticAnalyzer(LanguageNames.CSharp)] public class TestAnalyzer : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } } public override void Initialize(AnalysisContext context) { throw new NotImplementedException(); } }"; dir.CopyFile(typeof(System.Reflection.Metadata.MetadataReader).Assembly.Location); var immutable = dir.CopyFile(typeof(ImmutableArray).Assembly.Location); var analyzer = dir.CopyFile(typeof(DiagnosticAnalyzer).Assembly.Location); dir.CopyFile(typeof(Memory<>).Assembly.Location); dir.CopyFile(typeof(System.Runtime.CompilerServices.Unsafe).Assembly.Location); var analyzerCompilation = CSharpCompilation.Create( assemblyName, new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree(analyzerSource) }, new MetadataReference[] { NetStandard20.mscorlib, NetStandard20.netstandard, NetStandard20.SystemRuntime, MetadataReference.CreateFromFile(immutable.Path), MetadataReference.CreateFromFile(analyzer.Path) }, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); return dir.CreateFile(assemblyName + ".dll").WriteAllBytes(analyzerCompilation.EmitToArray()); } public static ImmutableArray<byte> CreateCSharpAnalyzerNetStandard13(string analyzerAssemblyName) { var minSystemCollectionsImmutableSource = @" [assembly: System.Reflection.AssemblyVersion(""1.2.3.0"")] namespace System.Collections.Immutable { public struct ImmutableArray<T> { } } "; var minCodeAnalysisSource = @" using System; [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] namespace Microsoft.CodeAnalysis.Diagnostics { [AttributeUsage(AttributeTargets.Class)] public sealed class DiagnosticAnalyzerAttribute : Attribute { public DiagnosticAnalyzerAttribute(string firstLanguage, params string[] additionalLanguages) {} } public abstract class DiagnosticAnalyzer { public abstract System.Collections.Immutable.ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } public abstract void Initialize(AnalysisContext context); } public abstract class AnalysisContext { } } namespace Microsoft.CodeAnalysis { public sealed class DiagnosticDescriptor { } } "; var minSystemCollectionsImmutableImage = CSharpCompilation.Create( "System.Collections.Immutable", new[] { SyntaxFactory.ParseSyntaxTree(minSystemCollectionsImmutableSource) }, new[] { MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Runtime) }, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, cryptoPublicKey: TestResources.TestKeys.PublicKey_b03f5f7f11d50a3a)).EmitToArray(); var minSystemCollectionsImmutableRef = MetadataReference.CreateFromImage(minSystemCollectionsImmutableImage); var minCodeAnalysisImage = CSharpCompilation.Create( "Microsoft.CodeAnalysis", new[] { SyntaxFactory.ParseSyntaxTree(minCodeAnalysisSource) }, new[] { MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Runtime), minSystemCollectionsImmutableRef }, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, cryptoPublicKey: TestResources.TestKeys.PublicKey_31bf3856ad364e35)).EmitToArray(); var minCodeAnalysisRef = MetadataReference.CreateFromImage(minCodeAnalysisImage); var analyzerSource = @" using System; using System.Collections.ObjectModel; using System.Collections.Immutable; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Net.Http; using System.Net.Security; using System.Net.Sockets; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security.AccessControl; using System.Security.Cryptography; using System.Security.Principal; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; using System.Xml.XPath; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.Win32.SafeHandles; [DiagnosticAnalyzer(""C#"")] public class TestAnalyzer : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => throw new NotImplementedException(new[] { typeof(Win32Exception), // Microsoft.Win32.Primitives typeof(AppContext), // System.AppContext typeof(Console), // System.Console typeof(ValueTuple), // System.ValueTuple typeof(FileVersionInfo), // System.Diagnostics.FileVersionInfo typeof(Process), // System.Diagnostics.Process typeof(ChineseLunisolarCalendar), // System.Globalization.Calendars typeof(ZipArchive), // System.IO.Compression typeof(ZipFile), // System.IO.Compression.ZipFile typeof(FileOptions), // System.IO.FileSystem typeof(FileAttributes), // System.IO.FileSystem.Primitives typeof(HttpClient), // System.Net.Http typeof(AuthenticatedStream), // System.Net.Security typeof(IOControlCode), // System.Net.Sockets typeof(RuntimeInformation), // System.Runtime.InteropServices.RuntimeInformation typeof(SerializationException), // System.Runtime.Serialization.Primitives typeof(GenericIdentity), // System.Security.Claims typeof(Aes), // System.Security.Cryptography.Algorithms typeof(CspParameters), // System.Security.Cryptography.Csp typeof(AsnEncodedData), // System.Security.Cryptography.Encoding typeof(AsymmetricAlgorithm), // System.Security.Cryptography.Primitives typeof(SafeX509ChainHandle), // System.Security.Cryptography.X509Certificates typeof(IXmlLineInfo), // System.Xml.ReaderWriter typeof(XmlNode), // System.Xml.XmlDocument typeof(XPathDocument), // System.Xml.XPath typeof(XDocumentExtensions), // System.Xml.XPath.XDocument typeof(CodePagesEncodingProvider),// System.Text.Encoding.CodePages typeof(ValueTask<>), // System.Threading.Tasks.Extensions // csc doesn't ship with facades for the following assemblies. // Analyzers can't use them unless they carry the facade with them. // typeof(SafePipeHandle), // System.IO.Pipes // typeof(StackFrame), // System.Diagnostics.StackTrace // typeof(BindingFlags), // System.Reflection.TypeExtensions // typeof(AccessControlActions), // System.Security.AccessControl // typeof(SafeAccessTokenHandle), // System.Security.Principal.Windows // typeof(Thread), // System.Threading.Thread }.Length.ToString()); public override void Initialize(AnalysisContext context) { } }"; var analyzerImage = CSharpCompilation.Create( analyzerAssemblyName, new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree(analyzerSource) }, new MetadataReference[] { minCodeAnalysisRef, minSystemCollectionsImmutableRef, MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.Microsoft_Win32_Primitives), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_AppContext), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Console), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_ValueTuple), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Diagnostics_FileVersionInfo), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Diagnostics_Process), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Diagnostics_StackTrace), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Globalization_Calendars), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_IO_Compression), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_IO_Compression_ZipFile), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_IO_FileSystem), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_IO_FileSystem_Primitives), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_IO_Pipes), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Net_Http), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Net_Security), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Net_Sockets), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Reflection_TypeExtensions), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Runtime), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Runtime_InteropServices_RuntimeInformation), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Runtime_Serialization_Primitives), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Security_AccessControl), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Security_Claims), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Security_Cryptography_Algorithms), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Security_Cryptography_Csp), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Security_Cryptography_Encoding), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Security_Cryptography_Primitives), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Security_Cryptography_X509Certificates), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Security_Principal_Windows), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Threading_Thread), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Threading_Tasks_Extensions), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Xml_ReaderWriter), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Xml_XmlDocument), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Xml_XPath), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Xml_XPath_XDocument), MetadataReference.CreateFromImage(ProprietaryTestResources.netstandard13.System_Text_Encoding_CodePages) }, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)).EmitToArray(); return analyzerImage; } public static string? GetMSBuildDirectory() { var vsVersion = Environment.GetEnvironmentVariable("VisualStudioVersion") ?? "14.0"; using (var key = Registry.LocalMachine.OpenSubKey($@"SOFTWARE\Microsoft\MSBuild\ToolsVersions\{vsVersion}", false)) { if (key != null) { var toolsPath = key.GetValue("MSBuildToolsPath"); if (toolsPath != null) { return toolsPath.ToString(); } } } return null; } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #if NET472 using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Resources.Proprietary; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.Win32; using Basic.Reference.Assemblies; namespace Roslyn.Test.Utilities { public static class DesktopTestHelpers { public static IEnumerable<Type> GetAllTypesImplementingGivenInterface(Assembly assembly, Type interfaceType) { if (assembly == null || interfaceType == null || !interfaceType.IsInterface) { throw new ArgumentException("interfaceType is not an interface.", nameof(interfaceType)); } return assembly.GetTypes().Where((t) => { // simplest way to get types that implement mef type // we might need to actually check whether type export the interface type later if (t.IsAbstract) { return false; } var candidate = t.GetInterface(interfaceType.ToString()); return candidate != null && candidate.Equals(interfaceType); }).ToList(); } public static IEnumerable<Type> GetAllTypesSubclassingType(Assembly assembly, Type type) { if (assembly == null || type == null) { throw new ArgumentException("Invalid arguments"); } return (from t in assembly.GetTypes() where !t.IsAbstract where type.IsAssignableFrom(t) select t).ToList(); } public static TempFile CreateCSharpAnalyzerAssemblyWithTestAnalyzer(TempDirectory dir, string assemblyName) { var analyzerSource = @" using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; [DiagnosticAnalyzer(LanguageNames.CSharp)] public class TestAnalyzer : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } } public override void Initialize(AnalysisContext context) { throw new NotImplementedException(); } }"; dir.CopyFile(typeof(System.Reflection.Metadata.MetadataReader).Assembly.Location); var immutable = dir.CopyFile(typeof(ImmutableArray).Assembly.Location); var analyzer = dir.CopyFile(typeof(DiagnosticAnalyzer).Assembly.Location); dir.CopyFile(typeof(Memory<>).Assembly.Location); dir.CopyFile(typeof(System.Runtime.CompilerServices.Unsafe).Assembly.Location); var analyzerCompilation = CSharpCompilation.Create( assemblyName, new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree(analyzerSource) }, new MetadataReference[] { NetStandard20.mscorlib, NetStandard20.netstandard, NetStandard20.SystemRuntime, MetadataReference.CreateFromFile(immutable.Path), MetadataReference.CreateFromFile(analyzer.Path) }, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); return dir.CreateFile(assemblyName + ".dll").WriteAllBytes(analyzerCompilation.EmitToArray()); } public static string? GetMSBuildDirectory() { var vsVersion = Environment.GetEnvironmentVariable("VisualStudioVersion") ?? "14.0"; using (var key = Registry.LocalMachine.OpenSubKey($@"SOFTWARE\Microsoft\MSBuild\ToolsVersions\{vsVersion}", false)) { if (key != null) { var toolsPath = key.GetValue("MSBuildToolsPath"); if (toolsPath != null) { return toolsPath.ToString(); } } } return null; } } } #endif
1
dotnet/roslyn
56,223
Rework our netstandard1.3 test references
The `netstandard1.3` test references were being provided by our MS.CA.Test.Resources.Proprietary package. The contents of this package get included in the output directory of every single unit test DLL that we build (which contributes to build output size). The references themselves though were only used in a very small number of tests. This change upgrades to a version of MS.CA.Test.Resources.Proprietary that has the `netstandard1.3` references removed and adds the `netstandard1.3` references to only the projects that needs them
jaredpar
"2021-09-07T20:35:04Z"
"2021-09-07T23:50:57Z"
0240973369997c88a2c2f1aaa22c14182ac17e9f
5dbd783367d7f6b105726b84558cc1809aa198ce
Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our MS.CA.Test.Resources.Proprietary package. The contents of this package get included in the output directory of every single unit test DLL that we build (which contributes to build output size). The references themselves though were only used in a very small number of tests. This change upgrades to a version of MS.CA.Test.Resources.Proprietary that has the `netstandard1.3` references removed and adds the `netstandard1.3` references to only the projects that needs them
./src/Compilers/Test/Core/TestBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.IO; using System.Reflection; using System.Threading; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.VisualBasic; using static TestReferences.NetFx; using static Roslyn.Test.Utilities.TestMetadata; using Microsoft.CodeAnalysis.Test.Resources.Proprietary; using Basic.Reference.Assemblies; namespace Roslyn.Test.Utilities { /// <summary> /// Base class for all unit test classes. /// </summary> public abstract class TestBase : IDisposable { private TempRoot _temp; protected TestBase() { } public static string GetUniqueName() { return Guid.NewGuid().ToString("D"); } public TempRoot Temp { get { if (_temp == null) { _temp = new TempRoot(); } return _temp; } } public virtual void Dispose() { if (_temp != null) { _temp.Dispose(); } } #region Metadata References /// <summary> /// Helper for atomically acquiring and saving a metadata reference. Necessary /// if the acquired reference will ever be used in object identity comparisons. /// </summary> private static MetadataReference GetOrCreateMetadataReference(ref MetadataReference field, Func<MetadataReference> getReference) { if (field == null) { Interlocked.CompareExchange(ref field, getReference(), null); } return field; } private static readonly Lazy<MetadataReference[]> s_lazyDefaultVbReferences = new Lazy<MetadataReference[]>( () => new[] { Net40.mscorlib, Net40.System, Net40.SystemCore, Net40.MicrosoftVisualBasic }, LazyThreadSafetyMode.PublicationOnly); public static MetadataReference[] DefaultVbReferences => s_lazyDefaultVbReferences.Value; private static readonly Lazy<MetadataReference[]> s_lazyLatestVbReferences = new Lazy<MetadataReference[]>( () => new[] { Net451.mscorlib, Net451.System, Net451.SystemCore, Net451.MicrosoftVisualBasic }, LazyThreadSafetyMode.PublicationOnly); public static MetadataReference[] LatestVbReferences => s_lazyLatestVbReferences.Value; public static readonly AssemblyName RuntimeCorLibName = RuntimeUtilities.IsCoreClrRuntime ? new AssemblyName("netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51") : new AssemblyName("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); /// <summary> /// The array of 7 metadataimagereferences that are required to compile /// against windows.winmd (including windows.winmd itself). /// </summary> private static readonly Lazy<MetadataReference[]> s_winRtRefs = new Lazy<MetadataReference[]>( () => { var winmd = AssemblyMetadata.CreateFromImage(TestResources.WinRt.Windows).GetReference(display: "Windows"); var windowsruntime = AssemblyMetadata.CreateFromImage(ProprietaryTestResources.v4_0_30319_17929.System_Runtime_WindowsRuntime).GetReference(display: "System.Runtime.WindowsRuntime.dll"); var runtime = AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemRuntime).GetReference(display: "System.Runtime.dll"); var objectModel = AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemObjectModel).GetReference(display: "System.ObjectModel.dll"); var uixaml = AssemblyMetadata.CreateFromImage(ProprietaryTestResources.v4_0_30319_17929.System_Runtime_WindowsRuntime_UI_Xaml). GetReference(display: "System.Runtime.WindowsRuntime.UI.Xaml.dll"); var interop = AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemRuntimeInteropServicesWindowsRuntime). GetReference(display: "System.Runtime.InteropServices.WindowsRuntime.dll"); //Not mentioned in the adapter doc but pointed to from System.Runtime, so we'll put it here. var system = AssemblyMetadata.CreateFromImage(ResourcesNet451.System).GetReference(display: "System.dll"); var mscor = AssemblyMetadata.CreateFromImage(ResourcesNet451.mscorlib).GetReference(display: "mscorlib"); return new MetadataReference[] { winmd, windowsruntime, runtime, objectModel, uixaml, interop, system, mscor }; }, LazyThreadSafetyMode.PublicationOnly); public static MetadataReference[] WinRtRefs => s_winRtRefs.Value; /// <summary> /// The array of minimal references for portable library (mscorlib.dll and System.Runtime.dll) /// </summary> private static readonly Lazy<MetadataReference[]> s_portableRefsMinimal = new Lazy<MetadataReference[]>( () => new MetadataReference[] { MscorlibPP7Ref, SystemRuntimePP7Ref }, LazyThreadSafetyMode.PublicationOnly); public static MetadataReference[] PortableRefsMinimal => s_portableRefsMinimal.Value; /// <summary> /// Reference to an assembly that defines LINQ operators. /// </summary> public static MetadataReference LinqAssemblyRef => SystemCoreRef; /// <summary> /// Reference to an assembly that defines ExtensionAttribute. /// </summary> public static MetadataReference ExtensionAssemblyRef => SystemCoreRef; private static readonly Lazy<MetadataReference> s_systemCoreRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemCore).GetReference(display: "System.Core.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemCoreRef => s_systemCoreRef.Value; private static readonly Lazy<MetadataReference> s_systemCoreRef_v4_0_30319_17929 = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemCore).GetReference(display: "System.Core.v4_0_30319_17929.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemCoreRef_v4_0_30319_17929 => s_systemCoreRef_v4_0_30319_17929.Value; private static readonly Lazy<MetadataReference> s_systemCoreRef_v46 = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet461.SystemCore).GetReference(display: "System.Core.v4_6_1038_0.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemCoreRef_v46 => s_systemCoreRef_v4_0_30319_17929.Value; private static readonly Lazy<MetadataReference> s_systemWindowsFormsRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemWindowsForms).GetReference(display: "System.Windows.Forms.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemWindowsFormsRef => s_systemWindowsFormsRef.Value; private static readonly Lazy<MetadataReference> s_systemDrawingRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemDrawing).GetReference(display: "System.Drawing.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemDrawingRef => s_systemDrawingRef.Value; private static readonly Lazy<MetadataReference> s_systemDataRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemData).GetReference(display: "System.Data.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemDataRef => s_systemDataRef.Value; private static readonly Lazy<MetadataReference> s_mscorlibRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.mscorlib).GetReference(display: "mscorlib.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference MscorlibRef => s_mscorlibRef.Value; private static readonly Lazy<MetadataReference> s_mscorlibRefPortable = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ProprietaryTestResources.v4_0_30319.mscorlib_portable).GetReference(display: "mscorlib.v4_0_30319.portable.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference MscorlibRefPortable => s_mscorlibRefPortable.Value; private static readonly Lazy<MetadataReference> s_aacorlibRef = new Lazy<MetadataReference>( () => { var source = TestResources.NetFX.aacorlib_v15_0_3928.aacorlib_v15_0_3928_cs; var syntaxTree = Microsoft.CodeAnalysis.CSharp.SyntaxFactory.ParseSyntaxTree(source); var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); var compilation = CSharpCompilation.Create("aacorlib.v15.0.3928.dll", new[] { syntaxTree }, null, compilationOptions); Stream dllStream = new MemoryStream(); var emitResult = compilation.Emit(dllStream); if (!emitResult.Success) { emitResult.Diagnostics.Verify(); } dllStream.Seek(0, SeekOrigin.Begin); return AssemblyMetadata.CreateFromStream(dllStream).GetReference(display: "mscorlib.v4_0_30319.dll"); }, LazyThreadSafetyMode.PublicationOnly); public static MetadataReference AacorlibRef => s_aacorlibRef.Value; public static MetadataReference MscorlibRef_v20 => Net20.mscorlib; public static MetadataReference MscorlibRef_v4_0_30316_17626 => Net451.mscorlib; private static readonly Lazy<MetadataReference> s_mscorlibRef_v46 = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet461.mscorlib).GetReference(display: "mscorlib.v4_6_1038_0.dll", filePath: @"Z:\FxReferenceAssembliesUri"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference MscorlibRef_v46 => s_mscorlibRef_v46.Value; /// <summary> /// Reference to an mscorlib silverlight assembly in which the System.Array does not contain the special member LongLength. /// </summary> private static readonly Lazy<MetadataReference> s_mscorlibRef_silverlight = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ProprietaryTestResources.silverlight_v5_0_5_0.mscorlib_v5_0_5_0_silverlight).GetReference(display: "mscorlib.v5.0.5.0_silverlight.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference MscorlibRefSilverlight => s_mscorlibRef_silverlight.Value; public static MetadataReference MinCorlibRef => TestReferences.NetFx.Minimal.mincorlib; public static MetadataReference MinAsyncCorlibRef => TestReferences.NetFx.Minimal.minasynccorlib; public static MetadataReference ValueTupleRef => TestReferences.NetFx.ValueTuple.tuplelib; public static MetadataReference MsvbRef => Net451.MicrosoftVisualBasic; public static MetadataReference MsvbRef_v4_0_30319_17929 => Net451.MicrosoftVisualBasic; public static MetadataReference CSharpRef => CSharpDesktopRef; private static readonly Lazy<MetadataReference> s_desktopCSharpRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.MicrosoftCSharp).GetReference(display: "Microsoft.CSharp.v4.0.30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference CSharpDesktopRef => s_desktopCSharpRef.Value; private static readonly Lazy<MetadataReference> s_std20Ref = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(NetStandard20.Resources.netstandard).GetReference(display: "netstandard20.netstandard.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference NetStandard20Ref => s_std20Ref.Value; private static readonly Lazy<MetadataReference> s_46NetStandardFacade = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesBuildExtensions.NetStandardToNet461).GetReference(display: "netstandard20.netstandard.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference Net46StandardFacade => s_46NetStandardFacade.Value; private static readonly Lazy<MetadataReference> s_systemDynamicRuntimeRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ProprietaryTestResources.netstandard13.System_Dynamic_Runtime).GetReference(display: "System.Dynamic.Runtime.dll (netstandard 1.3 ref)"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemDynamicRuntimeRef => s_systemDynamicRuntimeRef.Value; private static readonly Lazy<MetadataReference> s_systemRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.System).GetReference(display: "System.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemRef => s_systemRef.Value; private static readonly Lazy<MetadataReference> s_systemRef_v46 = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet461.System).GetReference(display: "System.v4_6_1038_0.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemRef_v46 => s_systemRef_v46.Value; private static readonly Lazy<MetadataReference> s_systemRef_v4_0_30319_17929 = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.System).GetReference(display: "System.v4_0_30319_17929.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemRef_v4_0_30319_17929 => s_systemRef_v4_0_30319_17929.Value; private static readonly Lazy<MetadataReference> s_systemRef_v20 = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet20.System).GetReference(display: "System.v2_0_50727.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemRef_v20 => s_systemRef_v20.Value; private static readonly Lazy<MetadataReference> s_systemXmlRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemXml).GetReference(display: "System.Xml.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemXmlRef => s_systemXmlRef.Value; private static readonly Lazy<MetadataReference> s_systemXmlLinqRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemXmlLinq).GetReference(display: "System.Xml.Linq.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemXmlLinqRef => s_systemXmlLinqRef.Value; private static readonly Lazy<MetadataReference> s_mscorlibFacadeRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.mscorlib).GetReference(display: "mscorlib.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference MscorlibFacadeRef => s_mscorlibFacadeRef.Value; private static readonly Lazy<MetadataReference> s_systemRuntimeFacadeRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemRuntime).GetReference(display: "System.Runtime.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemRuntimeFacadeRef => s_systemRuntimeFacadeRef.Value; private static readonly Lazy<MetadataReference> s_systemThreadingFacadeRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemThreading).GetReference(display: "System.Threading.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemThreadingFacadeRef => s_systemThreadingTasksFacadeRef.Value; private static readonly Lazy<MetadataReference> s_systemThreadingTasksFacadeRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemThreadingTasks).GetReference(display: "System.Threading.Tasks.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemThreadingTaskFacadeRef => s_systemThreadingTasksFacadeRef.Value; private static readonly Lazy<MetadataReference> s_mscorlibPP7Ref = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ProprietaryTestResources.ReferenceAssemblies_PortableProfile7.mscorlib).GetReference(display: "mscorlib.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference MscorlibPP7Ref => s_mscorlibPP7Ref.Value; private static readonly Lazy<MetadataReference> s_systemRuntimePP7Ref = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ProprietaryTestResources.ReferenceAssemblies_PortableProfile7.System_Runtime).GetReference(display: "System.Runtime.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemRuntimePP7Ref => s_systemRuntimePP7Ref.Value; private static readonly Lazy<MetadataReference> s_FSharpTestLibraryRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.FSharpTestLibrary).GetReference(display: "FSharpTestLibrary.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference FSharpTestLibraryRef => s_FSharpTestLibraryRef.Value; public static readonly MetadataReference InvalidRef = new TestMetadataReference(fullPath: @"R:\Invalid.dll"); #endregion #region Diagnostics internal static DiagnosticDescription Diagnostic( object code, string squiggledText = null, object[] arguments = null, LinePosition? startLocation = null, Func<SyntaxNode, bool> syntaxNodePredicate = null, bool argumentOrderDoesNotMatter = false, bool isSuppressed = false) { return TestHelpers.Diagnostic( code, squiggledText, arguments, startLocation, syntaxNodePredicate, argumentOrderDoesNotMatter, isSuppressed: isSuppressed); } internal static DiagnosticDescription Diagnostic( object code, XCData squiggledText, object[] arguments = null, LinePosition? startLocation = null, Func<SyntaxNode, bool> syntaxNodePredicate = null, bool argumentOrderDoesNotMatter = false, bool isSuppressed = false) { return TestHelpers.Diagnostic( code, squiggledText, arguments, startLocation, syntaxNodePredicate, argumentOrderDoesNotMatter, isSuppressed: isSuppressed); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Threading; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.VisualBasic; using static TestReferences.NetFx; using static Roslyn.Test.Utilities.TestMetadata; using Microsoft.CodeAnalysis.Test.Resources.Proprietary; using Basic.Reference.Assemblies; namespace Roslyn.Test.Utilities { /// <summary> /// Base class for all unit test classes. /// </summary> public abstract class TestBase : IDisposable { private TempRoot _temp; protected TestBase() { } public static string GetUniqueName() { return Guid.NewGuid().ToString("D"); } public TempRoot Temp { get { if (_temp == null) { _temp = new TempRoot(); } return _temp; } } public virtual void Dispose() { if (_temp != null) { _temp.Dispose(); } } #region Metadata References /// <summary> /// Helper for atomically acquiring and saving a metadata reference. Necessary /// if the acquired reference will ever be used in object identity comparisons. /// </summary> private static MetadataReference GetOrCreateMetadataReference(ref MetadataReference field, Func<MetadataReference> getReference) { if (field == null) { Interlocked.CompareExchange(ref field, getReference(), null); } return field; } private static readonly Lazy<MetadataReference[]> s_lazyDefaultVbReferences = new Lazy<MetadataReference[]>( () => new[] { Net40.mscorlib, Net40.System, Net40.SystemCore, Net40.MicrosoftVisualBasic }, LazyThreadSafetyMode.PublicationOnly); public static MetadataReference[] DefaultVbReferences => s_lazyDefaultVbReferences.Value; private static readonly Lazy<MetadataReference[]> s_lazyLatestVbReferences = new Lazy<MetadataReference[]>( () => new[] { Net451.mscorlib, Net451.System, Net451.SystemCore, Net451.MicrosoftVisualBasic }, LazyThreadSafetyMode.PublicationOnly); public static MetadataReference[] LatestVbReferences => s_lazyLatestVbReferences.Value; public static readonly AssemblyName RuntimeCorLibName = RuntimeUtilities.IsCoreClrRuntime ? new AssemblyName("netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51") : new AssemblyName("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); /// <summary> /// The array of 7 metadataimagereferences that are required to compile /// against windows.winmd (including windows.winmd itself). /// </summary> private static readonly Lazy<MetadataReference[]> s_winRtRefs = new Lazy<MetadataReference[]>( () => { var winmd = AssemblyMetadata.CreateFromImage(TestResources.WinRt.Windows).GetReference(display: "Windows"); var windowsruntime = AssemblyMetadata.CreateFromImage(ProprietaryTestResources.v4_0_30319_17929.System_Runtime_WindowsRuntime).GetReference(display: "System.Runtime.WindowsRuntime.dll"); var runtime = AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemRuntime).GetReference(display: "System.Runtime.dll"); var objectModel = AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemObjectModel).GetReference(display: "System.ObjectModel.dll"); var uixaml = AssemblyMetadata.CreateFromImage(ProprietaryTestResources.v4_0_30319_17929.System_Runtime_WindowsRuntime_UI_Xaml). GetReference(display: "System.Runtime.WindowsRuntime.UI.Xaml.dll"); var interop = AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemRuntimeInteropServicesWindowsRuntime). GetReference(display: "System.Runtime.InteropServices.WindowsRuntime.dll"); //Not mentioned in the adapter doc but pointed to from System.Runtime, so we'll put it here. var system = AssemblyMetadata.CreateFromImage(ResourcesNet451.System).GetReference(display: "System.dll"); var mscor = AssemblyMetadata.CreateFromImage(ResourcesNet451.mscorlib).GetReference(display: "mscorlib"); return new MetadataReference[] { winmd, windowsruntime, runtime, objectModel, uixaml, interop, system, mscor }; }, LazyThreadSafetyMode.PublicationOnly); public static MetadataReference[] WinRtRefs => s_winRtRefs.Value; /// <summary> /// The array of minimal references for portable library (mscorlib.dll and System.Runtime.dll) /// </summary> private static readonly Lazy<MetadataReference[]> s_portableRefsMinimal = new Lazy<MetadataReference[]>( () => new MetadataReference[] { MscorlibPP7Ref, SystemRuntimePP7Ref }, LazyThreadSafetyMode.PublicationOnly); public static MetadataReference[] PortableRefsMinimal => s_portableRefsMinimal.Value; /// <summary> /// Reference to an assembly that defines LINQ operators. /// </summary> public static MetadataReference LinqAssemblyRef => SystemCoreRef; /// <summary> /// Reference to an assembly that defines ExtensionAttribute. /// </summary> public static MetadataReference ExtensionAssemblyRef => SystemCoreRef; private static readonly Lazy<MetadataReference> s_systemCoreRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemCore).GetReference(display: "System.Core.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemCoreRef => s_systemCoreRef.Value; private static readonly Lazy<MetadataReference> s_systemCoreRef_v4_0_30319_17929 = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemCore).GetReference(display: "System.Core.v4_0_30319_17929.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemCoreRef_v4_0_30319_17929 => s_systemCoreRef_v4_0_30319_17929.Value; private static readonly Lazy<MetadataReference> s_systemCoreRef_v46 = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet461.SystemCore).GetReference(display: "System.Core.v4_6_1038_0.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemCoreRef_v46 => s_systemCoreRef_v4_0_30319_17929.Value; private static readonly Lazy<MetadataReference> s_systemWindowsFormsRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemWindowsForms).GetReference(display: "System.Windows.Forms.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemWindowsFormsRef => s_systemWindowsFormsRef.Value; private static readonly Lazy<MetadataReference> s_systemDrawingRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemDrawing).GetReference(display: "System.Drawing.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemDrawingRef => s_systemDrawingRef.Value; private static readonly Lazy<MetadataReference> s_systemDataRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemData).GetReference(display: "System.Data.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemDataRef => s_systemDataRef.Value; private static readonly Lazy<MetadataReference> s_mscorlibRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.mscorlib).GetReference(display: "mscorlib.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference MscorlibRef => s_mscorlibRef.Value; private static readonly Lazy<MetadataReference> s_mscorlibRefPortable = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ProprietaryTestResources.v4_0_30319.mscorlib_portable).GetReference(display: "mscorlib.v4_0_30319.portable.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference MscorlibRefPortable => s_mscorlibRefPortable.Value; private static readonly Lazy<MetadataReference> s_aacorlibRef = new Lazy<MetadataReference>( () => { var source = TestResources.NetFX.aacorlib_v15_0_3928.aacorlib_v15_0_3928_cs; var syntaxTree = Microsoft.CodeAnalysis.CSharp.SyntaxFactory.ParseSyntaxTree(source); var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); var compilation = CSharpCompilation.Create("aacorlib.v15.0.3928.dll", new[] { syntaxTree }, null, compilationOptions); Stream dllStream = new MemoryStream(); var emitResult = compilation.Emit(dllStream); if (!emitResult.Success) { emitResult.Diagnostics.Verify(); } dllStream.Seek(0, SeekOrigin.Begin); return AssemblyMetadata.CreateFromStream(dllStream).GetReference(display: "mscorlib.v4_0_30319.dll"); }, LazyThreadSafetyMode.PublicationOnly); public static MetadataReference AacorlibRef => s_aacorlibRef.Value; public static MetadataReference MscorlibRef_v20 => Net20.mscorlib; public static MetadataReference MscorlibRef_v4_0_30316_17626 => Net451.mscorlib; private static readonly Lazy<MetadataReference> s_mscorlibRef_v46 = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet461.mscorlib).GetReference(display: "mscorlib.v4_6_1038_0.dll", filePath: @"Z:\FxReferenceAssembliesUri"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference MscorlibRef_v46 => s_mscorlibRef_v46.Value; /// <summary> /// Reference to an mscorlib silverlight assembly in which the System.Array does not contain the special member LongLength. /// </summary> private static readonly Lazy<MetadataReference> s_mscorlibRef_silverlight = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ProprietaryTestResources.silverlight_v5_0_5_0.mscorlib_v5_0_5_0_silverlight).GetReference(display: "mscorlib.v5.0.5.0_silverlight.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference MscorlibRefSilverlight => s_mscorlibRef_silverlight.Value; public static MetadataReference MinCorlibRef => TestReferences.NetFx.Minimal.mincorlib; public static MetadataReference MinAsyncCorlibRef => TestReferences.NetFx.Minimal.minasynccorlib; public static MetadataReference ValueTupleRef => TestReferences.NetFx.ValueTuple.tuplelib; public static MetadataReference MsvbRef => Net451.MicrosoftVisualBasic; public static MetadataReference MsvbRef_v4_0_30319_17929 => Net451.MicrosoftVisualBasic; public static MetadataReference CSharpRef => CSharpDesktopRef; private static readonly Lazy<MetadataReference> s_desktopCSharpRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.MicrosoftCSharp).GetReference(display: "Microsoft.CSharp.v4.0.30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference CSharpDesktopRef => s_desktopCSharpRef.Value; private static readonly Lazy<MetadataReference> s_std20Ref = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(NetStandard20.Resources.netstandard).GetReference(display: "netstandard20.netstandard.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference NetStandard20Ref => s_std20Ref.Value; private static readonly Lazy<MetadataReference> s_46NetStandardFacade = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesBuildExtensions.NetStandardToNet461).GetReference(display: "netstandard20.netstandard.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference Net46StandardFacade => s_46NetStandardFacade.Value; private static readonly Lazy<MetadataReference> s_systemRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.System).GetReference(display: "System.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemRef => s_systemRef.Value; private static readonly Lazy<MetadataReference> s_systemRef_v46 = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet461.System).GetReference(display: "System.v4_6_1038_0.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemRef_v46 => s_systemRef_v46.Value; private static readonly Lazy<MetadataReference> s_systemRef_v4_0_30319_17929 = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.System).GetReference(display: "System.v4_0_30319_17929.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemRef_v4_0_30319_17929 => s_systemRef_v4_0_30319_17929.Value; private static readonly Lazy<MetadataReference> s_systemRef_v20 = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet20.System).GetReference(display: "System.v2_0_50727.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemRef_v20 => s_systemRef_v20.Value; private static readonly Lazy<MetadataReference> s_systemXmlRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemXml).GetReference(display: "System.Xml.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemXmlRef => s_systemXmlRef.Value; private static readonly Lazy<MetadataReference> s_systemXmlLinqRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemXmlLinq).GetReference(display: "System.Xml.Linq.v4_0_30319.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemXmlLinqRef => s_systemXmlLinqRef.Value; private static readonly Lazy<MetadataReference> s_mscorlibFacadeRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.mscorlib).GetReference(display: "mscorlib.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference MscorlibFacadeRef => s_mscorlibFacadeRef.Value; private static readonly Lazy<MetadataReference> s_systemRuntimeFacadeRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemRuntime).GetReference(display: "System.Runtime.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemRuntimeFacadeRef => s_systemRuntimeFacadeRef.Value; private static readonly Lazy<MetadataReference> s_systemThreadingFacadeRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemThreading).GetReference(display: "System.Threading.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemThreadingFacadeRef => s_systemThreadingTasksFacadeRef.Value; private static readonly Lazy<MetadataReference> s_systemThreadingTasksFacadeRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemThreadingTasks).GetReference(display: "System.Threading.Tasks.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemThreadingTaskFacadeRef => s_systemThreadingTasksFacadeRef.Value; private static readonly Lazy<MetadataReference> s_mscorlibPP7Ref = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ProprietaryTestResources.ReferenceAssemblies_PortableProfile7.mscorlib).GetReference(display: "mscorlib.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference MscorlibPP7Ref => s_mscorlibPP7Ref.Value; private static readonly Lazy<MetadataReference> s_systemRuntimePP7Ref = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(ProprietaryTestResources.ReferenceAssemblies_PortableProfile7.System_Runtime).GetReference(display: "System.Runtime.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference SystemRuntimePP7Ref => s_systemRuntimePP7Ref.Value; private static readonly Lazy<MetadataReference> s_FSharpTestLibraryRef = new Lazy<MetadataReference>( () => AssemblyMetadata.CreateFromImage(TestResources.General.FSharpTestLibrary).GetReference(display: "FSharpTestLibrary.dll"), LazyThreadSafetyMode.PublicationOnly); public static MetadataReference FSharpTestLibraryRef => s_FSharpTestLibraryRef.Value; public static readonly MetadataReference InvalidRef = new TestMetadataReference(fullPath: @"R:\Invalid.dll"); #endregion #region Diagnostics internal static DiagnosticDescription Diagnostic( object code, string squiggledText = null, object[] arguments = null, LinePosition? startLocation = null, Func<SyntaxNode, bool> syntaxNodePredicate = null, bool argumentOrderDoesNotMatter = false, bool isSuppressed = false) { return TestHelpers.Diagnostic( code, squiggledText, arguments, startLocation, syntaxNodePredicate, argumentOrderDoesNotMatter, isSuppressed: isSuppressed); } internal static DiagnosticDescription Diagnostic( object code, XCData squiggledText, object[] arguments = null, LinePosition? startLocation = null, Func<SyntaxNode, bool> syntaxNodePredicate = null, bool argumentOrderDoesNotMatter = false, bool isSuppressed = false) { return TestHelpers.Diagnostic( code, squiggledText, arguments, startLocation, syntaxNodePredicate, argumentOrderDoesNotMatter, isSuppressed: isSuppressed); } #endregion } }
1
dotnet/roslyn
56,223
Rework our netstandard1.3 test references
The `netstandard1.3` test references were being provided by our MS.CA.Test.Resources.Proprietary package. The contents of this package get included in the output directory of every single unit test DLL that we build (which contributes to build output size). The references themselves though were only used in a very small number of tests. This change upgrades to a version of MS.CA.Test.Resources.Proprietary that has the `netstandard1.3` references removed and adds the `netstandard1.3` references to only the projects that needs them
jaredpar
"2021-09-07T20:35:04Z"
"2021-09-07T23:50:57Z"
0240973369997c88a2c2f1aaa22c14182ac17e9f
5dbd783367d7f6b105726b84558cc1809aa198ce
Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our MS.CA.Test.Resources.Proprietary package. The contents of this package get included in the output directory of every single unit test DLL that we build (which contributes to build output size). The references themselves though were only used in a very small number of tests. This change upgrades to a version of MS.CA.Test.Resources.Proprietary that has the `netstandard1.3` references removed and adds the `netstandard1.3` references to only the projects that needs them
./src/Scripting/CSharpTest/InteractiveSessionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.Scripting.Hosting; using Microsoft.CodeAnalysis.Scripting.Test; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests { using static TestCompilationFactory; public class HostModel { public readonly int Goo; } public class InteractiveSessionTests : TestBase { internal static readonly Assembly HostAssembly = typeof(InteractiveSessionTests).GetTypeInfo().Assembly; #region Namespaces, Types [Fact(Skip = "https://github.com/dotnet/roslyn/issues/17869")] public void CompilationChain_NestedTypesClass() { var script = CSharpScript.Create(@" static string outerStr = null; public static void Goo(string str) { outerStr = str; } class InnerClass { public string innerStr = null; public void Goo() { Goo(""test""); innerStr = outerStr; } } ").ContinueWith(@" InnerClass iC = new InnerClass(); iC.Goo(); ").ContinueWith(@" System.Console.WriteLine(iC.innerStr); "); ScriptingTestHelpers.RunScriptWithOutput(script, "test"); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/17869")] public void CompilationChain_NestedTypesStruct() { var script = CSharpScript.Create(@" static string outerStr = null; public static void Goo(string str) { outerStr = str; } struct InnerStruct { public string innerStr; public void Goo() { Goo(""test""); innerStr = outerStr; } } ").ContinueWith(@" InnerStruct iS = new InnerStruct(); iS.Goo(); ").ContinueWith(@" System.Console.WriteLine(iS.innerStr); "); ScriptingTestHelpers.RunScriptWithOutput(script, "test"); } [Fact] public async Task CompilationChain_InterfaceTypes() { var script = CSharpScript.Create(@" interface I1 { int Goo();} class InnerClass : I1 { public int Goo() { return 1; } }").ContinueWith(@" I1 iC = new InnerClass(); ").ContinueWith(@" iC.Goo() "); Assert.Equal(1, await script.EvaluateAsync()); } [Fact] public void ScriptMemberAccessFromNestedClass() { var script = CSharpScript.Create(@" object field; object Property { get; set; } void Method() { } ").ContinueWith(@" class C { public void Goo() { object f = field; object p = Property; Method(); } } "); ScriptingTestHelpers.AssertCompilationError(script, // (6,20): error CS0120: An object reference is required for the non-static field, method, or property 'field' Diagnostic(ErrorCode.ERR_ObjectRequired, "field").WithArguments("field"), // (7,20): error CS0120: An object reference is required for the non-static field, method, or property 'Property' Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("Property"), // (8,9): error CS0120: An object reference is required for the non-static field, method, or property 'Method()' Diagnostic(ErrorCode.ERR_ObjectRequired, "Method").WithArguments("Method()")); } #region Anonymous Types [Fact] public void AnonymousTypes_TopLevel_MultipleSubmissions() { var script = CSharpScript.Create(@" var a = new { f = 1 }; ").ContinueWith(@" var b = new { g = 1 }; ").ContinueWith<Array>(@" var c = new { f = 1 }; var d = new { g = 1 }; new object[] { new[] { a, c }, new[] { b, d } } "); var result = script.EvaluateAsync().Result; Assert.Equal(2, result.Length); Assert.Equal(2, ((Array)result.GetValue(0)).Length); Assert.Equal(2, ((Array)result.GetValue(1)).Length); } [Fact] public void AnonymousTypes_TopLevel_MultipleSubmissions2() { var script = CSharpScript.Create(@" var a = new { f = 1 }; ").ContinueWith(@" var b = new { g = 1 }; ").ContinueWith(@" var c = new { f = 1 }; var d = new { g = 1 }; object.ReferenceEquals(a.GetType(), c.GetType()).ToString() + "" "" + object.ReferenceEquals(a.GetType(), b.GetType()).ToString() + "" "" + object.ReferenceEquals(b.GetType(), d.GetType()).ToString() "); Assert.Equal("True False True", script.EvaluateAsync().Result.ToString()); } [WorkItem(543863, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543863")] [Fact] public void AnonymousTypes_Redefinition() { var script = CSharpScript.Create(@" var x = new { Goo = ""goo"" }; ").ContinueWith(@" var x = new { Goo = ""goo"" }; ").ContinueWith(@" x.Goo "); var result = script.EvaluateAsync().Result; Assert.Equal("goo", result); } [Fact] public void AnonymousTypes_TopLevel_Empty() { var script = CSharpScript.Create(@" var a = new { }; ").ContinueWith(@" var b = new { }; ").ContinueWith<Array>(@" var c = new { }; var d = new { }; new object[] { new[] { a, c }, new[] { b, d } } "); var result = script.EvaluateAsync().Result; Assert.Equal(2, result.Length); Assert.Equal(2, ((Array)result.GetValue(0)).Length); Assert.Equal(2, ((Array)result.GetValue(1)).Length); } #endregion #region Dynamic [Fact] public void Dynamic_Expando() { var options = ScriptOptions.Default. AddReferences( typeof(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException).GetTypeInfo().Assembly, typeof(System.Dynamic.ExpandoObject).GetTypeInfo().Assembly). AddImports( "System.Dynamic"); var script = CSharpScript.Create(@" dynamic expando = new ExpandoObject(); ", options).ContinueWith(@" expando.goo = 1; ").ContinueWith(@" expando.goo "); Assert.Equal(1, script.EvaluateAsync().Result); } #endregion [Fact] public void Enums() { var script = CSharpScript.Create(@" public enum Enum1 { A, B, C } Enum1 E = Enum1.C; E "); var e = script.EvaluateAsync().Result; Assert.True(e.GetType().GetTypeInfo().IsEnum, "Expected enum"); Assert.Equal(typeof(int), Enum.GetUnderlyingType(e.GetType())); } #endregion #region Attributes [Fact] public void PInvoke() { var source = @" using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [DllImport(""goo"", EntryPoint = ""bar"", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = true, SetLastError = true, BestFitMapping = true, ThrowOnUnmappableChar = true)] public static extern void M(); class C { } typeof(C) "; Type c = CSharpScript.EvaluateAsync<Type>(source).Result; var m = c.DeclaringType.GetTypeInfo().GetDeclaredMethod("M"); Assert.Equal(MethodImplAttributes.PreserveSig, m.MethodImplementationFlags); // Reflection synthesizes DllImportAttribute var dllImport = (DllImportAttribute)m.GetCustomAttributes(typeof(DllImportAttribute), inherit: false).Single(); Assert.True(dllImport.BestFitMapping); Assert.Equal(CallingConvention.Cdecl, dllImport.CallingConvention); Assert.Equal(CharSet.Unicode, dllImport.CharSet); Assert.True(dllImport.ExactSpelling); Assert.True(dllImport.SetLastError); Assert.True(dllImport.PreserveSig); Assert.True(dllImport.ThrowOnUnmappableChar); Assert.Equal("bar", dllImport.EntryPoint); Assert.Equal("goo", dllImport.Value); } #endregion // extension methods - must be private, can be top level #region Modifiers and Visibility [Fact] public void PrivateTopLevel() { var script = CSharpScript.Create<int>(@" private int goo() { return 1; } private static int bar() { return 10; } private static int f = 100; goo() + bar() + f "); Assert.Equal(111, script.EvaluateAsync().Result); script = script.ContinueWith<int>(@" goo() + bar() + f "); Assert.Equal(111, script.EvaluateAsync().Result); script = script.ContinueWith<int>(@" class C { public static int baz() { return bar() + f; } } C.baz() "); Assert.Equal(110, script.EvaluateAsync().Result); } [Fact] public void NestedVisibility() { var script = CSharpScript.Create(@" private class C { internal class D { internal static int goo() { return 1; } } private class E { internal static int goo() { return 1; } } public class F { internal protected static int goo() { return 1; } } internal protected class G { internal static int goo() { return 1; } } } "); Assert.Equal(1, script.ContinueWith<int>("C.D.goo()").EvaluateAsync().Result); Assert.Equal(1, script.ContinueWith<int>("C.F.goo()").EvaluateAsync().Result); Assert.Equal(1, script.ContinueWith<int>("C.G.goo()").EvaluateAsync().Result); ScriptingTestHelpers.AssertCompilationError(script.ContinueWith<int>(@"C.E.goo()"), // error CS0122: 'C.E' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "E").WithArguments("C.E")); } [Fact] public void Fields_Visibility() { var script = CSharpScript.Create(@" private int i = 2; // test comment; public int j = 2; protected int k = 2; internal protected int l = 2; internal int pi = 2; ").ContinueWith(@" i = i + i; j = j + j; k = k + k; l = l + l; ").ContinueWith(@" pi = i + j + k + l; "); Assert.Equal(4, script.ContinueWith<int>("i").EvaluateAsync().Result); Assert.Equal(4, script.ContinueWith<int>("j").EvaluateAsync().Result); Assert.Equal(4, script.ContinueWith<int>("k").EvaluateAsync().Result); Assert.Equal(4, script.ContinueWith<int>("l").EvaluateAsync().Result); Assert.Equal(16, script.ContinueWith<int>("pi").EvaluateAsync().Result); } [WorkItem(100639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/100639")] [Fact] public void ExternDestructor() { var script = CSharpScript.Create( @"class C { extern ~C(); }"); Assert.Null(script.EvaluateAsync().Result); } #endregion #region Chaining [Fact] public void CompilationChain_BasicFields() { var script = CSharpScript.Create("var x = 1;").ContinueWith("x"); Assert.Equal(1, script.EvaluateAsync().Result); } [Fact] public void CompilationChain_GlobalNamespaceAndUsings() { var result = CSharpScript.Create("using InteractiveFixtures.C;", ScriptOptions.Default.AddReferences(HostAssembly)). ContinueWith("using InteractiveFixtures.C;"). ContinueWith("System.Environment.ProcessorCount"). EvaluateAsync().Result; Assert.Equal(Environment.ProcessorCount, result); } [Fact] public void CompilationChain_CurrentSubmissionUsings() { var s0 = CSharpScript.RunAsync("", ScriptOptions.Default.AddReferences(HostAssembly)); var state = s0. ContinueWith("class X { public int goo() { return 1; } }"). ContinueWith("class X { public int goo() { return 1; } }"). ContinueWith("using InteractiveFixtures.A;"). ContinueWith("new X().goo()"); Assert.Equal(1, state.Result.ReturnValue); state = s0. ContinueWith("class X { public int goo() { return 1; } }"). ContinueWith(@" using InteractiveFixtures.A; new X().goo() "); Assert.Equal(1, state.Result.ReturnValue); } [Fact] public void CompilationChain_UsingDuplicates() { var script = CSharpScript.Create(@" using System; using System; ").ContinueWith(@" using System; using System; ").ContinueWith(@" Environment.ProcessorCount "); Assert.Equal(Environment.ProcessorCount, script.EvaluateAsync().Result); } [Fact] public void CompilationChain_GlobalImports() { var options = ScriptOptions.Default.AddImports("System"); var state = CSharpScript.RunAsync("Environment.ProcessorCount", options); Assert.Equal(Environment.ProcessorCount, state.Result.ReturnValue); state = state.ContinueWith("Environment.ProcessorCount"); Assert.Equal(Environment.ProcessorCount, state.Result.ReturnValue); } [Fact] public void CompilationChain_Accessibility() { // Submissions have internal and protected access to one another. var state1 = CSharpScript.RunAsync("internal class C1 { } protected int X; 1"); var compilation1 = state1.Result.Script.GetCompilation(); compilation1.VerifyDiagnostics( // (1,39): warning CS0628: 'X': new protected member declared in sealed type // internal class C1 { } protected int X; 1 Diagnostic(ErrorCode.WRN_ProtectedInSealed, "X").WithArguments("X").WithLocation(1, 39) ); Assert.Equal(1, state1.Result.ReturnValue); var state2 = state1.ContinueWith("internal class C2 : C1 { } 2"); var compilation2 = state2.Result.Script.GetCompilation(); compilation2.VerifyDiagnostics(); Assert.Equal(2, state2.Result.ReturnValue); var c2C2 = (INamedTypeSymbol)lookupMember(compilation2, "Submission#1", "C2"); var c2C1 = c2C2.BaseType; var c2X = lookupMember(compilation1, "Submission#0", "X"); Assert.True(compilation2.IsSymbolAccessibleWithin(c2C1, c2C2)); Assert.True(compilation2.IsSymbolAccessibleWithin(c2C2, c2C1)); Assert.True(compilation2.IsSymbolAccessibleWithin(c2X, c2C2)); // access not enforced among submission symbols var state3 = state2.ContinueWith("private class C3 : C2 { } 3"); var compilation3 = state3.Result.Script.GetCompilation(); compilation3.VerifyDiagnostics(); Assert.Equal(3, state3.Result.ReturnValue); var c3C3 = (INamedTypeSymbol)lookupMember(compilation3, "Submission#2", "C3"); var c3C1 = c3C3.BaseType; Assert.Throws<ArgumentException>(() => compilation2.IsSymbolAccessibleWithin(c3C3, c3C1)); Assert.True(compilation3.IsSymbolAccessibleWithin(c3C3, c3C1)); INamedTypeSymbol lookupType(Compilation c, string name) { return c.GlobalNamespace.GetMembers(name).Single() as INamedTypeSymbol; } ISymbol lookupMember(Compilation c, string typeName, string memberName) { return lookupType(c, typeName).GetMembers(memberName).Single(); } } [Fact] public void CompilationChain_SubmissionSlotResize() { var state = CSharpScript.RunAsync(""); for (int i = 0; i < 17; i++) { state = state.ContinueWith(@"public int i = 1;"); } ScriptingTestHelpers.ContinueRunScriptWithOutput(state, @"System.Console.WriteLine(i);", "1"); } [Fact] public void CompilationChain_UsingNotHidingPreviousSubmission() { int result1 = CSharpScript.Create("using System;"). ContinueWith("int Environment = 1;"). ContinueWith<int>("Environment"). EvaluateAsync().Result; Assert.Equal(1, result1); int result2 = CSharpScript.Create("int Environment = 1;"). ContinueWith("using System;"). ContinueWith<int>("Environment"). EvaluateAsync().Result; Assert.Equal(1, result2); } [Fact] public void CompilationChain_DefinitionHidesGlobal() { var result = CSharpScript.Create("int System = 1;"). ContinueWith("System"). EvaluateAsync().Result; Assert.Equal(1, result); } public class C1 { public readonly int System = 1; public readonly int Environment = 2; } /// <summary> /// Symbol declaration in host object model hides global definition. /// </summary> [Fact] public void CompilationChain_HostObjectMembersHidesGlobal() { var result = CSharpScript.RunAsync("System", globals: new C1()). Result.ReturnValue; Assert.Equal(1, result); } [Fact] public void CompilationChain_UsingNotHidingHostObjectMembers() { var result = CSharpScript.RunAsync("using System;", globals: new C1()). ContinueWith("Environment"). Result.ReturnValue; Assert.Equal(2, result); } [Fact] public void CompilationChain_DefinitionHidesHostObjectMembers() { var result = CSharpScript.RunAsync("int System = 2;", globals: new C1()). ContinueWith("System"). Result.ReturnValue; Assert.Equal(2, result); } [Fact] public void Submissions_ExecutionOrder1() { var s0 = CSharpScript.Create("int x = 1;"); var s1 = s0.ContinueWith("int y = 2;"); var s2 = s1.ContinueWith<int>("x + y"); Assert.Equal(3, s2.EvaluateAsync().Result); Assert.Null(s1.EvaluateAsync().Result); Assert.Null(s0.EvaluateAsync().Result); Assert.Equal(3, s2.EvaluateAsync().Result); Assert.Null(s1.EvaluateAsync().Result); Assert.Null(s0.EvaluateAsync().Result); Assert.Equal(3, s2.EvaluateAsync().Result); Assert.Equal(3, s2.EvaluateAsync().Result); } [Fact] public async Task Submissions_ExecutionOrder2() { var s0 = await CSharpScript.RunAsync("int x = 1;"); Assert.Throws<CompilationErrorException>(() => s0.ContinueWithAsync("invalid$syntax").Result); var s1 = await s0.ContinueWithAsync("x = 2; x = 10"); Assert.Throws<CompilationErrorException>(() => s1.ContinueWithAsync("invalid$syntax").Result); Assert.Throws<CompilationErrorException>(() => s1.ContinueWithAsync("x = undefined_symbol").Result); var s2 = await s1.ContinueWithAsync("int y = 2;"); Assert.Null(s2.ReturnValue); var s3 = await s2.ContinueWithAsync("x + y"); Assert.Equal(12, s3.ReturnValue); } public class HostObjectWithOverrides { public override bool Equals(object obj) => true; public override int GetHashCode() => 1234567; public override string ToString() => "HostObjectToString impl"; } [Fact] public async Task ObjectOverrides1() { var state0 = await CSharpScript.RunAsync("", globals: new HostObjectWithOverrides()); var state1 = await state0.ContinueWithAsync<bool>("Equals(null)"); Assert.True(state1.ReturnValue); var state2 = await state1.ContinueWithAsync<int>("GetHashCode()"); Assert.Equal(1234567, state2.ReturnValue); var state3 = await state2.ContinueWithAsync<string>("ToString()"); Assert.Equal("HostObjectToString impl", state3.ReturnValue); } [Fact] public async Task ObjectOverrides2() { var state0 = await CSharpScript.RunAsync("", globals: new object()); var state1 = await state0.ContinueWithAsync<bool>(@" object x = 1; object y = x; ReferenceEquals(x, y)"); Assert.True(state1.ReturnValue); var state2 = await state1.ContinueWithAsync<string>("ToString()"); Assert.Equal("System.Object", state2.ReturnValue); var state3 = await state2.ContinueWithAsync<bool>("Equals(null)"); Assert.False(state3.ReturnValue); } [Fact] public void ObjectOverrides3() { var state0 = CSharpScript.RunAsync(""); var src1 = @" Equals(null); GetHashCode(); ToString(); ReferenceEquals(null, null);"; ScriptingTestHelpers.AssertCompilationError(state0, src1, // (2,1): error CS0103: The name 'Equals' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "Equals").WithArguments("Equals"), // (3,1): error CS0103: The name 'GetHashCode' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "GetHashCode").WithArguments("GetHashCode"), // (4,1): error CS0103: The name 'ToString' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "ToString").WithArguments("ToString"), // (5,1): error CS0103: The name 'ReferenceEquals' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "ReferenceEquals").WithArguments("ReferenceEquals")); var src2 = @" public override string ToString() { return null; } "; ScriptingTestHelpers.AssertCompilationError(state0, src2, // (1,24): error CS0115: 'ToString()': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "ToString").WithArguments("ToString()")); } #endregion #region Generics [Fact, WorkItem(201759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/201759")] public void CompilationChain_GenericTypes() { var script = CSharpScript.Create(@" class InnerClass<T> { public int method(int value) { return value + 1; } public int field = 2; }").ContinueWith(@" InnerClass<int> iC = new InnerClass<int>(); ").ContinueWith(@" iC.method(iC.field) "); Assert.Equal(3, script.EvaluateAsync().Result); } [WorkItem(529243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529243")] [Fact] public void RecursiveBaseType() { CSharpScript.EvaluateAsync(@" class A<T> { } class B<T> : A<B<B<T>>> { } "); } [WorkItem(5378, "DevDiv_Projects/Roslyn")] [Fact] public void CompilationChain_GenericMethods() { var s0 = CSharpScript.Create(@" public int goo<T, R>(T arg) { return 1; } public static T bar<T>(T i) { return i; } "); Assert.Equal(1, s0.ContinueWith(@"goo<int, int>(1)").EvaluateAsync().Result); Assert.Equal(5, s0.ContinueWith(@"bar(5)").EvaluateAsync().Result); } /// <summary> /// Tests that we emit ldftn and ldvirtftn instructions correctly. /// </summary> [Fact] public void CompilationChain_Ldftn() { var state = CSharpScript.RunAsync(@" public class C { public static int f() { return 1; } public int g() { return 10; } public virtual int h() { return 100; } public static int gf<T>() { return 2; } public int gg<T>() { return 20; } public virtual int gh<T>() { return 200; } } "); state = state.ContinueWith(@" new System.Func<int>(C.f)() + new System.Func<int>(new C().g)() + new System.Func<int>(new C().h)()" ); Assert.Equal(111, state.Result.ReturnValue); state = state.ContinueWith(@" new System.Func<int>(C.gf<int>)() + new System.Func<int>(new C().gg<object>)() + new System.Func<int>(new C().gh<bool>)() "); Assert.Equal(222, state.Result.ReturnValue); } /// <summary> /// Tests that we emit ldftn and ldvirtftn instructions correctly. /// </summary> [Fact] public void CompilationChain_Ldftn_GenericType() { var state = CSharpScript.RunAsync(@" public class C<S> { public static int f() { return 1; } public int g() { return 10; } public virtual int h() { return 100; } public static int gf<T>() { return 2; } public int gg<T>() { return 20; } public virtual int gh<T>() { return 200; } } "); state = state.ContinueWith(@" new System.Func<int>(C<byte>.f)() + new System.Func<int>(new C<byte>().g)() + new System.Func<int>(new C<byte>().h)() "); Assert.Equal(111, state.Result.ReturnValue); state = state.ContinueWith(@" new System.Func<int>(C<byte>.gf<int>)() + new System.Func<int>(new C<byte>().gg<object>)() + new System.Func<int>(new C<byte>().gh<bool>)() "); Assert.Equal(222, state.Result.ReturnValue); } #endregion #region Statements and Expressions [Fact] public void IfStatement() { var result = CSharpScript.EvaluateAsync<int>(@" using static System.Console; int x; if (true) { x = 5; } else { x = 6; } x ").Result; Assert.Equal(5, result); } [Fact] public void ExprStmtParenthesesUsedToOverrideDefaultEval() { Assert.Equal(18, CSharpScript.EvaluateAsync<int>("(4 + 5) * 2").Result); Assert.Equal(1, CSharpScript.EvaluateAsync<long>("6 / (2 * 3)").Result); } [WorkItem(5397, "DevDiv_Projects/Roslyn")] [Fact] public void TopLevelLambda() { var s = CSharpScript.RunAsync(@" using System; delegate void TestDelegate(string s); "); s = s.ContinueWith(@" TestDelegate testDelB = delegate (string s) { Console.WriteLine(s); }; "); ScriptingTestHelpers.ContinueRunScriptWithOutput(s, @"testDelB(""hello"");", "hello"); } [Fact] public void Closure() { var f = CSharpScript.EvaluateAsync<Func<int, int>>(@" int Goo(int arg) { return arg + 1; } System.Func<int, int> f = (arg) => { return Goo(arg); }; f ").Result; Assert.Equal(3, f(2)); } [Fact] public void Closure2() { var result = CSharpScript.EvaluateAsync<List<string>>(@" #r ""System.Core"" using System; using System.Linq; using System.Collections.Generic; List<string> result = new List<string>(); string s = ""hello""; Enumerable.ToList(Enumerable.Range(1, 2)).ForEach(x => result.Add(s)); result ").Result; AssertEx.Equal(new[] { "hello", "hello" }, result); } [Fact] public void UseDelegateMixStaticAndDynamic() { var f = CSharpScript.RunAsync("using System;"). ContinueWith("int Sqr(int x) {return x*x;}"). ContinueWith<Func<int, int>>("new Func<int,int>(Sqr)").Result.ReturnValue; Assert.Equal(4, f(2)); } [WorkItem(9229, "DevDiv_Projects/Roslyn")] [Fact] public void Arrays() { var s = CSharpScript.RunAsync(@" int[] arr_1 = { 1, 2, 3 }; int[] arr_2 = new int[] { 1, 2, 3 }; int[] arr_3 = new int[5]; ").ContinueWith(@" arr_2[0] = 5; "); Assert.Equal(3, s.ContinueWith(@"arr_1[2]").Result.ReturnValue); Assert.Equal(5, s.ContinueWith(@"arr_2[0]").Result.ReturnValue); Assert.Equal(0, s.ContinueWith(@"arr_3[0]").Result.ReturnValue); } [Fact] public void FieldInitializers() { var result = CSharpScript.EvaluateAsync<List<int>>(@" using System.Collections.Generic; static List<int> result = new List<int>(); int b = 2; int a; int x = 1, y = b; static int g = 1; static int f = g + 1; a = x + y; result.Add(a); int z = 4 + f; result.Add(z); result.Add(a * z); result ").Result; Assert.Equal(3, result.Count); Assert.Equal(3, result[0]); Assert.Equal(6, result[1]); Assert.Equal(18, result[2]); } [Fact] public void FieldInitializersWithBlocks() { var result = CSharpScript.EvaluateAsync<List<int>>(@" using System.Collections.Generic; static List<int> result = new List<int>(); const int constant = 1; { int x = constant; result.Add(x); } int field = 2; { int x = field; result.Add(x); } result.Add(constant); result.Add(field); result ").Result; Assert.Equal(4, result.Count); Assert.Equal(1, result[0]); Assert.Equal(2, result[1]); Assert.Equal(1, result[2]); Assert.Equal(2, result[3]); } [Fact] public void TestInteractiveClosures() { var result = CSharpScript.RunAsync(@" using System.Collections.Generic; static List<int> result = new List<int>();"). ContinueWith("int x = 1;"). ContinueWith("System.Func<int> f = () => x++;"). ContinueWith("result.Add(f());"). ContinueWith("result.Add(x);"). ContinueWith<List<int>>("result").Result.ReturnValue; Assert.Equal(2, result.Count); Assert.Equal(1, result[0]); Assert.Equal(2, result[1]); } [Fact] public void ExtensionMethods() { var options = ScriptOptions.Default.AddReferences( typeof(Enumerable).GetTypeInfo().Assembly); var result = CSharpScript.EvaluateAsync<int>(@" using System.Linq; string[] fruit = { ""banana"", ""orange"", ""lime"", ""apple"", ""kiwi"" }; fruit.Skip(1).Where(s => s.Length > 4).Count()", options).Result; Assert.Equal(2, result); } [Fact] public void ImplicitlyTypedFields() { var result = CSharpScript.EvaluateAsync<object[]>(@" var x = 1; var y = x; var z = goo(x); string goo(int a) { return null; } int goo(string a) { return 0; } new object[] { x, y, z } ").Result; AssertEx.Equal(new object[] { 1, 1, null }, result); } /// <summary> /// Name of PrivateImplementationDetails type needs to be unique across submissions. /// The compiler should suffix it with a MVID of the current submission module so we should be fine. /// </summary> [WorkItem(949559, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/949559")] [WorkItem(540237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540237")] [WorkItem(9229, "DevDiv_Projects/Roslyn")] [WorkItem(2721, "https://github.com/dotnet/roslyn/issues/2721")] [Fact] public async Task PrivateImplementationDetailsType() { var result1 = await CSharpScript.EvaluateAsync<int[]>("new int[] { 1,2,3,4 }"); AssertEx.Equal(new[] { 1, 2, 3, 4 }, result1); var result2 = await CSharpScript.EvaluateAsync<int[]>("new int[] { 1,2,3,4,5 }"); AssertEx.Equal(new[] { 1, 2, 3, 4, 5 }, result2); var s1 = await CSharpScript.RunAsync<int[]>("new int[] { 1,2,3,4,5,6 }"); AssertEx.Equal(new[] { 1, 2, 3, 4, 5, 6 }, s1.ReturnValue); var s2 = await s1.ContinueWithAsync<int[]>("new int[] { 1,2,3,4,5,6,7 }"); AssertEx.Equal(new[] { 1, 2, 3, 4, 5, 6, 7 }, s2.ReturnValue); var s3 = await s2.ContinueWithAsync<int[]>("new int[] { 1,2,3,4,5,6,7,8 }"); AssertEx.Equal(new[] { 1, 2, 3, 4, 5, 6, 7, 8 }, s3.ReturnValue); } [Fact] public void NoAwait() { // No await. The return value is Task<int> rather than int. var result = CSharpScript.EvaluateAsync("System.Threading.Tasks.Task.FromResult(1)").Result; Assert.Equal(1, ((Task<int>)result).Result); } /// <summary> /// 'await' expression at top-level. /// </summary> [Fact] public void Await() { Assert.Equal(2, CSharpScript.EvaluateAsync("await System.Threading.Tasks.Task.FromResult(2)").Result); } /// <summary> /// 'await' in sub-expression. /// </summary> [Fact] public void AwaitSubExpression() { Assert.Equal(3, CSharpScript.EvaluateAsync<int>("0 + await System.Threading.Tasks.Task.FromResult(3)").Result); } [Fact] public void AwaitVoid() { var task = CSharpScript.EvaluateAsync<object>("await System.Threading.Tasks.Task.Run(() => { })"); Assert.Null(task.Result); Assert.Equal(TaskStatus.RanToCompletion, task.Status); } /// <summary> /// 'await' in lambda should be ignored. /// </summary> [Fact] public async Task AwaitInLambda() { var s0 = await CSharpScript.RunAsync(@" using System; using System.Threading.Tasks; static T F<T>(Func<Task<T>> f) { return f().Result; } static T G<T>(T t, Func<T, Task<T>> f) { return f(t).Result; }"); var s1 = await s0.ContinueWithAsync("F(async () => await Task.FromResult(4))"); Assert.Equal(4, s1.ReturnValue); var s2 = await s1.ContinueWithAsync("G(5, async x => await Task.FromResult(x))"); Assert.Equal(5, s2.ReturnValue); } [Fact] public void AwaitChain1() { var options = ScriptOptions.Default. AddReferences(typeof(Task).GetTypeInfo().Assembly). AddImports("System.Threading.Tasks"); var state = CSharpScript.RunAsync("int i = 0;", options). ContinueWith("await Task.Delay(1); i++;"). ContinueWith("await Task.Delay(1); i++;"). ContinueWith("await Task.Delay(1); i++;"). ContinueWith("i"). Result; Assert.Equal(3, state.ReturnValue); } [Fact] public void AwaitChain2() { var options = ScriptOptions.Default. AddReferences(typeof(Task).GetTypeInfo().Assembly). AddImports("System.Threading.Tasks"); var state = CSharpScript.Create("int i = 0;", options). ContinueWith("await Task.Delay(1); i++;"). ContinueWith("await Task.Delay(1); i++;"). RunAsync(). ContinueWith("await Task.Delay(1); i++;"). ContinueWith("i"). Result; Assert.Equal(3, state.ReturnValue); } [Fact, WorkItem(39548, "https://github.com/dotnet/roslyn/issues/39548")] public async Task PatternVariableDeclaration() { var state = await CSharpScript.RunAsync("var x = (false, 4);"); state = await state.ContinueWithAsync("x is (false, var y)"); Assert.Equal(true, state.ReturnValue); } [Fact, WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] public async Task CSharp9PatternForms() { var options = ScriptOptions.Default.WithLanguageVersion(MessageID.IDS_FeatureAndPattern.RequiredVersion()); var state = await CSharpScript.RunAsync("object x = 1;", options: options); state = await state.ContinueWithAsync("x is long or int", options: options); Assert.Equal(true, state.ReturnValue); state = await state.ContinueWithAsync("x is int and < 10", options: options); Assert.Equal(true, state.ReturnValue); state = await state.ContinueWithAsync("x is (long or < 10L)", options: options); Assert.Equal(false, state.ReturnValue); state = await state.ContinueWithAsync("x is not > 100", options: options); Assert.Equal(true, state.ReturnValue); } #endregion #region References [Fact(Skip = "https://github.com/dotnet/roslyn/issues/53391")] [WorkItem(15860, "https://github.com/dotnet/roslyn/issues/53391")] public void ReferenceDirective_FileWithDependencies() { var file1 = Temp.CreateFile(); var file2 = Temp.CreateFile(); var lib1 = CreateCSharpCompilationWithCorlib(@" public interface I { int F(); }"); lib1.Emit(file1.Path); var lib2 = CreateCSharpCompilation(@" public class C : I { public int F() => 1; }", new MetadataReference[] { TestReferences.NetStandard13.SystemRuntime, lib1.ToMetadataReference() }); lib2.Emit(file2.Path); object result = CSharpScript.EvaluateAsync($@" #r ""{file1.Path}"" #r ""{file2.Path}"" new C() ").Result; Assert.NotNull(result); } [ConditionalFact(typeof(WindowsOnly)), WorkItem(15860, "https://github.com/dotnet/roslyn/issues/15860")] public void ReferenceDirective_RelativeToBaseParent() { var file = Temp.CreateFile(); var lib = CreateCSharpCompilationWithCorlib("public class C {}"); lib.Emit(file.Path); string dir = Path.Combine(Path.GetDirectoryName(file.Path), "subdir"); string libFileName = Path.GetFileName(file.Path); string scriptPath = Path.Combine(dir, "a.csx"); var script = CSharpScript.Create( $@"#r ""{Path.Combine("..", libFileName)}""", ScriptOptions.Default.WithFilePath(scriptPath)); script.GetCompilation().VerifyDiagnostics(); } [ConditionalFact(typeof(WindowsOnly)), WorkItem(15860, "https://github.com/dotnet/roslyn/issues/15860")] public void ReferenceDirective_RelativeToBaseRoot() { var file = Temp.CreateFile(); var lib = CreateCSharpCompilationWithCorlib("public class C {}"); lib.Emit(file.Path); string root = Path.GetPathRoot(file.Path); string unrooted = file.Path.Substring(root.Length); string dir = Path.Combine(root, "goo", "bar", "baz"); string scriptPath = Path.Combine(dir, "a.csx"); var script = CSharpScript.Create( $@"#r ""\{unrooted}""", ScriptOptions.Default.WithFilePath(scriptPath)); script.GetCompilation().VerifyDiagnostics(); } [Fact] public void ExtensionPriority1() { string mainName = "Main_" + Guid.NewGuid(); string libName = "Lib_" + Guid.NewGuid(); var libExe = CreateCSharpCompilationWithCorlib(@"public class C { public string F = ""exe""; }", libName); var libDll = CreateCSharpCompilationWithCorlib(@"public class C { public string F = ""dll""; }", libName); var libWinmd = CreateCSharpCompilationWithCorlib(@"public class C { public string F = ""winmd""; }", libName); var main = CreateCSharpCompilation( @"public static class M { public static readonly C X = new C(); }", new MetadataReference[] { TestReferences.NetStandard13.SystemRuntime, libExe.ToMetadataReference() }, mainName); var exeImage = libExe.EmitToArray(); var dllImage = libDll.EmitToArray(); var winmdImage = libWinmd.EmitToArray(); var mainImage = main.EmitToArray(); var dir = Temp.CreateDirectory(); var fileMain = dir.CreateFile(mainName + ".dll").WriteAllBytes(mainImage); dir.CreateFile(libName + ".exe").WriteAllBytes(exeImage); dir.CreateFile(libName + ".winmd").WriteAllBytes(winmdImage); var r2 = CSharpScript.Create($@"#r ""{fileMain.Path}""").ContinueWith($@"M.X.F").RunAsync().Result.ReturnValue; Assert.Equal("exe", r2); } [Fact] public void ExtensionPriority2() { string mainName = "Main_" + Guid.NewGuid(); string libName = "Lib_" + Guid.NewGuid(); var libExe = CreateCSharpCompilationWithCorlib(@"public class C { public string F = ""exe""; }", libName); var libDll = CreateCSharpCompilationWithCorlib(@"public class C { public string F = ""dll""; }", libName); var libWinmd = CreateCSharpCompilationWithCorlib(@"public class C { public string F = ""winmd""; }", libName); var main = CreateCSharpCompilation( @"public static class M { public static readonly C X = new C(); }", new MetadataReference[] { TestReferences.NetStandard13.SystemRuntime, libExe.ToMetadataReference() }, mainName); var exeImage = libExe.EmitToArray(); var dllImage = libDll.EmitToArray(); var winmdImage = libWinmd.EmitToArray(); var mainImage = main.EmitToArray(); var dir = Temp.CreateDirectory(); var fileMain = dir.CreateFile(mainName + ".dll").WriteAllBytes(mainImage); dir.CreateFile(libName + ".exe").WriteAllBytes(exeImage); dir.CreateFile(libName + ".dll").WriteAllBytes(dllImage); dir.CreateFile(libName + ".winmd").WriteAllBytes(winmdImage); var r2 = CSharpScript.Create($@"#r ""{fileMain.Path}""").ContinueWith($@"M.X.F").RunAsync().Result.ReturnValue; Assert.Equal("dll", r2); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/6015")] public void UsingExternalAliasesForHiding() { string source = @" namespace N { public class C { } } public class D { } public class E { } "; var libRef = CreateCSharpCompilationWithCorlib(source, "lib").EmitToImageReference(); var script = CSharpScript.Create(@"new C()", ScriptOptions.Default.WithReferences(libRef.WithAliases(new[] { "Hidden" })).WithImports("Hidden::N")); script.Compile().Verify(); } #endregion #region UsingDeclarations [Fact] public void UsingAlias() { object result = CSharpScript.EvaluateAsync(@" using D = System.Collections.Generic.Dictionary<string, int>; D d = new D(); d ").Result; Assert.True(result is Dictionary<string, int>, "Expected Dictionary<string, int>"); } [WorkItem(9229, "DevDiv_Projects/Roslyn")] [Fact] public void Usings1() { var options = ScriptOptions.Default. AddImports("System", "System.Linq"). AddReferences(typeof(Enumerable).GetTypeInfo().Assembly); object result = CSharpScript.EvaluateAsync("new int[] { 1, 2, 3 }.First()", options).Result; Assert.Equal(1, result); } [WorkItem(9229, "DevDiv_Projects/Roslyn")] [Fact] public void Usings2() { var options = ScriptOptions.Default. AddImports("System", "System.Linq"). AddReferences(typeof(Enumerable).GetTypeInfo().Assembly); var s1 = CSharpScript.RunAsync("new int[] { 1, 2, 3 }.First()", options); Assert.Equal(1, s1.Result.ReturnValue); var s2 = s1.ContinueWith("new List<int>()", options.AddImports("System.Collections.Generic")); Assert.IsType<List<int>>(s2.Result.ReturnValue); } [Fact] public void AddNamespaces_Errors() { // no immediate error, error is reported if the namespace can't be found when compiling: var options = ScriptOptions.Default.AddImports("?1", "?2"); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("1", options), // error CS0246: The type or namespace name '?1' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound).WithArguments("?1"), // error CS0246: The type or namespace name '?2' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound).WithArguments("?2")); options = ScriptOptions.Default.AddImports(""); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("1", options), // error CS7088: Invalid 'Usings' value: ''. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "")); options = ScriptOptions.Default.AddImports(".abc"); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("1", options), // error CS7088: Invalid 'Usings' value: '.abc'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", ".abc")); options = ScriptOptions.Default.AddImports("a\0bc"); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("1", options), // error CS7088: Invalid 'Usings' value: '.abc'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "a\0bc")); } #endregion #region Host Object Binding and Conversions public class C<T> { } [Fact] public void Submission_HostConversions() { Assert.Equal(2, CSharpScript.EvaluateAsync<int>("1+1").Result); Assert.Null(CSharpScript.EvaluateAsync<string>("null").Result); try { CSharpScript.RunAsync<C<int>>("null"); Assert.True(false, "Expected an exception"); } catch (CompilationErrorException e) { // error CS0400: The type or namespace name 'Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Source.InteractiveSessionTests+C`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], Roslyn.Compilers.CSharp.Emit.UnitTests, Version=42.42.42.42, Culture=neutral, PublicKeyToken=fc793a00266884fb' could not be found in the global namespace (are you missing an assembly reference?) Assert.Equal(ErrorCode.ERR_GlobalSingleTypeNameNotFound, (ErrorCode)e.Diagnostics.Single().Code); // Can't use Verify() because the version number of the test dll is different in the build lab. } var options = ScriptOptions.Default.AddReferences(HostAssembly); var cint = CSharpScript.EvaluateAsync<C<int>>("null", options).Result; Assert.Null(cint); Assert.Null(CSharpScript.EvaluateAsync<int?>("null", options).Result); try { CSharpScript.RunAsync<int>("null"); Assert.True(false, "Expected an exception"); } catch (CompilationErrorException e) { e.Diagnostics.Verify( // (1,1): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // null Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int")); } try { CSharpScript.RunAsync<string>("1+1"); Assert.True(false, "Expected an exception"); } catch (CompilationErrorException e) { e.Diagnostics.Verify( // (1,1): error CS0029: Cannot implicitly convert type 'int' to 'string' // 1+1 Diagnostic(ErrorCode.ERR_NoImplicitConv, "1+1").WithArguments("int", "string")); } } [Fact] public void Submission_HostVarianceConversions() { var value = CSharpScript.EvaluateAsync<IEnumerable<Exception>>(@" using System; using System.Collections.Generic; new List<ArgumentException>() ").Result; Assert.Null(value.FirstOrDefault()); } public class B { public int x = 1, w = 4; } public class C : B, I { public static readonly int StaticField = 123; public int Y => 2; public string N { get; set; } = "2"; public int Z() => 3; public override int GetHashCode() => 123; } public interface I { string N { get; set; } int Z(); } private class PrivateClass : I { public string N { get; set; } = null; public int Z() => 3; } public class M<T> { private int F() => 3; public T G() => default(T); } [Fact] public void HostObjectBinding_PublicClassMembers() { var c = new C(); var s0 = CSharpScript.RunAsync<int>("x + Y + Z()", globals: c); Assert.Equal(6, s0.Result.ReturnValue); var s1 = s0.ContinueWith<int>("x"); Assert.Equal(1, s1.Result.ReturnValue); var s2 = s1.ContinueWith<int>("int x = 20;"); var s3 = s2.ContinueWith<int>("x"); Assert.Equal(20, s3.Result.ReturnValue); } [Fact] public void HostObjectBinding_PublicGenericClassMembers() { var m = new M<string>(); var result = CSharpScript.EvaluateAsync<string>("G()", globals: m); Assert.Null(result.Result); } [Fact] public async Task HostObjectBinding_Interface() { var c = new C(); var s0 = await CSharpScript.RunAsync<int>("Z()", globals: c, globalsType: typeof(I)); Assert.Equal(3, s0.ReturnValue); ScriptingTestHelpers.AssertCompilationError(s0, @"x + Y", // The name '{0}' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x"), Diagnostic(ErrorCode.ERR_NameNotInContext, "Y").WithArguments("Y")); var s1 = await s0.ContinueWithAsync<string>("N"); Assert.Equal("2", s1.ReturnValue); } [Fact] public void HostObjectBinding_PrivateClass() { var c = new PrivateClass(); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("Z()", globals: c), // (1,1): error CS0122: '<Fully Qualified Name of PrivateClass>.Z()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "Z").WithArguments(typeof(PrivateClass).FullName.Replace("+", ".") + ".Z()")); } [Fact] public void HostObjectBinding_PrivateMembers() { object c = new M<int>(); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("Z()", globals: c), // (1,1): error CS0103: The name 'z' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "Z").WithArguments("Z")); } [Fact] public void HostObjectBinding_PrivateClassImplementingPublicInterface() { var c = new PrivateClass(); var result = CSharpScript.EvaluateAsync<int>("Z()", globals: c, globalsType: typeof(I)); Assert.Equal(3, result.Result); } [Fact] public void HostObjectBinding_StaticMembers() { var s0 = CSharpScript.RunAsync("static int goo = StaticField;", globals: new C()); var s1 = s0.ContinueWith("static int bar { get { return goo; } }"); var s2 = s1.ContinueWith("class C { public static int baz() { return bar; } }"); var s3 = s2.ContinueWith("C.baz()"); Assert.Equal(123, s3.Result.ReturnValue); } public class D { public int goo(int a) { return 0; } } /// <summary> /// Host object members don't form a method group with submission members. /// </summary> [Fact] public void HostObjectBinding_Overloads() { var s0 = CSharpScript.RunAsync("int goo(double a) { return 2; }", globals: new D()); var s1 = s0.ContinueWith("goo(1)"); Assert.Equal(2, s1.Result.ReturnValue); var s2 = s1.ContinueWith("goo(1.0)"); Assert.Equal(2, s2.Result.ReturnValue); } [Fact] public void HostObjectInRootNamespace() { var obj = new InteractiveFixtures_TopLevelHostObject { X = 1, Y = 2, Z = 3 }; var r0 = CSharpScript.EvaluateAsync<int>("X + Y + Z", globals: obj); Assert.Equal(6, r0.Result); obj = new InteractiveFixtures_TopLevelHostObject { X = 1, Y = 2, Z = 3 }; var r1 = CSharpScript.EvaluateAsync<int>("X", globals: obj); Assert.Equal(1, r1.Result); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30303")] public void HostObjectAssemblyReference1() { var scriptCompilation = CSharpScript.Create( "nameof(Microsoft.CodeAnalysis.Scripting)", ScriptOptions.Default.WithMetadataResolver(TestRuntimeMetadataReferenceResolver.Instance), globalsType: typeof(CommandLineScriptGlobals)).GetCompilation(); scriptCompilation.VerifyDiagnostics( // (1,8): error CS0234: The type or namespace name 'CodeAnalysis' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?) // nameof(Microsoft.CodeAnalysis.Scripting) Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "Microsoft.CodeAnalysis").WithArguments("CodeAnalysis", "Microsoft").WithLocation(1, 8)); string corAssemblyName = typeof(object).GetTypeInfo().Assembly.GetName().Name; string hostObjectAssemblyName = scriptCompilation.ScriptCompilationInfo.GlobalsType.GetTypeInfo().Assembly.GetName().Name; // The host adds // 1) a reference to typeof(object).Assembly // 2) a reference to GlobalsType with alias <host> applied recursively. // References returned from ResolveMissingAssembly have <implicit> alias. foreach (var (assembly, aliases) in scriptCompilation.GetBoundReferenceManager().GetReferencedAssemblyAliases()) { string name = assembly.Identity.Name; switch (name) { case "Microsoft.CodeAnalysis.CSharp.Scripting": case "Microsoft.CodeAnalysis.CSharp": // assemblies not referenced Assert.False(true); break; case "Microsoft.CodeAnalysis": case "System.Collections.Immutable": // Microsoft.CodeAnalysis.Scripting contains host object and is thus referenced recursively with <host> alias. // The script doesn't reference the assemblies explicitly. AssertEx.SetEqual(new[] { "<implicit>", "<host>" }, aliases); break; default: if (name == corAssemblyName) { // Host object depends on System.Object, thus <host> is applied on CorLib. AssertEx.SetEqual(new[] { "<host>", "global" }, aliases); } else if (name == hostObjectAssemblyName) { // Host object is only referenced by the host and thus the assembly is hidden behind <host> alias. AssertEx.SetEqual(new[] { "<host>" }, aliases); } break; } } } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/dotnet/roslyn/issues/30303")] public void HostObjectAssemblyReference2() { var scriptCompilation = CSharpScript.Create( "typeof(Microsoft.CodeAnalysis.Scripting.Script)", options: ScriptOptions.Default. WithMetadataResolver(TestRuntimeMetadataReferenceResolver.Instance). WithReferences(typeof(CSharpScript).GetTypeInfo().Assembly), globalsType: typeof(CommandLineScriptGlobals)).GetCompilation(); scriptCompilation.VerifyDiagnostics(); string corAssemblyName = typeof(object).GetTypeInfo().Assembly.GetName().Name; string hostObjectAssemblyName = scriptCompilation.ScriptCompilationInfo.GlobalsType.GetTypeInfo().Assembly.GetName().Name; // The host adds // 1) a reference to typeof(object).Assembly // 2) a reference to GlobalsType with alias <host> applied recursively. // References returned from ResolveMissingAssembly have <implicit> alias. foreach (var (assembly, aliases) in scriptCompilation.GetBoundReferenceManager().GetReferencedAssemblyAliases()) { string name = assembly.Identity.Name; switch (name) { case "Microsoft.CodeAnalysis.CSharp.Scripting": // we have an explicit reference to CSharpScript assembly: AssertEx.SetEqual(Array.Empty<string>(), aliases); break; case "Microsoft.CodeAnalysis.CSharp": // The script has a recursive reference to Microsoft.CodeAnalysis.CSharp.Scripting, which references these assemblies. // The script doesn't reference the assembly explicitly. AssertEx.SetEqual(new[] { "<implicit>", "global" }, aliases); break; case "Microsoft.CodeAnalysis": case "System.Collections.Immutable": // The script has a recursive reference to Microsoft.CodeAnalysis.CSharp.Scripting, which references these assemblies. // Microsoft.CodeAnalysis.Scripting contains host object and is thus referenced recursively with <host> alias. // The script doesn't reference the assemblies explicitly. AssertEx.SetEqual(new[] { "<implicit>", "<host>", "global" }, aliases); break; default: if (name == corAssemblyName) { // Host object depends on System.Object, thus <host> is applied on CorLib. AssertEx.SetEqual(new[] { "<host>", "global" }, aliases); } else if (name == hostObjectAssemblyName) { // Host object is defined in an assembly that CSharpScript depends on. // CSharpScript assembly was references (recursively) hence host object assembly is // available to the script (global alias). AssertEx.SetEqual(new[] { "<host>", "global" }, aliases); } break; } } } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/dotnet/roslyn/issues/30303")] public void HostObjectAssemblyReference3() { string source = $@" #r ""{typeof(CSharpScript).GetTypeInfo().Assembly.ManifestModule.FullyQualifiedName}"" typeof(Microsoft.CodeAnalysis.Scripting.Script) "; var scriptCompilation = CSharpScript.Create( source, ScriptOptions.Default.WithMetadataResolver(TestRuntimeMetadataReferenceResolver.Instance), globalsType: typeof(CommandLineScriptGlobals)).GetCompilation(); scriptCompilation.VerifyDiagnostics(); string corAssemblyName = typeof(object).GetTypeInfo().Assembly.GetName().Name; string hostObjectAssemblyName = scriptCompilation.ScriptCompilationInfo.GlobalsType.GetTypeInfo().Assembly.GetName().Name; // The host adds // 1) a reference to typeof(object).Assembly // 2) a reference to GlobalsType with alias <host> applied recursively. // References returned from ResolveMissingAssembly have <implicit> alias. foreach (var (assembly, aliases) in scriptCompilation.GetBoundReferenceManager().GetReferencedAssemblyAliases()) { string name = assembly.Identity.Name; switch (name) { case "Microsoft.CodeAnalysis.CSharp.Scripting": // we have an explicit reference to CSharpScript assembly: AssertEx.SetEqual(Array.Empty<string>(), aliases); break; case "Microsoft.CodeAnalysis.CSharp": // The script has a recursive reference to Microsoft.CodeAnalysis.CSharp.Scripting, which references these assemblies. // The script doesn't reference the assembly explicitly. AssertEx.SetEqual(new[] { "<implicit>", "global" }, aliases); break; case "Microsoft.CodeAnalysis": case "System.Collections.Immutable": // The script has a recursive reference to Microsoft.CodeAnalysis.CSharp.Scripting, which references these assemblies. // Microsoft.CodeAnalysis.Scripting contains host object and is thus referenced recursively with <host> alias. // The script doesn't reference the assemblies explicitly. AssertEx.SetEqual(new[] { "<implicit>", "<host>", "global" }, aliases); break; default: if (name == corAssemblyName) { // Host object depends on System.Object, thus <host> is applied on CorLib. AssertEx.SetEqual(new[] { "<host>", "global" }, aliases); } else if (name == hostObjectAssemblyName) { // Host object is defined in an assembly that CSharpScript depends on. // CSharpScript assembly was references (recursively) hence host object assembly is // available to the script (global alias). AssertEx.SetEqual(new[] { "<host>", "global" }, aliases); } break; } } } public class E { public bool TryGetValue(out object obj) { obj = new object(); return true; } } [Fact] [WorkItem(39565, "https://github.com/dotnet/roslyn/issues/39565")] public async Task MethodCallWithImplicitReceiverAndOutVar() { var code = @" if(TryGetValue(out var result)){ _ = result; } return true; "; var result = await CSharpScript.EvaluateAsync<bool>(code, globalsType: typeof(E), globals: new E()); Assert.True(result); } public class F { public bool Value = true; } [Fact] public void StaticMethodCannotAccessGlobalInstance() { var code = @" static bool M() { return Value; } return M(); "; var script = CSharpScript.Create<bool>(code, globalsType: typeof(F)); ScriptingTestHelpers.AssertCompilationError(() => script.RunAsync(new F()).Wait(), // (4,9): error CS0120: An object reference is required for the non-static field, method, or property 'InteractiveSessionTests.F.Value' // return Value; Diagnostic(ErrorCode.ERR_ObjectRequired, "Value").WithArguments("Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests.InteractiveSessionTests.F.Value").WithLocation(4, 9)); } [Fact] [WorkItem(39581, "https://github.com/dotnet/roslyn/issues/39581")] public void StaticLocalFunctionCannotAccessGlobalInstance() { var code = @" bool M() { return Inner(); static bool Inner() { return Value; } } return M(); "; var script = CSharpScript.Create<bool>(code, globalsType: typeof(F)); ScriptingTestHelpers.AssertCompilationError(() => script.RunAsync(new F()).Wait(), // (7,10): error CS0120: An object reference is required for the non-static field, method, or property 'InteractiveSessionTests.F.Value' // return Value; Diagnostic(ErrorCode.ERR_ObjectRequired, "Value").WithArguments("Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests.InteractiveSessionTests.F.Value").WithLocation(7, 10)); } [Fact] public async Task LocalFunctionCanAccessGlobalInstance() { var code = @" bool M() { return Inner(); bool Inner() { return Value; } } return M(); "; var result = await CSharpScript.EvaluateAsync<bool>(code, globalsType: typeof(F), globals: new F()); Assert.True(result); } #endregion #region Exceptions [Fact] [WorkItem(6580, "https://github.com/dotnet/roslyn/issues/6580")] [WorkItem(10883, "https://github.com/dotnet/roslyn/issues/10883")] public async Task PreservingDeclarationsOnException1() { var s0 = CSharpScript.Create(@" int i = 10; throw new System.Exception(""Bang!""); int j = 2; "); var s1 = s0.ContinueWith(@" int F() => i + j; "); var state1 = await s1.RunAsync(catchException: e => true); Assert.Equal("Bang!", state1.Exception.Message); var state2 = await state1.ContinueWithAsync<int>("F()"); Assert.Equal(10, state2.ReturnValue); } [Fact] [WorkItem(6580, "https://github.com/dotnet/roslyn/issues/6580")] [WorkItem(10883, "https://github.com/dotnet/roslyn/issues/10883")] public async Task PreservingDeclarationsOnException2() { var s0 = CSharpScript.Create(@" int i = 100; "); var s1 = s0.ContinueWith(@" int j = 20; throw new System.Exception(""Bang!""); int k = 3; "); var s2 = s1.ContinueWith(@" int F() => i + j + k; "); var state2 = await s2.RunAsync(catchException: e => true); Assert.Equal("Bang!", state2.Exception.Message); var state3 = await state2.ContinueWithAsync<int>("F()"); Assert.Equal(120, state3.ReturnValue); } [Fact] [WorkItem(6580, "https://github.com/dotnet/roslyn/issues/6580")] [WorkItem(10883, "https://github.com/dotnet/roslyn/issues/10883")] public async Task PreservingDeclarationsOnException3() { var s0 = CSharpScript.Create(@" int i = 1000; "); var s1 = s0.ContinueWith(@" int j = 200; throw new System.Exception(""Bang!""); int k = 30; "); var s2 = s1.ContinueWith(@" int l = 4; "); var s3 = s2.ContinueWith(@" int F() => i + j + k + l; "); var state3 = await s3.RunAsync(catchException: e => true); Assert.Equal("Bang!", state3.Exception.Message); var state4 = await state3.ContinueWithAsync<int>("F()"); Assert.Equal(1200, state4.ReturnValue); } [Fact] [WorkItem(6580, "https://github.com/dotnet/roslyn/issues/6580")] [WorkItem(10883, "https://github.com/dotnet/roslyn/issues/10883")] public async Task PreservingDeclarationsOnException4() { var state0 = await CSharpScript.RunAsync(@" int i = 1000; "); var state1 = await state0.ContinueWithAsync(@" int j = 200; throw new System.Exception(""Bang 1!""); int k = 30; ", catchException: e => true); Assert.Equal("Bang 1!", state1.Exception.Message); var state2 = await state1.ContinueWithAsync<int>(@" int l = 4; throw new System.Exception(""Bang 2!""); 1 ", catchException: e => true); Assert.Equal("Bang 2!", state2.Exception.Message); var state4 = await state2.ContinueWithAsync(@" i + j + k + l "); Assert.Equal(1204, state4.ReturnValue); } [Fact] public async Task PreservingDeclarationsOnCancellation1() { var cancellationSource = new CancellationTokenSource(); var globals = new StrongBox<CancellationTokenSource>(); globals.Value = cancellationSource; var s0 = CSharpScript.Create(@" int i = 1000; ", globalsType: globals.GetType()); var s1 = s0.ContinueWith(@" int j = 200; Value.Cancel(); int k = 30; "); // cancellation exception is thrown just before we start evaluating s2: var s2 = s1.ContinueWith(@" int l = 4; "); var s3 = s2.ContinueWith(@" int F() => i + j + k + l; "); var state3 = await s3.RunAsync(globals, catchException: e => true, cancellationToken: cancellationSource.Token); Assert.IsType<OperationCanceledException>(state3.Exception); var state4 = await state3.ContinueWithAsync<int>("F()"); Assert.Equal(1230, state4.ReturnValue); } [Fact] public async Task PreservingDeclarationsOnCancellation2() { var cancellationSource = new CancellationTokenSource(); var globals = new StrongBox<CancellationTokenSource>(); globals.Value = cancellationSource; var s0 = CSharpScript.Create(@" int i = 1000; ", globalsType: globals.GetType()); var s1 = s0.ContinueWith(@" int j = 200; int k = 30; "); var s2 = s1.ContinueWith(@" int l = 4; Value.Cancel(); "); // cancellation exception is thrown just before we start evaluating s3: var s3 = s2.ContinueWith(@" int F() => i + j + k + l; "); var state3 = await s3.RunAsync(globals, catchException: e => true, cancellationToken: cancellationSource.Token); Assert.IsType<OperationCanceledException>(state3.Exception); var state4 = await state3.ContinueWithAsync<int>("F()"); Assert.Equal(1234, state4.ReturnValue); } [Fact] public async Task PreservingDeclarationsOnCancellation3() { var cancellationSource = new CancellationTokenSource(); var globals = new StrongBox<CancellationTokenSource>(); globals.Value = cancellationSource; var s0 = CSharpScript.Create(@" int i = 1000; ", globalsType: globals.GetType()); var s1 = s0.ContinueWith(@" int j = 200; Value.Cancel(); int k = 30; "); // cancellation exception is thrown just before we start evaluating s2: var s2 = s1.ContinueWith(@" int l = 4; "); var s3 = s2.ContinueWith(@" int F() => i + j + k + l; "); await Assert.ThrowsAsync<OperationCanceledException>(() => s3.RunAsync(globals, catchException: e => !(e is OperationCanceledException), cancellationToken: cancellationSource.Token)); } #endregion #region Local Functions [Fact] public void LocalFunction_PreviousSubmissionAndGlobal() { var result = CSharpScript.RunAsync( @"int InInitialSubmission() { return LocalFunction(); int LocalFunction() => Y; }", globals: new C()). ContinueWith( @"var lambda = new System.Func<int>(() => { return LocalFunction(); int LocalFunction() => Y + InInitialSubmission(); }); lambda.Invoke()"). Result.ReturnValue; Assert.Equal(4, result); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.Scripting.Hosting; using Microsoft.CodeAnalysis.Scripting.Test; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Basic.Reference.Assemblies; namespace Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests { using static TestCompilationFactory; public class HostModel { public readonly int Goo; } public class InteractiveSessionTests : TestBase { internal static readonly Assembly HostAssembly = typeof(InteractiveSessionTests).GetTypeInfo().Assembly; #region Namespaces, Types [Fact(Skip = "https://github.com/dotnet/roslyn/issues/17869")] public void CompilationChain_NestedTypesClass() { var script = CSharpScript.Create(@" static string outerStr = null; public static void Goo(string str) { outerStr = str; } class InnerClass { public string innerStr = null; public void Goo() { Goo(""test""); innerStr = outerStr; } } ").ContinueWith(@" InnerClass iC = new InnerClass(); iC.Goo(); ").ContinueWith(@" System.Console.WriteLine(iC.innerStr); "); ScriptingTestHelpers.RunScriptWithOutput(script, "test"); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/17869")] public void CompilationChain_NestedTypesStruct() { var script = CSharpScript.Create(@" static string outerStr = null; public static void Goo(string str) { outerStr = str; } struct InnerStruct { public string innerStr; public void Goo() { Goo(""test""); innerStr = outerStr; } } ").ContinueWith(@" InnerStruct iS = new InnerStruct(); iS.Goo(); ").ContinueWith(@" System.Console.WriteLine(iS.innerStr); "); ScriptingTestHelpers.RunScriptWithOutput(script, "test"); } [Fact] public async Task CompilationChain_InterfaceTypes() { var script = CSharpScript.Create(@" interface I1 { int Goo();} class InnerClass : I1 { public int Goo() { return 1; } }").ContinueWith(@" I1 iC = new InnerClass(); ").ContinueWith(@" iC.Goo() "); Assert.Equal(1, await script.EvaluateAsync()); } [Fact] public void ScriptMemberAccessFromNestedClass() { var script = CSharpScript.Create(@" object field; object Property { get; set; } void Method() { } ").ContinueWith(@" class C { public void Goo() { object f = field; object p = Property; Method(); } } "); ScriptingTestHelpers.AssertCompilationError(script, // (6,20): error CS0120: An object reference is required for the non-static field, method, or property 'field' Diagnostic(ErrorCode.ERR_ObjectRequired, "field").WithArguments("field"), // (7,20): error CS0120: An object reference is required for the non-static field, method, or property 'Property' Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("Property"), // (8,9): error CS0120: An object reference is required for the non-static field, method, or property 'Method()' Diagnostic(ErrorCode.ERR_ObjectRequired, "Method").WithArguments("Method()")); } #region Anonymous Types [Fact] public void AnonymousTypes_TopLevel_MultipleSubmissions() { var script = CSharpScript.Create(@" var a = new { f = 1 }; ").ContinueWith(@" var b = new { g = 1 }; ").ContinueWith<Array>(@" var c = new { f = 1 }; var d = new { g = 1 }; new object[] { new[] { a, c }, new[] { b, d } } "); var result = script.EvaluateAsync().Result; Assert.Equal(2, result.Length); Assert.Equal(2, ((Array)result.GetValue(0)).Length); Assert.Equal(2, ((Array)result.GetValue(1)).Length); } [Fact] public void AnonymousTypes_TopLevel_MultipleSubmissions2() { var script = CSharpScript.Create(@" var a = new { f = 1 }; ").ContinueWith(@" var b = new { g = 1 }; ").ContinueWith(@" var c = new { f = 1 }; var d = new { g = 1 }; object.ReferenceEquals(a.GetType(), c.GetType()).ToString() + "" "" + object.ReferenceEquals(a.GetType(), b.GetType()).ToString() + "" "" + object.ReferenceEquals(b.GetType(), d.GetType()).ToString() "); Assert.Equal("True False True", script.EvaluateAsync().Result.ToString()); } [WorkItem(543863, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543863")] [Fact] public void AnonymousTypes_Redefinition() { var script = CSharpScript.Create(@" var x = new { Goo = ""goo"" }; ").ContinueWith(@" var x = new { Goo = ""goo"" }; ").ContinueWith(@" x.Goo "); var result = script.EvaluateAsync().Result; Assert.Equal("goo", result); } [Fact] public void AnonymousTypes_TopLevel_Empty() { var script = CSharpScript.Create(@" var a = new { }; ").ContinueWith(@" var b = new { }; ").ContinueWith<Array>(@" var c = new { }; var d = new { }; new object[] { new[] { a, c }, new[] { b, d } } "); var result = script.EvaluateAsync().Result; Assert.Equal(2, result.Length); Assert.Equal(2, ((Array)result.GetValue(0)).Length); Assert.Equal(2, ((Array)result.GetValue(1)).Length); } #endregion #region Dynamic [Fact] public void Dynamic_Expando() { var options = ScriptOptions.Default. AddReferences( typeof(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException).GetTypeInfo().Assembly, typeof(System.Dynamic.ExpandoObject).GetTypeInfo().Assembly). AddImports( "System.Dynamic"); var script = CSharpScript.Create(@" dynamic expando = new ExpandoObject(); ", options).ContinueWith(@" expando.goo = 1; ").ContinueWith(@" expando.goo "); Assert.Equal(1, script.EvaluateAsync().Result); } #endregion [Fact] public void Enums() { var script = CSharpScript.Create(@" public enum Enum1 { A, B, C } Enum1 E = Enum1.C; E "); var e = script.EvaluateAsync().Result; Assert.True(e.GetType().GetTypeInfo().IsEnum, "Expected enum"); Assert.Equal(typeof(int), Enum.GetUnderlyingType(e.GetType())); } #endregion #region Attributes [Fact] public void PInvoke() { var source = @" using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [DllImport(""goo"", EntryPoint = ""bar"", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = true, SetLastError = true, BestFitMapping = true, ThrowOnUnmappableChar = true)] public static extern void M(); class C { } typeof(C) "; Type c = CSharpScript.EvaluateAsync<Type>(source).Result; var m = c.DeclaringType.GetTypeInfo().GetDeclaredMethod("M"); Assert.Equal(MethodImplAttributes.PreserveSig, m.MethodImplementationFlags); // Reflection synthesizes DllImportAttribute var dllImport = (DllImportAttribute)m.GetCustomAttributes(typeof(DllImportAttribute), inherit: false).Single(); Assert.True(dllImport.BestFitMapping); Assert.Equal(CallingConvention.Cdecl, dllImport.CallingConvention); Assert.Equal(CharSet.Unicode, dllImport.CharSet); Assert.True(dllImport.ExactSpelling); Assert.True(dllImport.SetLastError); Assert.True(dllImport.PreserveSig); Assert.True(dllImport.ThrowOnUnmappableChar); Assert.Equal("bar", dllImport.EntryPoint); Assert.Equal("goo", dllImport.Value); } #endregion // extension methods - must be private, can be top level #region Modifiers and Visibility [Fact] public void PrivateTopLevel() { var script = CSharpScript.Create<int>(@" private int goo() { return 1; } private static int bar() { return 10; } private static int f = 100; goo() + bar() + f "); Assert.Equal(111, script.EvaluateAsync().Result); script = script.ContinueWith<int>(@" goo() + bar() + f "); Assert.Equal(111, script.EvaluateAsync().Result); script = script.ContinueWith<int>(@" class C { public static int baz() { return bar() + f; } } C.baz() "); Assert.Equal(110, script.EvaluateAsync().Result); } [Fact] public void NestedVisibility() { var script = CSharpScript.Create(@" private class C { internal class D { internal static int goo() { return 1; } } private class E { internal static int goo() { return 1; } } public class F { internal protected static int goo() { return 1; } } internal protected class G { internal static int goo() { return 1; } } } "); Assert.Equal(1, script.ContinueWith<int>("C.D.goo()").EvaluateAsync().Result); Assert.Equal(1, script.ContinueWith<int>("C.F.goo()").EvaluateAsync().Result); Assert.Equal(1, script.ContinueWith<int>("C.G.goo()").EvaluateAsync().Result); ScriptingTestHelpers.AssertCompilationError(script.ContinueWith<int>(@"C.E.goo()"), // error CS0122: 'C.E' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "E").WithArguments("C.E")); } [Fact] public void Fields_Visibility() { var script = CSharpScript.Create(@" private int i = 2; // test comment; public int j = 2; protected int k = 2; internal protected int l = 2; internal int pi = 2; ").ContinueWith(@" i = i + i; j = j + j; k = k + k; l = l + l; ").ContinueWith(@" pi = i + j + k + l; "); Assert.Equal(4, script.ContinueWith<int>("i").EvaluateAsync().Result); Assert.Equal(4, script.ContinueWith<int>("j").EvaluateAsync().Result); Assert.Equal(4, script.ContinueWith<int>("k").EvaluateAsync().Result); Assert.Equal(4, script.ContinueWith<int>("l").EvaluateAsync().Result); Assert.Equal(16, script.ContinueWith<int>("pi").EvaluateAsync().Result); } [WorkItem(100639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/100639")] [Fact] public void ExternDestructor() { var script = CSharpScript.Create( @"class C { extern ~C(); }"); Assert.Null(script.EvaluateAsync().Result); } #endregion #region Chaining [Fact] public void CompilationChain_BasicFields() { var script = CSharpScript.Create("var x = 1;").ContinueWith("x"); Assert.Equal(1, script.EvaluateAsync().Result); } [Fact] public void CompilationChain_GlobalNamespaceAndUsings() { var result = CSharpScript.Create("using InteractiveFixtures.C;", ScriptOptions.Default.AddReferences(HostAssembly)). ContinueWith("using InteractiveFixtures.C;"). ContinueWith("System.Environment.ProcessorCount"). EvaluateAsync().Result; Assert.Equal(Environment.ProcessorCount, result); } [Fact] public void CompilationChain_CurrentSubmissionUsings() { var s0 = CSharpScript.RunAsync("", ScriptOptions.Default.AddReferences(HostAssembly)); var state = s0. ContinueWith("class X { public int goo() { return 1; } }"). ContinueWith("class X { public int goo() { return 1; } }"). ContinueWith("using InteractiveFixtures.A;"). ContinueWith("new X().goo()"); Assert.Equal(1, state.Result.ReturnValue); state = s0. ContinueWith("class X { public int goo() { return 1; } }"). ContinueWith(@" using InteractiveFixtures.A; new X().goo() "); Assert.Equal(1, state.Result.ReturnValue); } [Fact] public void CompilationChain_UsingDuplicates() { var script = CSharpScript.Create(@" using System; using System; ").ContinueWith(@" using System; using System; ").ContinueWith(@" Environment.ProcessorCount "); Assert.Equal(Environment.ProcessorCount, script.EvaluateAsync().Result); } [Fact] public void CompilationChain_GlobalImports() { var options = ScriptOptions.Default.AddImports("System"); var state = CSharpScript.RunAsync("Environment.ProcessorCount", options); Assert.Equal(Environment.ProcessorCount, state.Result.ReturnValue); state = state.ContinueWith("Environment.ProcessorCount"); Assert.Equal(Environment.ProcessorCount, state.Result.ReturnValue); } [Fact] public void CompilationChain_Accessibility() { // Submissions have internal and protected access to one another. var state1 = CSharpScript.RunAsync("internal class C1 { } protected int X; 1"); var compilation1 = state1.Result.Script.GetCompilation(); compilation1.VerifyDiagnostics( // (1,39): warning CS0628: 'X': new protected member declared in sealed type // internal class C1 { } protected int X; 1 Diagnostic(ErrorCode.WRN_ProtectedInSealed, "X").WithArguments("X").WithLocation(1, 39) ); Assert.Equal(1, state1.Result.ReturnValue); var state2 = state1.ContinueWith("internal class C2 : C1 { } 2"); var compilation2 = state2.Result.Script.GetCompilation(); compilation2.VerifyDiagnostics(); Assert.Equal(2, state2.Result.ReturnValue); var c2C2 = (INamedTypeSymbol)lookupMember(compilation2, "Submission#1", "C2"); var c2C1 = c2C2.BaseType; var c2X = lookupMember(compilation1, "Submission#0", "X"); Assert.True(compilation2.IsSymbolAccessibleWithin(c2C1, c2C2)); Assert.True(compilation2.IsSymbolAccessibleWithin(c2C2, c2C1)); Assert.True(compilation2.IsSymbolAccessibleWithin(c2X, c2C2)); // access not enforced among submission symbols var state3 = state2.ContinueWith("private class C3 : C2 { } 3"); var compilation3 = state3.Result.Script.GetCompilation(); compilation3.VerifyDiagnostics(); Assert.Equal(3, state3.Result.ReturnValue); var c3C3 = (INamedTypeSymbol)lookupMember(compilation3, "Submission#2", "C3"); var c3C1 = c3C3.BaseType; Assert.Throws<ArgumentException>(() => compilation2.IsSymbolAccessibleWithin(c3C3, c3C1)); Assert.True(compilation3.IsSymbolAccessibleWithin(c3C3, c3C1)); INamedTypeSymbol lookupType(Compilation c, string name) { return c.GlobalNamespace.GetMembers(name).Single() as INamedTypeSymbol; } ISymbol lookupMember(Compilation c, string typeName, string memberName) { return lookupType(c, typeName).GetMembers(memberName).Single(); } } [Fact] public void CompilationChain_SubmissionSlotResize() { var state = CSharpScript.RunAsync(""); for (int i = 0; i < 17; i++) { state = state.ContinueWith(@"public int i = 1;"); } ScriptingTestHelpers.ContinueRunScriptWithOutput(state, @"System.Console.WriteLine(i);", "1"); } [Fact] public void CompilationChain_UsingNotHidingPreviousSubmission() { int result1 = CSharpScript.Create("using System;"). ContinueWith("int Environment = 1;"). ContinueWith<int>("Environment"). EvaluateAsync().Result; Assert.Equal(1, result1); int result2 = CSharpScript.Create("int Environment = 1;"). ContinueWith("using System;"). ContinueWith<int>("Environment"). EvaluateAsync().Result; Assert.Equal(1, result2); } [Fact] public void CompilationChain_DefinitionHidesGlobal() { var result = CSharpScript.Create("int System = 1;"). ContinueWith("System"). EvaluateAsync().Result; Assert.Equal(1, result); } public class C1 { public readonly int System = 1; public readonly int Environment = 2; } /// <summary> /// Symbol declaration in host object model hides global definition. /// </summary> [Fact] public void CompilationChain_HostObjectMembersHidesGlobal() { var result = CSharpScript.RunAsync("System", globals: new C1()). Result.ReturnValue; Assert.Equal(1, result); } [Fact] public void CompilationChain_UsingNotHidingHostObjectMembers() { var result = CSharpScript.RunAsync("using System;", globals: new C1()). ContinueWith("Environment"). Result.ReturnValue; Assert.Equal(2, result); } [Fact] public void CompilationChain_DefinitionHidesHostObjectMembers() { var result = CSharpScript.RunAsync("int System = 2;", globals: new C1()). ContinueWith("System"). Result.ReturnValue; Assert.Equal(2, result); } [Fact] public void Submissions_ExecutionOrder1() { var s0 = CSharpScript.Create("int x = 1;"); var s1 = s0.ContinueWith("int y = 2;"); var s2 = s1.ContinueWith<int>("x + y"); Assert.Equal(3, s2.EvaluateAsync().Result); Assert.Null(s1.EvaluateAsync().Result); Assert.Null(s0.EvaluateAsync().Result); Assert.Equal(3, s2.EvaluateAsync().Result); Assert.Null(s1.EvaluateAsync().Result); Assert.Null(s0.EvaluateAsync().Result); Assert.Equal(3, s2.EvaluateAsync().Result); Assert.Equal(3, s2.EvaluateAsync().Result); } [Fact] public async Task Submissions_ExecutionOrder2() { var s0 = await CSharpScript.RunAsync("int x = 1;"); Assert.Throws<CompilationErrorException>(() => s0.ContinueWithAsync("invalid$syntax").Result); var s1 = await s0.ContinueWithAsync("x = 2; x = 10"); Assert.Throws<CompilationErrorException>(() => s1.ContinueWithAsync("invalid$syntax").Result); Assert.Throws<CompilationErrorException>(() => s1.ContinueWithAsync("x = undefined_symbol").Result); var s2 = await s1.ContinueWithAsync("int y = 2;"); Assert.Null(s2.ReturnValue); var s3 = await s2.ContinueWithAsync("x + y"); Assert.Equal(12, s3.ReturnValue); } public class HostObjectWithOverrides { public override bool Equals(object obj) => true; public override int GetHashCode() => 1234567; public override string ToString() => "HostObjectToString impl"; } [Fact] public async Task ObjectOverrides1() { var state0 = await CSharpScript.RunAsync("", globals: new HostObjectWithOverrides()); var state1 = await state0.ContinueWithAsync<bool>("Equals(null)"); Assert.True(state1.ReturnValue); var state2 = await state1.ContinueWithAsync<int>("GetHashCode()"); Assert.Equal(1234567, state2.ReturnValue); var state3 = await state2.ContinueWithAsync<string>("ToString()"); Assert.Equal("HostObjectToString impl", state3.ReturnValue); } [Fact] public async Task ObjectOverrides2() { var state0 = await CSharpScript.RunAsync("", globals: new object()); var state1 = await state0.ContinueWithAsync<bool>(@" object x = 1; object y = x; ReferenceEquals(x, y)"); Assert.True(state1.ReturnValue); var state2 = await state1.ContinueWithAsync<string>("ToString()"); Assert.Equal("System.Object", state2.ReturnValue); var state3 = await state2.ContinueWithAsync<bool>("Equals(null)"); Assert.False(state3.ReturnValue); } [Fact] public void ObjectOverrides3() { var state0 = CSharpScript.RunAsync(""); var src1 = @" Equals(null); GetHashCode(); ToString(); ReferenceEquals(null, null);"; ScriptingTestHelpers.AssertCompilationError(state0, src1, // (2,1): error CS0103: The name 'Equals' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "Equals").WithArguments("Equals"), // (3,1): error CS0103: The name 'GetHashCode' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "GetHashCode").WithArguments("GetHashCode"), // (4,1): error CS0103: The name 'ToString' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "ToString").WithArguments("ToString"), // (5,1): error CS0103: The name 'ReferenceEquals' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "ReferenceEquals").WithArguments("ReferenceEquals")); var src2 = @" public override string ToString() { return null; } "; ScriptingTestHelpers.AssertCompilationError(state0, src2, // (1,24): error CS0115: 'ToString()': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "ToString").WithArguments("ToString()")); } #endregion #region Generics [Fact, WorkItem(201759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/201759")] public void CompilationChain_GenericTypes() { var script = CSharpScript.Create(@" class InnerClass<T> { public int method(int value) { return value + 1; } public int field = 2; }").ContinueWith(@" InnerClass<int> iC = new InnerClass<int>(); ").ContinueWith(@" iC.method(iC.field) "); Assert.Equal(3, script.EvaluateAsync().Result); } [WorkItem(529243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529243")] [Fact] public void RecursiveBaseType() { CSharpScript.EvaluateAsync(@" class A<T> { } class B<T> : A<B<B<T>>> { } "); } [WorkItem(5378, "DevDiv_Projects/Roslyn")] [Fact] public void CompilationChain_GenericMethods() { var s0 = CSharpScript.Create(@" public int goo<T, R>(T arg) { return 1; } public static T bar<T>(T i) { return i; } "); Assert.Equal(1, s0.ContinueWith(@"goo<int, int>(1)").EvaluateAsync().Result); Assert.Equal(5, s0.ContinueWith(@"bar(5)").EvaluateAsync().Result); } /// <summary> /// Tests that we emit ldftn and ldvirtftn instructions correctly. /// </summary> [Fact] public void CompilationChain_Ldftn() { var state = CSharpScript.RunAsync(@" public class C { public static int f() { return 1; } public int g() { return 10; } public virtual int h() { return 100; } public static int gf<T>() { return 2; } public int gg<T>() { return 20; } public virtual int gh<T>() { return 200; } } "); state = state.ContinueWith(@" new System.Func<int>(C.f)() + new System.Func<int>(new C().g)() + new System.Func<int>(new C().h)()" ); Assert.Equal(111, state.Result.ReturnValue); state = state.ContinueWith(@" new System.Func<int>(C.gf<int>)() + new System.Func<int>(new C().gg<object>)() + new System.Func<int>(new C().gh<bool>)() "); Assert.Equal(222, state.Result.ReturnValue); } /// <summary> /// Tests that we emit ldftn and ldvirtftn instructions correctly. /// </summary> [Fact] public void CompilationChain_Ldftn_GenericType() { var state = CSharpScript.RunAsync(@" public class C<S> { public static int f() { return 1; } public int g() { return 10; } public virtual int h() { return 100; } public static int gf<T>() { return 2; } public int gg<T>() { return 20; } public virtual int gh<T>() { return 200; } } "); state = state.ContinueWith(@" new System.Func<int>(C<byte>.f)() + new System.Func<int>(new C<byte>().g)() + new System.Func<int>(new C<byte>().h)() "); Assert.Equal(111, state.Result.ReturnValue); state = state.ContinueWith(@" new System.Func<int>(C<byte>.gf<int>)() + new System.Func<int>(new C<byte>().gg<object>)() + new System.Func<int>(new C<byte>().gh<bool>)() "); Assert.Equal(222, state.Result.ReturnValue); } #endregion #region Statements and Expressions [Fact] public void IfStatement() { var result = CSharpScript.EvaluateAsync<int>(@" using static System.Console; int x; if (true) { x = 5; } else { x = 6; } x ").Result; Assert.Equal(5, result); } [Fact] public void ExprStmtParenthesesUsedToOverrideDefaultEval() { Assert.Equal(18, CSharpScript.EvaluateAsync<int>("(4 + 5) * 2").Result); Assert.Equal(1, CSharpScript.EvaluateAsync<long>("6 / (2 * 3)").Result); } [WorkItem(5397, "DevDiv_Projects/Roslyn")] [Fact] public void TopLevelLambda() { var s = CSharpScript.RunAsync(@" using System; delegate void TestDelegate(string s); "); s = s.ContinueWith(@" TestDelegate testDelB = delegate (string s) { Console.WriteLine(s); }; "); ScriptingTestHelpers.ContinueRunScriptWithOutput(s, @"testDelB(""hello"");", "hello"); } [Fact] public void Closure() { var f = CSharpScript.EvaluateAsync<Func<int, int>>(@" int Goo(int arg) { return arg + 1; } System.Func<int, int> f = (arg) => { return Goo(arg); }; f ").Result; Assert.Equal(3, f(2)); } [Fact] public void Closure2() { var result = CSharpScript.EvaluateAsync<List<string>>(@" #r ""System.Core"" using System; using System.Linq; using System.Collections.Generic; List<string> result = new List<string>(); string s = ""hello""; Enumerable.ToList(Enumerable.Range(1, 2)).ForEach(x => result.Add(s)); result ").Result; AssertEx.Equal(new[] { "hello", "hello" }, result); } [Fact] public void UseDelegateMixStaticAndDynamic() { var f = CSharpScript.RunAsync("using System;"). ContinueWith("int Sqr(int x) {return x*x;}"). ContinueWith<Func<int, int>>("new Func<int,int>(Sqr)").Result.ReturnValue; Assert.Equal(4, f(2)); } [WorkItem(9229, "DevDiv_Projects/Roslyn")] [Fact] public void Arrays() { var s = CSharpScript.RunAsync(@" int[] arr_1 = { 1, 2, 3 }; int[] arr_2 = new int[] { 1, 2, 3 }; int[] arr_3 = new int[5]; ").ContinueWith(@" arr_2[0] = 5; "); Assert.Equal(3, s.ContinueWith(@"arr_1[2]").Result.ReturnValue); Assert.Equal(5, s.ContinueWith(@"arr_2[0]").Result.ReturnValue); Assert.Equal(0, s.ContinueWith(@"arr_3[0]").Result.ReturnValue); } [Fact] public void FieldInitializers() { var result = CSharpScript.EvaluateAsync<List<int>>(@" using System.Collections.Generic; static List<int> result = new List<int>(); int b = 2; int a; int x = 1, y = b; static int g = 1; static int f = g + 1; a = x + y; result.Add(a); int z = 4 + f; result.Add(z); result.Add(a * z); result ").Result; Assert.Equal(3, result.Count); Assert.Equal(3, result[0]); Assert.Equal(6, result[1]); Assert.Equal(18, result[2]); } [Fact] public void FieldInitializersWithBlocks() { var result = CSharpScript.EvaluateAsync<List<int>>(@" using System.Collections.Generic; static List<int> result = new List<int>(); const int constant = 1; { int x = constant; result.Add(x); } int field = 2; { int x = field; result.Add(x); } result.Add(constant); result.Add(field); result ").Result; Assert.Equal(4, result.Count); Assert.Equal(1, result[0]); Assert.Equal(2, result[1]); Assert.Equal(1, result[2]); Assert.Equal(2, result[3]); } [Fact] public void TestInteractiveClosures() { var result = CSharpScript.RunAsync(@" using System.Collections.Generic; static List<int> result = new List<int>();"). ContinueWith("int x = 1;"). ContinueWith("System.Func<int> f = () => x++;"). ContinueWith("result.Add(f());"). ContinueWith("result.Add(x);"). ContinueWith<List<int>>("result").Result.ReturnValue; Assert.Equal(2, result.Count); Assert.Equal(1, result[0]); Assert.Equal(2, result[1]); } [Fact] public void ExtensionMethods() { var options = ScriptOptions.Default.AddReferences( typeof(Enumerable).GetTypeInfo().Assembly); var result = CSharpScript.EvaluateAsync<int>(@" using System.Linq; string[] fruit = { ""banana"", ""orange"", ""lime"", ""apple"", ""kiwi"" }; fruit.Skip(1).Where(s => s.Length > 4).Count()", options).Result; Assert.Equal(2, result); } [Fact] public void ImplicitlyTypedFields() { var result = CSharpScript.EvaluateAsync<object[]>(@" var x = 1; var y = x; var z = goo(x); string goo(int a) { return null; } int goo(string a) { return 0; } new object[] { x, y, z } ").Result; AssertEx.Equal(new object[] { 1, 1, null }, result); } /// <summary> /// Name of PrivateImplementationDetails type needs to be unique across submissions. /// The compiler should suffix it with a MVID of the current submission module so we should be fine. /// </summary> [WorkItem(949559, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/949559")] [WorkItem(540237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540237")] [WorkItem(9229, "DevDiv_Projects/Roslyn")] [WorkItem(2721, "https://github.com/dotnet/roslyn/issues/2721")] [Fact] public async Task PrivateImplementationDetailsType() { var result1 = await CSharpScript.EvaluateAsync<int[]>("new int[] { 1,2,3,4 }"); AssertEx.Equal(new[] { 1, 2, 3, 4 }, result1); var result2 = await CSharpScript.EvaluateAsync<int[]>("new int[] { 1,2,3,4,5 }"); AssertEx.Equal(new[] { 1, 2, 3, 4, 5 }, result2); var s1 = await CSharpScript.RunAsync<int[]>("new int[] { 1,2,3,4,5,6 }"); AssertEx.Equal(new[] { 1, 2, 3, 4, 5, 6 }, s1.ReturnValue); var s2 = await s1.ContinueWithAsync<int[]>("new int[] { 1,2,3,4,5,6,7 }"); AssertEx.Equal(new[] { 1, 2, 3, 4, 5, 6, 7 }, s2.ReturnValue); var s3 = await s2.ContinueWithAsync<int[]>("new int[] { 1,2,3,4,5,6,7,8 }"); AssertEx.Equal(new[] { 1, 2, 3, 4, 5, 6, 7, 8 }, s3.ReturnValue); } [Fact] public void NoAwait() { // No await. The return value is Task<int> rather than int. var result = CSharpScript.EvaluateAsync("System.Threading.Tasks.Task.FromResult(1)").Result; Assert.Equal(1, ((Task<int>)result).Result); } /// <summary> /// 'await' expression at top-level. /// </summary> [Fact] public void Await() { Assert.Equal(2, CSharpScript.EvaluateAsync("await System.Threading.Tasks.Task.FromResult(2)").Result); } /// <summary> /// 'await' in sub-expression. /// </summary> [Fact] public void AwaitSubExpression() { Assert.Equal(3, CSharpScript.EvaluateAsync<int>("0 + await System.Threading.Tasks.Task.FromResult(3)").Result); } [Fact] public void AwaitVoid() { var task = CSharpScript.EvaluateAsync<object>("await System.Threading.Tasks.Task.Run(() => { })"); Assert.Null(task.Result); Assert.Equal(TaskStatus.RanToCompletion, task.Status); } /// <summary> /// 'await' in lambda should be ignored. /// </summary> [Fact] public async Task AwaitInLambda() { var s0 = await CSharpScript.RunAsync(@" using System; using System.Threading.Tasks; static T F<T>(Func<Task<T>> f) { return f().Result; } static T G<T>(T t, Func<T, Task<T>> f) { return f(t).Result; }"); var s1 = await s0.ContinueWithAsync("F(async () => await Task.FromResult(4))"); Assert.Equal(4, s1.ReturnValue); var s2 = await s1.ContinueWithAsync("G(5, async x => await Task.FromResult(x))"); Assert.Equal(5, s2.ReturnValue); } [Fact] public void AwaitChain1() { var options = ScriptOptions.Default. AddReferences(typeof(Task).GetTypeInfo().Assembly). AddImports("System.Threading.Tasks"); var state = CSharpScript.RunAsync("int i = 0;", options). ContinueWith("await Task.Delay(1); i++;"). ContinueWith("await Task.Delay(1); i++;"). ContinueWith("await Task.Delay(1); i++;"). ContinueWith("i"). Result; Assert.Equal(3, state.ReturnValue); } [Fact] public void AwaitChain2() { var options = ScriptOptions.Default. AddReferences(typeof(Task).GetTypeInfo().Assembly). AddImports("System.Threading.Tasks"); var state = CSharpScript.Create("int i = 0;", options). ContinueWith("await Task.Delay(1); i++;"). ContinueWith("await Task.Delay(1); i++;"). RunAsync(). ContinueWith("await Task.Delay(1); i++;"). ContinueWith("i"). Result; Assert.Equal(3, state.ReturnValue); } [Fact, WorkItem(39548, "https://github.com/dotnet/roslyn/issues/39548")] public async Task PatternVariableDeclaration() { var state = await CSharpScript.RunAsync("var x = (false, 4);"); state = await state.ContinueWithAsync("x is (false, var y)"); Assert.Equal(true, state.ReturnValue); } [Fact, WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] public async Task CSharp9PatternForms() { var options = ScriptOptions.Default.WithLanguageVersion(MessageID.IDS_FeatureAndPattern.RequiredVersion()); var state = await CSharpScript.RunAsync("object x = 1;", options: options); state = await state.ContinueWithAsync("x is long or int", options: options); Assert.Equal(true, state.ReturnValue); state = await state.ContinueWithAsync("x is int and < 10", options: options); Assert.Equal(true, state.ReturnValue); state = await state.ContinueWithAsync("x is (long or < 10L)", options: options); Assert.Equal(false, state.ReturnValue); state = await state.ContinueWithAsync("x is not > 100", options: options); Assert.Equal(true, state.ReturnValue); } #endregion #region References [Fact(Skip = "https://github.com/dotnet/roslyn/issues/53391")] [WorkItem(15860, "https://github.com/dotnet/roslyn/issues/53391")] public void ReferenceDirective_FileWithDependencies() { var file1 = Temp.CreateFile(); var file2 = Temp.CreateFile(); var lib1 = CreateCSharpCompilationWithCorlib(@" public interface I { int F(); }"); lib1.Emit(file1.Path); var lib2 = CreateCSharpCompilation(@" public class C : I { public int F() => 1; }", new MetadataReference[] { NetStandard13.SystemRuntime, lib1.ToMetadataReference() }); lib2.Emit(file2.Path); object result = CSharpScript.EvaluateAsync($@" #r ""{file1.Path}"" #r ""{file2.Path}"" new C() ").Result; Assert.NotNull(result); } [ConditionalFact(typeof(WindowsOnly)), WorkItem(15860, "https://github.com/dotnet/roslyn/issues/15860")] public void ReferenceDirective_RelativeToBaseParent() { var file = Temp.CreateFile(); var lib = CreateCSharpCompilationWithCorlib("public class C {}"); lib.Emit(file.Path); string dir = Path.Combine(Path.GetDirectoryName(file.Path), "subdir"); string libFileName = Path.GetFileName(file.Path); string scriptPath = Path.Combine(dir, "a.csx"); var script = CSharpScript.Create( $@"#r ""{Path.Combine("..", libFileName)}""", ScriptOptions.Default.WithFilePath(scriptPath)); script.GetCompilation().VerifyDiagnostics(); } [ConditionalFact(typeof(WindowsOnly)), WorkItem(15860, "https://github.com/dotnet/roslyn/issues/15860")] public void ReferenceDirective_RelativeToBaseRoot() { var file = Temp.CreateFile(); var lib = CreateCSharpCompilationWithCorlib("public class C {}"); lib.Emit(file.Path); string root = Path.GetPathRoot(file.Path); string unrooted = file.Path.Substring(root.Length); string dir = Path.Combine(root, "goo", "bar", "baz"); string scriptPath = Path.Combine(dir, "a.csx"); var script = CSharpScript.Create( $@"#r ""\{unrooted}""", ScriptOptions.Default.WithFilePath(scriptPath)); script.GetCompilation().VerifyDiagnostics(); } [Fact] public void ExtensionPriority1() { string mainName = "Main_" + Guid.NewGuid(); string libName = "Lib_" + Guid.NewGuid(); var libExe = CreateCSharpCompilationWithCorlib(@"public class C { public string F = ""exe""; }", libName); var libDll = CreateCSharpCompilationWithCorlib(@"public class C { public string F = ""dll""; }", libName); var libWinmd = CreateCSharpCompilationWithCorlib(@"public class C { public string F = ""winmd""; }", libName); var main = CreateCSharpCompilation( @"public static class M { public static readonly C X = new C(); }", new MetadataReference[] { NetStandard13.SystemRuntime, libExe.ToMetadataReference() }, mainName); var exeImage = libExe.EmitToArray(); var dllImage = libDll.EmitToArray(); var winmdImage = libWinmd.EmitToArray(); var mainImage = main.EmitToArray(); var dir = Temp.CreateDirectory(); var fileMain = dir.CreateFile(mainName + ".dll").WriteAllBytes(mainImage); dir.CreateFile(libName + ".exe").WriteAllBytes(exeImage); dir.CreateFile(libName + ".winmd").WriteAllBytes(winmdImage); var r2 = CSharpScript.Create($@"#r ""{fileMain.Path}""").ContinueWith($@"M.X.F").RunAsync().Result.ReturnValue; Assert.Equal("exe", r2); } [Fact] public void ExtensionPriority2() { string mainName = "Main_" + Guid.NewGuid(); string libName = "Lib_" + Guid.NewGuid(); var libExe = CreateCSharpCompilationWithCorlib(@"public class C { public string F = ""exe""; }", libName); var libDll = CreateCSharpCompilationWithCorlib(@"public class C { public string F = ""dll""; }", libName); var libWinmd = CreateCSharpCompilationWithCorlib(@"public class C { public string F = ""winmd""; }", libName); var main = CreateCSharpCompilation( @"public static class M { public static readonly C X = new C(); }", new MetadataReference[] { NetStandard13.SystemRuntime, libExe.ToMetadataReference() }, mainName); var exeImage = libExe.EmitToArray(); var dllImage = libDll.EmitToArray(); var winmdImage = libWinmd.EmitToArray(); var mainImage = main.EmitToArray(); var dir = Temp.CreateDirectory(); var fileMain = dir.CreateFile(mainName + ".dll").WriteAllBytes(mainImage); dir.CreateFile(libName + ".exe").WriteAllBytes(exeImage); dir.CreateFile(libName + ".dll").WriteAllBytes(dllImage); dir.CreateFile(libName + ".winmd").WriteAllBytes(winmdImage); var r2 = CSharpScript.Create($@"#r ""{fileMain.Path}""").ContinueWith($@"M.X.F").RunAsync().Result.ReturnValue; Assert.Equal("dll", r2); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/6015")] public void UsingExternalAliasesForHiding() { string source = @" namespace N { public class C { } } public class D { } public class E { } "; var libRef = CreateCSharpCompilationWithCorlib(source, "lib").EmitToImageReference(); var script = CSharpScript.Create(@"new C()", ScriptOptions.Default.WithReferences(libRef.WithAliases(new[] { "Hidden" })).WithImports("Hidden::N")); script.Compile().Verify(); } #endregion #region UsingDeclarations [Fact] public void UsingAlias() { object result = CSharpScript.EvaluateAsync(@" using D = System.Collections.Generic.Dictionary<string, int>; D d = new D(); d ").Result; Assert.True(result is Dictionary<string, int>, "Expected Dictionary<string, int>"); } [WorkItem(9229, "DevDiv_Projects/Roslyn")] [Fact] public void Usings1() { var options = ScriptOptions.Default. AddImports("System", "System.Linq"). AddReferences(typeof(Enumerable).GetTypeInfo().Assembly); object result = CSharpScript.EvaluateAsync("new int[] { 1, 2, 3 }.First()", options).Result; Assert.Equal(1, result); } [WorkItem(9229, "DevDiv_Projects/Roslyn")] [Fact] public void Usings2() { var options = ScriptOptions.Default. AddImports("System", "System.Linq"). AddReferences(typeof(Enumerable).GetTypeInfo().Assembly); var s1 = CSharpScript.RunAsync("new int[] { 1, 2, 3 }.First()", options); Assert.Equal(1, s1.Result.ReturnValue); var s2 = s1.ContinueWith("new List<int>()", options.AddImports("System.Collections.Generic")); Assert.IsType<List<int>>(s2.Result.ReturnValue); } [Fact] public void AddNamespaces_Errors() { // no immediate error, error is reported if the namespace can't be found when compiling: var options = ScriptOptions.Default.AddImports("?1", "?2"); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("1", options), // error CS0246: The type or namespace name '?1' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound).WithArguments("?1"), // error CS0246: The type or namespace name '?2' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound).WithArguments("?2")); options = ScriptOptions.Default.AddImports(""); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("1", options), // error CS7088: Invalid 'Usings' value: ''. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "")); options = ScriptOptions.Default.AddImports(".abc"); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("1", options), // error CS7088: Invalid 'Usings' value: '.abc'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", ".abc")); options = ScriptOptions.Default.AddImports("a\0bc"); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("1", options), // error CS7088: Invalid 'Usings' value: '.abc'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "a\0bc")); } #endregion #region Host Object Binding and Conversions public class C<T> { } [Fact] public void Submission_HostConversions() { Assert.Equal(2, CSharpScript.EvaluateAsync<int>("1+1").Result); Assert.Null(CSharpScript.EvaluateAsync<string>("null").Result); try { CSharpScript.RunAsync<C<int>>("null"); Assert.True(false, "Expected an exception"); } catch (CompilationErrorException e) { // error CS0400: The type or namespace name 'Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Source.InteractiveSessionTests+C`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], Roslyn.Compilers.CSharp.Emit.UnitTests, Version=42.42.42.42, Culture=neutral, PublicKeyToken=fc793a00266884fb' could not be found in the global namespace (are you missing an assembly reference?) Assert.Equal(ErrorCode.ERR_GlobalSingleTypeNameNotFound, (ErrorCode)e.Diagnostics.Single().Code); // Can't use Verify() because the version number of the test dll is different in the build lab. } var options = ScriptOptions.Default.AddReferences(HostAssembly); var cint = CSharpScript.EvaluateAsync<C<int>>("null", options).Result; Assert.Null(cint); Assert.Null(CSharpScript.EvaluateAsync<int?>("null", options).Result); try { CSharpScript.RunAsync<int>("null"); Assert.True(false, "Expected an exception"); } catch (CompilationErrorException e) { e.Diagnostics.Verify( // (1,1): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // null Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int")); } try { CSharpScript.RunAsync<string>("1+1"); Assert.True(false, "Expected an exception"); } catch (CompilationErrorException e) { e.Diagnostics.Verify( // (1,1): error CS0029: Cannot implicitly convert type 'int' to 'string' // 1+1 Diagnostic(ErrorCode.ERR_NoImplicitConv, "1+1").WithArguments("int", "string")); } } [Fact] public void Submission_HostVarianceConversions() { var value = CSharpScript.EvaluateAsync<IEnumerable<Exception>>(@" using System; using System.Collections.Generic; new List<ArgumentException>() ").Result; Assert.Null(value.FirstOrDefault()); } public class B { public int x = 1, w = 4; } public class C : B, I { public static readonly int StaticField = 123; public int Y => 2; public string N { get; set; } = "2"; public int Z() => 3; public override int GetHashCode() => 123; } public interface I { string N { get; set; } int Z(); } private class PrivateClass : I { public string N { get; set; } = null; public int Z() => 3; } public class M<T> { private int F() => 3; public T G() => default(T); } [Fact] public void HostObjectBinding_PublicClassMembers() { var c = new C(); var s0 = CSharpScript.RunAsync<int>("x + Y + Z()", globals: c); Assert.Equal(6, s0.Result.ReturnValue); var s1 = s0.ContinueWith<int>("x"); Assert.Equal(1, s1.Result.ReturnValue); var s2 = s1.ContinueWith<int>("int x = 20;"); var s3 = s2.ContinueWith<int>("x"); Assert.Equal(20, s3.Result.ReturnValue); } [Fact] public void HostObjectBinding_PublicGenericClassMembers() { var m = new M<string>(); var result = CSharpScript.EvaluateAsync<string>("G()", globals: m); Assert.Null(result.Result); } [Fact] public async Task HostObjectBinding_Interface() { var c = new C(); var s0 = await CSharpScript.RunAsync<int>("Z()", globals: c, globalsType: typeof(I)); Assert.Equal(3, s0.ReturnValue); ScriptingTestHelpers.AssertCompilationError(s0, @"x + Y", // The name '{0}' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x"), Diagnostic(ErrorCode.ERR_NameNotInContext, "Y").WithArguments("Y")); var s1 = await s0.ContinueWithAsync<string>("N"); Assert.Equal("2", s1.ReturnValue); } [Fact] public void HostObjectBinding_PrivateClass() { var c = new PrivateClass(); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("Z()", globals: c), // (1,1): error CS0122: '<Fully Qualified Name of PrivateClass>.Z()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "Z").WithArguments(typeof(PrivateClass).FullName.Replace("+", ".") + ".Z()")); } [Fact] public void HostObjectBinding_PrivateMembers() { object c = new M<int>(); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("Z()", globals: c), // (1,1): error CS0103: The name 'z' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "Z").WithArguments("Z")); } [Fact] public void HostObjectBinding_PrivateClassImplementingPublicInterface() { var c = new PrivateClass(); var result = CSharpScript.EvaluateAsync<int>("Z()", globals: c, globalsType: typeof(I)); Assert.Equal(3, result.Result); } [Fact] public void HostObjectBinding_StaticMembers() { var s0 = CSharpScript.RunAsync("static int goo = StaticField;", globals: new C()); var s1 = s0.ContinueWith("static int bar { get { return goo; } }"); var s2 = s1.ContinueWith("class C { public static int baz() { return bar; } }"); var s3 = s2.ContinueWith("C.baz()"); Assert.Equal(123, s3.Result.ReturnValue); } public class D { public int goo(int a) { return 0; } } /// <summary> /// Host object members don't form a method group with submission members. /// </summary> [Fact] public void HostObjectBinding_Overloads() { var s0 = CSharpScript.RunAsync("int goo(double a) { return 2; }", globals: new D()); var s1 = s0.ContinueWith("goo(1)"); Assert.Equal(2, s1.Result.ReturnValue); var s2 = s1.ContinueWith("goo(1.0)"); Assert.Equal(2, s2.Result.ReturnValue); } [Fact] public void HostObjectInRootNamespace() { var obj = new InteractiveFixtures_TopLevelHostObject { X = 1, Y = 2, Z = 3 }; var r0 = CSharpScript.EvaluateAsync<int>("X + Y + Z", globals: obj); Assert.Equal(6, r0.Result); obj = new InteractiveFixtures_TopLevelHostObject { X = 1, Y = 2, Z = 3 }; var r1 = CSharpScript.EvaluateAsync<int>("X", globals: obj); Assert.Equal(1, r1.Result); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30303")] public void HostObjectAssemblyReference1() { var scriptCompilation = CSharpScript.Create( "nameof(Microsoft.CodeAnalysis.Scripting)", ScriptOptions.Default.WithMetadataResolver(TestRuntimeMetadataReferenceResolver.Instance), globalsType: typeof(CommandLineScriptGlobals)).GetCompilation(); scriptCompilation.VerifyDiagnostics( // (1,8): error CS0234: The type or namespace name 'CodeAnalysis' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?) // nameof(Microsoft.CodeAnalysis.Scripting) Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "Microsoft.CodeAnalysis").WithArguments("CodeAnalysis", "Microsoft").WithLocation(1, 8)); string corAssemblyName = typeof(object).GetTypeInfo().Assembly.GetName().Name; string hostObjectAssemblyName = scriptCompilation.ScriptCompilationInfo.GlobalsType.GetTypeInfo().Assembly.GetName().Name; // The host adds // 1) a reference to typeof(object).Assembly // 2) a reference to GlobalsType with alias <host> applied recursively. // References returned from ResolveMissingAssembly have <implicit> alias. foreach (var (assembly, aliases) in scriptCompilation.GetBoundReferenceManager().GetReferencedAssemblyAliases()) { string name = assembly.Identity.Name; switch (name) { case "Microsoft.CodeAnalysis.CSharp.Scripting": case "Microsoft.CodeAnalysis.CSharp": // assemblies not referenced Assert.False(true); break; case "Microsoft.CodeAnalysis": case "System.Collections.Immutable": // Microsoft.CodeAnalysis.Scripting contains host object and is thus referenced recursively with <host> alias. // The script doesn't reference the assemblies explicitly. AssertEx.SetEqual(new[] { "<implicit>", "<host>" }, aliases); break; default: if (name == corAssemblyName) { // Host object depends on System.Object, thus <host> is applied on CorLib. AssertEx.SetEqual(new[] { "<host>", "global" }, aliases); } else if (name == hostObjectAssemblyName) { // Host object is only referenced by the host and thus the assembly is hidden behind <host> alias. AssertEx.SetEqual(new[] { "<host>" }, aliases); } break; } } } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/dotnet/roslyn/issues/30303")] public void HostObjectAssemblyReference2() { var scriptCompilation = CSharpScript.Create( "typeof(Microsoft.CodeAnalysis.Scripting.Script)", options: ScriptOptions.Default. WithMetadataResolver(TestRuntimeMetadataReferenceResolver.Instance). WithReferences(typeof(CSharpScript).GetTypeInfo().Assembly), globalsType: typeof(CommandLineScriptGlobals)).GetCompilation(); scriptCompilation.VerifyDiagnostics(); string corAssemblyName = typeof(object).GetTypeInfo().Assembly.GetName().Name; string hostObjectAssemblyName = scriptCompilation.ScriptCompilationInfo.GlobalsType.GetTypeInfo().Assembly.GetName().Name; // The host adds // 1) a reference to typeof(object).Assembly // 2) a reference to GlobalsType with alias <host> applied recursively. // References returned from ResolveMissingAssembly have <implicit> alias. foreach (var (assembly, aliases) in scriptCompilation.GetBoundReferenceManager().GetReferencedAssemblyAliases()) { string name = assembly.Identity.Name; switch (name) { case "Microsoft.CodeAnalysis.CSharp.Scripting": // we have an explicit reference to CSharpScript assembly: AssertEx.SetEqual(Array.Empty<string>(), aliases); break; case "Microsoft.CodeAnalysis.CSharp": // The script has a recursive reference to Microsoft.CodeAnalysis.CSharp.Scripting, which references these assemblies. // The script doesn't reference the assembly explicitly. AssertEx.SetEqual(new[] { "<implicit>", "global" }, aliases); break; case "Microsoft.CodeAnalysis": case "System.Collections.Immutable": // The script has a recursive reference to Microsoft.CodeAnalysis.CSharp.Scripting, which references these assemblies. // Microsoft.CodeAnalysis.Scripting contains host object and is thus referenced recursively with <host> alias. // The script doesn't reference the assemblies explicitly. AssertEx.SetEqual(new[] { "<implicit>", "<host>", "global" }, aliases); break; default: if (name == corAssemblyName) { // Host object depends on System.Object, thus <host> is applied on CorLib. AssertEx.SetEqual(new[] { "<host>", "global" }, aliases); } else if (name == hostObjectAssemblyName) { // Host object is defined in an assembly that CSharpScript depends on. // CSharpScript assembly was references (recursively) hence host object assembly is // available to the script (global alias). AssertEx.SetEqual(new[] { "<host>", "global" }, aliases); } break; } } } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/dotnet/roslyn/issues/30303")] public void HostObjectAssemblyReference3() { string source = $@" #r ""{typeof(CSharpScript).GetTypeInfo().Assembly.ManifestModule.FullyQualifiedName}"" typeof(Microsoft.CodeAnalysis.Scripting.Script) "; var scriptCompilation = CSharpScript.Create( source, ScriptOptions.Default.WithMetadataResolver(TestRuntimeMetadataReferenceResolver.Instance), globalsType: typeof(CommandLineScriptGlobals)).GetCompilation(); scriptCompilation.VerifyDiagnostics(); string corAssemblyName = typeof(object).GetTypeInfo().Assembly.GetName().Name; string hostObjectAssemblyName = scriptCompilation.ScriptCompilationInfo.GlobalsType.GetTypeInfo().Assembly.GetName().Name; // The host adds // 1) a reference to typeof(object).Assembly // 2) a reference to GlobalsType with alias <host> applied recursively. // References returned from ResolveMissingAssembly have <implicit> alias. foreach (var (assembly, aliases) in scriptCompilation.GetBoundReferenceManager().GetReferencedAssemblyAliases()) { string name = assembly.Identity.Name; switch (name) { case "Microsoft.CodeAnalysis.CSharp.Scripting": // we have an explicit reference to CSharpScript assembly: AssertEx.SetEqual(Array.Empty<string>(), aliases); break; case "Microsoft.CodeAnalysis.CSharp": // The script has a recursive reference to Microsoft.CodeAnalysis.CSharp.Scripting, which references these assemblies. // The script doesn't reference the assembly explicitly. AssertEx.SetEqual(new[] { "<implicit>", "global" }, aliases); break; case "Microsoft.CodeAnalysis": case "System.Collections.Immutable": // The script has a recursive reference to Microsoft.CodeAnalysis.CSharp.Scripting, which references these assemblies. // Microsoft.CodeAnalysis.Scripting contains host object and is thus referenced recursively with <host> alias. // The script doesn't reference the assemblies explicitly. AssertEx.SetEqual(new[] { "<implicit>", "<host>", "global" }, aliases); break; default: if (name == corAssemblyName) { // Host object depends on System.Object, thus <host> is applied on CorLib. AssertEx.SetEqual(new[] { "<host>", "global" }, aliases); } else if (name == hostObjectAssemblyName) { // Host object is defined in an assembly that CSharpScript depends on. // CSharpScript assembly was references (recursively) hence host object assembly is // available to the script (global alias). AssertEx.SetEqual(new[] { "<host>", "global" }, aliases); } break; } } } public class E { public bool TryGetValue(out object obj) { obj = new object(); return true; } } [Fact] [WorkItem(39565, "https://github.com/dotnet/roslyn/issues/39565")] public async Task MethodCallWithImplicitReceiverAndOutVar() { var code = @" if(TryGetValue(out var result)){ _ = result; } return true; "; var result = await CSharpScript.EvaluateAsync<bool>(code, globalsType: typeof(E), globals: new E()); Assert.True(result); } public class F { public bool Value = true; } [Fact] public void StaticMethodCannotAccessGlobalInstance() { var code = @" static bool M() { return Value; } return M(); "; var script = CSharpScript.Create<bool>(code, globalsType: typeof(F)); ScriptingTestHelpers.AssertCompilationError(() => script.RunAsync(new F()).Wait(), // (4,9): error CS0120: An object reference is required for the non-static field, method, or property 'InteractiveSessionTests.F.Value' // return Value; Diagnostic(ErrorCode.ERR_ObjectRequired, "Value").WithArguments("Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests.InteractiveSessionTests.F.Value").WithLocation(4, 9)); } [Fact] [WorkItem(39581, "https://github.com/dotnet/roslyn/issues/39581")] public void StaticLocalFunctionCannotAccessGlobalInstance() { var code = @" bool M() { return Inner(); static bool Inner() { return Value; } } return M(); "; var script = CSharpScript.Create<bool>(code, globalsType: typeof(F)); ScriptingTestHelpers.AssertCompilationError(() => script.RunAsync(new F()).Wait(), // (7,10): error CS0120: An object reference is required for the non-static field, method, or property 'InteractiveSessionTests.F.Value' // return Value; Diagnostic(ErrorCode.ERR_ObjectRequired, "Value").WithArguments("Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests.InteractiveSessionTests.F.Value").WithLocation(7, 10)); } [Fact] public async Task LocalFunctionCanAccessGlobalInstance() { var code = @" bool M() { return Inner(); bool Inner() { return Value; } } return M(); "; var result = await CSharpScript.EvaluateAsync<bool>(code, globalsType: typeof(F), globals: new F()); Assert.True(result); } #endregion #region Exceptions [Fact] [WorkItem(6580, "https://github.com/dotnet/roslyn/issues/6580")] [WorkItem(10883, "https://github.com/dotnet/roslyn/issues/10883")] public async Task PreservingDeclarationsOnException1() { var s0 = CSharpScript.Create(@" int i = 10; throw new System.Exception(""Bang!""); int j = 2; "); var s1 = s0.ContinueWith(@" int F() => i + j; "); var state1 = await s1.RunAsync(catchException: e => true); Assert.Equal("Bang!", state1.Exception.Message); var state2 = await state1.ContinueWithAsync<int>("F()"); Assert.Equal(10, state2.ReturnValue); } [Fact] [WorkItem(6580, "https://github.com/dotnet/roslyn/issues/6580")] [WorkItem(10883, "https://github.com/dotnet/roslyn/issues/10883")] public async Task PreservingDeclarationsOnException2() { var s0 = CSharpScript.Create(@" int i = 100; "); var s1 = s0.ContinueWith(@" int j = 20; throw new System.Exception(""Bang!""); int k = 3; "); var s2 = s1.ContinueWith(@" int F() => i + j + k; "); var state2 = await s2.RunAsync(catchException: e => true); Assert.Equal("Bang!", state2.Exception.Message); var state3 = await state2.ContinueWithAsync<int>("F()"); Assert.Equal(120, state3.ReturnValue); } [Fact] [WorkItem(6580, "https://github.com/dotnet/roslyn/issues/6580")] [WorkItem(10883, "https://github.com/dotnet/roslyn/issues/10883")] public async Task PreservingDeclarationsOnException3() { var s0 = CSharpScript.Create(@" int i = 1000; "); var s1 = s0.ContinueWith(@" int j = 200; throw new System.Exception(""Bang!""); int k = 30; "); var s2 = s1.ContinueWith(@" int l = 4; "); var s3 = s2.ContinueWith(@" int F() => i + j + k + l; "); var state3 = await s3.RunAsync(catchException: e => true); Assert.Equal("Bang!", state3.Exception.Message); var state4 = await state3.ContinueWithAsync<int>("F()"); Assert.Equal(1200, state4.ReturnValue); } [Fact] [WorkItem(6580, "https://github.com/dotnet/roslyn/issues/6580")] [WorkItem(10883, "https://github.com/dotnet/roslyn/issues/10883")] public async Task PreservingDeclarationsOnException4() { var state0 = await CSharpScript.RunAsync(@" int i = 1000; "); var state1 = await state0.ContinueWithAsync(@" int j = 200; throw new System.Exception(""Bang 1!""); int k = 30; ", catchException: e => true); Assert.Equal("Bang 1!", state1.Exception.Message); var state2 = await state1.ContinueWithAsync<int>(@" int l = 4; throw new System.Exception(""Bang 2!""); 1 ", catchException: e => true); Assert.Equal("Bang 2!", state2.Exception.Message); var state4 = await state2.ContinueWithAsync(@" i + j + k + l "); Assert.Equal(1204, state4.ReturnValue); } [Fact] public async Task PreservingDeclarationsOnCancellation1() { var cancellationSource = new CancellationTokenSource(); var globals = new StrongBox<CancellationTokenSource>(); globals.Value = cancellationSource; var s0 = CSharpScript.Create(@" int i = 1000; ", globalsType: globals.GetType()); var s1 = s0.ContinueWith(@" int j = 200; Value.Cancel(); int k = 30; "); // cancellation exception is thrown just before we start evaluating s2: var s2 = s1.ContinueWith(@" int l = 4; "); var s3 = s2.ContinueWith(@" int F() => i + j + k + l; "); var state3 = await s3.RunAsync(globals, catchException: e => true, cancellationToken: cancellationSource.Token); Assert.IsType<OperationCanceledException>(state3.Exception); var state4 = await state3.ContinueWithAsync<int>("F()"); Assert.Equal(1230, state4.ReturnValue); } [Fact] public async Task PreservingDeclarationsOnCancellation2() { var cancellationSource = new CancellationTokenSource(); var globals = new StrongBox<CancellationTokenSource>(); globals.Value = cancellationSource; var s0 = CSharpScript.Create(@" int i = 1000; ", globalsType: globals.GetType()); var s1 = s0.ContinueWith(@" int j = 200; int k = 30; "); var s2 = s1.ContinueWith(@" int l = 4; Value.Cancel(); "); // cancellation exception is thrown just before we start evaluating s3: var s3 = s2.ContinueWith(@" int F() => i + j + k + l; "); var state3 = await s3.RunAsync(globals, catchException: e => true, cancellationToken: cancellationSource.Token); Assert.IsType<OperationCanceledException>(state3.Exception); var state4 = await state3.ContinueWithAsync<int>("F()"); Assert.Equal(1234, state4.ReturnValue); } [Fact] public async Task PreservingDeclarationsOnCancellation3() { var cancellationSource = new CancellationTokenSource(); var globals = new StrongBox<CancellationTokenSource>(); globals.Value = cancellationSource; var s0 = CSharpScript.Create(@" int i = 1000; ", globalsType: globals.GetType()); var s1 = s0.ContinueWith(@" int j = 200; Value.Cancel(); int k = 30; "); // cancellation exception is thrown just before we start evaluating s2: var s2 = s1.ContinueWith(@" int l = 4; "); var s3 = s2.ContinueWith(@" int F() => i + j + k + l; "); await Assert.ThrowsAsync<OperationCanceledException>(() => s3.RunAsync(globals, catchException: e => !(e is OperationCanceledException), cancellationToken: cancellationSource.Token)); } #endregion #region Local Functions [Fact] public void LocalFunction_PreviousSubmissionAndGlobal() { var result = CSharpScript.RunAsync( @"int InInitialSubmission() { return LocalFunction(); int LocalFunction() => Y; }", globals: new C()). ContinueWith( @"var lambda = new System.Func<int>(() => { return LocalFunction(); int LocalFunction() => Y + InInitialSubmission(); }); lambda.Invoke()"). Result.ReturnValue; Assert.Equal(4, result); } #endregion } }
1
dotnet/roslyn
56,223
Rework our netstandard1.3 test references
The `netstandard1.3` test references were being provided by our MS.CA.Test.Resources.Proprietary package. The contents of this package get included in the output directory of every single unit test DLL that we build (which contributes to build output size). The references themselves though were only used in a very small number of tests. This change upgrades to a version of MS.CA.Test.Resources.Proprietary that has the `netstandard1.3` references removed and adds the `netstandard1.3` references to only the projects that needs them
jaredpar
"2021-09-07T20:35:04Z"
"2021-09-07T23:50:57Z"
0240973369997c88a2c2f1aaa22c14182ac17e9f
5dbd783367d7f6b105726b84558cc1809aa198ce
Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our MS.CA.Test.Resources.Proprietary package. The contents of this package get included in the output directory of every single unit test DLL that we build (which contributes to build output size). The references themselves though were only used in a very small number of tests. This change upgrades to a version of MS.CA.Test.Resources.Proprietary that has the `netstandard1.3` references removed and adds the `netstandard1.3` references to only the projects that needs them
./src/Scripting/CoreTestUtilities/Microsoft.CodeAnalysis.Scripting.TestUtilities.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> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <TargetFramework>netstandard2.0</TargetFramework> <NoStdLib>true</NoStdLib> <IsShipping>false</IsShipping> <ExcludeFromSourceBuild>true</ExcludeFromSourceBuild> </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\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\Core\Microsoft.CodeAnalysis.Scripting.csproj" /> <ProjectReference Include="..\CSharp\Microsoft.CodeAnalysis.CSharp.Scripting.csproj" /> <ProjectReference Include="..\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Scripting.vbproj" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Scripting.Desktop.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Scripting.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Scripting.Desktop.UnitTests" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.CSharp" Version="$(MicrosoftCSharpVersion)" /> <PackageReference Include="Microsoft.NETCore.Platforms" Version="$(MicrosoftNETCorePlatformsVersion)" /> </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> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <TargetFramework>netstandard2.0</TargetFramework> <NoStdLib>true</NoStdLib> <IsShipping>false</IsShipping> <ExcludeFromSourceBuild>true</ExcludeFromSourceBuild> </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\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\Core\Microsoft.CodeAnalysis.Scripting.csproj" /> <ProjectReference Include="..\CSharp\Microsoft.CodeAnalysis.CSharp.Scripting.csproj" /> <ProjectReference Include="..\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Scripting.vbproj" /> <PackageReference Include="Basic.Reference.Assemblies.NetStandard13" Version="$(BasicReferenceAssembliesNetStandard13Version)" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Scripting.Desktop.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Scripting.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Scripting.Desktop.UnitTests" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.CSharp" Version="$(MicrosoftCSharpVersion)" /> <PackageReference Include="Microsoft.NETCore.Platforms" Version="$(MicrosoftNETCorePlatformsVersion)" /> </ItemGroup> </Project>
1
dotnet/roslyn
56,223
Rework our netstandard1.3 test references
The `netstandard1.3` test references were being provided by our MS.CA.Test.Resources.Proprietary package. The contents of this package get included in the output directory of every single unit test DLL that we build (which contributes to build output size). The references themselves though were only used in a very small number of tests. This change upgrades to a version of MS.CA.Test.Resources.Proprietary that has the `netstandard1.3` references removed and adds the `netstandard1.3` references to only the projects that needs them
jaredpar
"2021-09-07T20:35:04Z"
"2021-09-07T23:50:57Z"
0240973369997c88a2c2f1aaa22c14182ac17e9f
5dbd783367d7f6b105726b84558cc1809aa198ce
Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our MS.CA.Test.Resources.Proprietary package. The contents of this package get included in the output directory of every single unit test DLL that we build (which contributes to build output size). The references themselves though were only used in a very small number of tests. This change upgrades to a version of MS.CA.Test.Resources.Proprietary that has the `netstandard1.3` references removed and adds the `netstandard1.3` references to only the projects that needs them
./src/Scripting/CoreTestUtilities/TestCompilationFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.Scripting { internal static class TestCompilationFactory { // TODO: we need to clean up and refactor CreateCompilationWithMscorlib in compiler tests // so that it can be used in portable tests. internal static Compilation CreateCSharpCompilationWithCorlib(string source, string assemblyName = null) { return CSharpCompilation.Create( assemblyName ?? Guid.NewGuid().ToString(), new[] { CSharp.SyntaxFactory.ParseSyntaxTree(source) }, new[] { TestReferences.NetStandard13.SystemRuntime }, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); } internal static Compilation CreateVisualBasicCompilationWithCorlib(string source, string assemblyName = null) { return VisualBasicCompilation.Create( assemblyName ?? Guid.NewGuid().ToString(), new[] { VisualBasic.SyntaxFactory.ParseSyntaxTree(source) }, new[] { TestReferences.NetStandard13.SystemRuntime }, new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); } internal static Compilation CreateCSharpCompilation(string source, IEnumerable<MetadataReference> references, string assemblyName = null, CSharpCompilationOptions options = null) { return CSharpCompilation.Create( assemblyName ?? Guid.NewGuid().ToString(), new[] { CSharp.SyntaxFactory.ParseSyntaxTree(source) }, references, options ?? new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.VisualBasic; using Basic.Reference.Assemblies; namespace Microsoft.CodeAnalysis.Scripting { internal static class TestCompilationFactory { // TODO: we need to clean up and refactor CreateCompilationWithMscorlib in compiler tests // so that it can be used in portable tests. internal static Compilation CreateCSharpCompilationWithCorlib(string source, string assemblyName = null) { return CSharpCompilation.Create( assemblyName ?? Guid.NewGuid().ToString(), new[] { CSharp.SyntaxFactory.ParseSyntaxTree(source) }, new[] { NetStandard13.SystemRuntime }, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); } internal static Compilation CreateVisualBasicCompilationWithCorlib(string source, string assemblyName = null) { return VisualBasicCompilation.Create( assemblyName ?? Guid.NewGuid().ToString(), new[] { VisualBasic.SyntaxFactory.ParseSyntaxTree(source) }, new[] { NetStandard13.SystemRuntime }, new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); } internal static Compilation CreateCSharpCompilation(string source, IEnumerable<MetadataReference> references, string assemblyName = null, CSharpCompilationOptions options = null) { return CSharpCompilation.Create( assemblyName ?? Guid.NewGuid().ToString(), new[] { CSharp.SyntaxFactory.ParseSyntaxTree(source) }, references, options ?? new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); } } }
1
dotnet/roslyn
56,223
Rework our netstandard1.3 test references
The `netstandard1.3` test references were being provided by our MS.CA.Test.Resources.Proprietary package. The contents of this package get included in the output directory of every single unit test DLL that we build (which contributes to build output size). The references themselves though were only used in a very small number of tests. This change upgrades to a version of MS.CA.Test.Resources.Proprietary that has the `netstandard1.3` references removed and adds the `netstandard1.3` references to only the projects that needs them
jaredpar
"2021-09-07T20:35:04Z"
"2021-09-07T23:50:57Z"
0240973369997c88a2c2f1aaa22c14182ac17e9f
5dbd783367d7f6b105726b84558cc1809aa198ce
Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our MS.CA.Test.Resources.Proprietary package. The contents of this package get included in the output directory of every single unit test DLL that we build (which contributes to build output size). The references themselves though were only used in a very small number of tests. This change upgrades to a version of MS.CA.Test.Resources.Proprietary that has the `netstandard1.3` references removed and adds the `netstandard1.3` references to only the projects that needs them
./src/VisualStudio/VisualStudioDiagnosticsToolWindow/VenusMargin/ProjectionSpanTagger.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ComponentModel.Composition; using System.Linq; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; namespace Roslyn.Hosting.Diagnostics.VenusMargin { [Export(typeof(IViewTaggerProvider))] [ContentType("text")] [TagType(typeof(TextMarkerTag))] internal class ProjectionSpanTaggerProvider : IViewTaggerProvider { public const string PropertyName = "Projection Tags"; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ProjectionSpanTaggerProvider() { } public ITagger<T> CreateTagger<T>(ITextView textView, ITextBuffer buffer) where T : ITag { return new Tagger(textView) as ITagger<T>; } internal class Tagger : ITagger<TextMarkerTag>, IDisposable { private readonly ITextView _textView; public Tagger(ITextView textView) { _textView = textView; ProjectionBufferMargin.SelectionChanged += OnProjectionBufferMarginSelectionChanged; } public event EventHandler<SnapshotSpanEventArgs> TagsChanged; private void OnProjectionBufferMarginSelectionChanged(object sender, EventArgs e) { var snapshot = _textView.TextBuffer.CurrentSnapshot; RaiseTagsChanged(new SnapshotSpanEventArgs(new SnapshotSpan(snapshot, new Span(0, snapshot.Length)))); } private void RaiseTagsChanged(SnapshotSpanEventArgs args) { this.TagsChanged?.Invoke(this, args); } public IEnumerable<ITagSpan<TextMarkerTag>> GetTags(NormalizedSnapshotSpanCollection spans) { if (!_textView.Properties.TryGetProperty(PropertyName, out List<Span> allSpans)) { return null; } return allSpans .Where(s => spans.Any(ss => ss.IntersectsWith(s))) .Select(s => new TagSpan<TextMarkerTag>(new SnapshotSpan(spans.First().Snapshot, s), ProjectionSpanTag.Instance)); } public void Dispose() { ProjectionBufferMargin.SelectionChanged -= OnProjectionBufferMarginSelectionChanged; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ComponentModel.Composition; using System.Linq; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; namespace Roslyn.Hosting.Diagnostics.VenusMargin { [Export(typeof(IViewTaggerProvider))] [ContentType("text")] [TagType(typeof(TextMarkerTag))] internal class ProjectionSpanTaggerProvider : IViewTaggerProvider { public const string PropertyName = "Projection Tags"; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ProjectionSpanTaggerProvider() { } public ITagger<T> CreateTagger<T>(ITextView textView, ITextBuffer buffer) where T : ITag { return new Tagger(textView) as ITagger<T>; } internal class Tagger : ITagger<TextMarkerTag>, IDisposable { private readonly ITextView _textView; public Tagger(ITextView textView) { _textView = textView; ProjectionBufferMargin.SelectionChanged += OnProjectionBufferMarginSelectionChanged; } public event EventHandler<SnapshotSpanEventArgs> TagsChanged; private void OnProjectionBufferMarginSelectionChanged(object sender, EventArgs e) { var snapshot = _textView.TextBuffer.CurrentSnapshot; RaiseTagsChanged(new SnapshotSpanEventArgs(new SnapshotSpan(snapshot, new Span(0, snapshot.Length)))); } private void RaiseTagsChanged(SnapshotSpanEventArgs args) { this.TagsChanged?.Invoke(this, args); } public IEnumerable<ITagSpan<TextMarkerTag>> GetTags(NormalizedSnapshotSpanCollection spans) { if (!_textView.Properties.TryGetProperty(PropertyName, out List<Span> allSpans)) { return null; } return allSpans .Where(s => spans.Any(ss => ss.IntersectsWith(s))) .Select(s => new TagSpan<TextMarkerTag>(new SnapshotSpan(spans.First().Snapshot, s), ProjectionSpanTag.Instance)); } public void Dispose() { ProjectionBufferMargin.SelectionChanged -= OnProjectionBufferMarginSelectionChanged; } } } }
-1
dotnet/roslyn
56,223
Rework our netstandard1.3 test references
The `netstandard1.3` test references were being provided by our MS.CA.Test.Resources.Proprietary package. The contents of this package get included in the output directory of every single unit test DLL that we build (which contributes to build output size). The references themselves though were only used in a very small number of tests. This change upgrades to a version of MS.CA.Test.Resources.Proprietary that has the `netstandard1.3` references removed and adds the `netstandard1.3` references to only the projects that needs them
jaredpar
"2021-09-07T20:35:04Z"
"2021-09-07T23:50:57Z"
0240973369997c88a2c2f1aaa22c14182ac17e9f
5dbd783367d7f6b105726b84558cc1809aa198ce
Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our MS.CA.Test.Resources.Proprietary package. The contents of this package get included in the output directory of every single unit test DLL that we build (which contributes to build output size). The references themselves though were only used in a very small number of tests. This change upgrades to a version of MS.CA.Test.Resources.Proprietary that has the `netstandard1.3` references removed and adds the `netstandard1.3` references to only the projects that needs them
./src/VisualStudio/Core/Def/Implementation/Progression/GraphQueries/OverriddenByGraphQuery.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.GraphModel; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal sealed class OverriddenByGraphQuery : IGraphQuery { public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false); foreach (var node in context.InputNodes) { var symbol = graphBuilder.GetSymbol(node, cancellationToken); if (symbol != null) { var overriddenMember = symbol.GetOverriddenMember(); if (overriddenMember != null) { var symbolNode = await graphBuilder.AddNodeAsync( overriddenMember, relatedNode: node, cancellationToken).ConfigureAwait(false); graphBuilder.AddLink(node, RoslynGraphCategories.Overrides, symbolNode, cancellationToken); } } } return graphBuilder; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.GraphModel; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal sealed class OverriddenByGraphQuery : IGraphQuery { public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false); foreach (var node in context.InputNodes) { var symbol = graphBuilder.GetSymbol(node, cancellationToken); if (symbol != null) { var overriddenMember = symbol.GetOverriddenMember(); if (overriddenMember != null) { var symbolNode = await graphBuilder.AddNodeAsync( overriddenMember, relatedNode: node, cancellationToken).ConfigureAwait(false); graphBuilder.AddLink(node, RoslynGraphCategories.Overrides, symbolNode, cancellationToken); } } } return graphBuilder; } } }
-1
dotnet/roslyn
56,223
Rework our netstandard1.3 test references
The `netstandard1.3` test references were being provided by our MS.CA.Test.Resources.Proprietary package. The contents of this package get included in the output directory of every single unit test DLL that we build (which contributes to build output size). The references themselves though were only used in a very small number of tests. This change upgrades to a version of MS.CA.Test.Resources.Proprietary that has the `netstandard1.3` references removed and adds the `netstandard1.3` references to only the projects that needs them
jaredpar
"2021-09-07T20:35:04Z"
"2021-09-07T23:50:57Z"
0240973369997c88a2c2f1aaa22c14182ac17e9f
5dbd783367d7f6b105726b84558cc1809aa198ce
Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our MS.CA.Test.Resources.Proprietary package. The contents of this package get included in the output directory of every single unit test DLL that we build (which contributes to build output size). The references themselves though were only used in a very small number of tests. This change upgrades to a version of MS.CA.Test.Resources.Proprietary that has the `netstandard1.3` references removed and adds the `netstandard1.3` references to only the projects that needs them
./src/Features/Lsif/Generator/Graph/Range.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph { /// <summary> /// Represents a Range for serialization. See https://github.com/Microsoft/language-server-protocol/blob/master/indexFormat/specification.md#ranges for further details. /// </summary> internal sealed class Range : Vertex { public Position Start { get; } public Position End { get; } public Range(Position start, Position end, IdFactory idFactory) : base(label: "range", idFactory) { Start = start; End = end; } public static Range FromTextSpan(TextSpan textSpan, SourceText sourceText, IdFactory idFactory) { var linePositionSpan = sourceText.Lines.GetLinePositionSpan(textSpan); return new Range(start: ConvertLinePositionToPosition(linePositionSpan.Start), end: ConvertLinePositionToPosition(linePositionSpan.End), idFactory); } internal static Position ConvertLinePositionToPosition(LinePosition linePosition) { return new Position { Line = linePosition.Line, Character = linePosition.Character }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph { /// <summary> /// Represents a Range for serialization. See https://github.com/Microsoft/language-server-protocol/blob/master/indexFormat/specification.md#ranges for further details. /// </summary> internal sealed class Range : Vertex { public Position Start { get; } public Position End { get; } public Range(Position start, Position end, IdFactory idFactory) : base(label: "range", idFactory) { Start = start; End = end; } public static Range FromTextSpan(TextSpan textSpan, SourceText sourceText, IdFactory idFactory) { var linePositionSpan = sourceText.Lines.GetLinePositionSpan(textSpan); return new Range(start: ConvertLinePositionToPosition(linePositionSpan.Start), end: ConvertLinePositionToPosition(linePositionSpan.End), idFactory); } internal static Position ConvertLinePositionToPosition(LinePosition linePosition) { return new Position { Line = linePosition.Line, Character = linePosition.Character }; } } }
-1
dotnet/roslyn
56,223
Rework our netstandard1.3 test references
The `netstandard1.3` test references were being provided by our MS.CA.Test.Resources.Proprietary package. The contents of this package get included in the output directory of every single unit test DLL that we build (which contributes to build output size). The references themselves though were only used in a very small number of tests. This change upgrades to a version of MS.CA.Test.Resources.Proprietary that has the `netstandard1.3` references removed and adds the `netstandard1.3` references to only the projects that needs them
jaredpar
"2021-09-07T20:35:04Z"
"2021-09-07T23:50:57Z"
0240973369997c88a2c2f1aaa22c14182ac17e9f
5dbd783367d7f6b105726b84558cc1809aa198ce
Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our MS.CA.Test.Resources.Proprietary package. The contents of this package get included in the output directory of every single unit test DLL that we build (which contributes to build output size). The references themselves though were only used in a very small number of tests. This change upgrades to a version of MS.CA.Test.Resources.Proprietary that has the `netstandard1.3` references removed and adds the `netstandard1.3` references to only the projects that needs them
./src/Tools/BuildBoss/Extensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.IO.Packaging; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BuildBoss { internal static class Extensions { internal static string GetRelativeName(this PackagePart part) { var relativeName = part.Uri.ToString().Replace('/', '\\'); if (!string.IsNullOrEmpty(relativeName) && relativeName[0] == '\\') { relativeName = relativeName.Substring(1); } return relativeName; } internal static string GetName(this PackagePart part) => Path.GetFileName(GetRelativeName(part)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.IO.Packaging; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BuildBoss { internal static class Extensions { internal static string GetRelativeName(this PackagePart part) { var relativeName = part.Uri.ToString().Replace('/', '\\'); if (!string.IsNullOrEmpty(relativeName) && relativeName[0] == '\\') { relativeName = relativeName.Substring(1); } return relativeName; } internal static string GetName(this PackagePart part) => Path.GetFileName(GetRelativeName(part)); } }
-1
dotnet/roslyn
56,223
Rework our netstandard1.3 test references
The `netstandard1.3` test references were being provided by our MS.CA.Test.Resources.Proprietary package. The contents of this package get included in the output directory of every single unit test DLL that we build (which contributes to build output size). The references themselves though were only used in a very small number of tests. This change upgrades to a version of MS.CA.Test.Resources.Proprietary that has the `netstandard1.3` references removed and adds the `netstandard1.3` references to only the projects that needs them
jaredpar
"2021-09-07T20:35:04Z"
"2021-09-07T23:50:57Z"
0240973369997c88a2c2f1aaa22c14182ac17e9f
5dbd783367d7f6b105726b84558cc1809aa198ce
Rework our netstandard1.3 test references. The `netstandard1.3` test references were being provided by our MS.CA.Test.Resources.Proprietary package. The contents of this package get included in the output directory of every single unit test DLL that we build (which contributes to build output size). The references themselves though were only used in a very small number of tests. This change upgrades to a version of MS.CA.Test.Resources.Proprietary that has the `netstandard1.3` references removed and adds the `netstandard1.3` references to only the projects that needs them
./src/Compilers/CSharp/Test/Semantic/Semantics/InterpolationTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using System.Collections.Immutable; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { public class InterpolationTests : CompilingTestBase { [Fact] public void TestSimpleInterp() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""Jenny don\'t change your number { number }.""); Console.WriteLine($""Jenny don\'t change your number { number , -12 }.""); Console.WriteLine($""Jenny don\'t change your number { number , 12 }.""); Console.WriteLine($""Jenny don\'t change your number { number :###-####}.""); Console.WriteLine($""Jenny don\'t change your number { number , -12 :###-####}.""); Console.WriteLine($""Jenny don\'t change your number { number , 12 :###-####}.""); Console.WriteLine($""{number}""); } }"; string expectedOutput = @"Jenny don't change your number 8675309. Jenny don't change your number 8675309 . Jenny don't change your number 8675309. Jenny don't change your number 867-5309. Jenny don't change your number 867-5309 . Jenny don't change your number 867-5309. 8675309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestOnlyInterp() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""{number}""); } }"; string expectedOutput = @"8675309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestDoubleInterp01() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""{number}{number}""); } }"; string expectedOutput = @"86753098675309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestDoubleInterp02() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""Jenny don\'t change your number { number :###-####} { number :###-####}.""); } }"; string expectedOutput = @"Jenny don't change your number 867-5309 867-5309."; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestEmptyInterp() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { /*trash*/ }.""); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,73): error CS1733: Expected expression // Console.WriteLine("Jenny don\'t change your number \{ /*trash*/ }."); Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(5, 73) ); } [Fact] public void TestHalfOpenInterp01() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { ""); } }"; // too many diagnostics perhaps, but it starts the right way. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,63): error CS1010: Newline in constant // Console.WriteLine($"Jenny don\'t change your number { "); Diagnostic(ErrorCode.ERR_NewlineInConst, "").WithLocation(5, 63), // (5,66): error CS8967: Newlines are not allowed inside a non-verbatim interpolated string // Console.WriteLine($"Jenny don\'t change your number { "); Diagnostic(ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, "").WithLocation(5, 66), // (6,6): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(6, 6), // (6,6): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 6), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2)); } [Fact] public void TestHalfOpenInterp02() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { 8675309 // ""); } }"; // too many diagnostics perhaps, but it starts the right way. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,71): error CS8077: A single-line comment may not be used in an interpolated string. // Console.WriteLine($"Jenny don\'t change your number { 8675309 // "); Diagnostic(ErrorCode.ERR_SingleLineCommentInExpressionHole, "//").WithLocation(5, 71), // (6,6): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(6, 6), // (6,6): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 6), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2)); } [Fact] public void TestHalfOpenInterp03() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { 8675309 /* ""); } }"; // too many diagnostics perhaps, but it starts the right way. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,71): error CS1035: End-of-file found, '*/' expected // Console.WriteLine($"Jenny don\'t change your number { 8675309 /* "); Diagnostic(ErrorCode.ERR_OpenEndedComment, "").WithLocation(5, 71), // (5,77): error CS8967: Newlines are not allowed inside a non-verbatim interpolated string // Console.WriteLine($"Jenny don\'t change your number { 8675309 /* "); Diagnostic(ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, "").WithLocation(5, 77), // (7,2): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 2), // (7,2): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 2), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2)); } [Fact] public void LambdaInInterp() { string source = @"using System; class Program { static void Main(string[] args) { //Console.WriteLine(""jenny {0:(408) ###-####}"", new object[] { ((Func<int>)(() => { return number; })).Invoke() }); Console.WriteLine($""jenny { ((Func<int>)(() => { return number; })).Invoke() :(408) ###-####}""); } static int number = 8675309; } "; string expectedOutput = @"jenny (408) 867-5309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OneLiteral() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""Hello"" ); } }"; string expectedOutput = @"Hello"; var verifier = CompileAndVerify(source, expectedOutput: expectedOutput); verifier.VerifyIL("Program.Main", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldstr ""Hello"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: ret } "); } [Fact] public void OneInsert() { string source = @"using System; class Program { static void Main(string[] args) { var hello = $""Hello""; Console.WriteLine( $""{hello}"" ); } }"; string expectedOutput = @"Hello"; var verifier = CompileAndVerify(source, expectedOutput: expectedOutput); verifier.VerifyIL("Program.Main", @" { // Code size 20 (0x14) .maxstack 2 IL_0000: ldstr ""Hello"" IL_0005: dup IL_0006: brtrue.s IL_000e IL_0008: pop IL_0009: ldstr """" IL_000e: call ""void System.Console.WriteLine(string)"" IL_0013: ret } "); } [Fact] public void TwoInserts() { string source = @"using System; class Program { static void Main(string[] args) { var hello = $""Hello""; var world = $""world"" ; Console.WriteLine( $""{hello}, { world }."" ); } }"; string expectedOutput = @"Hello, world."; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TwoInserts02() { string source = @"using System; class Program { static void Main(string[] args) { var hello = $""Hello""; var world = $""world"" ; Console.WriteLine( $@""{ hello }, { world }."" ); } }"; string expectedOutput = @"Hello, world."; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact, WorkItem(306, "https://github.com/dotnet/roslyn/issues/306"), WorkItem(308, "https://github.com/dotnet/roslyn/issues/308")] public void DynamicInterpolation() { string source = @"using System; using System.Linq.Expressions; class Program { static void Main(string[] args) { dynamic nil = null; dynamic a = new string[] {""Hello"", ""world""}; Console.WriteLine($""<{nil}>""); Console.WriteLine($""<{a}>""); } Expression<Func<string>> M(dynamic d) { return () => $""Dynamic: {d}""; } }"; string expectedOutput = @"<> <System.String[]>"; var verifier = CompileAndVerify(source, new[] { CSharpRef }, expectedOutput: expectedOutput).VerifyDiagnostics(); } [Fact] public void UnclosedInterpolation01() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,31): error CS1010: Newline in constant // Console.WriteLine( $"{" ); Diagnostic(ErrorCode.ERR_NewlineInConst, "").WithLocation(6, 31), // (6,35): error CS8958: Newlines are not allowed inside a non-verbatim interpolated string // Console.WriteLine( $"{" ); Diagnostic(ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, "").WithLocation(6, 35), // (7,6): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 6), // (7,6): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 6), // (8,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(8, 2)); } [Fact] public void UnclosedInterpolation02() { string source = @"class Program { static void Main(string[] args) { var x = $"";"; // The precise error messages are not important, but this must be an error. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,19): error CS1010: Newline in constant // var x = $"; Diagnostic(ErrorCode.ERR_NewlineInConst, ";").WithLocation(5, 19), // (5,20): error CS1002: ; expected // var x = $"; Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(5, 20), // (5,20): error CS1513: } expected // var x = $"; Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 20), // (5,20): error CS1513: } expected // var x = $"; Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 20) ); } [Fact] public void EmptyFormatSpecifier() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{3:}"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,32): error CS8089: Empty format specifier. // Console.WriteLine( $"{3:}" ); Diagnostic(ErrorCode.ERR_EmptyFormatSpecifier, ":").WithLocation(6, 32) ); } [Fact] public void TrailingSpaceInFormatSpecifier() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{3:d }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,32): error CS8088: A format specifier may not contain trailing whitespace. // Console.WriteLine( $"{3:d }" ); Diagnostic(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, ":d ").WithLocation(6, 32) ); } [Fact] public void TrailingSpaceInFormatSpecifier02() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $@""{3:d }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,33): error CS8088: A format specifier may not contain trailing whitespace. // Console.WriteLine( $@"{3:d Diagnostic(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, @":d ").WithLocation(6, 33) ); } [Fact] public void MissingInterpolationExpression01() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{ }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,32): error CS1733: Expected expression // Console.WriteLine( $"{ }" ); Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(6, 32) ); } [Fact] public void MissingInterpolationExpression02() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $@""{ }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,33): error CS1733: Expected expression // Console.WriteLine( $@"{ }" ); Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(6, 33) ); } [Fact] public void MissingInterpolationExpression03() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( "; var normal = "$\""; var verbat = "$@\""; // ensure reparsing of interpolated string token is precise in error scenarios (assertions do not fail) Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + " ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + "{").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + "{ ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + " ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + "{").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + "{ ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void MisplacedNewline01() { string source = @"using System; class Program { static void Main(string[] args) { var s = $""{ @"" "" } ""; } }"; // The precise error messages are not important, but this must be an error. Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void MisplacedNewline02() { string source = @"using System; class Program { static void Main(string[] args) { var s = $""{ @"" ""} ""; } }"; // The precise error messages are not important, but this must be an error. Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void PreprocessorInsideInterpolation() { string source = @"class Program { static void Main() { var s = $@""{ #region : #endregion 0 }""; } }"; // The precise error messages are not important, but this must be an error. Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void EscapedCurly() { string source = @"class Program { static void Main() { var s1 = $"" \u007B ""; var s2 = $"" \u007D""; } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,21): error CS8087: A '{' character may only be escaped by doubling '{{' in an interpolated string. // var s1 = $" \u007B "; Diagnostic(ErrorCode.ERR_EscapedCurly, @"\u007B").WithArguments("{").WithLocation(5, 21), // (6,21): error CS8087: A '}' character may only be escaped by doubling '}}' in an interpolated string. // var s2 = $" \u007D"; Diagnostic(ErrorCode.ERR_EscapedCurly, @"\u007D").WithArguments("}").WithLocation(6, 21) ); } [Fact, WorkItem(1119878, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119878")] public void NoFillIns01() { string source = @"class Program { static void Main() { System.Console.Write($""{{ x }}""); System.Console.WriteLine($@""This is a test""); } }"; string expectedOutput = @"{ x }This is a test"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BadAlignment() { string source = @"class Program { static void Main() { var s = $""{1,1E10}""; var t = $""{1,(int)1E10}""; } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,22): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // var s = $"{1,1E10}"; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1E10").WithArguments("double", "int").WithLocation(5, 22), // (5,22): error CS0150: A constant value is expected // var s = $"{1,1E10}"; Diagnostic(ErrorCode.ERR_ConstantExpected, "1E10").WithLocation(5, 22), // (6,22): error CS0221: Constant value '10000000000' cannot be converted to a 'int' (use 'unchecked' syntax to override) // var t = $"{1,(int)1E10}"; Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "(int)1E10").WithArguments("10000000000", "int").WithLocation(6, 22), // (6,22): error CS0150: A constant value is expected // var t = $"{1,(int)1E10}"; Diagnostic(ErrorCode.ERR_ConstantExpected, "(int)1E10").WithLocation(6, 22) ); } [Fact] public void NestedInterpolatedVerbatim() { string source = @"using System; class Program { static void Main(string[] args) { var s = $@""{$@""{1}""}""; Console.WriteLine(s); } }"; string expectedOutput = @"1"; CompileAndVerify(source, expectedOutput: expectedOutput); } // Since the platform type System.FormattableString is not yet in our platforms (at the // time of writing), we explicitly include the required platform types into the sources under test. private const string formattableString = @" /*============================================================ ** ** Class: FormattableString ** ** ** Purpose: implementation of the FormattableString ** class. ** ===========================================================*/ namespace System { /// <summary> /// A composite format string along with the arguments to be formatted. An instance of this /// type may result from the use of the C# or VB language primitive ""interpolated string"". /// </summary> public abstract class FormattableString : IFormattable { /// <summary> /// The composite format string. /// </summary> public abstract string Format { get; } /// <summary> /// Returns an object array that contains zero or more objects to format. Clients should not /// mutate the contents of the array. /// </summary> public abstract object[] GetArguments(); /// <summary> /// The number of arguments to be formatted. /// </summary> public abstract int ArgumentCount { get; } /// <summary> /// Returns one argument to be formatted from argument position <paramref name=""index""/>. /// </summary> public abstract object GetArgument(int index); /// <summary> /// Format to a string using the given culture. /// </summary> public abstract string ToString(IFormatProvider formatProvider); string IFormattable.ToString(string ignored, IFormatProvider formatProvider) { return ToString(formatProvider); } /// <summary> /// Format the given object in the invariant culture. This static method may be /// imported in C# by /// <code> /// using static System.FormattableString; /// </code>. /// Within the scope /// of that import directive an interpolated string may be formatted in the /// invariant culture by writing, for example, /// <code> /// Invariant($""{{ lat = {latitude}; lon = {longitude} }}"") /// </code> /// </summary> public static string Invariant(FormattableString formattable) { if (formattable == null) { throw new ArgumentNullException(""formattable""); } return formattable.ToString(Globalization.CultureInfo.InvariantCulture); } public override string ToString() { return ToString(Globalization.CultureInfo.CurrentCulture); } } } /*============================================================ ** ** Class: FormattableStringFactory ** ** ** Purpose: implementation of the FormattableStringFactory ** class. ** ===========================================================*/ namespace System.Runtime.CompilerServices { /// <summary> /// A factory type used by compilers to create instances of the type <see cref=""FormattableString""/>. /// </summary> public static class FormattableStringFactory { /// <summary> /// Create a <see cref=""FormattableString""/> from a composite format string and object /// array containing zero or more objects to format. /// </summary> public static FormattableString Create(string format, params object[] arguments) { if (format == null) { throw new ArgumentNullException(""format""); } if (arguments == null) { throw new ArgumentNullException(""arguments""); } return new ConcreteFormattableString(format, arguments); } private sealed class ConcreteFormattableString : FormattableString { private readonly string _format; private readonly object[] _arguments; internal ConcreteFormattableString(string format, object[] arguments) { _format = format; _arguments = arguments; } public override string Format { get { return _format; } } public override object[] GetArguments() { return _arguments; } public override int ArgumentCount { get { return _arguments.Length; } } public override object GetArgument(int index) { return _arguments[index]; } public override string ToString(IFormatProvider formatProvider) { return string.Format(formatProvider, Format, _arguments); } } } } "; [Fact] public void TargetType01() { string source = @"using System; class Program { public static void Main(string[] args) { IFormattable f = $""test""; Console.Write(f is System.FormattableString); } }"; CompileAndVerify(source + formattableString, expectedOutput: "True"); } [Fact] public void TargetType02() { string source = @"using System; interface I1 { void M(String s); } interface I2 { void M(FormattableString s); } interface I3 { void M(IFormattable s); } interface I4 : I1, I2 {} interface I5 : I1, I3 {} interface I6 : I2, I3 {} interface I7 : I1, I2, I3 {} class C : I1, I2, I3, I4, I5, I6, I7 { public void M(String s) { Console.Write(1); } public void M(FormattableString s) { Console.Write(2); } public void M(IFormattable s) { Console.Write(3); } } class Program { public static void Main(string[] args) { C c = new C(); ((I1)c).M($""""); ((I2)c).M($""""); ((I3)c).M($""""); ((I4)c).M($""""); ((I5)c).M($""""); ((I6)c).M($""""); ((I7)c).M($""""); ((C)c).M($""""); } }"; CompileAndVerify(source + formattableString, expectedOutput: "12311211"); } [Fact] public void MissingHelper() { string source = @"using System; class Program { public static void Main(string[] args) { IFormattable f = $""test""; } }"; CreateCompilationWithMscorlib40(source).VerifyEmitDiagnostics( // (5,26): error CS0518: Predefined type 'System.Runtime.CompilerServices.FormattableStringFactory' is not defined or imported // IFormattable f = $"test"; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"$""test""").WithArguments("System.Runtime.CompilerServices.FormattableStringFactory").WithLocation(5, 26) ); } [Fact] public void AsyncInterp() { string source = @"using System; using System.Threading.Tasks; class Program { public static void Main(string[] args) { Task<string> hello = Task.FromResult(""Hello""); Task<string> world = Task.FromResult(""world""); M(hello, world).Wait(); } public static async Task M(Task<string> hello, Task<string> world) { Console.WriteLine($""{ await hello }, { await world }!""); } }"; CompileAndVerify( source, references: new[] { MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929 }, expectedOutput: "Hello, world!", targetFramework: TargetFramework.Empty); } [Fact] public void AlignmentExpression() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { 123 , -(3+4) }.""); } }"; CompileAndVerify(source + formattableString, expectedOutput: "X = 123 ."); } [Fact] public void AlignmentMagnitude() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { 123 , (32768) }.""); Console.WriteLine($""X = { 123 , -(32768) }.""); Console.WriteLine($""X = { 123 , (32767) }.""); Console.WriteLine($""X = { 123 , -(32767) }.""); Console.WriteLine($""X = { 123 , int.MaxValue }.""); Console.WriteLine($""X = { 123 , int.MinValue }.""); } }"; CreateCompilation(source).VerifyDiagnostics( // (5,42): warning CS8094: Alignment value 32768 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , (32768) }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "32768").WithArguments("32768", "32767").WithLocation(5, 42), // (6,41): warning CS8094: Alignment value -32768 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , -(32768) }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "-(32768)").WithArguments("-32768", "32767").WithLocation(6, 41), // (9,41): warning CS8094: Alignment value 2147483647 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , int.MaxValue }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "int.MaxValue").WithArguments("2147483647", "32767").WithLocation(9, 41), // (10,41): warning CS8094: Alignment value -2147483648 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , int.MinValue }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "int.MinValue").WithArguments("-2147483648", "32767").WithLocation(10, 41) ); } [WorkItem(1097388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097388")] [Fact] public void InterpolationExpressionMustBeValue01() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { String }.""); Console.WriteLine($""X = { null }.""); } }"; CreateCompilation(source).VerifyDiagnostics( // (5,35): error CS0119: 'string' is a type, which is not valid in the given context // Console.WriteLine($"X = { String }."); Diagnostic(ErrorCode.ERR_BadSKunknown, "String").WithArguments("string", "type").WithLocation(5, 35) ); } [Fact] public void InterpolationExpressionMustBeValue02() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { x=>3 }.""); Console.WriteLine($""X = { Program.Main }.""); Console.WriteLine($""X = { Program.Main(null) }.""); } }"; CreateCompilation(source, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (5,35): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // Console.WriteLine($"X = { x=>3 }."); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x=>3").WithArguments("lambda expression", "object").WithLocation(5, 35), // (6,43): error CS0428: Cannot convert method group 'Main' to non-delegate type 'object'. Did you intend to invoke the method? // Console.WriteLine($"X = { Program.Main }."); Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "object").WithLocation(6, 43), // (7,35): error CS0029: Cannot implicitly convert type 'void' to 'object' // Console.WriteLine($"X = { Program.Main(null) }."); Diagnostic(ErrorCode.ERR_NoImplicitConv, "Program.Main(null)").WithArguments("void", "object").WithLocation(7, 35) ); CreateCompilation(source).VerifyDiagnostics( // (5,35): error CS8917: The delegate type could not be inferred. // Console.WriteLine($"X = { x=>3 }."); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x=>3").WithLocation(5, 35), // (7,35): error CS0029: Cannot implicitly convert type 'void' to 'object' // Console.WriteLine($"X = { Program.Main(null) }."); Diagnostic(ErrorCode.ERR_NoImplicitConv, "Program.Main(null)").WithArguments("void", "object").WithLocation(7, 35) ); } [WorkItem(1097428, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097428")] [Fact] public void BadCorelib01() { var text = @"namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } } public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } } public struct Char { } public class String { } internal class Program { public static void Main() { var s = $""X = { 1 } ""; } } }"; CreateEmptyCompilation(text, options: TestOptions.DebugExe) .VerifyEmitDiagnostics(new CodeAnalysis.Emit.EmitOptions(runtimeMetadataVersion: "x.y"), // (15,21): error CS0117: 'string' does not contain a definition for 'Format' // var s = $"X = { 1 } "; Diagnostic(ErrorCode.ERR_NoSuchMember, @"$""X = { 1 } """).WithArguments("string", "Format").WithLocation(15, 21) ); } [WorkItem(1097428, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097428")] [Fact] public void BadCorelib02() { var text = @"namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } } public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } } public struct Char { } public class String { public static Boolean Format(string format, int arg) { return true; } } internal class Program { public static void Main() { var s = $""X = { 1 } ""; } } }"; CreateEmptyCompilation(text, options: TestOptions.DebugExe) .VerifyEmitDiagnostics(new CodeAnalysis.Emit.EmitOptions(runtimeMetadataVersion: "x.y"), // (17,21): error CS0029: Cannot implicitly convert type 'bool' to 'string' // var s = $"X = { 1 } "; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""X = { 1 } """).WithArguments("bool", "string").WithLocation(17, 21) ); } [Fact] public void SillyCoreLib01() { var text = @"namespace System { interface IFormattable { } namespace Runtime.CompilerServices { public static class FormattableStringFactory { public static Bozo Create(string format, int arg) { return new Bozo(); } } } public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } } public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } } public struct Char { } public class String { public static Bozo Format(string format, int arg) { return new Bozo(); } } public class FormattableString { } public class Bozo { public static implicit operator string(Bozo bozo) { return ""zz""; } public static implicit operator FormattableString(Bozo bozo) { return new FormattableString(); } } internal class Program { public static void Main() { var s1 = $""X = { 1 } ""; FormattableString s2 = $""X = { 1 } ""; } } }"; var comp = CreateEmptyCompilation(text, options: Test.Utilities.TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); var compilation = CompileAndVerify(comp, verify: Verification.Fails); compilation.VerifyIL("System.Program.Main", @"{ // Code size 35 (0x23) .maxstack 2 IL_0000: ldstr ""X = {0} "" IL_0005: ldc.i4.1 IL_0006: call ""System.Bozo string.Format(string, int)"" IL_000b: call ""string System.Bozo.op_Implicit(System.Bozo)"" IL_0010: pop IL_0011: ldstr ""X = {0} "" IL_0016: ldc.i4.1 IL_0017: call ""System.Bozo System.Runtime.CompilerServices.FormattableStringFactory.Create(string, int)"" IL_001c: call ""System.FormattableString System.Bozo.op_Implicit(System.Bozo)"" IL_0021: pop IL_0022: ret }"); } [WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")] [Fact] public void Syntax01() { var text = @"using System; class Program { static void Main(string[] args) { var x = $""{ Math.Abs(value: 1):\}""; var y = x; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,40): error CS8087: A '}' character may only be escaped by doubling '}}' in an interpolated string. // var x = $"{ Math.Abs(value: 1):\}"; Diagnostic(ErrorCode.ERR_EscapedCurly, @"\").WithArguments("}").WithLocation(6, 40), // (6,40): error CS1009: Unrecognized escape sequence // var x = $"{ Math.Abs(value: 1):\}"; Diagnostic(ErrorCode.ERR_IllegalEscape, @"\}").WithLocation(6, 40) ); } [WorkItem(1097941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097941")] [Fact] public void Syntax02() { var text = @"using S = System; class C { void M() { var x = $""{ (S: } }"; // the precise diagnostics do not matter, as long as it is an error and not a crash. Assert.True(SyntaxFactory.ParseSyntaxTree(text).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")] [Fact] public void Syntax03() { var text = @"using System; class Program { static void Main(string[] args) { var x = $""{ Math.Abs(value: 1):}}""; var y = x; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,18): error CS8076: Missing close delimiter '}' for interpolated expression started with '{'. // var x = $"{ Math.Abs(value: 1):}}"; Diagnostic(ErrorCode.ERR_UnclosedExpressionHole, @"""{").WithLocation(6, 18) ); } [WorkItem(1099105, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1099105")] [Fact] public void NoUnexpandedForm() { string source = @"using System; class Program { public static void Main(string[] args) { string[] arr1 = new string[] { ""xyzzy"" }; object[] arr2 = arr1; Console.WriteLine($""-{null}-""); Console.WriteLine($""-{arr1}-""); Console.WriteLine($""-{arr2}-""); } }"; CompileAndVerify(source + formattableString, expectedOutput: @"-- -System.String[]- -System.String[]-"); } [WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")] [Fact] public void Dynamic01() { var text = @"class C { const dynamic a = a; string s = $""{0,a}""; }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (3,19): error CS0110: The evaluation of the constant value for 'C.a' involves a circular definition // const dynamic a = a; Diagnostic(ErrorCode.ERR_CircConstValue, "a").WithArguments("C.a").WithLocation(3, 19), // (3,23): error CS0134: 'C.a' is of type 'dynamic'. A const field of a reference type other than string can only be initialized with null. // const dynamic a = a; Diagnostic(ErrorCode.ERR_NotNullConstRefField, "a").WithArguments("C.a", "dynamic").WithLocation(3, 23), // (4,21): error CS0150: A constant value is expected // string s = $"{0,a}"; Diagnostic(ErrorCode.ERR_ConstantExpected, "a").WithLocation(4, 21) ); } [WorkItem(1099238, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1099238")] [Fact] public void Syntax04() { var text = @"using System; using System.Linq.Expressions; class Program { static void Main() { Expression<Func<string>> e = () => $""\u1{0:\u2}""; Console.WriteLine(e); } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (8,46): error CS1009: Unrecognized escape sequence // Expression<Func<string>> e = () => $"\u1{0:\u2}"; Diagnostic(ErrorCode.ERR_IllegalEscape, @"\u1").WithLocation(8, 46), // (8,52): error CS1009: Unrecognized escape sequence // Expression<Func<string>> e = () => $"\u1{0:\u2}"; Diagnostic(ErrorCode.ERR_IllegalEscape, @"\u2").WithLocation(8, 52) ); } [Fact, WorkItem(1098612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1098612")] public void MissingConversionFromFormattableStringToIFormattable() { var text = @"namespace System.Runtime.CompilerServices { public static class FormattableStringFactory { public static FormattableString Create(string format, params object[] arguments) { return null; } } } namespace System { public abstract class FormattableString { } } static class C { static void Main() { System.IFormattable i = $""{""""}""; } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyEmitDiagnostics( // (23,33): error CS0029: Cannot implicitly convert type 'FormattableString' to 'IFormattable' // System.IFormattable i = $"{""}"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{""""}""").WithArguments("System.FormattableString", "System.IFormattable").WithLocation(23, 33) ); } [Theory, WorkItem(54702, "https://github.com/dotnet/roslyn/issues/54702")] [InlineData(@"$""{s1}{s2}""", @"$""{s1}{s2}{s3}""", @"$""{s1}{s2}{s3}{s4}""", @"$""{s1}{s2}{s3}{s4}{s5}""")] [InlineData(@"$""{s1}"" + $""{s2}""", @"$""{s1}"" + $""{s2}"" + $""{s3}""", @"$""{s1}"" + $""{s2}"" + $""{s3}"" + $""{s4}""", @"$""{s1}"" + $""{s2}"" + $""{s3}"" + $""{s4}"" + $""{s5}""")] public void InterpolatedStringHandler_ConcatPreferencesForAllStringElements(string twoComponents, string threeComponents, string fourComponents, string fiveComponents) { var code = @" using System; Console.WriteLine(TwoComponents()); Console.WriteLine(ThreeComponents()); Console.WriteLine(FourComponents()); Console.WriteLine(FiveComponents()); string TwoComponents() { string s1 = ""1""; string s2 = ""2""; return " + twoComponents + @"; } string ThreeComponents() { string s1 = ""1""; string s2 = ""2""; string s3 = ""3""; return " + threeComponents + @"; } string FourComponents() { string s1 = ""1""; string s2 = ""2""; string s3 = ""3""; string s4 = ""4""; return " + fourComponents + @"; } string FiveComponents() { string s1 = ""1""; string s2 = ""2""; string s3 = ""3""; string s4 = ""4""; string s5 = ""5""; return " + fiveComponents + @"; } "; var handler = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { code, handler }, expectedOutput: @" 12 123 1234 value:1 value:2 value:3 value:4 value:5 "); verifier.VerifyIL("Program.<<Main>$>g__TwoComponents|0_0()", @" { // Code size 18 (0x12) .maxstack 2 .locals init (string V_0) //s2 IL_0000: ldstr ""1"" IL_0005: ldstr ""2"" IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: call ""string string.Concat(string, string)"" IL_0011: ret } "); verifier.VerifyIL("Program.<<Main>$>g__ThreeComponents|0_1()", @" { // Code size 25 (0x19) .maxstack 3 .locals init (string V_0, //s2 string V_1) //s3 IL_0000: ldstr ""1"" IL_0005: ldstr ""2"" IL_000a: stloc.0 IL_000b: ldstr ""3"" IL_0010: stloc.1 IL_0011: ldloc.0 IL_0012: ldloc.1 IL_0013: call ""string string.Concat(string, string, string)"" IL_0018: ret } "); verifier.VerifyIL("Program.<<Main>$>g__FourComponents|0_2()", @" { // Code size 32 (0x20) .maxstack 4 .locals init (string V_0, //s2 string V_1, //s3 string V_2) //s4 IL_0000: ldstr ""1"" IL_0005: ldstr ""2"" IL_000a: stloc.0 IL_000b: ldstr ""3"" IL_0010: stloc.1 IL_0011: ldstr ""4"" IL_0016: stloc.2 IL_0017: ldloc.0 IL_0018: ldloc.1 IL_0019: ldloc.2 IL_001a: call ""string string.Concat(string, string, string, string)"" IL_001f: ret } "); verifier.VerifyIL("Program.<<Main>$>g__FiveComponents|0_3()", @" { // Code size 89 (0x59) .maxstack 3 .locals init (string V_0, //s1 string V_1, //s2 string V_2, //s3 string V_3, //s4 string V_4, //s5 System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_5) IL_0000: ldstr ""1"" IL_0005: stloc.0 IL_0006: ldstr ""2"" IL_000b: stloc.1 IL_000c: ldstr ""3"" IL_0011: stloc.2 IL_0012: ldstr ""4"" IL_0017: stloc.3 IL_0018: ldstr ""5"" IL_001d: stloc.s V_4 IL_001f: ldloca.s V_5 IL_0021: ldc.i4.0 IL_0022: ldc.i4.5 IL_0023: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0028: ldloca.s V_5 IL_002a: ldloc.0 IL_002b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0030: ldloca.s V_5 IL_0032: ldloc.1 IL_0033: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0038: ldloca.s V_5 IL_003a: ldloc.2 IL_003b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0040: ldloca.s V_5 IL_0042: ldloc.3 IL_0043: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0048: ldloca.s V_5 IL_004a: ldloc.s V_4 IL_004c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0051: ldloca.s V_5 IL_0053: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0058: ret } "); } [Theory] [CombinatorialData] public void InterpolatedStringHandler_OverloadsAndBoolReturns( bool useDefaultParameters, bool useBoolReturns, bool constructorBoolArg, [CombinatorialValues(@"$""base{a}{a,1}{a:X}{a,2:Y}""", @"$""base"" + $""{a}"" + $""{a,1}"" + $""{a:X}"" + $""{a,2:Y}""")] string expression) { var source = @"int a = 1; System.Console.WriteLine(" + expression + @");"; string interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters, useBoolReturns, constructorBoolArg: constructorBoolArg); string expectedOutput = useDefaultParameters ? @"base value:1,alignment:0:format: value:1,alignment:1:format: value:1,alignment:0:format:X value:1,alignment:2:format:Y" : @"base value:1 value:1,alignment:1 value:1:format:X value:1,alignment:2:format:Y"; string expectedIl = getIl(); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: expectedOutput); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); var comp1 = CreateCompilation(interpolatedStringBuilder); foreach (var reference in new[] { comp1.EmitToImageReference(), comp1.ToMetadataReference() }) { var comp2 = CreateCompilation(source, new[] { reference }); verifier = CompileAndVerify(comp2, expectedOutput: expectedOutput); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); } string getIl() => (useDefaultParameters, useBoolReturns, constructorBoolArg) switch { (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 80 (0x50) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_1 IL_0019: ldloc.0 IL_001a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_001f: ldloca.s V_1 IL_0021: ldloc.0 IL_0022: ldc.i4.1 IL_0023: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_0028: ldloca.s V_1 IL_002a: ldloc.0 IL_002b: ldstr ""X"" IL_0030: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldloc.0 IL_0038: ldc.i4.2 IL_0039: ldstr ""Y"" IL_003e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0043: ldloca.s V_1 IL_0045: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_004a: call ""void System.Console.WriteLine(string)"" IL_004f: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 84 (0x54) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_1 IL_0019: ldloc.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0021: ldloca.s V_1 IL_0023: ldloc.0 IL_0024: ldc.i4.1 IL_0025: ldnull IL_0026: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_002b: ldloca.s V_1 IL_002d: ldloc.0 IL_002e: ldc.i4.0 IL_002f: ldstr ""X"" IL_0034: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0039: ldloca.s V_1 IL_003b: ldloc.0 IL_003c: ldc.i4.2 IL_003d: ldstr ""Y"" IL_0042: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0047: ldloca.s V_1 IL_0049: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_004e: call ""void System.Console.WriteLine(string)"" IL_0053: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 92 (0x5c) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: brfalse.s IL_004d IL_0019: ldloca.s V_1 IL_001b: ldloc.0 IL_001c: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0021: brfalse.s IL_004d IL_0023: ldloca.s V_1 IL_0025: ldloc.0 IL_0026: ldc.i4.1 IL_0027: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_002c: brfalse.s IL_004d IL_002e: ldloca.s V_1 IL_0030: ldloc.0 IL_0031: ldstr ""X"" IL_0036: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_003b: brfalse.s IL_004d IL_003d: ldloca.s V_1 IL_003f: ldloc.0 IL_0040: ldc.i4.2 IL_0041: ldstr ""Y"" IL_0046: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004b: br.s IL_004e IL_004d: ldc.i4.0 IL_004e: pop IL_004f: ldloca.s V_1 IL_0051: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0056: call ""void System.Console.WriteLine(string)"" IL_005b: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 96 (0x60) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: brfalse.s IL_0051 IL_0019: ldloca.s V_1 IL_001b: ldloc.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0023: brfalse.s IL_0051 IL_0025: ldloca.s V_1 IL_0027: ldloc.0 IL_0028: ldc.i4.1 IL_0029: ldnull IL_002a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_002f: brfalse.s IL_0051 IL_0031: ldloca.s V_1 IL_0033: ldloc.0 IL_0034: ldc.i4.0 IL_0035: ldstr ""X"" IL_003a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_003f: brfalse.s IL_0051 IL_0041: ldloca.s V_1 IL_0043: ldloc.0 IL_0044: ldc.i4.2 IL_0045: ldstr ""Y"" IL_004a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004f: br.s IL_0052 IL_0051: ldc.i4.0 IL_0052: pop IL_0053: ldloca.s V_1 IL_0055: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005a: call ""void System.Console.WriteLine(string)"" IL_005f: ret } ", (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 89 (0x59) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_004a IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: ldloca.s V_1 IL_001d: ldloc.0 IL_001e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0023: ldloca.s V_1 IL_0025: ldloc.0 IL_0026: ldc.i4.1 IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_002c: ldloca.s V_1 IL_002e: ldloc.0 IL_002f: ldstr ""X"" IL_0034: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_0039: ldloca.s V_1 IL_003b: ldloc.0 IL_003c: ldc.i4.2 IL_003d: ldstr ""Y"" IL_0042: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0047: ldc.i4.1 IL_0048: br.s IL_004b IL_004a: ldc.i4.0 IL_004b: pop IL_004c: ldloca.s V_1 IL_004e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0053: call ""void System.Console.WriteLine(string)"" IL_0058: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 93 (0x5d) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_004e IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: ldloca.s V_1 IL_001d: ldloc.0 IL_001e: ldc.i4.0 IL_001f: ldnull IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0025: ldloca.s V_1 IL_0027: ldloc.0 IL_0028: ldc.i4.1 IL_0029: ldnull IL_002a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_002f: ldloca.s V_1 IL_0031: ldloc.0 IL_0032: ldc.i4.0 IL_0033: ldstr ""X"" IL_0038: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_003d: ldloca.s V_1 IL_003f: ldloc.0 IL_0040: ldc.i4.2 IL_0041: ldstr ""Y"" IL_0046: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004b: ldc.i4.1 IL_004c: br.s IL_004f IL_004e: ldc.i4.0 IL_004f: pop IL_0050: ldloca.s V_1 IL_0052: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0057: call ""void System.Console.WriteLine(string)"" IL_005c: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 96 (0x60) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_0051 IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: brfalse.s IL_0051 IL_001d: ldloca.s V_1 IL_001f: ldloc.0 IL_0020: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0025: brfalse.s IL_0051 IL_0027: ldloca.s V_1 IL_0029: ldloc.0 IL_002a: ldc.i4.1 IL_002b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_0030: brfalse.s IL_0051 IL_0032: ldloca.s V_1 IL_0034: ldloc.0 IL_0035: ldstr ""X"" IL_003a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_003f: brfalse.s IL_0051 IL_0041: ldloca.s V_1 IL_0043: ldloc.0 IL_0044: ldc.i4.2 IL_0045: ldstr ""Y"" IL_004a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004f: br.s IL_0052 IL_0051: ldc.i4.0 IL_0052: pop IL_0053: ldloca.s V_1 IL_0055: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005a: call ""void System.Console.WriteLine(string)"" IL_005f: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 100 (0x64) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_0055 IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: brfalse.s IL_0055 IL_001d: ldloca.s V_1 IL_001f: ldloc.0 IL_0020: ldc.i4.0 IL_0021: ldnull IL_0022: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0027: brfalse.s IL_0055 IL_0029: ldloca.s V_1 IL_002b: ldloc.0 IL_002c: ldc.i4.1 IL_002d: ldnull IL_002e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0033: brfalse.s IL_0055 IL_0035: ldloca.s V_1 IL_0037: ldloc.0 IL_0038: ldc.i4.0 IL_0039: ldstr ""X"" IL_003e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0043: brfalse.s IL_0055 IL_0045: ldloca.s V_1 IL_0047: ldloc.0 IL_0048: ldc.i4.2 IL_0049: ldstr ""Y"" IL_004e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0053: br.s IL_0056 IL_0055: ldc.i4.0 IL_0056: pop IL_0057: ldloca.s V_1 IL_0059: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005e: call ""void System.Console.WriteLine(string)"" IL_0063: ret } ", }; } [Fact] public void UseOfSpanInInterpolationHole_CSharp9() { var source = @" using System; ReadOnlySpan<char> span = stackalloc char[1]; Console.WriteLine($""{span}"");"; var comp = CreateCompilation(new[] { source, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false) }, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,22): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // Console.WriteLine($"{span}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "span").WithArguments("interpolated string handlers", "10.0").WithLocation(4, 22) ); } [ConditionalTheory(typeof(MonoOrCoreClrOnly))] [CombinatorialData] public void UseOfSpanInInterpolationHole(bool useDefaultParameters, bool useBoolReturns, bool constructorBoolArg, [CombinatorialValues(@"$""base{a}{a,1}{a:X}{a,2:Y}""", @"$""base"" + $""{a}"" + $""{a,1}"" + $""{a:X}"" + $""{a,2:Y}""")] string expression) { var source = @" using System; ReadOnlySpan<char> a = ""1""; System.Console.WriteLine(" + expression + ");"; string interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters, useBoolReturns, constructorBoolArg: constructorBoolArg); string expectedOutput = useDefaultParameters ? @"base value:1,alignment:0:format: value:1,alignment:1:format: value:1,alignment:0:format:X value:1,alignment:2:format:Y" : @"base value:1 value:1,alignment:1 value:1:format:X value:1,alignment:2:format:Y"; string expectedIl = getIl(); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: expectedOutput, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular10); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); var comp1 = CreateCompilation(interpolatedStringBuilder, targetFramework: TargetFramework.NetCoreApp); foreach (var reference in new[] { comp1.EmitToImageReference(), comp1.ToMetadataReference() }) { var comp2 = CreateCompilation(source, new[] { reference }, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular10); verifier = CompileAndVerify(comp2, expectedOutput: expectedOutput); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); } string getIl() => (useDefaultParameters, useBoolReturns, constructorBoolArg) switch { (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 89 (0x59) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: ldloca.s V_1 IL_0022: ldloc.0 IL_0023: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_0028: ldloca.s V_1 IL_002a: ldloc.0 IL_002b: ldc.i4.1 IL_002c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0031: ldloca.s V_1 IL_0033: ldloc.0 IL_0034: ldstr ""X"" IL_0039: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_003e: ldloca.s V_1 IL_0040: ldloc.0 IL_0041: ldc.i4.2 IL_0042: ldstr ""Y"" IL_0047: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_004c: ldloca.s V_1 IL_004e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0053: call ""void System.Console.WriteLine(string)"" IL_0058: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 93 (0x5d) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: ldloca.s V_1 IL_0022: ldloc.0 IL_0023: ldc.i4.0 IL_0024: ldnull IL_0025: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_002a: ldloca.s V_1 IL_002c: ldloc.0 IL_002d: ldc.i4.1 IL_002e: ldnull IL_002f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0034: ldloca.s V_1 IL_0036: ldloc.0 IL_0037: ldc.i4.0 IL_0038: ldstr ""X"" IL_003d: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0042: ldloca.s V_1 IL_0044: ldloc.0 IL_0045: ldc.i4.2 IL_0046: ldstr ""Y"" IL_004b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0050: ldloca.s V_1 IL_0052: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0057: call ""void System.Console.WriteLine(string)"" IL_005c: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 101 (0x65) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: brfalse.s IL_0056 IL_0022: ldloca.s V_1 IL_0024: ldloc.0 IL_0025: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_002a: brfalse.s IL_0056 IL_002c: ldloca.s V_1 IL_002e: ldloc.0 IL_002f: ldc.i4.1 IL_0030: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0035: brfalse.s IL_0056 IL_0037: ldloca.s V_1 IL_0039: ldloc.0 IL_003a: ldstr ""X"" IL_003f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_0044: brfalse.s IL_0056 IL_0046: ldloca.s V_1 IL_0048: ldloc.0 IL_0049: ldc.i4.2 IL_004a: ldstr ""Y"" IL_004f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0054: br.s IL_0057 IL_0056: ldc.i4.0 IL_0057: pop IL_0058: ldloca.s V_1 IL_005a: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005f: call ""void System.Console.WriteLine(string)"" IL_0064: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 105 (0x69) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: brfalse.s IL_005a IL_0022: ldloca.s V_1 IL_0024: ldloc.0 IL_0025: ldc.i4.0 IL_0026: ldnull IL_0027: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_002c: brfalse.s IL_005a IL_002e: ldloca.s V_1 IL_0030: ldloc.0 IL_0031: ldc.i4.1 IL_0032: ldnull IL_0033: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0038: brfalse.s IL_005a IL_003a: ldloca.s V_1 IL_003c: ldloc.0 IL_003d: ldc.i4.0 IL_003e: ldstr ""X"" IL_0043: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0048: brfalse.s IL_005a IL_004a: ldloca.s V_1 IL_004c: ldloc.0 IL_004d: ldc.i4.2 IL_004e: ldstr ""Y"" IL_0053: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0058: br.s IL_005b IL_005a: ldc.i4.0 IL_005b: pop IL_005c: ldloca.s V_1 IL_005e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0063: call ""void System.Console.WriteLine(string)"" IL_0068: ret } ", (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 98 (0x62) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_0053 IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: ldloca.s V_1 IL_0026: ldloc.0 IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_002c: ldloca.s V_1 IL_002e: ldloc.0 IL_002f: ldc.i4.1 IL_0030: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0035: ldloca.s V_1 IL_0037: ldloc.0 IL_0038: ldstr ""X"" IL_003d: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_0042: ldloca.s V_1 IL_0044: ldloc.0 IL_0045: ldc.i4.2 IL_0046: ldstr ""Y"" IL_004b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0050: ldc.i4.1 IL_0051: br.s IL_0054 IL_0053: ldc.i4.0 IL_0054: pop IL_0055: ldloca.s V_1 IL_0057: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005c: call ""void System.Console.WriteLine(string)"" IL_0061: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 105 (0x69) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_005a IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: brfalse.s IL_005a IL_0026: ldloca.s V_1 IL_0028: ldloc.0 IL_0029: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_002e: brfalse.s IL_005a IL_0030: ldloca.s V_1 IL_0032: ldloc.0 IL_0033: ldc.i4.1 IL_0034: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0039: brfalse.s IL_005a IL_003b: ldloca.s V_1 IL_003d: ldloc.0 IL_003e: ldstr ""X"" IL_0043: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_0048: brfalse.s IL_005a IL_004a: ldloca.s V_1 IL_004c: ldloc.0 IL_004d: ldc.i4.2 IL_004e: ldstr ""Y"" IL_0053: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0058: br.s IL_005b IL_005a: ldc.i4.0 IL_005b: pop IL_005c: ldloca.s V_1 IL_005e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0063: call ""void System.Console.WriteLine(string)"" IL_0068: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 102 (0x66) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_0057 IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: ldloca.s V_1 IL_0026: ldloc.0 IL_0027: ldc.i4.0 IL_0028: ldnull IL_0029: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_002e: ldloca.s V_1 IL_0030: ldloc.0 IL_0031: ldc.i4.1 IL_0032: ldnull IL_0033: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0038: ldloca.s V_1 IL_003a: ldloc.0 IL_003b: ldc.i4.0 IL_003c: ldstr ""X"" IL_0041: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0046: ldloca.s V_1 IL_0048: ldloc.0 IL_0049: ldc.i4.2 IL_004a: ldstr ""Y"" IL_004f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0054: ldc.i4.1 IL_0055: br.s IL_0058 IL_0057: ldc.i4.0 IL_0058: pop IL_0059: ldloca.s V_1 IL_005b: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0060: call ""void System.Console.WriteLine(string)"" IL_0065: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 109 (0x6d) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_005e IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: brfalse.s IL_005e IL_0026: ldloca.s V_1 IL_0028: ldloc.0 IL_0029: ldc.i4.0 IL_002a: ldnull IL_002b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0030: brfalse.s IL_005e IL_0032: ldloca.s V_1 IL_0034: ldloc.0 IL_0035: ldc.i4.1 IL_0036: ldnull IL_0037: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_003c: brfalse.s IL_005e IL_003e: ldloca.s V_1 IL_0040: ldloc.0 IL_0041: ldc.i4.0 IL_0042: ldstr ""X"" IL_0047: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_004c: brfalse.s IL_005e IL_004e: ldloca.s V_1 IL_0050: ldloc.0 IL_0051: ldc.i4.2 IL_0052: ldstr ""Y"" IL_0057: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_005c: br.s IL_005f IL_005e: ldc.i4.0 IL_005f: pop IL_0060: ldloca.s V_1 IL_0062: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0067: call ""void System.Console.WriteLine(string)"" IL_006c: ret } ", }; } [Theory] [InlineData(@"$""base{Throw()}{a = 2}""")] [InlineData(@"$""base"" + $""{Throw()}"" + $""{a = 2}""")] public void BoolReturns_ShortCircuit(string expression) { var source = @" using System; int a = 1; Console.Write(" + expression + @"); Console.WriteLine(a); string Throw() => throw new Exception();"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true, returnExpression: "false"); CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" base 1"); } [Theory] [CombinatorialData] public void BoolOutParameter_ShortCircuits(bool useBoolReturns, [CombinatorialValues(@"$""{Throw()}{a = 2}""", @"$""{Throw()}"" + $""{a = 2}""")] string expression) { var source = @" using System; int a = 1; Console.WriteLine(a); Console.WriteLine(" + expression + @"); Console.WriteLine(a); string Throw() => throw new Exception(); "; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: useBoolReturns, constructorBoolArg: true, constructorSuccessResult: false); CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" 1 1"); } [Theory] [InlineData(@"$""base{await Hole()}""")] [InlineData(@"$""base"" + $""{await Hole()}""")] public void AwaitInHoles_UsesFormat(string expression) { var source = @" using System; using System.Threading.Tasks; Console.WriteLine(" + expression + @"); Task<int> Hole() => Task.FromResult(1);"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"base1"); verifier.VerifyIL("Program.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", !expression.Contains("+") ? @" { // Code size 164 (0xa4) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_003e IL_000a: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__Hole|0_0()"" IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0014: stloc.2 IL_0015: ldloca.s V_2 IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_001c: brtrue.s IL_005a IL_001e: ldarg.0 IL_001f: ldc.i4.0 IL_0020: dup IL_0021: stloc.0 IL_0022: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0027: ldarg.0 IL_0028: ldloc.2 IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_002e: ldarg.0 IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0034: ldloca.s V_2 IL_0036: ldarg.0 IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_003c: leave.s IL_00a3 IL_003e: ldarg.0 IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_0044: stloc.2 IL_0045: ldarg.0 IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0051: ldarg.0 IL_0052: ldc.i4.m1 IL_0053: dup IL_0054: stloc.0 IL_0055: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_005a: ldloca.s V_2 IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0061: stloc.1 IL_0062: ldstr ""base{0}"" IL_0067: ldloc.1 IL_0068: box ""int"" IL_006d: call ""string string.Format(string, object)"" IL_0072: call ""void System.Console.WriteLine(string)"" IL_0077: leave.s IL_0090 } catch System.Exception { IL_0079: stloc.3 IL_007a: ldarg.0 IL_007b: ldc.i4.s -2 IL_007d: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0082: ldarg.0 IL_0083: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0088: ldloc.3 IL_0089: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_008e: leave.s IL_00a3 } IL_0090: ldarg.0 IL_0091: ldc.i4.s -2 IL_0093: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0098: ldarg.0 IL_0099: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_009e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00a3: ret } " : @" { // Code size 174 (0xae) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_003e IL_000a: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__Hole|0_0()"" IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0014: stloc.2 IL_0015: ldloca.s V_2 IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_001c: brtrue.s IL_005a IL_001e: ldarg.0 IL_001f: ldc.i4.0 IL_0020: dup IL_0021: stloc.0 IL_0022: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0027: ldarg.0 IL_0028: ldloc.2 IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_002e: ldarg.0 IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0034: ldloca.s V_2 IL_0036: ldarg.0 IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_003c: leave.s IL_00ad IL_003e: ldarg.0 IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_0044: stloc.2 IL_0045: ldarg.0 IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0051: ldarg.0 IL_0052: ldc.i4.m1 IL_0053: dup IL_0054: stloc.0 IL_0055: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_005a: ldloca.s V_2 IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0061: stloc.1 IL_0062: ldstr ""base"" IL_0067: ldstr ""{0}"" IL_006c: ldloc.1 IL_006d: box ""int"" IL_0072: call ""string string.Format(string, object)"" IL_0077: call ""string string.Concat(string, string)"" IL_007c: call ""void System.Console.WriteLine(string)"" IL_0081: leave.s IL_009a } catch System.Exception { IL_0083: stloc.3 IL_0084: ldarg.0 IL_0085: ldc.i4.s -2 IL_0087: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_008c: ldarg.0 IL_008d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0092: ldloc.3 IL_0093: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_0098: leave.s IL_00ad } IL_009a: ldarg.0 IL_009b: ldc.i4.s -2 IL_009d: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_00a2: ldarg.0 IL_00a3: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_00a8: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00ad: ret }"); } [Theory] [InlineData(@"$""base{hole}""")] [InlineData(@"$""base"" + $""{hole}""")] public void NoAwaitInHoles_UsesBuilder(string expression) { var source = @" using System; using System.Threading.Tasks; var hole = await Hole(); Console.WriteLine(" + expression + @"); Task<int> Hole() => Task.FromResult(1);"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" base value:1"); verifier.VerifyIL("Program.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 185 (0xb9) .maxstack 3 .locals init (int V_0, int V_1, //hole System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_003e IL_000a: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__Hole|0_0()"" IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0014: stloc.2 IL_0015: ldloca.s V_2 IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_001c: brtrue.s IL_005a IL_001e: ldarg.0 IL_001f: ldc.i4.0 IL_0020: dup IL_0021: stloc.0 IL_0022: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0027: ldarg.0 IL_0028: ldloc.2 IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_002e: ldarg.0 IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0034: ldloca.s V_2 IL_0036: ldarg.0 IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_003c: leave.s IL_00b8 IL_003e: ldarg.0 IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_0044: stloc.2 IL_0045: ldarg.0 IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0051: ldarg.0 IL_0052: ldc.i4.m1 IL_0053: dup IL_0054: stloc.0 IL_0055: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_005a: ldloca.s V_2 IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0061: stloc.1 IL_0062: ldc.i4.4 IL_0063: ldc.i4.1 IL_0064: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0069: stloc.3 IL_006a: ldloca.s V_3 IL_006c: ldstr ""base"" IL_0071: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0076: ldloca.s V_3 IL_0078: ldloc.1 IL_0079: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_007e: ldloca.s V_3 IL_0080: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0085: call ""void System.Console.WriteLine(string)"" IL_008a: leave.s IL_00a5 } catch System.Exception { IL_008c: stloc.s V_4 IL_008e: ldarg.0 IL_008f: ldc.i4.s -2 IL_0091: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0096: ldarg.0 IL_0097: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_009c: ldloc.s V_4 IL_009e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00a3: leave.s IL_00b8 } IL_00a5: ldarg.0 IL_00a6: ldc.i4.s -2 IL_00a8: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_00ad: ldarg.0 IL_00ae: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_00b3: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00b8: ret } "); } [Theory] [InlineData(@"$""base{hole}""")] [InlineData(@"$""base"" + $""{hole}""")] public void NoAwaitInHoles_AwaitInExpression_UsesBuilder(string expression) { var source = @" using System; using System.Threading.Tasks; var hole = 2; Test(await M(1), " + expression + @", await M(3)); void Test(int i1, string s, int i2) => Console.WriteLine(s); Task<int> M(int i) { Console.WriteLine(i); return Task.FromResult(1); }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" 1 3 base value:2"); verifier.VerifyIL("Program.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 328 (0x148) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0050 IL_000a: ldloc.0 IL_000b: ldc.i4.1 IL_000c: beq IL_00dc IL_0011: ldarg.0 IL_0012: ldc.i4.2 IL_0013: stfld ""int Program.<<Main>$>d__0.<hole>5__2"" IL_0018: ldc.i4.1 IL_0019: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__M|0_1(int)"" IL_001e: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0023: stloc.2 IL_0024: ldloca.s V_2 IL_0026: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_002b: brtrue.s IL_006c IL_002d: ldarg.0 IL_002e: ldc.i4.0 IL_002f: dup IL_0030: stloc.0 IL_0031: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0036: ldarg.0 IL_0037: ldloc.2 IL_0038: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_003d: ldarg.0 IL_003e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0043: ldloca.s V_2 IL_0045: ldarg.0 IL_0046: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_004b: leave IL_0147 IL_0050: ldarg.0 IL_0051: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_0056: stloc.2 IL_0057: ldarg.0 IL_0058: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_005d: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0063: ldarg.0 IL_0064: ldc.i4.m1 IL_0065: dup IL_0066: stloc.0 IL_0067: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_006c: ldarg.0 IL_006d: ldloca.s V_2 IL_006f: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0074: stfld ""int Program.<<Main>$>d__0.<>7__wrap2"" IL_0079: ldarg.0 IL_007a: ldc.i4.4 IL_007b: ldc.i4.1 IL_007c: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0081: stloc.3 IL_0082: ldloca.s V_3 IL_0084: ldstr ""base"" IL_0089: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_008e: ldloca.s V_3 IL_0090: ldarg.0 IL_0091: ldfld ""int Program.<<Main>$>d__0.<hole>5__2"" IL_0096: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_009b: ldloca.s V_3 IL_009d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_00a2: stfld ""string Program.<<Main>$>d__0.<>7__wrap3"" IL_00a7: ldc.i4.3 IL_00a8: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__M|0_1(int)"" IL_00ad: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_00b2: stloc.2 IL_00b3: ldloca.s V_2 IL_00b5: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_00ba: brtrue.s IL_00f8 IL_00bc: ldarg.0 IL_00bd: ldc.i4.1 IL_00be: dup IL_00bf: stloc.0 IL_00c0: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_00c5: ldarg.0 IL_00c6: ldloc.2 IL_00c7: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_00cc: ldarg.0 IL_00cd: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_00d2: ldloca.s V_2 IL_00d4: ldarg.0 IL_00d5: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_00da: leave.s IL_0147 IL_00dc: ldarg.0 IL_00dd: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_00e2: stloc.2 IL_00e3: ldarg.0 IL_00e4: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_00e9: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_00ef: ldarg.0 IL_00f0: ldc.i4.m1 IL_00f1: dup IL_00f2: stloc.0 IL_00f3: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_00f8: ldloca.s V_2 IL_00fa: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_00ff: stloc.1 IL_0100: ldarg.0 IL_0101: ldfld ""int Program.<<Main>$>d__0.<>7__wrap2"" IL_0106: ldarg.0 IL_0107: ldfld ""string Program.<<Main>$>d__0.<>7__wrap3"" IL_010c: ldloc.1 IL_010d: call ""void Program.<<Main>$>g__Test|0_0(int, string, int)"" IL_0112: ldarg.0 IL_0113: ldnull IL_0114: stfld ""string Program.<<Main>$>d__0.<>7__wrap3"" IL_0119: leave.s IL_0134 } catch System.Exception { IL_011b: stloc.s V_4 IL_011d: ldarg.0 IL_011e: ldc.i4.s -2 IL_0120: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0125: ldarg.0 IL_0126: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_012b: ldloc.s V_4 IL_012d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_0132: leave.s IL_0147 } IL_0134: ldarg.0 IL_0135: ldc.i4.s -2 IL_0137: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_013c: ldarg.0 IL_013d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0142: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_0147: ret } "); } [Theory, WorkItem(55609, "https://github.com/dotnet/roslyn/issues/55609")] [InlineData(@"$""base{hole}""")] [InlineData(@"$""base"" + $""{hole}""")] public void DynamicInHoles_UsesFormat(string expression) { var source = @" using System; using System.Threading.Tasks; dynamic hole = 1; Console.WriteLine(" + expression + @"); "; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerifyWithCSharp(new[] { source, interpolatedStringBuilder }, expectedOutput: @"base1"); verifier.VerifyIL("<top-level-statements-entry-point>", expression.Contains('+') ? @" { // Code size 34 (0x22) .maxstack 3 .locals init (object V_0) //hole IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldstr ""base"" IL_000c: ldstr ""{0}"" IL_0011: ldloc.0 IL_0012: call ""string string.Format(string, object)"" IL_0017: call ""string string.Concat(string, string)"" IL_001c: call ""void System.Console.WriteLine(string)"" IL_0021: ret } " : @" { // Code size 24 (0x18) .maxstack 2 .locals init (object V_0) //hole IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldstr ""base{0}"" IL_000c: ldloc.0 IL_000d: call ""string string.Format(string, object)"" IL_0012: call ""void System.Console.WriteLine(string)"" IL_0017: ret } "); } [Theory, WorkItem(55609, "https://github.com/dotnet/roslyn/issues/55609")] [InlineData(@"$""{hole}base""")] [InlineData(@"$""{hole}"" + $""base""")] public void DynamicInHoles_UsesFormat2(string expression) { var source = @" using System; using System.Threading.Tasks; dynamic hole = 1; Console.WriteLine(" + expression + @"); "; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerifyWithCSharp(new[] { source, interpolatedStringBuilder }, expectedOutput: @"1base"); verifier.VerifyIL("<top-level-statements-entry-point>", expression.Contains('+') ? @" { // Code size 34 (0x22) .maxstack 2 .locals init (object V_0) //hole IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldstr ""{0}"" IL_000c: ldloc.0 IL_000d: call ""string string.Format(string, object)"" IL_0012: ldstr ""base"" IL_0017: call ""string string.Concat(string, string)"" IL_001c: call ""void System.Console.WriteLine(string)"" IL_0021: ret } " : @" { // Code size 24 (0x18) .maxstack 2 .locals init (object V_0) //hole IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldstr ""{0}base"" IL_000c: ldloc.0 IL_000d: call ""string string.Format(string, object)"" IL_0012: call ""void System.Console.WriteLine(string)"" IL_0017: ret } "); } [Fact] public void ImplicitConversionsInConstructor() { var code = @" using System.Runtime.CompilerServices; CustomHandler c = $""""; [InterpolatedStringHandler] struct CustomHandler { public CustomHandler(object literalLength, object formattedCount) {} } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerAttribute }); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: box ""int"" IL_0006: ldc.i4.0 IL_0007: box ""int"" IL_000c: newobj ""CustomHandler..ctor(object, object)"" IL_0011: pop IL_0012: ret } "); } [Fact] public void MissingCreate_01() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public override string ToString() => throw null; public void Dispose() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 2 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 3 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "3").WithLocation(1, 5) ); } [Fact] public void MissingCreate_02() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength) => throw null; public override string ToString() => throw null; public void Dispose() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 2 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 3 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "3").WithLocation(1, 5) ); } [Fact] public void MissingCreate_03() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(ref int literalLength, int formattedCount) => throw null; public override string ToString() => throw null; public void Dispose() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS1620: Argument 1 must be passed with the 'ref' keyword // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadArgRef, @"$""{(object)1}""").WithArguments("1", "ref").WithLocation(1, 5) ); } [Theory] [InlineData(null)] [InlineData("public string ToStringAndClear(int literalLength) => throw null;")] [InlineData("public void ToStringAndClear() => throw null;")] [InlineData("public static string ToStringAndClear() => throw null;")] public void MissingWellKnownMethod_ToStringAndClear(string toStringAndClearMethod) { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; " + toStringAndClearMethod + @" public override string ToString() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( // (1,5): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear' // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "ToStringAndClear").WithLocation(1, 5) ); } [Fact] public void ObsoleteCreateMethod() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { [System.Obsolete(""Constructor is obsolete"", error: true)] public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; public void Dispose() => throw null; public override string ToString() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS0619: 'DefaultInterpolatedStringHandler.DefaultInterpolatedStringHandler(int, int)' is obsolete: 'Constructor is obsolete' // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.DefaultInterpolatedStringHandler(int, int)", "Constructor is obsolete").WithLocation(1, 5) ); } [Fact] public void ObsoleteAppendLiteralMethod() { var code = @"_ = $""base{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; public void Dispose() => throw null; public override string ToString() => throw null; [System.Obsolete(""AppendLiteral is obsolete"", error: true)] public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,7): error CS0619: 'DefaultInterpolatedStringHandler.AppendLiteral(string)' is obsolete: 'AppendLiteral is obsolete' // _ = $"base{(object)1}"; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "base").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "AppendLiteral is obsolete").WithLocation(1, 7) ); } [Fact] public void ObsoleteAppendFormattedMethod() { var code = @"_ = $""base{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; public void Dispose() => throw null; public override string ToString() => throw null; public void AppendLiteral(string value) => throw null; [System.Obsolete(""AppendFormatted is obsolete"", error: true)] public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,11): error CS0619: 'DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)' is obsolete: 'AppendFormatted is obsolete' // _ = $"base{(object)1}"; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "{(object)1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)", "AppendFormatted is obsolete").WithLocation(1, 11) ); } private const string UnmanagedCallersOnlyIl = @" .class public auto ansi sealed beforefieldinit System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute extends [mscorlib]System.Attribute { .custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = ( 01 00 40 00 00 00 01 00 54 02 09 49 6e 68 65 72 69 74 65 64 00 ) .field public class [mscorlib]System.Type[] CallConvs .field public string EntryPoint .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { ldarg.0 call instance void [mscorlib]System.Attribute::.ctor() ret } }"; [Fact] public void UnmanagedCallersOnlyAppendFormattedMethod() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" .class public sequential ansi sealed beforefieldinit System.Runtime.CompilerServices.DefaultInterpolatedStringHandler extends [mscorlib]System.ValueType { .custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [mscorlib]System.ObsoleteAttribute::.ctor(string, bool) = ( 01 00 52 54 79 70 65 73 20 77 69 74 68 20 65 6d 62 65 64 64 65 64 20 72 65 66 65 72 65 6e 63 65 73 20 61 72 65 20 6e 6f 74 20 73 75 70 70 6f 72 74 65 64 20 69 6e 20 74 68 69 73 20 76 65 72 73 69 6f 6e 20 6f 66 20 79 6f 75 72 20 63 6f 6d 70 69 6c 65 72 2e 01 00 00 ) .pack 0 .size 1 .method public hidebysig specialname rtspecialname instance void .ctor ( int32 literalLength, int32 formattedCount ) cil managed { ldnull throw } .method public hidebysig instance void Dispose () cil managed { ldnull throw } .method public hidebysig virtual instance string ToString () cil managed { ldnull throw } .method public hidebysig instance void AppendLiteral ( string 'value' ) cil managed { ldnull throw } .method public hidebysig instance void AppendFormatted<T> ( !!T hole, [opt] int32 'alignment', [opt] string format ) cil managed { .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) .param [2] = int32(0) .param [3] = nullref ldnull throw } } "; var comp = CreateCompilationWithIL(code, ilSource: interpolatedStringBuilder + UnmanagedCallersOnlyIl); comp.VerifyDiagnostics( // (1,7): error CS0570: 'DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)' is not supported by the language // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BindToBogus, "{(object)1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)").WithLocation(1, 7) ); } [Fact] public void UnmanagedCallersOnlyToStringMethod() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" .class public sequential ansi sealed beforefieldinit System.Runtime.CompilerServices.DefaultInterpolatedStringHandler extends [mscorlib]System.ValueType { .custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [mscorlib]System.ObsoleteAttribute::.ctor(string, bool) = ( 01 00 52 54 79 70 65 73 20 77 69 74 68 20 65 6d 62 65 64 64 65 64 20 72 65 66 65 72 65 6e 63 65 73 20 61 72 65 20 6e 6f 74 20 73 75 70 70 6f 72 74 65 64 20 69 6e 20 74 68 69 73 20 76 65 72 73 69 6f 6e 20 6f 66 20 79 6f 75 72 20 63 6f 6d 70 69 6c 65 72 2e 01 00 00 ) .pack 0 .size 1 .method public hidebysig specialname rtspecialname instance void .ctor ( int32 literalLength, int32 formattedCount ) cil managed { ldnull throw } .method public hidebysig instance string ToStringAndClear () cil managed { .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) ldnull throw } .method public hidebysig instance void AppendLiteral ( string 'value' ) cil managed { ldnull throw } .method public hidebysig instance void AppendFormatted<T> ( !!T hole, [opt] int32 'alignment', [opt] string format ) cil managed { .param [2] = int32(0) .param [3] = nullref ldnull throw } } "; var comp = CreateCompilationWithIL(code, ilSource: interpolatedStringBuilder + UnmanagedCallersOnlyIl); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( // (1,5): error CS0570: 'DefaultInterpolatedStringHandler.ToStringAndClear()' is not supported by the language // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BindToBogus, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()").WithLocation(1, 5) ); } [Theory] [InlineData(@"$""{i}{s}""")] [InlineData(@"$""{i}"" + $""{s}""")] public void UnsupportedArgumentType(string expression) { var source = @" unsafe { int* i = null; var s = new S(); _ = " + expression + @"; } ref struct S { }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: true, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, options: TestOptions.UnsafeReleaseExe, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (6,11): error CS0306: The type 'int*' may not be used as a type argument // _ = $"{i}{s}"; Diagnostic(ErrorCode.ERR_BadTypeArgument, "{i}").WithArguments("int*").WithLocation(6, 11), // (6,14): error CS0306: The type 'S' may not be used as a type argument // _ = $"{i}{s}"; Diagnostic(ErrorCode.ERR_BadTypeArgument, "{s}").WithArguments("S").WithLocation(6, 5 + expression.Length) ); } [Theory] [InlineData(@"$""{b switch { true => 1, false => null }}{(!b ? null : 2)}{default}{null}""")] [InlineData(@"$""{b switch { true => 1, false => null }}"" + $""{(!b ? null : 2)}"" + $""{default}"" + $""{null}""")] public void TargetTypedInterpolationHoles(string expression) { var source = @" bool b = true; System.Console.WriteLine(" + expression + @");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" value:1 value:2 value: value:"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 81 (0x51) .maxstack 3 .locals init (bool V_0, //b object V_1, System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_2 IL_0004: ldc.i4.0 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloc.0 IL_000c: brfalse.s IL_0017 IL_000e: ldc.i4.1 IL_000f: box ""int"" IL_0014: stloc.1 IL_0015: br.s IL_0019 IL_0017: ldnull IL_0018: stloc.1 IL_0019: ldloca.s V_2 IL_001b: ldloc.1 IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)"" IL_0021: ldloca.s V_2 IL_0023: ldloc.0 IL_0024: brfalse.s IL_002e IL_0026: ldc.i4.2 IL_0027: box ""int"" IL_002c: br.s IL_002f IL_002e: ldnull IL_002f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)"" IL_0034: ldloca.s V_2 IL_0036: ldnull IL_0037: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_003c: ldloca.s V_2 IL_003e: ldnull IL_003f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0044: ldloca.s V_2 IL_0046: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_004b: call ""void System.Console.WriteLine(string)"" IL_0050: ret } "); } [Theory] [InlineData(@"$""{(null, default)}{new()}""")] [InlineData(@"$""{(null, default)}"" + $""{new()}""")] public void TargetTypedInterpolationHoles_Errors(string expression) { var source = @"System.Console.WriteLine(" + expression + @");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,29): error CS1503: Argument 1: cannot convert from '(<null>, default)' to 'object' // System.Console.WriteLine($"{(null, default)}{new()}"); Diagnostic(ErrorCode.ERR_BadArgType, "(null, default)").WithArguments("1", "(<null>, default)", "object").WithLocation(1, 29), // (1,29): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // System.Console.WriteLine($"{(null, default)}{new()}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(null, default)").WithArguments("interpolated string handlers", "10.0").WithLocation(1, 29), // (1,46): error CS1729: 'string' does not contain a constructor that takes 0 arguments // System.Console.WriteLine($"{(null, default)}{new()}"); Diagnostic(ErrorCode.ERR_BadCtorArgCount, "new()").WithArguments("string", "0").WithLocation(1, 19 + expression.Length) ); } [Fact] public void RefTernary() { var source = @" bool b = true; int i = 1; System.Console.WriteLine($""{(!b ? ref i : ref i)}"");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"value:1"); } [Fact] public void NestedInterpolatedStrings_01() { var source = @" int i = 1; System.Console.WriteLine($""{$""{i}""}"");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"value:1"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 32 (0x20) .maxstack 3 .locals init (int V_0, //i System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.0 IL_0005: ldc.i4.1 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldloc.0 IL_000e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0013: ldloca.s V_1 IL_0015: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_001a: call ""void System.Console.WriteLine(string)"" IL_001f: ret } "); } [Theory] [InlineData(@"$""{$""{i1}""}{$""{i2}""}""")] [InlineData(@"$""{$""{i1}""}"" + $""{$""{i2}""}""")] public void NestedInterpolatedStrings_02(string expression) { var source = @" int i1 = 1; int i2 = 2; System.Console.WriteLine(" + expression + @");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" value:1 value:2"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 63 (0x3f) .maxstack 4 .locals init (int V_0, //i1 int V_1, //i2 System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.2 IL_0003: stloc.1 IL_0004: ldloca.s V_2 IL_0006: ldc.i4.0 IL_0007: ldc.i4.1 IL_0008: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000d: ldloca.s V_2 IL_000f: ldloc.0 IL_0010: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0015: ldloca.s V_2 IL_0017: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_001c: ldloca.s V_2 IL_001e: ldc.i4.0 IL_001f: ldc.i4.1 IL_0020: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0025: ldloca.s V_2 IL_0027: ldloc.1 IL_0028: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_002d: ldloca.s V_2 IL_002f: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0034: call ""string string.Concat(string, string)"" IL_0039: call ""void System.Console.WriteLine(string)"" IL_003e: ret } "); } [Fact] public void ExceptionFilter_01() { var source = @" using System; int i = 1; try { Console.WriteLine(""Starting try""); throw new MyException { Prop = i }; } // Test DefaultInterpolatedStringHandler renders specially, so we're actually comparing to ""value:Prop"" plus some whitespace catch (MyException e) when (e.ToString() == $""{i}"".Trim()) { Console.WriteLine(""Caught""); } class MyException : Exception { public int Prop { get; set; } public override string ToString() => ""value:"" + Prop.ToString(); }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" Starting try Caught"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 95 (0x5f) .maxstack 4 .locals init (int V_0, //i System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 .try { IL_0002: ldstr ""Starting try"" IL_0007: call ""void System.Console.WriteLine(string)"" IL_000c: newobj ""MyException..ctor()"" IL_0011: dup IL_0012: ldloc.0 IL_0013: callvirt ""void MyException.Prop.set"" IL_0018: throw } filter { IL_0019: isinst ""MyException"" IL_001e: dup IL_001f: brtrue.s IL_0025 IL_0021: pop IL_0022: ldc.i4.0 IL_0023: br.s IL_004f IL_0025: callvirt ""string object.ToString()"" IL_002a: ldloca.s V_1 IL_002c: ldc.i4.0 IL_002d: ldc.i4.1 IL_002e: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0033: ldloca.s V_1 IL_0035: ldloc.0 IL_0036: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_003b: ldloca.s V_1 IL_003d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0042: callvirt ""string string.Trim()"" IL_0047: call ""bool string.op_Equality(string, string)"" IL_004c: ldc.i4.0 IL_004d: cgt.un IL_004f: endfilter } // end filter { // handler IL_0051: pop IL_0052: ldstr ""Caught"" IL_0057: call ""void System.Console.WriteLine(string)"" IL_005c: leave.s IL_005e } IL_005e: ret } "); } [ConditionalFact(typeof(MonoOrCoreClrOnly), typeof(NoIOperationValidation))] public void ExceptionFilter_02() { var source = @" using System; ReadOnlySpan<char> s = new char[] { 'i' }; try { Console.WriteLine(""Starting try""); throw new MyException { Prop = s.ToString() }; } // Test DefaultInterpolatedStringHandler renders specially, so we're actually comparing to ""value:Prop"" plus some whitespace catch (MyException e) when (e.ToString() == $""{s}"".Trim()) { Console.WriteLine(""Caught""); } class MyException : Exception { public string Prop { get; set; } public override string ToString() => ""value:"" + Prop.ToString(); }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp, expectedOutput: @" Starting try Caught"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 122 (0x7a) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //s System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: newarr ""char"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 105 IL_000a: stelem.i2 IL_000b: call ""System.ReadOnlySpan<char> System.ReadOnlySpan<char>.op_Implicit(char[])"" IL_0010: stloc.0 .try { IL_0011: ldstr ""Starting try"" IL_0016: call ""void System.Console.WriteLine(string)"" IL_001b: newobj ""MyException..ctor()"" IL_0020: dup IL_0021: ldloca.s V_0 IL_0023: constrained. ""System.ReadOnlySpan<char>"" IL_0029: callvirt ""string object.ToString()"" IL_002e: callvirt ""void MyException.Prop.set"" IL_0033: throw } filter { IL_0034: isinst ""MyException"" IL_0039: dup IL_003a: brtrue.s IL_0040 IL_003c: pop IL_003d: ldc.i4.0 IL_003e: br.s IL_006a IL_0040: callvirt ""string object.ToString()"" IL_0045: ldloca.s V_1 IL_0047: ldc.i4.0 IL_0048: ldc.i4.1 IL_0049: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_004e: ldloca.s V_1 IL_0050: ldloc.0 IL_0051: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_0056: ldloca.s V_1 IL_0058: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005d: callvirt ""string string.Trim()"" IL_0062: call ""bool string.op_Equality(string, string)"" IL_0067: ldc.i4.0 IL_0068: cgt.un IL_006a: endfilter } // end filter { // handler IL_006c: pop IL_006d: ldstr ""Caught"" IL_0072: call ""void System.Console.WriteLine(string)"" IL_0077: leave.s IL_0079 } IL_0079: ret } "); } [ConditionalTheory(typeof(MonoOrCoreClrOnly), typeof(NoIOperationValidation))] [InlineData(@"$""{s}{c}""")] [InlineData(@"$""{s}"" + $""{c}""")] public void ImplicitUserDefinedConversionInHole(string expression) { var source = @" using System; S s = default; C c = new C(); Console.WriteLine(" + expression + @"); ref struct S { public static implicit operator ReadOnlySpan<char>(S s) => ""S converted""; } class C { public static implicit operator ReadOnlySpan<char>(C s) => ""C converted""; }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:S converted value:C"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 57 (0x39) .maxstack 3 .locals init (S V_0, //s C V_1, //c System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: newobj ""C..ctor()"" IL_000d: stloc.1 IL_000e: ldloca.s V_2 IL_0010: ldc.i4.0 IL_0011: ldc.i4.2 IL_0012: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0017: ldloca.s V_2 IL_0019: ldloc.0 IL_001a: call ""System.ReadOnlySpan<char> S.op_Implicit(S)"" IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_0024: ldloca.s V_2 IL_0026: ldloc.1 IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<C>(C)"" IL_002c: ldloca.s V_2 IL_002e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0033: call ""void System.Console.WriteLine(string)"" IL_0038: ret } "); } [Fact] public void ExplicitUserDefinedConversionInHole() { var source = @" using System; S s = default; Console.WriteLine($""{s}""); ref struct S { public static explicit operator ReadOnlySpan<char>(S s) => ""S converted""; } "; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (5,21): error CS0306: The type 'S' may not be used as a type argument // Console.WriteLine($"{s}"); Diagnostic(ErrorCode.ERR_BadTypeArgument, "{s}").WithArguments("S").WithLocation(5, 21) ); } [Theory] [InlineData(@"$""Text{1}""")] [InlineData(@"$""Text"" + $""{1}""")] public void ImplicitUserDefinedConversionInLiteral(string expression) { var source = @" using System; Console.WriteLine(" + expression + @"); public struct CustomStruct { public static implicit operator CustomStruct(string s) => new CustomStruct { S = s }; public string S { get; set; } public override string ToString() => ""literal:"" + S; } namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public void AppendLiteral(CustomStruct s) => _builder.AppendLine(s.ToString()); public void AppendFormatted(object o) => _builder.AppendLine(""value:"" + o.ToString()); } }"; var verifier = CompileAndVerify(source, expectedOutput: @" literal:Text value:1"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 52 (0x34) .maxstack 3 .locals init (System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.1 IL_0004: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldstr ""Text"" IL_0010: call ""CustomStruct CustomStruct.op_Implicit(string)"" IL_0015: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(CustomStruct)"" IL_001a: ldloca.s V_0 IL_001c: ldc.i4.1 IL_001d: box ""int"" IL_0022: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)"" IL_0027: ldloca.s V_0 IL_0029: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_002e: call ""void System.Console.WriteLine(string)"" IL_0033: ret } "); } [Theory] [InlineData(@"$""Text{1}""")] [InlineData(@"$""Text"" + $""{1}""")] public void ExplicitUserDefinedConversionInLiteral(string expression) { var source = @" using System; Console.WriteLine(" + expression + @"); public struct CustomStruct { public static explicit operator CustomStruct(string s) => new CustomStruct { S = s }; public string S { get; set; } public override string ToString() => ""literal:"" + S; } namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public void AppendLiteral(CustomStruct s) => _builder.AppendLine(s.ToString()); public void AppendFormatted(object o) => _builder.AppendLine(""value:"" + o.ToString()); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,21): error CS1503: Argument 1: cannot convert from 'string' to 'CustomStruct' // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_BadArgType, "Text").WithArguments("1", "string", "CustomStruct").WithLocation(4, 21) ); } [Theory] [InlineData(@"$""Text{1}""")] [InlineData(@"$""Text"" + $""{1}""")] public void InvalidBuilderReturnType(string expression) { var source = @" using System; Console.WriteLine(" + expression + @"); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public int AppendLiteral(string s) => 0; public int AppendFormatted(object o) => 0; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,21): error CS8941: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' is malformed. It does not return 'void' or 'bool'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)").WithLocation(4, 21), // (4,25): error CS8941: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' is malformed. It does not return 'void' or 'bool'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)").WithLocation(4, 15 + expression.Length) ); } [Fact] public void MissingAppendMethods() { var source = @" using System.Runtime.CompilerServices; CustomHandler c = $""Literal{1}""; [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } } "; var comp = CreateCompilation(new[] { source, InterpolatedStringHandlerAttribute }); comp.VerifyDiagnostics( // (4,21): error CS1061: 'CustomHandler' does not contain a definition for 'AppendLiteral' and no accessible extension method 'AppendLiteral' accepting a first argument of type 'CustomHandler' could be found (are you missing a using directive or an assembly reference?) // CustomHandler c = $"Literal{1}"; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Literal").WithArguments("CustomHandler", "AppendLiteral").WithLocation(4, 21), // (4,21): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. // CustomHandler c = $"Literal{1}"; Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "Literal").WithArguments("?.()").WithLocation(4, 21), // (4,28): error CS1061: 'CustomHandler' does not contain a definition for 'AppendFormatted' and no accessible extension method 'AppendFormatted' accepting a first argument of type 'CustomHandler' could be found (are you missing a using directive or an assembly reference?) // CustomHandler c = $"Literal{1}"; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "{1}").WithArguments("CustomHandler", "AppendFormatted").WithLocation(4, 28), // (4,28): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. // CustomHandler c = $"Literal{1}"; Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{1}").WithArguments("?.()").WithLocation(4, 28) ); } [Fact] public void MissingBoolType() { var handlerSource = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var handlerRef = CreateCompilation(handlerSource).EmitToImageReference(); var source = @"CustomHandler c = $""Literal{1}"";"; var comp = CreateCompilation(source, references: new[] { handlerRef }); comp.MakeTypeMissing(SpecialType.System_Boolean); comp.VerifyDiagnostics( // (1,19): error CS0518: Predefined type 'System.Boolean' is not defined or imported // CustomHandler c = $"Literal{1}"; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"$""Literal{1}""").WithArguments("System.Boolean").WithLocation(1, 19) ); } [Fact] public void MissingVoidType() { var handlerSource = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var handlerRef = CreateCompilation(handlerSource).EmitToImageReference(); var source = @" class C { public bool M() { CustomHandler c = $""Literal{1}""; return true; } } "; var comp = CreateCompilation(source, references: new[] { handlerRef }); comp.MakeTypeMissing(SpecialType.System_Void); comp.VerifyEmitDiagnostics(); } [Theory] [InlineData(@"$""Text{1}""", @"$""{1}Text""")] [InlineData(@"$""Text"" + $""{1}""", @"$""{1}"" + $""Text""")] public void MixedBuilderReturnTypes_01(string expression1, string expression2) { var source = @" using System; Console.WriteLine(" + expression1 + @"); Console.WriteLine(" + expression2 + @"); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public bool AppendLiteral(string s) => true; public void AppendFormatted(object o) { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,25): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' has inconsistent return type. Expected to return 'bool'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)", "bool").WithLocation(4, 15 + expression1.Length), // (5,24): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' has inconsistent return type. Expected to return 'void'. // Console.WriteLine($"{1}Text"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "void").WithLocation(5, 14 + expression2.Length) ); } [Theory] [InlineData(@"$""Text{1}""", @"$""{1}Text""")] [InlineData(@"$""Text"" + $""{1}""", @"$""{1}"" + $""Text""")] public void MixedBuilderReturnTypes_02(string expression1, string expression2) { var source = @" using System; Console.WriteLine(" + expression1 + @"); Console.WriteLine(" + expression2 + @"); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public void AppendLiteral(string s) { } public bool AppendFormatted(object o) => true; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,25): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' has inconsistent return type. Expected to return 'void'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)", "void").WithLocation(4, 15 + expression1.Length), // (5,24): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' has inconsistent return type. Expected to return 'bool'. // Console.WriteLine($"{1}Text"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "bool").WithLocation(5, 14 + expression2.Length) ); } [Fact] public void MixedBuilderReturnTypes_03() { var source = @" using System; Console.WriteLine($""{1}""); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public bool AppendLiteral(string s) => true; public void AppendFormatted(object o) { _builder.AppendLine(""value:"" + o.ToString()); } } }"; CompileAndVerify(source, expectedOutput: "value:1"); } [Fact] public void MixedBuilderReturnTypes_04() { var source = @" using System; using System.Text; using System.Runtime.CompilerServices; Console.WriteLine((CustomHandler)$""l""); [InterpolatedStringHandler] public class CustomHandler { private readonly StringBuilder _builder; public CustomHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public override string ToString() => _builder.ToString(); public bool AppendFormatted(object o) => true; public void AppendLiteral(string s) { _builder.AppendLine(""literal:"" + s.ToString()); } } "; CompileAndVerify(new[] { source, InterpolatedStringHandlerAttribute }, expectedOutput: "literal:l"); } private static void VerifyInterpolatedStringExpression(CSharpCompilation comp, string handlerType = "CustomHandler") { var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var descendentNodes = tree.GetRoot().DescendantNodes(); var interpolatedString = (ExpressionSyntax)descendentNodes.OfType<BinaryExpressionSyntax>() .Where(b => b.DescendantNodes().OfType<InterpolatedStringExpressionSyntax>().Any()) .FirstOrDefault() ?? descendentNodes.OfType<InterpolatedStringExpressionSyntax>().Single(); var semanticInfo = model.GetSemanticInfoSummary(interpolatedString); Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType); Assert.Equal(handlerType, semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.InterpolatedStringHandler, semanticInfo.ImplicitConversion.Kind); Assert.True(semanticInfo.ImplicitConversion.Exists); Assert.True(semanticInfo.ImplicitConversion.IsValid); Assert.True(semanticInfo.ImplicitConversion.IsInterpolatedStringHandler); Assert.Null(semanticInfo.ImplicitConversion.Method); if (interpolatedString is BinaryExpressionSyntax) { Assert.False(semanticInfo.ConstantValue.HasValue); AssertEx.Equal("System.String System.String.op_Addition(System.String left, System.String right)", semanticInfo.Symbol.ToTestDisplayString()); } // https://github.com/dotnet/roslyn/issues/54505 Assert IConversionOperation.IsImplicit when IOperation is implemented for interpolated strings. } private CompilationVerifier CompileAndVerifyOnCorrectPlatforms(CSharpCompilation compilation, string expectedOutput) => CompileAndVerify( compilation, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expectedOutput : null, verify: ExecutionConditionUtil.IsMonoOrCoreClr ? Verification.Passes : Verification.Skipped); [Theory] [CombinatorialData] public void CustomHandlerLocal([CombinatorialValues("class", "struct")] string type, bool useBoolReturns, [CombinatorialValues(@"$""Literal{1,2:f}""", @"$""Literal"" + $""{1,2:f}""")] string expression) { var code = @" CustomHandler builder = " + expression + @"; System.Console.WriteLine(builder.ToString());"; var builder = GetInterpolatedStringCustomHandlerType("CustomHandler", type, useBoolReturns); var comp = CreateCompilation(new[] { code, builder }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" literal:Literal value:1 alignment:2 format:f"); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (type, useBoolReturns) switch { (type: "struct", useBoolReturns: true) => @" { // Code size 67 (0x43) .maxstack 4 .locals init (CustomHandler V_0, //builder CustomHandler V_1) IL_0000: ldloca.s V_1 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_1 IL_000b: ldstr ""Literal"" IL_0010: call ""bool CustomHandler.AppendLiteral(string)"" IL_0015: brfalse.s IL_002c IL_0017: ldloca.s V_1 IL_0019: ldc.i4.1 IL_001a: box ""int"" IL_001f: ldc.i4.2 IL_0020: ldstr ""f"" IL_0025: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_002a: br.s IL_002d IL_002c: ldc.i4.0 IL_002d: pop IL_002e: ldloc.1 IL_002f: stloc.0 IL_0030: ldloca.s V_0 IL_0032: constrained. ""CustomHandler"" IL_0038: callvirt ""string object.ToString()"" IL_003d: call ""void System.Console.WriteLine(string)"" IL_0042: ret } ", (type: "struct", useBoolReturns: false) => @" { // Code size 61 (0x3d) .maxstack 4 .locals init (CustomHandler V_0, //builder CustomHandler V_1) IL_0000: ldloca.s V_1 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_1 IL_000b: ldstr ""Literal"" IL_0010: call ""void CustomHandler.AppendLiteral(string)"" IL_0015: ldloca.s V_1 IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: ldc.i4.2 IL_001e: ldstr ""f"" IL_0023: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0028: ldloc.1 IL_0029: stloc.0 IL_002a: ldloca.s V_0 IL_002c: constrained. ""CustomHandler"" IL_0032: callvirt ""string object.ToString()"" IL_0037: call ""void System.Console.WriteLine(string)"" IL_003c: ret } ", (type: "class", useBoolReturns: true) => @" { // Code size 55 (0x37) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""Literal"" IL_000e: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0013: brfalse.s IL_0029 IL_0015: ldloc.0 IL_0016: ldc.i4.1 IL_0017: box ""int"" IL_001c: ldc.i4.2 IL_001d: ldstr ""f"" IL_0022: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: callvirt ""string object.ToString()"" IL_0031: call ""void System.Console.WriteLine(string)"" IL_0036: ret } ", (type: "class", useBoolReturns: false) => @" { // Code size 47 (0x2f) .maxstack 5 IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldstr ""Literal"" IL_000d: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0012: dup IL_0013: ldc.i4.1 IL_0014: box ""int"" IL_0019: ldc.i4.2 IL_001a: ldstr ""f"" IL_001f: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0024: callvirt ""string object.ToString()"" IL_0029: call ""void System.Console.WriteLine(string)"" IL_002e: ret } ", _ => throw ExceptionUtilities.Unreachable }; } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void CustomHandlerMethodArgument(string expression) { var code = @" M(" + expression + @"); void M(CustomHandler b) { System.Console.WriteLine(b.ToString()); }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"<top-level-statements-entry-point>", @" { // Code size 50 (0x32) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_0031: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"($""{1,2:f}"" + $""Literal"")")] public void ExplicitHandlerCast_InCode(string expression) { var code = @"System.Console.WriteLine((CustomHandler)" + expression + @");"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); SyntaxNode syntax = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().Single(); var semanticInfo = model.GetSemanticInfoSummary(syntax); Assert.Equal("CustomHandler", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(SpecialType.System_Object, semanticInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind); syntax = ((CastExpressionSyntax)syntax).Expression; Assert.Equal(expression, syntax.ToString()); semanticInfo = model.GetSemanticInfoSummary(syntax); Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType); Assert.Equal(SpecialType.System_String, semanticInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); // https://github.com/dotnet/roslyn/issues/54505 Assert cast is explicit after IOperation is implemented var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 42 (0x2a) .maxstack 5 IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldc.i4.1 IL_0009: box ""int"" IL_000e: ldc.i4.2 IL_000f: ldstr ""f"" IL_0014: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0019: dup IL_001a: ldstr ""Literal"" IL_001f: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0024: call ""void System.Console.WriteLine(object)"" IL_0029: ret } "); } [Theory, WorkItem(55345, "https://github.com/dotnet/roslyn/issues/55345")] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void HandlerConversionPreferredOverStringForNonConstant(string expression) { var code = @" CultureInfoNormalizer.Normalize(); C.M(" + expression + @"); class C { public static void M(CustomHandler b) { System.Console.WriteLine(b.ToString()); } public static void M(string s) { System.Console.WriteLine(s); } } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular10); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"<top-level-statements-entry-point>", @" { // Code size 55 (0x37) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.7 IL_0006: ldc.i4.1 IL_0007: newobj ""CustomHandler..ctor(int, int)"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: ldc.i4.1 IL_000f: box ""int"" IL_0014: ldc.i4.2 IL_0015: ldstr ""f"" IL_001a: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001f: brfalse.s IL_002e IL_0021: ldloc.0 IL_0022: ldstr ""Literal"" IL_0027: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_002c: br.s IL_002f IL_002e: ldc.i4.0 IL_002f: pop IL_0030: ldloc.0 IL_0031: call ""void C.M(CustomHandler)"" IL_0036: ret } "); comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular9); verifier = CompileAndVerify(comp, expectedOutput: @"1.00Literal"); verifier.VerifyIL(@"<top-level-statements-entry-point>", expression.Contains('+') ? @" { // Code size 37 (0x25) .maxstack 2 IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldstr ""{0,2:f}"" IL_000a: ldc.i4.1 IL_000b: box ""int"" IL_0010: call ""string string.Format(string, object)"" IL_0015: ldstr ""Literal"" IL_001a: call ""string string.Concat(string, string)"" IL_001f: call ""void C.M(string)"" IL_0024: ret } " : @" { // Code size 27 (0x1b) .maxstack 2 IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldstr ""{0,2:f}Literal"" IL_000a: ldc.i4.1 IL_000b: box ""int"" IL_0010: call ""string string.Format(string, object)"" IL_0015: call ""void C.M(string)"" IL_001a: ret } "); } [Theory] [InlineData(@"$""{""Literal""}""")] [InlineData(@"$""{""Lit""}"" + $""{""eral""}""")] public void StringPreferredOverHandlerConversionForConstant(string expression) { var code = @" C.M(" + expression + @"); class C { public static void M(CustomHandler b) { throw null; } public static void M(string s) { System.Console.WriteLine(s); } } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); var verifier = CompileAndVerify(comp, expectedOutput: @"Literal"); verifier.VerifyIL(@"<top-level-statements-entry-point>", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldstr ""Literal"" IL_0005: call ""void C.M(string)"" IL_000a: ret } "); } [Theory] [InlineData(@"$""{1}{2}""")] [InlineData(@"$""{1}"" + $""{2}""")] public void HandlerConversionPreferredOverStringForNonConstant_AttributeConstructor(string expression) { var code = @" using System; [Attr(" + expression + @")] class Attr : Attribute { public Attr(string s) {} public Attr(CustomHandler c) {} } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); comp.VerifyDiagnostics( // (4,2): error CS0181: Attribute constructor parameter 'c' has type 'CustomHandler', which is not a valid attribute parameter type // [Attr($"{1}{2}")] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "Attr").WithArguments("c", "CustomHandler").WithLocation(4, 2) ); VerifyInterpolatedStringExpression(comp); var attr = comp.SourceAssembly.SourceModule.GlobalNamespace.GetTypeMember("Attr"); Assert.Equal("Attr..ctor(CustomHandler c)", attr.GetAttributes().Single().AttributeConstructor.ToTestDisplayString()); } [Theory] [InlineData(@"$""{""Literal""}""")] [InlineData(@"$""{""Lit""}"" + $""{""eral""}""")] public void StringPreferredOverHandlerConversionForConstant_AttributeConstructor(string expression) { var code = @" using System; [Attr(" + expression + @")] class Attr : Attribute { public Attr(string s) {} public Attr(CustomHandler c) {} } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); CompileAndVerify(comp, symbolValidator: validate, sourceSymbolValidator: validate); void validate(ModuleSymbol m) { var attr = m.GlobalNamespace.GetTypeMember("Attr"); Assert.Equal("Attr..ctor(System.String s)", attr.GetAttributes().Single().AttributeConstructor.ToTestDisplayString()); } } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void MultipleBuilderTypes(string expression) { var code = @" C.M(" + expression + @"); class C { public static void M(CustomHandler1 c) => throw null; public static void M(CustomHandler2 c) => throw null; }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler1", "struct", useBoolReturns: false), GetInterpolatedStringCustomHandlerType("CustomHandler2", "struct", useBoolReturns: false, includeOneTimeHelpers: false) }); comp.VerifyDiagnostics( // (2,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(CustomHandler1)' and 'C.M(CustomHandler2)' // C.M($""); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(CustomHandler1)", "C.M(CustomHandler2)").WithLocation(2, 3) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericOverloadResolution_01(string expression) { var code = @" using System; C.M(" + expression + @"); class C { public static void M<T>(T t) => throw null; public static void M(CustomHandler c) => Console.WriteLine(c); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 50 (0x32) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: call ""void C.M(CustomHandler)"" IL_0031: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericOverloadResolution_02(string expression) { var code = @" using System; C.M(" + expression + @"); class C { public static void M<T>(T t) where T : CustomHandler => throw null; public static void M(CustomHandler c) => Console.WriteLine(c); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 50 (0x32) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: call ""void C.M(CustomHandler)"" IL_0031: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericOverloadResolution_03(string expression) { var code = @" C.M(" + expression + @"); class C { public static void M<T>(T t) where T : CustomHandler => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); comp.VerifyDiagnostics( // (2,3): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'C.M<T>(T)'. There is no implicit reference conversion from 'string' to 'CustomHandler'. // C.M($"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M").WithArguments("C.M<T>(T)", "CustomHandler", "T", "string").WithLocation(2, 3) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericInference_01(string expression) { var code = @" C.M(" + expression + @", default(CustomHandler)); C.M(default(CustomHandler), " + expression + @"); class C { public static void M<T>(T t1, T t2) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (2,3): error CS0411: The type arguments for method 'C.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // C.M($"{1,2:f}Literal", default(CustomHandler)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, T)").WithLocation(2, 3), // (3,3): error CS0411: The type arguments for method 'C.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // C.M(default(CustomHandler), $"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, T)").WithLocation(3, 3) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericInference_02(string expression) { var code = @" using System; C.M(default(CustomHandler), () => " + expression + @"); class C { public static void M<T>(T t1, Func<T> t2) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); comp.VerifyDiagnostics( // (3,3): error CS0411: The type arguments for method 'C.M<T>(T, Func<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // C.M(default(CustomHandler), () => $"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, System.Func<T>)").WithLocation(3, 3) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericInference_03(string expression) { var code = @" using System; C.M(" + expression + @", default(CustomHandler)); class C { public static void M<T>(T t1, T t2) => Console.WriteLine(t1); } partial class CustomHandler { public static implicit operator CustomHandler(string s) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 51 (0x33) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: ldnull IL_002d: call ""void C.M<CustomHandler>(CustomHandler, CustomHandler)"" IL_0032: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericInference_04(string expression) { var code = @" using System; C.M(default(CustomHandler), () => " + expression + @"); class C { public static void M<T>(T t1, Func<T> t2) => Console.WriteLine(t2()); } partial class CustomHandler { public static implicit operator CustomHandler(string s) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("Program.<>c.<<Main>$>b__0_0()", @" { // Code size 45 (0x2d) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_01(string expression) { var code = @" using System; Func<CustomHandler> f = () => " + expression + @"; Console.WriteLine(f()); "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", @" { // Code size 45 (0x2d) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_02(string expression) { var code = @" using System; CultureInfoNormalizer.Normalize(); C.M(() => " + expression + @"); class C { public static void M(Func<string> f) => Console.WriteLine(f()); public static void M(Func<CustomHandler> f) => throw null; } "; // Interpolated string handler conversions are not considered when determining the natural type of an expression: the natural return type of this lambda is string, // so we don't even consider that there is a conversion from interpolated string expression to CustomHandler here (Sections 12.6.3.13 and 12.6.3.15 of the spec). var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); var verifier = CompileAndVerify(comp, expectedOutput: @"1.00Literal"); // No DefaultInterpolatedStringHandler was included in the compilation, so it falls back to string.Format verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", !expression.Contains('+') ? @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldstr ""{0,2:f}Literal"" IL_0005: ldc.i4.1 IL_0006: box ""int"" IL_000b: call ""string string.Format(string, object)"" IL_0010: ret } " : @" { // Code size 27 (0x1b) .maxstack 2 IL_0000: ldstr ""{0,2:f}"" IL_0005: ldc.i4.1 IL_0006: box ""int"" IL_000b: call ""string string.Format(string, object)"" IL_0010: ldstr ""Literal"" IL_0015: call ""string string.Concat(string, string)"" IL_001a: ret } "); } [Theory] [InlineData(@"$""{new S { Field = ""Field"" }}""")] [InlineData(@"$""{new S { Field = ""Field"" }}"" + $""""")] public void LambdaReturnInference_03(string expression) { // Same as 2, but using a type that isn't allowed in an interpolated string. There is an implicit conversion error on the ref struct // when converting to a string, because S cannot be a component of an interpolated string. This conversion error causes the lambda to // fail to bind as Func<string>, even though the natural return type is string, and the only successful bind is Func<CustomHandler>. var code = @" using System; C.M(() => " + expression + @"); static class C { public static void M(Func<string> f) => throw null; public static void M(Func<CustomHandler> f) => Console.WriteLine(f()); } public partial class CustomHandler { public void AppendFormatted(S value) => _builder.AppendLine(""value:"" + value.Field); } public ref struct S { public string Field { get; set; } } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"value:Field"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", @" { // Code size 35 (0x23) .maxstack 4 .locals init (S V_0) IL_0000: ldc.i4.0 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldloca.s V_0 IL_000a: initobj ""S"" IL_0010: ldloca.s V_0 IL_0012: ldstr ""Field"" IL_0017: call ""void S.Field.set"" IL_001c: ldloc.0 IL_001d: callvirt ""void CustomHandler.AppendFormatted(S)"" IL_0022: ret } "); } [Theory] [InlineData(@"$""{new S { Field = ""Field"" }}""")] [InlineData(@"$""{new S { Field = ""Field"" }}"" + $""""")] public void LambdaReturnInference_04(string expression) { // Same as 3, but with S added to DefaultInterpolatedStringHandler (which then allows the lambda to be bound as Func<string>, matching the natural return type) var code = @" using System; C.M(() => " + expression + @"); static class C { public static void M(Func<string> f) => Console.WriteLine(f()); public static void M(Func<CustomHandler> f) => throw null; } public partial class CustomHandler { public void AppendFormatted(S value) => throw null; } public ref struct S { public string Field { get; set; } } namespace System.Runtime.CompilerServices { public ref partial struct DefaultInterpolatedStringHandler { public void AppendFormatted(S value) => _builder.AppendLine(""value:"" + value.Field); } } "; string[] source = new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: false), GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: true, useBoolReturns: false) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (3,11): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // C.M(() => $"{new S { Field = "Field" }}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, expression).WithArguments("interpolated string handlers", "10.0").WithLocation(3, 11), // (3,14): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // C.M(() => $"{new S { Field = "Field" }}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, @"new S { Field = ""Field"" }").WithArguments("interpolated string handlers", "10.0").WithLocation(3, 14) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"value:Field"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", @" { // Code size 45 (0x2d) .maxstack 3 .locals init (System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_0, S V_1) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.1 IL_0004: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldloca.s V_1 IL_000d: initobj ""S"" IL_0013: ldloca.s V_1 IL_0015: ldstr ""Field"" IL_001a: call ""void S.Field.set"" IL_001f: ldloc.1 IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(S)"" IL_0025: ldloca.s V_0 IL_0027: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_002c: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_05(string expression) { var code = @" using System; C.M(b => { if (b) return default(CustomHandler); else return " + expression + @"; }); static class C { public static void M(Func<bool, string> f) => throw null; public static void M(Func<bool, CustomHandler> f) => Console.WriteLine(f(false)); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0(bool)", @" { // Code size 55 (0x37) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_000d IL_0003: ldloca.s V_0 IL_0005: initobj ""CustomHandler"" IL_000b: ldloc.0 IL_000c: ret IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_06(string expression) { // Same as 5, but with an implicit conversion from the builder type to string. This implicit conversion // means that a best common type can be inferred for all branches of the lambda expression (Section 12.6.3.15 of the spec) // and because there is a best common type, the inferred return type of the lambda is string. Since the inferred return type // has an identity conversion to the return type of Func<bool, string>, that is preferred. var code = @" using System; CultureInfoNormalizer.Normalize(); C.M(b => { if (b) return default(CustomHandler); else return " + expression + @"; }); static class C { public static void M(Func<bool, string> f) => Console.WriteLine(f(false)); public static void M(Func<bool, CustomHandler> f) => throw null; } public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0(bool)", !expression.Contains('+') ? @" { // Code size 35 (0x23) .maxstack 2 .locals init (CustomHandler V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_0012 IL_0003: ldloca.s V_0 IL_0005: initobj ""CustomHandler"" IL_000b: ldloc.0 IL_000c: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0011: ret IL_0012: ldstr ""{0,2:f}Literal"" IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: call ""string string.Format(string, object)"" IL_0022: ret } " : @" { // Code size 45 (0x2d) .maxstack 2 .locals init (CustomHandler V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_0012 IL_0003: ldloca.s V_0 IL_0005: initobj ""CustomHandler"" IL_000b: ldloc.0 IL_000c: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0011: ret IL_0012: ldstr ""{0,2:f}"" IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: call ""string string.Format(string, object)"" IL_0022: ldstr ""Literal"" IL_0027: call ""string string.Concat(string, string)"" IL_002c: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_07(string expression) { // Same as 5, but with an implicit conversion from string to the builder type. var code = @" using System; C.M(b => { if (b) return default(CustomHandler); else return " + expression + @"; }); static class C { public static void M(Func<bool, string> f) => Console.WriteLine(f(false)); public static void M(Func<bool, CustomHandler> f) => Console.WriteLine(f(false)); } public partial struct CustomHandler { public static implicit operator CustomHandler(string s) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0(bool)", @" { // Code size 55 (0x37) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_000d IL_0003: ldloca.s V_0 IL_0005: initobj ""CustomHandler"" IL_000b: ldloc.0 IL_000c: ret IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_08(string expression) { // Same as 5, but with an implicit conversion from the builder type to string and from string to the builder type. var code = @" using System; C.M(b => { if (b) return default(CustomHandler); else return " + expression + @"; }); static class C { public static void M(Func<bool, string> f) => Console.WriteLine(f(false)); public static void M(Func<bool, CustomHandler> f) => throw null; } public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; public static implicit operator CustomHandler(string c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (3,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Func<bool, string>)' and 'C.M(Func<bool, CustomHandler>)' // C.M(b => Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Func<bool, string>)", "C.M(System.Func<bool, CustomHandler>)").WithLocation(3, 3) ); } [Theory] [InlineData(@"$""{1}""")] [InlineData(@"$""{1}"" + $""{2}""")] public void LambdaInference_AmbiguousInOlderLangVersions(string expression) { var code = @" using System; C.M(param => { param = " + expression + @"; }); static class C { public static void M(Action<string> f) => throw null; public static void M(Action<CustomHandler> f) => throw null; } "; var source = new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); // This successful emit is being caused by https://github.com/dotnet/roslyn/issues/53761, along with the duplicate diagnostics in LambdaReturnInference_04 // We should not be changing binding behavior based on LangVersion. comp.VerifyEmitDiagnostics(); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (3,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Action<string>)' and 'C.M(Action<CustomHandler>)' // C.M(param => Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Action<string>)", "C.M(System.Action<CustomHandler>)").WithLocation(3, 3) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_01(string expression) { var code = @" using System; var x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 76 (0x4c) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brtrue.s IL_0038 IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: br.s IL_0041 IL_0038: ldloca.s V_0 IL_003a: initobj ""CustomHandler"" IL_0040: ldloc.0 IL_0041: box ""CustomHandler"" IL_0046: call ""void System.Console.WriteLine(object)"" IL_004b: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_02(string expression) { // Same as 01, but with a conversion from CustomHandler to string. The rules here are similar to LambdaReturnInference_06 var code = @" using System; CultureInfoNormalizer.Normalize(); var x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", !expression.Contains('+') ? @" { // Code size 56 (0x38) .maxstack 2 .locals init (CustomHandler V_0) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.0 IL_0006: box ""bool"" IL_000b: unbox.any ""bool"" IL_0010: brtrue.s IL_0024 IL_0012: ldstr ""{0,2:f}Literal"" IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: call ""string string.Format(string, object)"" IL_0022: br.s IL_0032 IL_0024: ldloca.s V_0 IL_0026: initobj ""CustomHandler"" IL_002c: ldloc.0 IL_002d: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0032: call ""void System.Console.WriteLine(string)"" IL_0037: ret } " : @" { // Code size 66 (0x42) .maxstack 2 .locals init (CustomHandler V_0) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.0 IL_0006: box ""bool"" IL_000b: unbox.any ""bool"" IL_0010: brtrue.s IL_002e IL_0012: ldstr ""{0,2:f}"" IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: call ""string string.Format(string, object)"" IL_0022: ldstr ""Literal"" IL_0027: call ""string string.Concat(string, string)"" IL_002c: br.s IL_003c IL_002e: ldloca.s V_0 IL_0030: initobj ""CustomHandler"" IL_0036: ldloc.0 IL_0037: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_003c: call ""void System.Console.WriteLine(string)"" IL_0041: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_03(string expression) { // Same as 02, but with a target-type var code = @" using System; CustomHandler x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,19): error CS0029: Cannot implicitly convert type 'string' to 'CustomHandler' // CustomHandler x = (bool)(object)false ? default(CustomHandler) : $"{1,2:f}Literal"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"(bool)(object)false ? default(CustomHandler) : " + expression).WithArguments("string", "CustomHandler").WithLocation(4, 19) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_04(string expression) { // Same 01, but with a conversion from string to CustomHandler. The rules here are similar to LambdaReturnInference_07 var code = @" using System; var x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 76 (0x4c) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brtrue.s IL_0038 IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: br.s IL_0041 IL_0038: ldloca.s V_0 IL_003a: initobj ""CustomHandler"" IL_0040: ldloc.0 IL_0041: box ""CustomHandler"" IL_0046: call ""void System.Console.WriteLine(object)"" IL_004b: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_05(string expression) { // Same 01, but with a conversion from string to CustomHandler and CustomHandler to string. var code = @" using System; var x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,9): error CS0172: Type of conditional expression cannot be determined because 'CustomHandler' and 'string' implicitly convert to one another // var x = (bool)(object)false ? default(CustomHandler) : $"{1,2:f}Literal"; Diagnostic(ErrorCode.ERR_AmbigQM, @"(bool)(object)false ? default(CustomHandler) : " + expression).WithArguments("CustomHandler", "string").WithLocation(4, 9) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_06(string expression) { // Same 05, but with a target type var code = @" using System; CustomHandler x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => c.ToString(); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 76 (0x4c) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brtrue.s IL_0038 IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: br.s IL_0041 IL_0038: ldloca.s V_0 IL_003a: initobj ""CustomHandler"" IL_0040: ldloc.0 IL_0041: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0046: call ""void System.Console.WriteLine(string)"" IL_004b: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_01(string expression) { // Switch expressions infer a best type based on _types_, not based on expressions (section 12.6.3.15 of the spec). Because this is based on types // and not on expression conversions, no best type can be found for this switch expression. var code = @" using System; var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,29): error CS8506: No best type was found for the switch expression. // var x = (bool)(object)false switch { true => default(CustomHandler), false => $"{1,2:f}Literal" }; Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(4, 29) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_02(string expression) { // Same as 01, but with a conversion from CustomHandler. This allows the switch expression to infer a best-common type, which is string. var code = @" using System; CultureInfoNormalizer.Normalize(); var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", !expression.Contains('+') ? @" { // Code size 59 (0x3b) .maxstack 2 .locals init (string V_0, CustomHandler V_1) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.0 IL_0006: box ""bool"" IL_000b: unbox.any ""bool"" IL_0010: brfalse.s IL_0023 IL_0012: ldloca.s V_1 IL_0014: initobj ""CustomHandler"" IL_001a: ldloc.1 IL_001b: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0020: stloc.0 IL_0021: br.s IL_0034 IL_0023: ldstr ""{0,2:f}Literal"" IL_0028: ldc.i4.1 IL_0029: box ""int"" IL_002e: call ""string string.Format(string, object)"" IL_0033: stloc.0 IL_0034: ldloc.0 IL_0035: call ""void System.Console.WriteLine(string)"" IL_003a: ret } " : @" { // Code size 69 (0x45) .maxstack 2 .locals init (string V_0, CustomHandler V_1) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.0 IL_0006: box ""bool"" IL_000b: unbox.any ""bool"" IL_0010: brfalse.s IL_0023 IL_0012: ldloca.s V_1 IL_0014: initobj ""CustomHandler"" IL_001a: ldloc.1 IL_001b: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0020: stloc.0 IL_0021: br.s IL_003e IL_0023: ldstr ""{0,2:f}"" IL_0028: ldc.i4.1 IL_0029: box ""int"" IL_002e: call ""string string.Format(string, object)"" IL_0033: ldstr ""Literal"" IL_0038: call ""string string.Concat(string, string)"" IL_003d: stloc.0 IL_003e: ldloc.0 IL_003f: call ""void System.Console.WriteLine(string)"" IL_0044: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_03(string expression) { // Same 02, but with a target-type. The natural type will fail to compile, so the switch will use a target type (unlike TernaryTypes_03, which fails to compile). var code = @" using System; CustomHandler x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => c.ToString(); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 79 (0x4f) .maxstack 4 .locals init (CustomHandler V_0, CustomHandler V_1) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brfalse.s IL_0019 IL_000d: ldloca.s V_1 IL_000f: initobj ""CustomHandler"" IL_0015: ldloc.1 IL_0016: stloc.0 IL_0017: br.s IL_0043 IL_0019: ldloca.s V_1 IL_001b: ldc.i4.7 IL_001c: ldc.i4.1 IL_001d: call ""CustomHandler..ctor(int, int)"" IL_0022: ldloca.s V_1 IL_0024: ldc.i4.1 IL_0025: box ""int"" IL_002a: ldc.i4.2 IL_002b: ldstr ""f"" IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldstr ""Literal"" IL_003c: call ""void CustomHandler.AppendLiteral(string)"" IL_0041: ldloc.1 IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0049: call ""void System.Console.WriteLine(string)"" IL_004e: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_04(string expression) { // Same as 01, but with a conversion to CustomHandler. This allows the switch expression to infer a best-common type, which is CustomHandler. var code = @" using System; var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 79 (0x4f) .maxstack 4 .locals init (CustomHandler V_0, CustomHandler V_1) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brfalse.s IL_0019 IL_000d: ldloca.s V_1 IL_000f: initobj ""CustomHandler"" IL_0015: ldloc.1 IL_0016: stloc.0 IL_0017: br.s IL_0043 IL_0019: ldloca.s V_1 IL_001b: ldc.i4.7 IL_001c: ldc.i4.1 IL_001d: call ""CustomHandler..ctor(int, int)"" IL_0022: ldloca.s V_1 IL_0024: ldc.i4.1 IL_0025: box ""int"" IL_002a: ldc.i4.2 IL_002b: ldstr ""f"" IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldstr ""Literal"" IL_003c: call ""void CustomHandler.AppendLiteral(string)"" IL_0041: ldloc.1 IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: box ""CustomHandler"" IL_0049: call ""void System.Console.WriteLine(object)"" IL_004e: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_05(string expression) { // Same as 01, but with conversions in both directions. No best common type can be found. var code = @" using System; var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,29): error CS8506: No best type was found for the switch expression. // var x = (bool)(object)false switch { true => default(CustomHandler), false => $"{1,2:f}Literal" }; Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(4, 29) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_06(string expression) { // Same as 05, but with a target type. var code = @" using System; CustomHandler x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => c.ToString(); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 79 (0x4f) .maxstack 4 .locals init (CustomHandler V_0, CustomHandler V_1) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brfalse.s IL_0019 IL_000d: ldloca.s V_1 IL_000f: initobj ""CustomHandler"" IL_0015: ldloc.1 IL_0016: stloc.0 IL_0017: br.s IL_0043 IL_0019: ldloca.s V_1 IL_001b: ldc.i4.7 IL_001c: ldc.i4.1 IL_001d: call ""CustomHandler..ctor(int, int)"" IL_0022: ldloca.s V_1 IL_0024: ldc.i4.1 IL_0025: box ""int"" IL_002a: ldc.i4.2 IL_002b: ldstr ""f"" IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldstr ""Literal"" IL_003c: call ""void CustomHandler.AppendLiteral(string)"" IL_0041: ldloc.1 IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0049: call ""void System.Console.WriteLine(string)"" IL_004e: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void PassAsRefWithoutKeyword_01(string expression) { var code = @" M(" + expression + @"); void M(ref CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 48 (0x30) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_0 IL_002a: call ""void Program.<<Main>$>g__M|0_0(ref CustomHandler)"" IL_002f: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void PassAsRefWithoutKeyword_02(string expression) { var code = @" M(" + expression + @"); M(ref " + expression + @"); void M(ref CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (2,3): error CS1620: Argument 1 must be passed with the 'ref' keyword // M($"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("1", "ref").WithLocation(2, 3), // (3,7): error CS1510: A ref or out value must be an assignable variable // M(ref $"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_RefLvalueExpected, expression).WithLocation(3, 7) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void PassAsRefWithoutKeyword_03(string expression) { var code = @" M(" + expression + @"); void M(in CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 45 (0x2d) .maxstack 5 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldc.i4.1 IL_0009: box ""int"" IL_000e: ldc.i4.2 IL_000f: ldstr ""f"" IL_0014: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0019: dup IL_001a: ldstr ""Literal"" IL_001f: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0024: stloc.0 IL_0025: ldloca.s V_0 IL_0027: call ""void Program.<<Main>$>g__M|0_0(in CustomHandler)"" IL_002c: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void PassAsRefWithoutKeyword_04(string expression) { var code = @" M(" + expression + @"); void M(in CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 48 (0x30) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_0 IL_002a: call ""void Program.<<Main>$>g__M|0_0(in CustomHandler)"" IL_002f: ret } "); } [Theory] [CombinatorialData] public void RefOverloadResolution_Struct([CombinatorialValues("in", "ref")] string refKind, [CombinatorialValues(@"$""{1,2:f}Literal""", @"$""{1,2:f}"" + $""Literal""")] string expression) { var code = @" C.M(" + expression + @"); class C { public static void M(CustomHandler c) => System.Console.WriteLine(c); public static void M(" + refKind + @" CustomHandler c) => throw null; }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloc.0 IL_0029: call ""void C.M(CustomHandler)"" IL_002e: ret } "); } [Theory] [CombinatorialData] public void RefOverloadResolution_Class([CombinatorialValues("in", "ref")] string refKind, [CombinatorialValues(@"$""{1,2:f}Literal""", @"$""{1,2:f}"" + $""Literal""")] string expression) { var code = @" C.M(" + expression + @"); class C { public static void M(CustomHandler c) => System.Console.WriteLine(c); public static void M(" + refKind + @" CustomHandler c) => System.Console.WriteLine(c); }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloc.0 IL_0029: call ""void C.M(CustomHandler)"" IL_002e: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void RefOverloadResolution_MultipleBuilderTypes(string expression) { var code = @" C.M(" + expression + @"); class C { public static void M(CustomHandler1 c) => System.Console.WriteLine(c); public static void M(ref CustomHandler2 c) => throw null; }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler1", "struct", useBoolReturns: false), GetInterpolatedStringCustomHandlerType("CustomHandler2", "struct", useBoolReturns: false, includeOneTimeHelpers: false) }); VerifyInterpolatedStringExpression(comp, "CustomHandler1"); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (CustomHandler1 V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler1..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler1.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler1.AppendLiteral(string)"" IL_0028: ldloc.0 IL_0029: call ""void C.M(CustomHandler1)"" IL_002e: ret } "); } private const string InterpolatedStringHandlerAttributesVB = @" Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Class Or AttributeTargets.Struct, AllowMultiple:=False, Inherited:=False)> Public NotInheritable Class InterpolatedStringHandlerAttribute Inherits Attribute End Class <AttributeUsage(AttributeTargets.Parameter, AllowMultiple:=False, Inherited:=False)> Public NotInheritable Class InterpolatedStringHandlerArgumentAttribute Inherits Attribute Public Sub New(argument As String) Arguments = { argument } End Sub Public Sub New(ParamArray arguments() as String) Me.Arguments = arguments End Sub Public ReadOnly Property Arguments As String() End Class End Namespace "; [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_NonHandlerType(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); class C { public static void M([InterpolatedStringHandlerArgumentAttribute] string s) {} } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute }); comp.VerifyDiagnostics( // (8,27): error CS8946: 'string' is not an interpolated string handler type. // public static void M([InterpolatedStringHandlerArgumentAttribute] string s) {} Diagnostic(ErrorCode.ERR_TypeIsNotAnInterpolatedStringHandlerType, "InterpolatedStringHandlerArgumentAttribute").WithArguments("string").WithLocation(8, 27) ); var sParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", sParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(sParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(sParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NonHandlerType_Metadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i as Integer, <InterpolatedStringHandlerArgument(""i"")> c As String) End Sub End Class "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); // Note: there is no compilation error here because the natural type of a string is still string, and // we just bind to that method without checking the handler attribute. var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics(); var sParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", sParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(sParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(sParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_InvalidArgument(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); class C { public static void M([InterpolatedStringHandlerArgumentAttribute(1)] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (8,70): error CS1503: Argument 1: cannot convert from 'int' to 'string' // public static void M([InterpolatedStringHandlerArgumentAttribute(1)] CustomHandler c) {} Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "string").WithLocation(8, 70) ); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_01(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""NonExistant"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 5), // (8,27): error CS8945: 'NonExistant' is not a valid parameter name from 'C.M(CustomHandler)'. // public static void M([InterpolatedStringHandlerArgumentAttribute("NonExistant")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant"")").WithArguments("NonExistant", "C.M(CustomHandler)").WithLocation(8, 27) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_01_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(""NonExistant"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_02(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(1, " + expression + @"); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"", ""NonExistant"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8945: 'NonExistant' is not a valid parameter name from 'C.M(int, CustomHandler)'. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("i", "NonExistant")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""i"", ""NonExistant"")").WithArguments("NonExistant", "C.M(int, CustomHandler)").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_02_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(""i"", ""NonExistant"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_03(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(1, " + expression + @"); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8945: 'NonExistant1' is not a valid parameter name from 'C.M(int, CustomHandler)'. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("NonExistant1", "NonExistant2")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")").WithArguments("NonExistant1", "C.M(int, CustomHandler)").WithLocation(8, 34), // (8,34): error CS8945: 'NonExistant2' is not a valid parameter name from 'C.M(int, CustomHandler)'. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("NonExistant1", "NonExistant2")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")").WithArguments("NonExistant2", "C.M(int, CustomHandler)").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_03_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(""NonExistant1"", ""NonExistant2"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_ReferenceSelf(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(1, " + expression + @"); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""c"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8948: InterpolatedStringHandlerArgumentAttribute arguments cannot refer to the parameter the attribute is used on. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("c")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_CannotUseSelfAsInterpolatedStringHandlerArgument, @"InterpolatedStringHandlerArgumentAttribute(""c"")").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_ReferencesSelf_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(""c"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(1, " + expression + @"); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(new string[] { null })] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8943: null is not a valid parameter name. To get access to the receiver of an instance method, use the empty string as the parameter name. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(new string[] { null })] CustomHandler c) {} Diagnostic(ErrorCode.ERR_NullInvalidInterpolatedStringHandlerArgumentName, "InterpolatedStringHandlerArgumentAttribute(new string[] { null })").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_01() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument({ Nothing })> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_02() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument({ Nothing, ""i"" })> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_03() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(CStr(Nothing))> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnStaticMethod(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); class C { public static void M([InterpolatedStringHandlerArgumentAttribute("""")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 5), // (8,27): error CS8944: 'C.M(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // public static void M([InterpolatedStringHandlerArgumentAttribute("")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute("""")").WithArguments("C.M(CustomHandler)").WithLocation(8, 27) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"{""""}")] [InlineData(@"""""")] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnStaticMethod_FromMetadata(string arg) { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(" + arg + @")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnConstructor(string expression) { var code = @" using System.Runtime.CompilerServices; _ = new C(" + expression + @"); class C { public C([InterpolatedStringHandlerArgumentAttribute("""")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,11): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // _ = new C($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 11), // (8,15): error CS8944: 'C.C(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // public C([InterpolatedStringHandlerArgumentAttribute("")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute("""")").WithArguments("C.C(CustomHandler)").WithLocation(8, 15) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod(".ctor").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"{""""}")] [InlineData(@"""""")] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnConstructor_FromMetadata(string arg) { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Sub New(<InterpolatedStringHandlerArgument(" + arg + @")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"_ = new C($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,11): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // _ = new C($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 11), // (1,11): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // _ = new C($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 11), // (1,11): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // _ = new C($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 11) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod(".ctor").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerAttributeArgumentError_SubstitutedTypeSymbol(string expression) { var code = @" using System.Runtime.CompilerServices; C<CustomHandler>.M(" + expression + @"); public class C<T> { public static void M([InterpolatedStringHandlerArgumentAttribute] T t) { } } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler }); comp.VerifyDiagnostics( // (4,20): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 20), // (8,27): error CS8946: 'T' is not an interpolated string handler type. // public static void M([InterpolatedStringHandlerArgumentAttribute] T t) { } Diagnostic(ErrorCode.ERR_TypeIsNotAnInterpolatedStringHandlerType, "InterpolatedStringHandlerArgumentAttribute").WithArguments("T").WithLocation(8, 27) ); var c = comp.SourceModule.GlobalNamespace.GetTypeMember("C"); var handler = comp.SourceModule.GlobalNamespace.GetTypeMember("CustomHandler"); var substitutedC = c.WithTypeArguments(ImmutableArray.Create(TypeWithAnnotations.Create(handler))); var cParam = substitutedC.GetMethod("M").Parameters.Single(); Assert.IsType<SubstitutedParameterSymbol>(cParam); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_SubstitutedTypeSymbol_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C(Of T) Public Shared Sub M(<InterpolatedStringHandlerArgument()> c As T) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C<CustomHandler>.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,20): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 20), // (1,20): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 20), // (1,20): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 20) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C`1").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttributeWarn_ParameterAfterHandler([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""text""", @"$""text"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; public class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, int i) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var goodCode = @" int i = 10; C.M(i: i, c: " + expression + @"); "; var comp = CreateCompilation(new[] { code, goodCode, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate, expectedOutput: @" i:10 literal:text "); verifier.VerifyDiagnostics( // (6,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller // to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, int i) => Console.WriteLine(c.ToString()); Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(6, 27) ); verifyIL(verifier); var badCode = @"C.M(" + expression + @", 1);"; comp = CreateCompilation(new[] { code, badCode, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (1,10): error CS8950: Parameter 'i' is an argument to the interpolated string handler conversion on parameter 'c', but is specified after the interpolated string constant. Reorder the arguments to move 'i' before 'c'. // C.M($"", 1); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString, "1").WithArguments("i", "c").WithLocation(1, 7 + expression.Length), // (6,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller // to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, int i) => Console.WriteLine(c.ToString()); Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(6, 27) ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.First(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(1, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } void verifyIL(CompilationVerifier verifier) { verifier.VerifyIL("<top-level-statements-entry-point>", extraConstructorArg == "" ? @" { // Code size 36 (0x24) .maxstack 4 .locals init (int V_0, int V_1, CustomHandler V_2) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: stloc.1 IL_0005: ldloca.s V_2 IL_0007: ldc.i4.4 IL_0008: ldc.i4.0 IL_0009: ldloc.0 IL_000a: call ""CustomHandler..ctor(int, int, int)"" IL_000f: ldloca.s V_2 IL_0011: ldstr ""text"" IL_0016: call ""bool CustomHandler.AppendLiteral(string)"" IL_001b: pop IL_001c: ldloc.2 IL_001d: ldloc.1 IL_001e: call ""void C.M(CustomHandler, int)"" IL_0023: ret } " : @" { // Code size 43 (0x2b) .maxstack 4 .locals init (int V_0, int V_1, CustomHandler V_2, bool V_3) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: stloc.1 IL_0005: ldc.i4.4 IL_0006: ldc.i4.0 IL_0007: ldloc.0 IL_0008: ldloca.s V_3 IL_000a: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000f: stloc.2 IL_0010: ldloc.3 IL_0011: brfalse.s IL_0021 IL_0013: ldloca.s V_2 IL_0015: ldstr ""text"" IL_001a: call ""bool CustomHandler.AppendLiteral(string)"" IL_001f: br.s IL_0022 IL_0021: ldc.i4.0 IL_0022: pop IL_0023: ldloc.2 IL_0024: ldloc.1 IL_0025: call ""void C.M(CustomHandler, int)"" IL_002a: ret } "); } } [Fact] public void InterpolatedStringHandlerArgumentAttributeWarn_ParameterAfterHandler_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(""i"")> c As CustomHandler, i As Integer) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation("", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics(); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.First(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(1, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_OptionalNotSpecifiedAtCallsite(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); public class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, int i = 0) { } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) { } } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler }); comp.VerifyDiagnostics( // (4,5): error CS8951: Parameter 'i' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter 'c'. Specify the value of 'i' before 'c'. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, expression).WithArguments("i", "c").WithLocation(4, 5), // (8,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, params int[] i) { } Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(8, 27) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_ParamsNotSpecifiedAtCallsite(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); public class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, params int[] i) { } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int[] i) : this(literalLength, formattedCount) { } } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler }); comp.VerifyDiagnostics( // (4,5): error CS8951: Parameter 'i' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter 'c'. Specify the value of 'i' before 'c'. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, expression).WithArguments("i", "c").WithLocation(4, 5), // (8,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, params int[] i) { } Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(8, 27) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MissingConstructor(string expression) { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate).VerifyDiagnostics(); CreateCompilation(@"C.M(1, " + expression + @");", new[] { comp.ToMetadataReference() }).VerifyDiagnostics( // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "3").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 4 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "4").WithLocation(1, 8) ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_InaccessibleConstructor_01(string expression) { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {} } public partial struct CustomHandler { private CustomHandler(int literalLength, int formattedCount, int i) : this() {} static void InCustomHandler() { C.M(1, " + expression + @"); } } "; var executableCode = @"C.M(1, " + expression + @");"; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (1,8): error CS0122: 'CustomHandler.CustomHandler(int, int, int)' is inaccessible due to its protection level // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadAccess, expression).WithArguments("CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 8) ); var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. CompileAndVerify(dependency, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics(); comp = CreateCompilation(executableCode, new[] { dependency.EmitToImageReference() }); comp.VerifyDiagnostics( // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 4 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "4").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "3").WithLocation(1, 8) ); comp = CreateCompilation(executableCode, new[] { dependency.ToMetadataReference() }); comp.VerifyDiagnostics( // (1,8): error CS0122: 'CustomHandler.CustomHandler(int, int, int)' is inaccessible due to its protection level // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadAccess, expression).WithArguments("CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 8) ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } } private void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes(string mRef, string customHandlerRef, string expression, params DiagnosticDescription[] expectedDiagnostics) { var code = @" using System.Runtime.CompilerServices; int i = 0; C.M(" + mRef + @" i, " + expression + @"); public class C { public static void M(" + mRef + @" int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) { " + (mRef == "out" ? "i = 0;" : "") + @" } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, " + customHandlerRef + @" int i) : this() { " + (customHandlerRef == "out" ? "i = 0;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics(expectedDiagnostics); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefNone(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "", expression, // (5,9): error CS1615: Argument 3 may not be passed with the 'ref' keyword // C.M(ref i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "ref").WithLocation(5, 9)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefOut(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "out", expression, // (5,9): error CS1620: Argument 3 must be passed with the 'out' keyword // C.M(ref i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 9)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefIn(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "in", expression, // (5,9): error CS1615: Argument 3 may not be passed with the 'ref' keyword // C.M(ref i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "ref").WithLocation(5, 9)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InNone(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "", expression, // (5,8): error CS1615: Argument 3 may not be passed with the 'in' keyword // C.M(in i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "in").WithLocation(5, 8)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InOut(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "out", expression, // (5,8): error CS1620: Argument 3 must be passed with the 'out' keyword // C.M(in i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 8)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InRef(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "ref", expression, // (5,8): error CS1620: Argument 3 must be passed with the 'ref' keyword // C.M(in i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 8)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_OutNone(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("out", "", expression, // (5,9): error CS1615: Argument 3 may not be passed with the 'out' keyword // C.M(out i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "out").WithLocation(5, 9)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_OutRef(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("out", "ref", expression, // (5,9): error CS1620: Argument 3 must be passed with the 'ref' keyword // C.M(out i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 9)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_NoneRef(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("", "ref", expression, // (5,6): error CS1620: Argument 3 must be passed with the 'ref' keyword // C.M( i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 6)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_NoneOut(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("", "out", expression, // (5,6): error CS1620: Argument 3 must be passed with the 'out' keyword // C.M( i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 6)); } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_MismatchedType([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression) { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {} } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s" + extraConstructorArg + @") : this() { " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var executableCode = @"C.M(1, " + expression + @");"; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var expectedDiagnostics = extraConstructorArg == "" ? new DiagnosticDescription[] { // (1,5): error CS1503: Argument 3: cannot convert from 'int' to 'string' // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("3", "int", "string").WithLocation(1, 5) } : new DiagnosticDescription[] { // (1,5): error CS1503: Argument 3: cannot convert from 'int' to 'string' // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("3", "int", "string").WithLocation(1, 5), // (1,8): error CS7036: There is no argument given that corresponds to the required formal parameter 'success' of 'CustomHandler.CustomHandler(int, int, string, out bool)' // C.M(1, $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("success", "CustomHandler.CustomHandler(int, int, string, out bool)").WithLocation(1, 8) }; var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics(expectedDiagnostics); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); CompileAndVerify(dependency, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics(); foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() }) { comp = CreateCompilation(executableCode, new[] { d }); comp.VerifyDiagnostics(expectedDiagnostics); } static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_SingleArg([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""2""", @"$""2"" + $""""")] string expression) { var code = @" using System.Runtime.CompilerServices; public class C { public static string M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) => c.ToString(); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var executableCode = @" using System; int i = 10; Console.WriteLine(C.M(i, " + expression + @")); "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i:10 literal:2"); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() }) { verifier = CompileAndVerify(executableCode, new[] { d }, expectedOutput: @" i:10 literal:2"); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); } static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } static void verifyIL(string extraConstructorArg, CompilationVerifier verifier) { verifier.VerifyIL("<top-level-statements-entry-point>", extraConstructorArg == "" ? @" { // Code size 39 (0x27) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldloca.s V_1 IL_0006: ldc.i4.1 IL_0007: ldc.i4.0 IL_0008: ldloc.0 IL_0009: call ""CustomHandler..ctor(int, int, int)"" IL_000e: ldloca.s V_1 IL_0010: ldstr ""2"" IL_0015: call ""bool CustomHandler.AppendLiteral(string)"" IL_001a: pop IL_001b: ldloc.1 IL_001c: call ""string C.M(int, CustomHandler)"" IL_0021: call ""void System.Console.WriteLine(string)"" IL_0026: ret } " : @" { // Code size 46 (0x2e) .maxstack 5 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldc.i4.1 IL_0005: ldc.i4.0 IL_0006: ldloc.0 IL_0007: ldloca.s V_2 IL_0009: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000e: stloc.1 IL_000f: ldloc.2 IL_0010: brfalse.s IL_0020 IL_0012: ldloca.s V_1 IL_0014: ldstr ""2"" IL_0019: call ""bool CustomHandler.AppendLiteral(string)"" IL_001e: br.s IL_0021 IL_0020: ldc.i4.0 IL_0021: pop IL_0022: ldloc.1 IL_0023: call ""string C.M(int, CustomHandler)"" IL_0028: call ""void System.Console.WriteLine(string)"" IL_002d: ret } "); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_MultipleArgs([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var executableCode = @" int i = 10; string s = ""arg""; C.M(i, s, " + expression + @"); "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); string expectedOutput = @" i:10 s:arg literal:literal "; var verifier = base.CompileAndVerify((Compilation)comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() }) { verifier = CompileAndVerify(executableCode, new[] { d }, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); } static void validator(ModuleSymbol verifier) { var cParam = verifier.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } static void verifyIL(string extraConstructorArg, CompilationVerifier verifier) { verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 44 (0x2c) .maxstack 7 .locals init (string V_0, //s int V_1, string V_2, CustomHandler V_3) IL_0000: ldc.i4.s 10 IL_0002: ldstr ""arg"" IL_0007: stloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldloc.0 IL_000b: stloc.2 IL_000c: ldloc.2 IL_000d: ldloca.s V_3 IL_000f: ldc.i4.7 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: ldloc.2 IL_0013: call ""CustomHandler..ctor(int, int, int, string)"" IL_0018: ldloca.s V_3 IL_001a: ldstr ""literal"" IL_001f: call ""bool CustomHandler.AppendLiteral(string)"" IL_0024: pop IL_0025: ldloc.3 IL_0026: call ""void C.M(int, string, CustomHandler)"" IL_002b: ret } " : @" { // Code size 52 (0x34) .maxstack 7 .locals init (string V_0, //s int V_1, string V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.s 10 IL_0002: ldstr ""arg"" IL_0007: stloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldloc.0 IL_000b: stloc.2 IL_000c: ldloc.2 IL_000d: ldc.i4.7 IL_000e: ldc.i4.0 IL_000f: ldloc.1 IL_0010: ldloc.2 IL_0011: ldloca.s V_4 IL_0013: newobj ""CustomHandler..ctor(int, int, int, string, out bool)"" IL_0018: stloc.3 IL_0019: ldloc.s V_4 IL_001b: brfalse.s IL_002b IL_001d: ldloca.s V_3 IL_001f: ldstr ""literal"" IL_0024: call ""bool CustomHandler.AppendLiteral(string)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.0 IL_002c: pop IL_002d: ldloc.3 IL_002e: call ""void C.M(int, string, CustomHandler)"" IL_0033: ret } "); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_RefKindsMatch([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; int i = 1; string s = null; object o; C.M(i, ref s, out o, " + expression + @"); Console.WriteLine(s); Console.WriteLine(o); public class C { public static void M(in int i, ref string s, out object o, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"", ""o"")] CustomHandler c) { Console.WriteLine(s); o = ""o in M""; s = ""s in M""; Console.Write(c.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, in int i, ref string s, out object o" + extraConstructorArg + @") : this(literalLength, formattedCount) { o = null; s = ""s in constructor""; _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" s in constructor i:1 literal:literal s in M o in M "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 67 (0x43) .maxstack 8 .locals init (int V_0, //i string V_1, //s object V_2, //o int& V_3, string& V_4, object& V_5, CustomHandler V_6) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldnull IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: stloc.3 IL_0007: ldloc.3 IL_0008: ldloca.s V_1 IL_000a: stloc.s V_4 IL_000c: ldloc.s V_4 IL_000e: ldloca.s V_2 IL_0010: stloc.s V_5 IL_0012: ldloc.s V_5 IL_0014: ldc.i4.7 IL_0015: ldc.i4.0 IL_0016: ldloc.3 IL_0017: ldloc.s V_4 IL_0019: ldloc.s V_5 IL_001b: newobj ""CustomHandler..ctor(int, int, in int, ref string, out object)"" IL_0020: stloc.s V_6 IL_0022: ldloca.s V_6 IL_0024: ldstr ""literal"" IL_0029: call ""bool CustomHandler.AppendLiteral(string)"" IL_002e: pop IL_002f: ldloc.s V_6 IL_0031: call ""void C.M(in int, ref string, out object, CustomHandler)"" IL_0036: ldloc.1 IL_0037: call ""void System.Console.WriteLine(string)"" IL_003c: ldloc.2 IL_003d: call ""void System.Console.WriteLine(object)"" IL_0042: ret } " : @" { // Code size 76 (0x4c) .maxstack 9 .locals init (int V_0, //i string V_1, //s object V_2, //o int& V_3, string& V_4, object& V_5, CustomHandler V_6, bool V_7) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldnull IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: stloc.3 IL_0007: ldloc.3 IL_0008: ldloca.s V_1 IL_000a: stloc.s V_4 IL_000c: ldloc.s V_4 IL_000e: ldloca.s V_2 IL_0010: stloc.s V_5 IL_0012: ldloc.s V_5 IL_0014: ldc.i4.7 IL_0015: ldc.i4.0 IL_0016: ldloc.3 IL_0017: ldloc.s V_4 IL_0019: ldloc.s V_5 IL_001b: ldloca.s V_7 IL_001d: newobj ""CustomHandler..ctor(int, int, in int, ref string, out object, out bool)"" IL_0022: stloc.s V_6 IL_0024: ldloc.s V_7 IL_0026: brfalse.s IL_0036 IL_0028: ldloca.s V_6 IL_002a: ldstr ""literal"" IL_002f: call ""bool CustomHandler.AppendLiteral(string)"" IL_0034: br.s IL_0037 IL_0036: ldc.i4.0 IL_0037: pop IL_0038: ldloc.s V_6 IL_003a: call ""void C.M(in int, ref string, out object, CustomHandler)"" IL_003f: ldloc.1 IL_0040: call ""void System.Console.WriteLine(string)"" IL_0045: ldloc.2 IL_0046: call ""void System.Console.WriteLine(object)"" IL_004b: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(3).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1, 2 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_ReorderedAttributePositions([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(GetInt(), GetString(), " + expression + @"); int GetInt() { Console.WriteLine(""GetInt""); return 10; } string GetString() { Console.WriteLine(""GetString""); return ""str""; } public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""s"", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""s:"" + s); _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" GetInt GetString s:str i:10 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 45 (0x2d) .maxstack 7 .locals init (string V_0, int V_1, CustomHandler V_2) IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string Program.<<Main>$>g__GetString|0_1()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: ldloca.s V_2 IL_0010: ldc.i4.7 IL_0011: ldc.i4.0 IL_0012: ldloc.0 IL_0013: ldloc.1 IL_0014: call ""CustomHandler..ctor(int, int, string, int)"" IL_0019: ldloca.s V_2 IL_001b: ldstr ""literal"" IL_0020: call ""bool CustomHandler.AppendLiteral(string)"" IL_0025: pop IL_0026: ldloc.2 IL_0027: call ""void C.M(int, string, CustomHandler)"" IL_002c: ret } " : @" { // Code size 52 (0x34) .maxstack 7 .locals init (string V_0, int V_1, CustomHandler V_2, bool V_3) IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string Program.<<Main>$>g__GetString|0_1()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: ldc.i4.7 IL_000f: ldc.i4.0 IL_0010: ldloc.0 IL_0011: ldloc.1 IL_0012: ldloca.s V_3 IL_0014: newobj ""CustomHandler..ctor(int, int, string, int, out bool)"" IL_0019: stloc.2 IL_001a: ldloc.3 IL_001b: brfalse.s IL_002b IL_001d: ldloca.s V_2 IL_001f: ldstr ""literal"" IL_0024: call ""bool CustomHandler.AppendLiteral(string)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.0 IL_002c: pop IL_002d: ldloc.2 IL_002e: call ""void C.M(int, string, CustomHandler)"" IL_0033: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 1, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_ParametersReordered([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; GetC().M(s: GetString(), i: GetInt(), c: " + expression + @"); C GetC() { Console.WriteLine(""GetC""); return new C { Field = 5 }; } int GetInt() { Console.WriteLine(""GetInt""); return 10; } string GetString() { Console.WriteLine(""GetString""); return ""str""; } public class C { public int Field; public void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""s"", """", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s, C c, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""s:"" + s); _builder.AppendLine(""c.Field:"" + c.Field.ToString()); _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" GetC GetString GetInt s:str c.Field:5 i:10 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 56 (0x38) .maxstack 9 .locals init (string V_0, C V_1, int V_2, string V_3, CustomHandler V_4) IL_0000: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string Program.<<Main>$>g__GetString|0_2()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: stloc.3 IL_000f: call ""int Program.<<Main>$>g__GetInt|0_1()"" IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: ldloc.3 IL_0017: ldloca.s V_4 IL_0019: ldc.i4.7 IL_001a: ldc.i4.0 IL_001b: ldloc.0 IL_001c: ldloc.1 IL_001d: ldloc.2 IL_001e: call ""CustomHandler..ctor(int, int, string, C, int)"" IL_0023: ldloca.s V_4 IL_0025: ldstr ""literal"" IL_002a: call ""bool CustomHandler.AppendLiteral(string)"" IL_002f: pop IL_0030: ldloc.s V_4 IL_0032: callvirt ""void C.M(int, string, CustomHandler)"" IL_0037: ret } " : @" { // Code size 65 (0x41) .maxstack 9 .locals init (string V_0, C V_1, int V_2, string V_3, CustomHandler V_4, bool V_5) IL_0000: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string Program.<<Main>$>g__GetString|0_2()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: stloc.3 IL_000f: call ""int Program.<<Main>$>g__GetInt|0_1()"" IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: ldloc.3 IL_0017: ldc.i4.7 IL_0018: ldc.i4.0 IL_0019: ldloc.0 IL_001a: ldloc.1 IL_001b: ldloc.2 IL_001c: ldloca.s V_5 IL_001e: newobj ""CustomHandler..ctor(int, int, string, C, int, out bool)"" IL_0023: stloc.s V_4 IL_0025: ldloc.s V_5 IL_0027: brfalse.s IL_0037 IL_0029: ldloca.s V_4 IL_002b: ldstr ""literal"" IL_0030: call ""bool CustomHandler.AppendLiteral(string)"" IL_0035: br.s IL_0038 IL_0037: ldc.i4.0 IL_0038: pop IL_0039: ldloc.s V_4 IL_003b: callvirt ""void C.M(int, string, CustomHandler)"" IL_0040: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 1, -1, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_Duplicated([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(GetInt(), """", " + expression + @"); int GetInt() { Console.WriteLine(""GetInt""); return 10; } public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, int i2" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""i2:"" + i2.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" GetInt i1:10 i2:10 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 43 (0x2b) .maxstack 7 .locals init (int V_0, CustomHandler V_1) IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr """" IL_000c: ldloca.s V_1 IL_000e: ldc.i4.7 IL_000f: ldc.i4.0 IL_0010: ldloc.0 IL_0011: ldloc.0 IL_0012: call ""CustomHandler..ctor(int, int, int, int)"" IL_0017: ldloca.s V_1 IL_0019: ldstr ""literal"" IL_001e: call ""bool CustomHandler.AppendLiteral(string)"" IL_0023: pop IL_0024: ldloc.1 IL_0025: call ""void C.M(int, string, CustomHandler)"" IL_002a: ret } " : @" { // Code size 50 (0x32) .maxstack 7 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr """" IL_000c: ldc.i4.7 IL_000d: ldc.i4.0 IL_000e: ldloc.0 IL_000f: ldloc.0 IL_0010: ldloca.s V_2 IL_0012: newobj ""CustomHandler..ctor(int, int, int, int, out bool)"" IL_0017: stloc.1 IL_0018: ldloc.2 IL_0019: brfalse.s IL_0029 IL_001b: ldloca.s V_1 IL_001d: ldstr ""literal"" IL_0022: call ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.1 IL_002c: call ""void C.M(int, string, CustomHandler)"" IL_0031: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_EmptyWithMatchingConstructor([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, """", " + expression + @"); public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute()] CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount" + extraConstructorArg + @") { " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: "CustomHandler").VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 19 (0x13) .maxstack 4 IL_0000: ldc.i4.1 IL_0001: ldstr """" IL_0006: ldc.i4.0 IL_0007: ldc.i4.0 IL_0008: newobj ""CustomHandler..ctor(int, int)"" IL_000d: call ""void C.M(int, string, CustomHandler)"" IL_0012: ret } " : @" { // Code size 21 (0x15) .maxstack 5 .locals init (bool V_0) IL_0000: ldc.i4.1 IL_0001: ldstr """" IL_0006: ldc.i4.0 IL_0007: ldc.i4.0 IL_0008: ldloca.s V_0 IL_000a: newobj ""CustomHandler..ctor(int, int, out bool)"" IL_000f: call ""void C.M(int, string, CustomHandler)"" IL_0014: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_EmptyWithoutMatchingConstructor([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression) { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute()] CustomHandler c) { } } [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") { " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. CompileAndVerify(comp, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics(); CreateCompilation(@"C.M(1, """", " + expression + @");", new[] { comp.EmitToImageReference() }).VerifyDiagnostics( (extraConstructorArg == "") ? new[] { // (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'CustomHandler.CustomHandler(int, int, int)' // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("i", "CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 12), // (1,12): error CS1615: Argument 3 may not be passed with the 'out' keyword // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, expression).WithArguments("3", "out").WithLocation(1, 12) } : new[] { // (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'CustomHandler.CustomHandler(int, int, int, out bool)' // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("i", "CustomHandler.CustomHandler(int, int, int, out bool)").WithLocation(1, 12), // (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'success' of 'CustomHandler.CustomHandler(int, int, int, out bool)' // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("success", "CustomHandler.CustomHandler(int, int, int, out bool)").WithLocation(1, 12) } ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_OnIndexerRvalue([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; var c = new C(); Console.WriteLine(c[10, ""str"", " + expression + @"]); public class C { public string this[int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c] { get => c.ToString(); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i1:10 s:str literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 52 (0x34) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldloca.s V_2 IL_0012: ldc.i4.7 IL_0013: ldc.i4.0 IL_0014: ldloc.0 IL_0015: ldloc.1 IL_0016: call ""CustomHandler..ctor(int, int, int, string)"" IL_001b: ldloca.s V_2 IL_001d: ldstr ""literal"" IL_0022: call ""bool CustomHandler.AppendLiteral(string)"" IL_0027: pop IL_0028: ldloc.2 IL_0029: callvirt ""string C.this[int, string, CustomHandler].get"" IL_002e: call ""void System.Console.WriteLine(string)"" IL_0033: ret } " : @" { // Code size 59 (0x3b) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2, bool V_3) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldc.i4.7 IL_0011: ldc.i4.0 IL_0012: ldloc.0 IL_0013: ldloc.1 IL_0014: ldloca.s V_3 IL_0016: newobj ""CustomHandler..ctor(int, int, int, string, out bool)"" IL_001b: stloc.2 IL_001c: ldloc.3 IL_001d: brfalse.s IL_002d IL_001f: ldloca.s V_2 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: pop IL_002f: ldloc.2 IL_0030: callvirt ""string C.this[int, string, CustomHandler].get"" IL_0035: call ""void System.Console.WriteLine(string)"" IL_003a: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetIndexer<PropertySymbol>("Item").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_OnIndexerLvalue([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; var c = new C(); c[10, ""str"", " + expression + @"] = """"; public class C { public string this[int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c] { set => Console.WriteLine(c.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i1:10 s:str literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 52 (0x34) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldloca.s V_2 IL_0012: ldc.i4.7 IL_0013: ldc.i4.0 IL_0014: ldloc.0 IL_0015: ldloc.1 IL_0016: call ""CustomHandler..ctor(int, int, int, string)"" IL_001b: ldloca.s V_2 IL_001d: ldstr ""literal"" IL_0022: call ""bool CustomHandler.AppendLiteral(string)"" IL_0027: pop IL_0028: ldloc.2 IL_0029: ldstr """" IL_002e: callvirt ""void C.this[int, string, CustomHandler].set"" IL_0033: ret } " : @" { // Code size 59 (0x3b) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2, bool V_3) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldc.i4.7 IL_0011: ldc.i4.0 IL_0012: ldloc.0 IL_0013: ldloc.1 IL_0014: ldloca.s V_3 IL_0016: newobj ""CustomHandler..ctor(int, int, int, string, out bool)"" IL_001b: stloc.2 IL_001c: ldloc.3 IL_001d: brfalse.s IL_002d IL_001f: ldloca.s V_2 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: pop IL_002f: ldloc.2 IL_0030: ldstr """" IL_0035: callvirt ""void C.this[int, string, CustomHandler].set"" IL_003a: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetIndexer<PropertySymbol>("Item").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_ThisParameter([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; (new C(5)).M((int)10, ""str"", " + expression + @"); public class C { public int Prop { get; } public C(int i) => Prop = i; public void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", """", ""s"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, C c, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""c.Prop:"" + c.Prop.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i1:10 c.Prop:5 s:str literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 51 (0x33) .maxstack 9 .locals init (int V_0, C V_1, string V_2, CustomHandler V_3) IL_0000: ldc.i4.5 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.1 IL_0007: ldloc.1 IL_0008: ldc.i4.s 10 IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: ldstr ""str"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldloca.s V_3 IL_0015: ldc.i4.7 IL_0016: ldc.i4.0 IL_0017: ldloc.0 IL_0018: ldloc.1 IL_0019: ldloc.2 IL_001a: call ""CustomHandler..ctor(int, int, int, C, string)"" IL_001f: ldloca.s V_3 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: pop IL_002c: ldloc.3 IL_002d: callvirt ""void C.M(int, string, CustomHandler)"" IL_0032: ret } " : @" { // Code size 59 (0x3b) .maxstack 9 .locals init (int V_0, C V_1, string V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.5 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.1 IL_0007: ldloc.1 IL_0008: ldc.i4.s 10 IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: ldstr ""str"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldc.i4.7 IL_0014: ldc.i4.0 IL_0015: ldloc.0 IL_0016: ldloc.1 IL_0017: ldloc.2 IL_0018: ldloca.s V_4 IL_001a: newobj ""CustomHandler..ctor(int, int, int, C, string, out bool)"" IL_001f: stloc.3 IL_0020: ldloc.s V_4 IL_0022: brfalse.s IL_0032 IL_0024: ldloca.s V_3 IL_0026: ldstr ""literal"" IL_002b: call ""bool CustomHandler.AppendLiteral(string)"" IL_0030: br.s IL_0033 IL_0032: ldc.i4.0 IL_0033: pop IL_0034: ldloc.3 IL_0035: callvirt ""void C.M(int, string, CustomHandler)"" IL_003a: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, -1, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [InlineData(@"$""literal""")] [InlineData(@"$"""" + $""literal""")] public void InterpolatedStringHandlerArgumentAttribute_OnConstructor(string expression) { var code = @" using System; using System.Runtime.CompilerServices; _ = new C(5, " + expression + @"); public class C { public int Prop { get; } public C(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")]CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" i:5 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 34 (0x22) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.5 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldloca.s V_1 IL_0005: ldc.i4.7 IL_0006: ldc.i4.0 IL_0007: ldloc.0 IL_0008: call ""CustomHandler..ctor(int, int, int)"" IL_000d: ldloca.s V_1 IL_000f: ldstr ""literal"" IL_0014: call ""bool CustomHandler.AppendLiteral(string)"" IL_0019: pop IL_001a: ldloc.1 IL_001b: newobj ""C..ctor(int, CustomHandler)"" IL_0020: pop IL_0021: ret } "); } [Theory] [CombinatorialData] public void RefReturningMethodAsReceiver_Success([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C c = new C(1); GetC(ref c).M(" + expression + @"); Console.WriteLine(c.I); ref C GetC(ref C c) { Console.WriteLine(""GetC""); return ref c; } public class C { public int I; public C(int i) { I = i; } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref C c" + extraConstructorArg + @") : this(literalLength, formattedCount) { c = new C(2); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, verify: ExecutionConditionUtil.IsWindowsDesktop ? Verification.Skipped : Verification.Passes, expectedOutput: @" GetC literal:literal 2 "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 57 (0x39) .maxstack 4 .locals init (C V_0, //c C& V_1, CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: call ""ref C Program.<<Main>$>g__GetC|0_0(ref C)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldind.ref IL_0011: ldc.i4.7 IL_0012: ldc.i4.0 IL_0013: ldloc.1 IL_0014: newobj ""CustomHandler..ctor(int, int, ref C)"" IL_0019: stloc.2 IL_001a: ldloca.s V_2 IL_001c: ldstr ""literal"" IL_0021: call ""bool CustomHandler.AppendLiteral(string)"" IL_0026: pop IL_0027: ldloc.2 IL_0028: callvirt ""void C.M(CustomHandler)"" IL_002d: ldloc.0 IL_002e: ldfld ""int C.I"" IL_0033: call ""void System.Console.WriteLine(int)"" IL_0038: ret } " : @" { // Code size 65 (0x41) .maxstack 5 .locals init (C V_0, //c C& V_1, CustomHandler V_2, bool V_3) IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: call ""ref C Program.<<Main>$>g__GetC|0_0(ref C)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldind.ref IL_0011: ldc.i4.7 IL_0012: ldc.i4.0 IL_0013: ldloc.1 IL_0014: ldloca.s V_3 IL_0016: newobj ""CustomHandler..ctor(int, int, ref C, out bool)"" IL_001b: stloc.2 IL_001c: ldloc.3 IL_001d: brfalse.s IL_002d IL_001f: ldloca.s V_2 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: pop IL_002f: ldloc.2 IL_0030: callvirt ""void C.M(CustomHandler)"" IL_0035: ldloc.0 IL_0036: ldfld ""int C.I"" IL_003b: call ""void System.Console.WriteLine(int)"" IL_0040: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { -1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void RefReturningMethodAsReceiver_Success_StructReceiver([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C c = new C(1); GetC(ref c).M(" + expression + @"); Console.WriteLine(c.I); ref C GetC(ref C c) { Console.WriteLine(""GetC""); return ref c; } public struct C { public int I; public C(int i) { I = i; } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref C c" + extraConstructorArg + @") : this(literalLength, formattedCount) { c = new C(2); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, verify: ExecutionConditionUtil.IsWindowsDesktop ? Verification.Skipped : Verification.Passes, expectedOutput: @" GetC literal:literal 2 "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 57 (0x39) .maxstack 4 .locals init (C V_0, //c C& V_1, CustomHandler V_2) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: call ""C..ctor(int)"" IL_0008: ldloca.s V_0 IL_000a: call ""ref C Program.<<Main>$>g__GetC|0_0(ref C)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.0 IL_0013: ldloc.1 IL_0014: newobj ""CustomHandler..ctor(int, int, ref C)"" IL_0019: stloc.2 IL_001a: ldloca.s V_2 IL_001c: ldstr ""literal"" IL_0021: call ""bool CustomHandler.AppendLiteral(string)"" IL_0026: pop IL_0027: ldloc.2 IL_0028: call ""void C.M(CustomHandler)"" IL_002d: ldloc.0 IL_002e: ldfld ""int C.I"" IL_0033: call ""void System.Console.WriteLine(int)"" IL_0038: ret } " : @" { // Code size 65 (0x41) .maxstack 5 .locals init (C V_0, //c C& V_1, CustomHandler V_2, bool V_3) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: call ""C..ctor(int)"" IL_0008: ldloca.s V_0 IL_000a: call ""ref C Program.<<Main>$>g__GetC|0_0(ref C)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.0 IL_0013: ldloc.1 IL_0014: ldloca.s V_3 IL_0016: newobj ""CustomHandler..ctor(int, int, ref C, out bool)"" IL_001b: stloc.2 IL_001c: ldloc.3 IL_001d: brfalse.s IL_002d IL_001f: ldloca.s V_2 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: pop IL_002f: ldloc.2 IL_0030: call ""void C.M(CustomHandler)"" IL_0035: ldloc.0 IL_0036: ldfld ""int C.I"" IL_003b: call ""void System.Console.WriteLine(int)"" IL_0040: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { -1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void RefReturningMethodAsReceiver_MismatchedRefness_01([CombinatorialValues("ref readonly", "")] string refness, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System.Runtime.CompilerServices; C c = new C(1); GetC().M(" + expression + @"); " + refness + @" C GetC() => throw null; public class C { public C(int i) { } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) { } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref C c) : this(literalLength, formattedCount) { } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (5,10): error CS1620: Argument 3 must be passed with the 'ref' keyword // GetC().M($"literal"); Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("3", "ref").WithLocation(5, 10) ); } [Theory] [CombinatorialData] public void RefReturningMethodAsReceiver_MismatchedRefness_02([CombinatorialValues("in", "")] string refness, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System.Runtime.CompilerServices; C c = new C(1); GetC(ref c).M(" + expression + @"); ref C GetC(ref C c) => ref c; public class C { public C(int i) { } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) { } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount," + refness + @" C c) : this(literalLength, formattedCount) { } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (5,15): error CS1615: Argument 3 may not be passed with the 'ref' keyword // GetC(ref c).M($"literal"); Diagnostic(ErrorCode.ERR_BadArgExtraRef, expression).WithArguments("3", "ref").WithLocation(5, 15) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void StructReceiver_Rvalue(string expression) { var code = @" using System; using System.Runtime.CompilerServices; S s1 = new S { I = 1 }; S s2 = new S { I = 2 }; s1.M(s2, " + expression + @"); public struct S { public int I; public void M(S s2, [InterpolatedStringHandlerArgument("""", ""s2"")]CustomHandler handler) { Console.WriteLine(""s1.I:"" + this.I.ToString()); Console.WriteLine(""s2.I:"" + s2.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, S s1, S s2) : this(literalLength, formattedCount) { s1.I = 3; s2.I = 4; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" s1.I:1 s2.I:2"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 56 (0x38) .maxstack 6 .locals init (S V_0, //s2 S V_1, S V_2) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: stfld ""int S.I"" IL_0010: ldloc.1 IL_0011: ldloca.s V_1 IL_0013: initobj ""S"" IL_0019: ldloca.s V_1 IL_001b: ldc.i4.2 IL_001c: stfld ""int S.I"" IL_0021: ldloc.1 IL_0022: stloc.0 IL_0023: stloc.1 IL_0024: ldloca.s V_1 IL_0026: ldloc.0 IL_0027: stloc.2 IL_0028: ldloc.2 IL_0029: ldc.i4.0 IL_002a: ldc.i4.0 IL_002b: ldloc.1 IL_002c: ldloc.2 IL_002d: newobj ""CustomHandler..ctor(int, int, S, S)"" IL_0032: call ""void S.M(S, CustomHandler)"" IL_0037: ret } "); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void StructReceiver_Lvalue(string expression) { var code = @" using System; using System.Runtime.CompilerServices; S s1 = new S { I = 1 }; S s2 = new S { I = 2 }; s1.M(ref s2, " + expression + @"); public struct S { public int I; public void M(ref S s2, [InterpolatedStringHandlerArgument("""", ""s2"")]CustomHandler handler) { Console.WriteLine(""s1.I:"" + this.I.ToString()); Console.WriteLine(""s2.I:"" + s2.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref S s1, ref S s2) : this(literalLength, formattedCount) { s1.I = 3; s2.I = 4; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (8,14): error CS1620: Argument 3 must be passed with the 'ref' keyword // s1.M(ref s2, $""); Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("3", "ref").WithLocation(8, 14) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void StructParameter_ByVal(string expression) { var code = @" using System; using System.Runtime.CompilerServices; S s = new S { I = 1 }; S.M(s, " + expression + @"); public struct S { public int I; public static void M(S s, [InterpolatedStringHandlerArgument(""s"")]CustomHandler handler) { Console.WriteLine(""s.I:"" + s.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, S s) : this(literalLength, formattedCount) { s.I = 2; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @"s.I:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 33 (0x21) .maxstack 4 .locals init (S V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloca.s V_0 IL_000a: ldc.i4.1 IL_000b: stfld ""int S.I"" IL_0010: ldloc.0 IL_0011: stloc.0 IL_0012: ldloc.0 IL_0013: ldc.i4.0 IL_0014: ldc.i4.0 IL_0015: ldloc.0 IL_0016: newobj ""CustomHandler..ctor(int, int, S)"" IL_001b: call ""void S.M(S, CustomHandler)"" IL_0020: ret } "); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void StructParameter_ByRef(string expression) { var code = @" using System; using System.Runtime.CompilerServices; S s = new S { I = 1 }; S.M(ref s, " + expression + @"); public struct S { public int I; public static void M(ref S s, [InterpolatedStringHandlerArgument(""s"")]CustomHandler handler) { Console.WriteLine(""s.I:"" + s.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref S s) : this(literalLength, formattedCount) { s.I = 2; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @"s.I:2"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 36 (0x24) .maxstack 4 .locals init (S V_0, //s S V_1, S& V_2) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: stfld ""int S.I"" IL_0010: ldloc.1 IL_0011: stloc.0 IL_0012: ldloca.s V_0 IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: ldc.i4.0 IL_0017: ldc.i4.0 IL_0018: ldloc.2 IL_0019: newobj ""CustomHandler..ctor(int, int, ref S)"" IL_001e: call ""void S.M(ref S, CustomHandler)"" IL_0023: ret } "); } [Theory] [CombinatorialData] public void SideEffects(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal""", @"$"""" + $""literal""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; GetReceiver().M( GetArg(""Unrelated parameter 1""), GetArg(""Second value""), GetArg(""Unrelated parameter 2""), GetArg(""First value""), " + expression + @", GetArg(""Unrelated parameter 4"")); C GetReceiver() { Console.WriteLine(""GetReceiver""); return new C() { Prop = ""Prop"" }; } string GetArg(string s) { Console.WriteLine(s); return s; } public class C { public string Prop { get; set; } public void M(string param1, string param2, string param3, string param4, [InterpolatedStringHandlerArgument(""param4"", """", ""param2"")] CustomHandler c, string param6) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s1, C c, string s2" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""s1:"" + s1); _builder.AppendLine(""c.Prop:"" + c.Prop); _builder.AppendLine(""s2:"" + s2); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns); var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }, expectedOutput: @" GetReceiver Unrelated parameter 1 Second value Unrelated parameter 2 First value Handler constructor Unrelated parameter 4 s1:First value c.Prop:Prop s2:Second value literal:literal "); verifier.VerifyDiagnostics(); } [Theory] [InlineData(@"$""literal""")] [InlineData(@"$""literal"" + $""""")] public void InterpolatedStringHandlerArgumentsAttribute_ConversionFromArgumentType(string expression) { var code = @" using System; using System.Globalization; using System.Runtime.CompilerServices; int i = 1; C.M(i, " + expression + @"); public class C { public static implicit operator C(int i) => throw null; public static implicit operator C(double d) { Console.WriteLine(d.ToString(""G"", CultureInfo.InvariantCulture)); return new C(); } public override string ToString() => ""C""; public static void M(double d, [InterpolatedStringHandlerArgument(""d"")] CustomHandler handler) => Console.WriteLine(handler.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount) { } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" 1 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 39 (0x27) .maxstack 5 .locals init (double V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: conv.r8 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldloca.s V_1 IL_0006: ldc.i4.7 IL_0007: ldc.i4.0 IL_0008: ldloc.0 IL_0009: call ""C C.op_Implicit(double)"" IL_000e: call ""CustomHandler..ctor(int, int, C)"" IL_0013: ldloca.s V_1 IL_0015: ldstr ""literal"" IL_001a: call ""bool CustomHandler.AppendLiteral(string)"" IL_001f: pop IL_0020: ldloc.1 IL_0021: call ""void C.M(double, CustomHandler)"" IL_0026: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_Indexer_01(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal{i}""", @"$""literal"" + $""{i}""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; int i = 3; GetC()[GetInt(1), " + expression + @"] += GetInt(2); static C GetC() { Console.WriteLine(""GetC""); return new C() { Prop = 2 }; } static int GetInt(int i) { Console.WriteLine(""GetInt"" + i.ToString()); return 1; } public class C { public int Prop { get; set; } public int this[int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c] { get { Console.WriteLine(""Indexer getter""); return 0; } set { Console.WriteLine(""Indexer setter""); Console.WriteLine(c.ToString()); } } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""arg1:"" + arg1); _builder.AppendLine(""C.Prop:"" + c.Prop.ToString()); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" GetC GetInt1 Handler constructor Indexer getter GetInt2 Indexer setter arg1:1 C.Prop:2 literal:literal value:3 alignment:0 format: "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 85 (0x55) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, CustomHandler V_5) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: stloc.3 IL_0011: ldloca.s V_5 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_5 IL_001e: ldstr ""literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_5 IL_002a: ldloc.0 IL_002b: box ""int"" IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0037: ldloc.s V_5 IL_0039: stloc.s V_4 IL_003b: ldloc.2 IL_003c: ldloc.3 IL_003d: ldloc.s V_4 IL_003f: ldloc.2 IL_0040: ldloc.3 IL_0041: ldloc.s V_4 IL_0043: callvirt ""int C.this[int, CustomHandler].get"" IL_0048: ldc.i4.2 IL_0049: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_004e: add IL_004f: callvirt ""void C.this[int, CustomHandler].set"" IL_0054: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 96 (0x60) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, CustomHandler V_5, bool V_6) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: stloc.3 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_6 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.s V_5 IL_001e: ldloc.s V_6 IL_0020: brfalse.s IL_0040 IL_0022: ldloca.s V_5 IL_0024: ldstr ""literal"" IL_0029: call ""void CustomHandler.AppendLiteral(string)"" IL_002e: ldloca.s V_5 IL_0030: ldloc.0 IL_0031: box ""int"" IL_0036: ldc.i4.0 IL_0037: ldnull IL_0038: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_003d: ldc.i4.1 IL_003e: br.s IL_0041 IL_0040: ldc.i4.0 IL_0041: pop IL_0042: ldloc.s V_5 IL_0044: stloc.s V_4 IL_0046: ldloc.2 IL_0047: ldloc.3 IL_0048: ldloc.s V_4 IL_004a: ldloc.2 IL_004b: ldloc.3 IL_004c: ldloc.s V_4 IL_004e: callvirt ""int C.this[int, CustomHandler].get"" IL_0053: ldc.i4.2 IL_0054: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0059: add IL_005a: callvirt ""void C.this[int, CustomHandler].set"" IL_005f: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 91 (0x5b) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, CustomHandler V_5) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: stloc.3 IL_0011: ldloca.s V_5 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_5 IL_001e: ldstr ""literal"" IL_0023: call ""bool CustomHandler.AppendLiteral(string)"" IL_0028: brfalse.s IL_003b IL_002a: ldloca.s V_5 IL_002c: ldloc.0 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.s V_5 IL_003f: stloc.s V_4 IL_0041: ldloc.2 IL_0042: ldloc.3 IL_0043: ldloc.s V_4 IL_0045: ldloc.2 IL_0046: ldloc.3 IL_0047: ldloc.s V_4 IL_0049: callvirt ""int C.this[int, CustomHandler].get"" IL_004e: ldc.i4.2 IL_004f: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0054: add IL_0055: callvirt ""void C.this[int, CustomHandler].set"" IL_005a: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 97 (0x61) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, CustomHandler V_5, bool V_6) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: stloc.3 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_6 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.s V_5 IL_001e: ldloc.s V_6 IL_0020: brfalse.s IL_0041 IL_0022: ldloca.s V_5 IL_0024: ldstr ""literal"" IL_0029: call ""bool CustomHandler.AppendLiteral(string)"" IL_002e: brfalse.s IL_0041 IL_0030: ldloca.s V_5 IL_0032: ldloc.0 IL_0033: box ""int"" IL_0038: ldc.i4.0 IL_0039: ldnull IL_003a: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_003f: br.s IL_0042 IL_0041: ldc.i4.0 IL_0042: pop IL_0043: ldloc.s V_5 IL_0045: stloc.s V_4 IL_0047: ldloc.2 IL_0048: ldloc.3 IL_0049: ldloc.s V_4 IL_004b: ldloc.2 IL_004c: ldloc.3 IL_004d: ldloc.s V_4 IL_004f: callvirt ""int C.this[int, CustomHandler].get"" IL_0054: ldc.i4.2 IL_0055: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_005a: add IL_005b: callvirt ""void C.this[int, CustomHandler].set"" IL_0060: ret } ", }; } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_Indexer_02(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal{i}""", @"$""literal"" + $""{i}""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; int i = 3; GetC()[GetInt(1), " + expression + @"] += GetInt(2); static C GetC() { Console.WriteLine(""GetC""); return new C() { Prop = 2 }; } static int GetInt(int i) { Console.WriteLine(""GetInt"" + i.ToString()); return 1; } public class C { private int field; public int Prop { get; set; } public ref int this[int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c] { get { Console.WriteLine(""Indexer getter""); Console.WriteLine(c.ToString()); return ref field; } } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""arg1:"" + arg1); _builder.AppendLine(""C.Prop:"" + c.Prop.ToString()); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" GetC GetInt1 Handler constructor Indexer getter arg1:1 C.Prop:2 literal:literal value:3 alignment:0 format: GetInt2 "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 72 (0x48) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_3 IL_002a: ldloc.0 IL_002b: box ""int"" IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0037: ldloc.3 IL_0038: callvirt ""ref int C.this[int, CustomHandler].get"" IL_003d: dup IL_003e: ldind.i4 IL_003f: ldc.i4.2 IL_0040: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0045: add IL_0046: stind.i4 IL_0047: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 82 (0x52) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_4 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.3 IL_001d: ldloc.s V_4 IL_001f: brfalse.s IL_003f IL_0021: ldloca.s V_3 IL_0023: ldstr ""literal"" IL_0028: call ""void CustomHandler.AppendLiteral(string)"" IL_002d: ldloca.s V_3 IL_002f: ldloc.0 IL_0030: box ""int"" IL_0035: ldc.i4.0 IL_0036: ldnull IL_0037: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_003c: ldc.i4.1 IL_003d: br.s IL_0040 IL_003f: ldc.i4.0 IL_0040: pop IL_0041: ldloc.3 IL_0042: callvirt ""ref int C.this[int, CustomHandler].get"" IL_0047: dup IL_0048: ldind.i4 IL_0049: ldc.i4.2 IL_004a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_004f: add IL_0050: stind.i4 IL_0051: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 78 (0x4e) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""bool CustomHandler.AppendLiteral(string)"" IL_0028: brfalse.s IL_003b IL_002a: ldloca.s V_3 IL_002c: ldloc.0 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.3 IL_003e: callvirt ""ref int C.this[int, CustomHandler].get"" IL_0043: dup IL_0044: ldind.i4 IL_0045: ldc.i4.2 IL_0046: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_004b: add IL_004c: stind.i4 IL_004d: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 83 (0x53) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_4 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.3 IL_001d: ldloc.s V_4 IL_001f: brfalse.s IL_0040 IL_0021: ldloca.s V_3 IL_0023: ldstr ""literal"" IL_0028: call ""bool CustomHandler.AppendLiteral(string)"" IL_002d: brfalse.s IL_0040 IL_002f: ldloca.s V_3 IL_0031: ldloc.0 IL_0032: box ""int"" IL_0037: ldc.i4.0 IL_0038: ldnull IL_0039: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_003e: br.s IL_0041 IL_0040: ldc.i4.0 IL_0041: pop IL_0042: ldloc.3 IL_0043: callvirt ""ref int C.this[int, CustomHandler].get"" IL_0048: dup IL_0049: ldind.i4 IL_004a: ldc.i4.2 IL_004b: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0050: add IL_0051: stind.i4 IL_0052: ret } ", }; } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_RefReturningMethod(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal{i}""", @"$""literal"" + $""{i}""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; int i = 3; GetC().M(GetInt(1), " + expression + @") += GetInt(2); static C GetC() { Console.WriteLine(""GetC""); return new C() { Prop = 2 }; } static int GetInt(int i) { Console.WriteLine(""GetInt"" + i.ToString()); return 1; } public class C { private int field; public int Prop { get; set; } public ref int M(int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c) { Console.WriteLine(""M""); Console.WriteLine(c.ToString()); return ref field; } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""arg1:"" + arg1); _builder.AppendLine(""C.Prop:"" + c.Prop.ToString()); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" GetC GetInt1 Handler constructor M arg1:1 C.Prop:2 literal:literal value:3 alignment:0 format: GetInt2 "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 72 (0x48) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_3 IL_002a: ldloc.0 IL_002b: box ""int"" IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0037: ldloc.3 IL_0038: callvirt ""ref int C.M(int, CustomHandler)"" IL_003d: dup IL_003e: ldind.i4 IL_003f: ldc.i4.2 IL_0040: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0045: add IL_0046: stind.i4 IL_0047: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 82 (0x52) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_4 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.3 IL_001d: ldloc.s V_4 IL_001f: brfalse.s IL_003f IL_0021: ldloca.s V_3 IL_0023: ldstr ""literal"" IL_0028: call ""void CustomHandler.AppendLiteral(string)"" IL_002d: ldloca.s V_3 IL_002f: ldloc.0 IL_0030: box ""int"" IL_0035: ldc.i4.0 IL_0036: ldnull IL_0037: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_003c: ldc.i4.1 IL_003d: br.s IL_0040 IL_003f: ldc.i4.0 IL_0040: pop IL_0041: ldloc.3 IL_0042: callvirt ""ref int C.M(int, CustomHandler)"" IL_0047: dup IL_0048: ldind.i4 IL_0049: ldc.i4.2 IL_004a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_004f: add IL_0050: stind.i4 IL_0051: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 78 (0x4e) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""bool CustomHandler.AppendLiteral(string)"" IL_0028: brfalse.s IL_003b IL_002a: ldloca.s V_3 IL_002c: ldloc.0 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.3 IL_003e: callvirt ""ref int C.M(int, CustomHandler)"" IL_0043: dup IL_0044: ldind.i4 IL_0045: ldc.i4.2 IL_0046: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_004b: add IL_004c: stind.i4 IL_004d: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 83 (0x53) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_4 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.3 IL_001d: ldloc.s V_4 IL_001f: brfalse.s IL_0040 IL_0021: ldloca.s V_3 IL_0023: ldstr ""literal"" IL_0028: call ""bool CustomHandler.AppendLiteral(string)"" IL_002d: brfalse.s IL_0040 IL_002f: ldloca.s V_3 IL_0031: ldloc.0 IL_0032: box ""int"" IL_0037: ldc.i4.0 IL_0038: ldnull IL_0039: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_003e: br.s IL_0041 IL_0040: ldc.i4.0 IL_0041: pop IL_0042: ldloc.3 IL_0043: callvirt ""ref int C.M(int, CustomHandler)"" IL_0048: dup IL_0049: ldind.i4 IL_004a: ldc.i4.2 IL_004b: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0050: add IL_0051: stind.i4 IL_0052: ret } ", }; } [Theory] [InlineData(@"$""literal""")] [InlineData(@"$"""" + $""literal""")] public void InterpolatedStringHandlerArgumentsAttribute_CollectionInitializerAdd(string expression) { var code = @" using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; _ = new C(1) { " + expression + @" }; public class C : IEnumerable<int> { public int Field; public C(int i) { Field = i; } public void Add([InterpolatedStringHandlerArgument("""")] CustomHandler c) { Console.WriteLine(c.ToString()); } public IEnumerator<int> GetEnumerator() => throw null; IEnumerator IEnumerable.GetEnumerator() => throw null; } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount) { _builder.AppendLine(""c.Field:"" + c.Field.ToString()); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" c.Field:1 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 37 (0x25) .maxstack 5 .locals init (C V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldloca.s V_1 IL_000a: ldc.i4.7 IL_000b: ldc.i4.0 IL_000c: ldloc.0 IL_000d: call ""CustomHandler..ctor(int, int, C)"" IL_0012: ldloca.s V_1 IL_0014: ldstr ""literal"" IL_0019: call ""void CustomHandler.AppendLiteral(string)"" IL_001e: ldloc.1 IL_001f: callvirt ""void C.Add(CustomHandler)"" IL_0024: ret } "); } [Theory] [InlineData(@"$""literal""")] [InlineData(@"$"""" + $""literal""")] public void InterpolatedStringHandlerArgumentsAttribute_DictionaryInitializer(string expression) { var code = @" using System; using System.Runtime.CompilerServices; _ = new C(1) { [" + expression + @"] = 1 }; public class C { public int Field; public C(int i) { Field = i; } public int this[[InterpolatedStringHandlerArgument("""")] CustomHandler c] { set => Console.WriteLine(c.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount) { _builder.AppendLine(""c.Field:"" + c.Field.ToString()); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" c.Field:1 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 40 (0x28) .maxstack 4 .locals init (C V_0, CustomHandler V_1, CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.0 IL_0007: ldloca.s V_2 IL_0009: ldc.i4.7 IL_000a: ldc.i4.0 IL_000b: ldloc.0 IL_000c: call ""CustomHandler..ctor(int, int, C)"" IL_0011: ldloca.s V_2 IL_0013: ldstr ""literal"" IL_0018: call ""void CustomHandler.AppendLiteral(string)"" IL_001d: ldloc.2 IL_001e: stloc.1 IL_001f: ldloc.0 IL_0020: ldloc.1 IL_0021: ldc.i4.1 IL_0022: callvirt ""void C.this[CustomHandler].set"" IL_0027: ret } "); } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_AttributeOnAppendFormatCall(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""{$""Inner string""}{2}""", @"$""{$""Inner string""}"" + $""{2}""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, " + expression + @"); class C { public static void M(int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler handler) { Console.WriteLine(handler.ToString()); } } public partial class CustomHandler { private int I = 0; public CustomHandler(int literalLength, int formattedCount, int i" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""int constructor""); I = i; " + (validityParameter ? "success = true;" : "") + @" } public CustomHandler(int literalLength, int formattedCount, CustomHandler c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""CustomHandler constructor""); _builder.AppendLine(""c.I:"" + c.I.ToString()); " + (validityParameter ? "success = true;" : "") + @" } public " + (useBoolReturns ? "bool" : "void") + @" AppendFormatted([InterpolatedStringHandlerArgument("""")]CustomHandler c) { _builder.AppendLine(""CustomHandler AppendFormatted""); _builder.Append(c.ToString()); " + (useBoolReturns ? "return true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" int constructor CustomHandler constructor CustomHandler AppendFormatted c.I:1 literal:Inner string value:2 alignment:0 format: "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 59 (0x3b) .maxstack 6 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: dup IL_000c: stloc.1 IL_000d: ldloc.1 IL_000e: ldc.i4.s 12 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0017: dup IL_0018: ldstr ""Inner string"" IL_001d: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0022: callvirt ""void CustomHandler.AppendFormatted(CustomHandler)"" IL_0027: dup IL_0028: ldc.i4.2 IL_0029: box ""int"" IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: call ""void C.M(int, CustomHandler)"" IL_003a: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 87 (0x57) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2, CustomHandler V_3, CustomHandler V_4, bool V_5) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.2 IL_000f: brfalse.s IL_004e IL_0011: ldloc.1 IL_0012: stloc.3 IL_0013: ldloc.3 IL_0014: ldc.i4.s 12 IL_0016: ldc.i4.0 IL_0017: ldloc.3 IL_0018: ldloca.s V_5 IL_001a: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_001f: stloc.s V_4 IL_0021: ldloc.s V_5 IL_0023: brfalse.s IL_0034 IL_0025: ldloc.s V_4 IL_0027: ldstr ""Inner string"" IL_002c: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0031: ldc.i4.1 IL_0032: br.s IL_0035 IL_0034: ldc.i4.0 IL_0035: pop IL_0036: ldloc.s V_4 IL_0038: callvirt ""void CustomHandler.AppendFormatted(CustomHandler)"" IL_003d: ldloc.1 IL_003e: ldc.i4.2 IL_003f: box ""int"" IL_0044: ldc.i4.0 IL_0045: ldnull IL_0046: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_004b: ldc.i4.1 IL_004c: br.s IL_004f IL_004e: ldc.i4.0 IL_004f: pop IL_0050: ldloc.1 IL_0051: call ""void C.M(int, CustomHandler)"" IL_0056: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 68 (0x44) .maxstack 5 .locals init (int V_0, CustomHandler V_1, CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: stloc.2 IL_000e: ldloc.2 IL_000f: ldc.i4.s 12 IL_0011: ldc.i4.0 IL_0012: ldloc.2 IL_0013: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0018: dup IL_0019: ldstr ""Inner string"" IL_001e: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0023: pop IL_0024: callvirt ""bool CustomHandler.AppendFormatted(CustomHandler)"" IL_0029: brfalse.s IL_003b IL_002b: ldloc.1 IL_002c: ldc.i4.2 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.1 IL_003e: call ""void C.M(int, CustomHandler)"" IL_0043: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 87 (0x57) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2, CustomHandler V_3, CustomHandler V_4, bool V_5) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.2 IL_000f: brfalse.s IL_004e IL_0011: ldloc.1 IL_0012: stloc.3 IL_0013: ldloc.3 IL_0014: ldc.i4.s 12 IL_0016: ldc.i4.0 IL_0017: ldloc.3 IL_0018: ldloca.s V_5 IL_001a: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_001f: stloc.s V_4 IL_0021: ldloc.s V_5 IL_0023: brfalse.s IL_0033 IL_0025: ldloc.s V_4 IL_0027: ldstr ""Inner string"" IL_002c: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0031: br.s IL_0034 IL_0033: ldc.i4.0 IL_0034: pop IL_0035: ldloc.s V_4 IL_0037: callvirt ""bool CustomHandler.AppendFormatted(CustomHandler)"" IL_003c: brfalse.s IL_004e IL_003e: ldloc.1 IL_003f: ldc.i4.2 IL_0040: box ""int"" IL_0045: ldc.i4.0 IL_0046: ldnull IL_0047: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_004c: br.s IL_004f IL_004e: ldc.i4.0 IL_004f: pop IL_0050: ldloc.1 IL_0051: call ""void C.M(int, CustomHandler)"" IL_0056: ret } ", }; } [Theory] [InlineData(@"$""literal""")] [InlineData(@"$"""" + $""literal""")] public void DiscardsUsedAsParameters(string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(out _, " + expression + @"); public class C { public static void M(out int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler c) { i = 0; Console.WriteLine(c.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, out int i) : this(literalLength, formattedCount) { i = 1; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @"literal:literal"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 31 (0x1f) .maxstack 4 .locals init (int V_0, CustomHandler V_1) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.0 IL_0004: ldloca.s V_0 IL_0006: newobj ""CustomHandler..ctor(int, int, out int)"" IL_000b: stloc.1 IL_000c: ldloca.s V_1 IL_000e: ldstr ""literal"" IL_0013: call ""void CustomHandler.AppendLiteral(string)"" IL_0018: ldloc.1 IL_0019: call ""void C.M(out int, CustomHandler)"" IL_001e: ret } "); } [Fact] public void DiscardsUsedAsParameters_DefinedInVB() { var vb = @" Imports System Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Public Class C Public Shared Sub M(<Out> ByRef i As Integer, <InterpolatedStringHandlerArgument(""i"")>c As CustomHandler) Console.WriteLine(i) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler Public Sub New(literalLength As Integer, formattedCount As Integer, <Out> ByRef i As Integer) i = 1 End Sub End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vb, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var code = @"C.M(out _, $"""");"; var comp = CreateCompilation(code, new[] { vbComp.EmitToImageReference() }); var verifier = CompileAndVerify(comp, expectedOutput: @"1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 17 (0x11) .maxstack 4 .locals init (int V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.0 IL_0004: ldloca.s V_0 IL_0006: newobj ""CustomHandler..ctor(int, int, out int)"" IL_000b: call ""void C.M(out int, CustomHandler)"" IL_0010: ret } "); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DisallowedInExpressionTrees(string expression) { var code = @" using System; using System.Linq.Expressions; Expression<Func<CustomHandler>> expr = () => " + expression + @"; "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, handler }); comp.VerifyDiagnostics( // (5,46): error CS8952: An expression tree may not contain an interpolated string handler conversion. // Expression<Func<CustomHandler>> expr = () => $""; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsInterpolatedStringHandlerConversion, expression).WithLocation(5, 46) ); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_01() { var code = @" using System; using System.Linq.Expressions; Expression<Func<string, string>> e = o => $""{o.Length}"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 127 (0x7f) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldc.i4.1 IL_006f: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0074: dup IL_0075: ldc.i4.0 IL_0076: ldloc.0 IL_0077: stelem.ref IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_007d: pop IL_007e: ret } "); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_02() { var code = @" using System.Linq.Expressions; Expression e = (string o) => $""{o.Length}"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 127 (0x7f) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldc.i4.1 IL_006f: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0074: dup IL_0075: ldc.i4.0 IL_0076: ldloc.0 IL_0077: stelem.ref IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_007d: pop IL_007e: ret } "); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_03() { var code = @" using System; using System.Linq.Expressions; Expression<Func<Func<string, string>>> e = () => o => $""{o.Length}"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 137 (0x89) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldc.i4.1 IL_006f: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0074: dup IL_0075: ldc.i4.0 IL_0076: ldloc.0 IL_0077: stelem.ref IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_007d: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()"" IL_0082: call ""System.Linq.Expressions.Expression<System.Func<System.Func<string, string>>> System.Linq.Expressions.Expression.Lambda<System.Func<System.Func<string, string>>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0087: pop IL_0088: ret } "); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_04() { var code = @" using System; using System.Linq.Expressions; Expression e = Func<string, string> () => (string o) => $""{o.Length}"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 137 (0x89) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldc.i4.1 IL_006f: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0074: dup IL_0075: ldc.i4.0 IL_0076: ldloc.0 IL_0077: stelem.ref IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_007d: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()"" IL_0082: call ""System.Linq.Expressions.Expression<System.Func<System.Func<string, string>>> System.Linq.Expressions.Expression.Lambda<System.Func<System.Func<string, string>>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0087: pop IL_0088: ret } "); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_05() { var code = @" using System; using System.Linq.Expressions; Expression<Func<string, string>> e = o => $""{o.Length}"" + $""literal"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 167 (0xa7) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldstr ""literal"" IL_0073: ldtoken ""string"" IL_0078: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_007d: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0082: ldtoken ""string string.Concat(string, string)"" IL_0087: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_008c: castclass ""System.Reflection.MethodInfo"" IL_0091: call ""System.Linq.Expressions.BinaryExpression System.Linq.Expressions.Expression.Add(System.Linq.Expressions.Expression, System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0096: ldc.i4.1 IL_0097: newarr ""System.Linq.Expressions.ParameterExpression"" IL_009c: dup IL_009d: ldc.i4.0 IL_009e: ldloc.0 IL_009f: stelem.ref IL_00a0: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_00a5: pop IL_00a6: ret } "); } [Theory] [CombinatorialData] public void CustomHandlerUsedAsArgumentToCustomHandler(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, " + expression + @", " + expression + @"); public class C { public static void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c1, [InterpolatedStringHandlerArgument(""c1"")] CustomHandler c2) => Console.WriteLine(c2.ToString()); } public partial class CustomHandler { private int i; public CustomHandler(int literalLength, int formattedCount, int i" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); this.i = i; " + (validityParameter ? "success = true;" : "") + @" } public CustomHandler(int literalLength, int formattedCount, CustomHandler c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { _builder.AppendLine(""c.i:"" + c.i.ToString()); " + (validityParameter ? "success = true;" : "") + @" } }"; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: "c.i:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 27 (0x1b) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: ldc.i4.0 IL_000e: ldc.i4.0 IL_000f: ldloc.1 IL_0010: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0015: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001a: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 31 (0x1f) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.1 IL_000f: ldc.i4.0 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: ldloca.s V_2 IL_0014: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_0019: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001e: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 27 (0x1b) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: ldc.i4.0 IL_000e: ldc.i4.0 IL_000f: ldloc.1 IL_0010: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0015: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001a: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 31 (0x1f) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.1 IL_000f: ldc.i4.0 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: ldloca.s V_2 IL_0014: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_0019: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001e: ret } ", }; } [Fact, WorkItem(1370647, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647")] public void AsFormattableString() { var code = @" M($""{1}"" + $""literal""); System.FormattableString s = $""{1}"" + $""literal""; void M(System.FormattableString s) { } "; var comp = CreateCompilation(code); comp.VerifyDiagnostics( // (2,3): error CS1503: Argument 1: cannot convert from 'string' to 'System.FormattableString' // M($"{1}" + $"literal"); Diagnostic(ErrorCode.ERR_BadArgType, @"$""{1}"" + $""literal""").WithArguments("1", "string", "System.FormattableString").WithLocation(2, 3), // (3,30): error CS0029: Cannot implicitly convert type 'string' to 'System.FormattableString' // System.FormattableString s = $"{1}" + $"literal"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{1}"" + $""literal""").WithArguments("string", "System.FormattableString").WithLocation(3, 30) ); } [Fact, WorkItem(1370647, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647")] public void AsIFormattable() { var code = @" M($""{1}"" + $""literal""); System.IFormattable s = $""{1}"" + $""literal""; void M(System.IFormattable s) { } "; var comp = CreateCompilation(code); comp.VerifyDiagnostics( // (2,3): error CS1503: Argument 1: cannot convert from 'string' to 'System.IFormattable' // M($"{1}" + $"literal"); Diagnostic(ErrorCode.ERR_BadArgType, @"$""{1}"" + $""literal""").WithArguments("1", "string", "System.IFormattable").WithLocation(2, 3), // (3,25): error CS0029: Cannot implicitly convert type 'string' to 'System.IFormattable' // System.IFormattable s = $"{1}" + $"literal"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{1}"" + $""literal""").WithArguments("string", "System.IFormattable").WithLocation(3, 25) ); } [Theory] [CombinatorialData] public void DefiniteAssignment_01(bool useBoolReturns, bool trailingOutParameter, [CombinatorialValues(@"$""{i = 1}{M(out var o)}{s = o.ToString()}""", @"$""{i = 1}"" + $""{M(out var o)}"" + $""{s = o.ToString()}""")] string expression) { var code = @" int i; string s; CustomHandler c = " + expression + @"; _ = i.ToString(); _ = o.ToString(); _ = s.ToString(); string M(out object o) { o = null; return null; } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns, includeTrailingOutConstructorParameter: trailingOutParameter); var comp = CreateCompilation(new[] { code, customHandler }); if (trailingOutParameter) { comp.VerifyDiagnostics( // (6,5): error CS0165: Use of unassigned local variable 'i' // _ = i.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(6, 5), // (7,5): error CS0165: Use of unassigned local variable 'o' // _ = o.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "o").WithArguments("o").WithLocation(7, 5), // (8,5): error CS0165: Use of unassigned local variable 's' // _ = s.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s").WithLocation(8, 5) ); } else if (useBoolReturns) { comp.VerifyDiagnostics( // (7,5): error CS0165: Use of unassigned local variable 'o' // _ = o.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "o").WithArguments("o").WithLocation(7, 5), // (8,5): error CS0165: Use of unassigned local variable 's' // _ = s.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s").WithLocation(8, 5) ); } else { comp.VerifyDiagnostics(); } } [Theory] [CombinatorialData] public void DefiniteAssignment_02(bool useBoolReturns, bool trailingOutParameter, [CombinatorialValues(@"$""{i = 1}""", @"$"""" + $""{i = 1}""", @"$""{i = 1}"" + $""""")] string expression) { var code = @" int i; CustomHandler c = " + expression + @"; _ = i.ToString(); "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns, includeTrailingOutConstructorParameter: trailingOutParameter); var comp = CreateCompilation(new[] { code, customHandler }); if (trailingOutParameter) { comp.VerifyDiagnostics( // (5,5): error CS0165: Use of unassigned local variable 'i' // _ = i.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(5, 5) ); } else { comp.VerifyDiagnostics(); } } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DynamicConstruction_01(string expression) { var code = @" using System.Runtime.CompilerServices; dynamic d = 1; M(d, " + expression + @"); void M(dynamic d, [InterpolatedStringHandlerArgument(""d"")]CustomHandler c) {} public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, dynamic d) : this() {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute }); comp.VerifyDiagnostics( // (4,6): error CS8953: An interpolated string handler construction cannot use dynamic. Manually construct an instance of 'CustomHandler'. // M(d, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, expression).WithArguments("CustomHandler").WithLocation(4, 6) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DynamicConstruction_02(string expression) { var code = @" using System.Runtime.CompilerServices; int i = 1; M(i, " + expression + @"); void M(dynamic d, [InterpolatedStringHandlerArgument(""d"")]CustomHandler c) {} public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, dynamic d) : this() {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute }); comp.VerifyDiagnostics( // (4,6): error CS8953: An interpolated string handler construction cannot use dynamic. Manually construct an instance of 'CustomHandler'. // M(d, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, expression).WithArguments("CustomHandler").WithLocation(4, 6) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DynamicConstruction_03(string expression) { var code = @" using System; using System.Runtime.CompilerServices; int i = 1; M(i, " + expression + @"); void M(int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler c) {} public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, dynamic d) : this(literalLength, formattedCount) { Console.WriteLine(""d:"" + d.ToString()); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false, includeOneTimeHelpers: false); var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "d:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 22 (0x16) .maxstack 4 .locals init (int V_0) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: box ""int"" IL_000b: newobj ""CustomHandler..ctor(int, int, dynamic)"" IL_0010: call ""void Program.<<Main>$>g__M|0_0(int, CustomHandler)"" IL_0015: ret } "); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DynamicConstruction_04(string expression) { var code = @" using System; using System.Runtime.CompilerServices; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(dynamic literalLength, int formattedCount) { Console.WriteLine(""ctor""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "ctor"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 18 (0x12) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: box ""int"" IL_0006: ldc.i4.0 IL_0007: newobj ""CustomHandler..ctor(dynamic, int)"" IL_000c: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_0011: ret } "); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DynamicConstruction_05(string expression) { var code = @" using System; using System.Runtime.CompilerServices; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { Console.WriteLine(""ctor""); } public CustomHandler(dynamic literalLength, int formattedCount) { throw null; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "ctor"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: ldc.i4.0 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_000c: ret } "); } [Theory] [InlineData(@"$""Literal""")] [InlineData(@"$"""" + $""Literal""")] public void DynamicConstruction_06(string expression) { var code = @" using System; using System.Runtime.CompilerServices; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public void AppendLiteral(dynamic d) { Console.WriteLine(""AppendLiteral""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "AppendLiteral"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 28 (0x1c) .maxstack 3 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.0 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldstr ""Literal"" IL_0010: call ""void CustomHandler.AppendLiteral(dynamic)"" IL_0015: ldloc.0 IL_0016: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_001b: ret } "); } [Theory] [InlineData(@"$""{1}""")] [InlineData(@"$""{1}"" + $""""")] public void DynamicConstruction_07(string expression) { var code = @" using System; using System.Runtime.CompilerServices; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public void AppendFormatted(dynamic d) { Console.WriteLine(""AppendFormatted""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "AppendFormatted"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 29 (0x1d) .maxstack 3 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: call ""void CustomHandler.AppendFormatted(dynamic)"" IL_0016: ldloc.0 IL_0017: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_001c: ret } "); } [Theory] [InlineData(@"$""literal{d}""")] [InlineData(@"$""literal"" + $""{d}""")] public void DynamicConstruction_08(string expression) { var code = @" using System; using System.Runtime.CompilerServices; dynamic d = 1; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public void AppendLiteral(dynamic d) { Console.WriteLine(""AppendLiteral""); } public void AppendFormatted(dynamic d) { Console.WriteLine(""AppendFormatted""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: @" AppendLiteral AppendFormatted"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 128 (0x80) .maxstack 9 .locals init (object V_0, //d CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldloca.s V_1 IL_0009: ldc.i4.7 IL_000a: ldc.i4.1 IL_000b: call ""CustomHandler..ctor(int, int)"" IL_0010: ldloca.s V_1 IL_0012: ldstr ""literal"" IL_0017: call ""void CustomHandler.AppendLiteral(dynamic)"" IL_001c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0"" IL_0021: brtrue.s IL_0062 IL_0023: ldc.i4 0x100 IL_0028: ldstr ""AppendFormatted"" IL_002d: ldnull IL_002e: ldtoken ""Program"" IL_0033: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0038: ldc.i4.2 IL_0039: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_003e: dup IL_003f: ldc.i4.0 IL_0040: ldc.i4.s 9 IL_0042: ldnull IL_0043: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0048: stelem.ref IL_0049: dup IL_004a: ldc.i4.1 IL_004b: ldc.i4.0 IL_004c: ldnull IL_004d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0052: stelem.ref IL_0053: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0058: call ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_005d: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0"" IL_0062: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0"" IL_0067: ldfld ""<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>>.Target"" IL_006c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0"" IL_0071: ldloca.s V_1 IL_0073: ldloc.0 IL_0074: callvirt ""void <>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, ref CustomHandler, dynamic)"" IL_0079: ldloc.1 IL_007a: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_007f: ret } "); } [Theory] [InlineData(@"$""literal{d}""")] [InlineData(@"$""literal"" + $""{d}""")] public void DynamicConstruction_09(string expression) { var code = @" using System; using System.Runtime.CompilerServices; dynamic d = 1; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public bool AppendLiteral(dynamic d) { Console.WriteLine(""AppendLiteral""); return true; } public bool AppendFormatted(dynamic d) { Console.WriteLine(""AppendFormatted""); return true; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: @" AppendLiteral AppendFormatted"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 196 (0xc4) .maxstack 11 .locals init (object V_0, //d CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldloca.s V_1 IL_0009: ldc.i4.7 IL_000a: ldc.i4.1 IL_000b: call ""CustomHandler..ctor(int, int)"" IL_0010: ldloca.s V_1 IL_0012: ldstr ""literal"" IL_0017: call ""bool CustomHandler.AppendLiteral(dynamic)"" IL_001c: brfalse IL_00bb IL_0021: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1"" IL_0026: brtrue.s IL_004c IL_0028: ldc.i4.0 IL_0029: ldtoken ""bool"" IL_002e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0033: ldtoken ""Program"" IL_0038: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0042: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0047: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1"" IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1"" IL_0051: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Target"" IL_0056: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1"" IL_005b: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0"" IL_0060: brtrue.s IL_009d IL_0062: ldc.i4.0 IL_0063: ldstr ""AppendFormatted"" IL_0068: ldnull IL_0069: ldtoken ""Program"" IL_006e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0073: ldc.i4.2 IL_0074: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0079: dup IL_007a: ldc.i4.0 IL_007b: ldc.i4.s 9 IL_007d: ldnull IL_007e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0083: stelem.ref IL_0084: dup IL_0085: ldc.i4.1 IL_0086: ldc.i4.0 IL_0087: ldnull IL_0088: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008d: stelem.ref IL_008e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0093: call ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0098: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0"" IL_009d: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0"" IL_00a2: ldfld ""<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>>.Target"" IL_00a7: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0"" IL_00ac: ldloca.s V_1 IL_00ae: ldloc.0 IL_00af: callvirt ""dynamic <>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, ref CustomHandler, dynamic)"" IL_00b4: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00b9: br.s IL_00bc IL_00bb: ldc.i4.0 IL_00bc: pop IL_00bd: ldloc.1 IL_00be: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_00c3: ret } "); } [Theory] [InlineData(@"$""{s}""")] [InlineData(@"$""{s}"" + $""""")] public void RefEscape_01(string expression) { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount) : this() {} public void AppendFormatted(Span<char> s) => this.s = s; public static CustomHandler M() { Span<char> s = stackalloc char[10]; return " + expression + @"; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,19): error CS8352: Cannot use local 's' in this context because it may expose referenced variables outside of their declaration scope // return $"{s}"; Diagnostic(ErrorCode.ERR_EscapeLocal, "s").WithArguments("s").WithLocation(17, 19) ); } [Theory] [InlineData(@"$""{s}""")] [InlineData(@"$""{s}"" + $""""")] public void RefEscape_02(string expression) { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount) : this() {} public void AppendFormatted(Span<char> s) => this.s = s; public static ref CustomHandler M() { Span<char> s = stackalloc char[10]; return " + expression + @"; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,9): error CS8150: By-value returns may only be used in methods that return by value // return $"{s}"; Diagnostic(ErrorCode.ERR_MustHaveRefReturn, "return").WithLocation(17, 9) ); } [Theory] [InlineData(@"$""{s}""")] [InlineData(@"$""{s}"" + $""""")] public void RefEscape_03(string expression) { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount) : this() {} public void AppendFormatted(Span<char> s) => this.s = s; public static ref CustomHandler M() { Span<char> s = stackalloc char[10]; return ref " + expression + @"; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,20): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // return ref $"{s}"; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, expression).WithLocation(17, 20) ); } [Theory] [InlineData(@"$""{s}""")] [InlineData(@"$""{s}"" + $""""")] public void RefEscape_04(string expression) { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { S1 s1; public CustomHandler(int literalLength, int formattedCount, ref S1 s1) : this() { this.s1 = s1; } public void AppendFormatted(Span<char> s) => this.s1.s = s; public static void M(ref S1 s1) { Span<char> s = stackalloc char[10]; M2(ref s1, " + expression + @"); } public static void M2(ref S1 s1, [InterpolatedStringHandlerArgument(""s1"")] ref CustomHandler handler) {} } public ref struct S1 { public Span<char> s; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,9): error CS8350: This combination of arguments to 'CustomHandler.M2(ref S1, ref CustomHandler)' is disallowed because it may expose variables referenced by parameter 'handler' outside of their declaration scope // M2(ref s1, $"{s}"); Diagnostic(ErrorCode.ERR_CallArgMixing, @"M2(ref s1, " + expression + @")").WithArguments("CustomHandler.M2(ref S1, ref CustomHandler)", "handler").WithLocation(17, 9), // (17,23): error CS8352: Cannot use local 's' in this context because it may expose referenced variables outside of their declaration scope // M2(ref s1, $"{s}"); Diagnostic(ErrorCode.ERR_EscapeLocal, "s").WithArguments("s").WithLocation(17, 23) ); } [Theory] [InlineData(@"$""{s1}""")] [InlineData(@"$""{s1}"" + $""""")] public void RefEscape_05(string expression) { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount, ref Span<char> s) : this() { this.s = s; } public void AppendFormatted(S1 s1) => s1.s = this.s; public static void M(ref S1 s1) { Span<char> s = stackalloc char[10]; M2(ref s, " + expression + @"); } public static void M2(ref Span<char> s, [InterpolatedStringHandlerArgument(""s"")] CustomHandler handler) {} } public ref struct S1 { public Span<char> s; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics(); } [Theory] [InlineData(@"$""{s2}""")] [InlineData(@"$""{s2}"" + $""""")] public void RefEscape_06(string expression) { var code = @" using System; using System.Runtime.CompilerServices; Span<char> s = stackalloc char[5]; Span<char> s2 = stackalloc char[10]; s.TryWrite(" + expression + @"); public static class MemoryExtensions { public static bool TryWrite(this Span<char> span, [InterpolatedStringHandlerArgument(""span"")] CustomHandler builder) => true; } [InterpolatedStringHandler] public ref struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, Span<char> s) : this() { } public bool AppendFormatted(Span<char> s) => true; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics(); } [Theory] [InlineData(@"$""{s2}""")] [InlineData(@"$""{s2}"" + $""""")] public void RefEscape_07(string expression) { var code = @" using System; using System.Runtime.CompilerServices; Span<char> s = stackalloc char[5]; Span<char> s2 = stackalloc char[10]; s.TryWrite(" + expression + @"); public static class MemoryExtensions { public static bool TryWrite(this Span<char> span, [InterpolatedStringHandlerArgument(""span"")] ref CustomHandler builder) => true; } [InterpolatedStringHandler] public ref struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, Span<char> s) : this() { } public bool AppendFormatted(Span<char> s) => true; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics(); } [Fact] public void RefEscape_08() { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount, ref Span<char> s) : this() { this.s = s; } public static CustomHandler M() { Span<char> s = stackalloc char[10]; ref CustomHandler c = ref M2(ref s, $""""); return c; } public static ref CustomHandler M2(ref Span<char> s, [InterpolatedStringHandlerArgument(""s"")] ref CustomHandler handler) { return ref handler; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (16,16): error CS8352: Cannot use local 'c' in this context because it may expose referenced variables outside of their declaration scope // return c; Diagnostic(ErrorCode.ERR_EscapeLocal, "c").WithArguments("c").WithLocation(16, 16) ); } [Fact] public void RefEscape_09() { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount, ref S1 s1) : this() { s1.Handler = this; } public static void M(ref S1 s1) { Span<char> s2 = stackalloc char[10]; M2(ref s1, $""{s2}""); } public static void M2(ref S1 s1, [InterpolatedStringHandlerArgument(""s1"")] CustomHandler handler) { } public void AppendFormatted(Span<char> s) { this.s = s; } } public ref struct S1 { public CustomHandler Handler; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (15,9): error CS8350: This combination of arguments to 'CustomHandler.M2(ref S1, CustomHandler)' is disallowed because it may expose variables referenced by parameter 'handler' outside of their declaration scope // M2(ref s1, $"{s2}"); Diagnostic(ErrorCode.ERR_CallArgMixing, @"M2(ref s1, $""{s2}"")").WithArguments("CustomHandler.M2(ref S1, CustomHandler)", "handler").WithLocation(15, 9), // (15,23): error CS8352: Cannot use local 's2' in this context because it may expose referenced variables outside of their declaration scope // M2(ref s1, $"{s2}"); Diagnostic(ErrorCode.ERR_EscapeLocal, "s2").WithArguments("s2").WithLocation(15, 23) ); } [Theory, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")] [InlineData(@"$""{{ {i} }}""")] [InlineData(@"$""{{ "" + $""{i}"" + $"" }}""")] public void BracesAreEscaped_01(string expression) { var code = @" int i = 1; System.Console.WriteLine(" + expression + @");"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" { value:1 }"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 56 (0x38) .maxstack 3 .locals init (int V_0, //i System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.1 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""{ "" IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_1 IL_0019: ldloc.0 IL_001a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_001f: ldloca.s V_1 IL_0021: ldstr "" }"" IL_0026: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_002b: ldloca.s V_1 IL_002d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0032: call ""void System.Console.WriteLine(string)"" IL_0037: ret } "); } [Theory, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")] [InlineData(@"$""{{ {i} }}""")] [InlineData(@"$""{{ "" + $""{i}"" + $"" }}""")] public void BracesAreEscaped_02(string expression) { var code = @" int i = 1; CustomHandler c = " + expression + @"; System.Console.WriteLine(c.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" literal:{ value:1 alignment:0 format: literal: }"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 71 (0x47) .maxstack 4 .locals init (int V_0, //i CustomHandler V_1, //c CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_2 IL_0004: ldc.i4.4 IL_0005: ldc.i4.1 IL_0006: call ""CustomHandler..ctor(int, int)"" IL_000b: ldloca.s V_2 IL_000d: ldstr ""{ "" IL_0012: call ""void CustomHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_2 IL_0019: ldloc.0 IL_001a: box ""int"" IL_001f: ldc.i4.0 IL_0020: ldnull IL_0021: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0026: ldloca.s V_2 IL_0028: ldstr "" }"" IL_002d: call ""void CustomHandler.AppendLiteral(string)"" IL_0032: ldloc.2 IL_0033: stloc.1 IL_0034: ldloca.s V_1 IL_0036: constrained. ""CustomHandler"" IL_003c: callvirt ""string object.ToString()"" IL_0041: call ""void System.Console.WriteLine(string)"" IL_0046: ret } "); } [Fact] public void InterpolatedStringsAddedUnderObjectAddition() { var code = @" int i1 = 1; int i2 = 2; int i3 = 3; int i4 = 4; System.Console.WriteLine($""{i1}"" + $""{i2}"" + $""{i3}"" + i4);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 value:2 value:3 4 "); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 66 (0x42) .maxstack 3 .locals init (int V_0, //i1 int V_1, //i2 int V_2, //i3 int V_3, //i4 System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_4) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.2 IL_0003: stloc.1 IL_0004: ldc.i4.3 IL_0005: stloc.2 IL_0006: ldc.i4.4 IL_0007: stloc.3 IL_0008: ldloca.s V_4 IL_000a: ldc.i4.0 IL_000b: ldc.i4.3 IL_000c: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0011: ldloca.s V_4 IL_0013: ldloc.0 IL_0014: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0019: ldloca.s V_4 IL_001b: ldloc.1 IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0021: ldloca.s V_4 IL_0023: ldloc.2 IL_0024: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0029: ldloca.s V_4 IL_002b: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0030: ldloca.s V_3 IL_0032: call ""string int.ToString()"" IL_0037: call ""string string.Concat(string, string)"" IL_003c: call ""void System.Console.WriteLine(string)"" IL_0041: ret } "); } [Theory] [InlineData(@"$""({i1}),"" + $""[{i2}],"" + $""{{{i3}}}""")] [InlineData(@"($""({i1}),"" + $""[{i2}],"") + $""{{{i3}}}""")] [InlineData(@"$""({i1}),"" + ($""[{i2}],"" + $""{{{i3}}}"")")] public void InterpolatedStringsAddedUnderObjectAddition2(string expression) { var code = $@" int i1 = 1; int i2 = 2; int i3 = 3; System.Console.WriteLine({expression});"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); CompileAndVerify(comp, expectedOutput: @" ( value:1 ), [ value:2 ], { value:3 } "); } [Fact] public void InterpolatedStringsAddedUnderObjectAddition3() { var code = @" #nullable enable using System; try { var s = string.Empty; Console.WriteLine($""{s = null}{s.Length}"" + $""""); } catch (NullReferenceException) { Console.WriteLine(""Null reference exception caught.""); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); CompileAndVerify(comp, expectedOutput: "Null reference exception caught.").VerifyIL("<top-level-statements-entry-point>", @" { // Code size 65 (0x41) .maxstack 3 .locals init (string V_0, //s System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) .try { IL_0000: ldsfld ""string string.Empty"" IL_0005: stloc.0 IL_0006: ldc.i4.0 IL_0007: ldc.i4.2 IL_0008: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000d: stloc.1 IL_000e: ldloca.s V_1 IL_0010: ldnull IL_0011: dup IL_0012: stloc.0 IL_0013: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0018: ldloca.s V_1 IL_001a: ldloc.0 IL_001b: callvirt ""int string.Length.get"" IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0025: ldloca.s V_1 IL_0027: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_002c: call ""void System.Console.WriteLine(string)"" IL_0031: leave.s IL_0040 } catch System.NullReferenceException { IL_0033: pop IL_0034: ldstr ""Null reference exception caught."" IL_0039: call ""void System.Console.WriteLine(string)"" IL_003e: leave.s IL_0040 } IL_0040: ret } ").VerifyDiagnostics( // (9,36): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine($"{s = null}{s.Length}" + $""); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 36) ); } [Fact] public void InterpolatedStringsAddedUnderObjectAddition_DefiniteAssignment() { var code = @" object o1; object o2; object o3; _ = $""{o1 = null}"" + $""{o2 = null}"" + $""{o3 = null}"" + 1; o1.ToString(); o2.ToString(); o3.ToString(); "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true) }); comp.VerifyDiagnostics( // (7,1): error CS0165: Use of unassigned local variable 'o2' // o2.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "o2").WithArguments("o2").WithLocation(7, 1), // (8,1): error CS0165: Use of unassigned local variable 'o3' // o3.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "o3").WithArguments("o3").WithLocation(8, 1) ); } [Fact] public void ParenthesizedAdditiveExpression_01() { var code = @" int i1 = 1; int i2 = 2; int i3 = 3; CustomHandler c = ($""{i1}"" + $""{i2}"") + $""{i3}""; System.Console.WriteLine(c.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:0 format: value:2 alignment:0 format: value:3 alignment:0 format: "); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 82 (0x52) .maxstack 4 .locals init (int V_0, //i1 int V_1, //i2 int V_2, //i3 CustomHandler V_3, //c CustomHandler V_4) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.2 IL_0003: stloc.1 IL_0004: ldc.i4.3 IL_0005: stloc.2 IL_0006: ldloca.s V_4 IL_0008: ldc.i4.0 IL_0009: ldc.i4.3 IL_000a: call ""CustomHandler..ctor(int, int)"" IL_000f: ldloca.s V_4 IL_0011: ldloc.0 IL_0012: box ""int"" IL_0017: ldc.i4.0 IL_0018: ldnull IL_0019: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001e: ldloca.s V_4 IL_0020: ldloc.1 IL_0021: box ""int"" IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_002d: ldloca.s V_4 IL_002f: ldloc.2 IL_0030: box ""int"" IL_0035: ldc.i4.0 IL_0036: ldnull IL_0037: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_003c: ldloc.s V_4 IL_003e: stloc.3 IL_003f: ldloca.s V_3 IL_0041: constrained. ""CustomHandler"" IL_0047: callvirt ""string object.ToString()"" IL_004c: call ""void System.Console.WriteLine(string)"" IL_0051: ret }"); } [Fact] public void ParenthesizedAdditiveExpression_02() { var code = @" int i1 = 1; int i2 = 2; int i3 = 3; CustomHandler c = $""{i1}"" + ($""{i2}"" + $""{i3}""); System.Console.WriteLine(c.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (6,19): error CS0029: Cannot implicitly convert type 'string' to 'CustomHandler' // CustomHandler c = $"{i1}" + ($"{i2}" + $"{i3}"); Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{i1}"" + ($""{i2}"" + $""{i3}"")").WithArguments("string", "CustomHandler").WithLocation(6, 19) ); } [Theory] [InlineData(@"$""{1}"", $""{2}""")] [InlineData(@"$""{1}"" + $"""", $""{2}"" + $""""")] public void TupleDeclaration_01(string initializer) { var code = @" (CustomHandler c1, CustomHandler c2) = (" + initializer + @"); System.Console.Write(c1.ToString()); System.Console.WriteLine(c2.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:0 format: value:2 alignment:0 format: "); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 91 (0x5b) .maxstack 4 .locals init (CustomHandler V_0, //c1 CustomHandler V_1, //c2 CustomHandler V_2, CustomHandler V_3) IL_0000: ldloca.s V_3 IL_0002: ldc.i4.0 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_3 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.0 IL_0012: ldnull IL_0013: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0018: ldloc.3 IL_0019: stloc.2 IL_001a: ldloca.s V_3 IL_001c: ldc.i4.0 IL_001d: ldc.i4.1 IL_001e: call ""CustomHandler..ctor(int, int)"" IL_0023: ldloca.s V_3 IL_0025: ldc.i4.2 IL_0026: box ""int"" IL_002b: ldc.i4.0 IL_002c: ldnull IL_002d: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0032: ldloc.3 IL_0033: ldloc.2 IL_0034: stloc.0 IL_0035: stloc.1 IL_0036: ldloca.s V_0 IL_0038: constrained. ""CustomHandler"" IL_003e: callvirt ""string object.ToString()"" IL_0043: call ""void System.Console.Write(string)"" IL_0048: ldloca.s V_1 IL_004a: constrained. ""CustomHandler"" IL_0050: callvirt ""string object.ToString()"" IL_0055: call ""void System.Console.WriteLine(string)"" IL_005a: ret } "); } [Theory] [InlineData(@"$""{1}"", $""{2}""")] [InlineData(@"$""{1}"" + $"""", $""{2}"" + $""""")] public void TupleDeclaration_02(string initializer) { var code = @" (CustomHandler c1, CustomHandler c2) t = (" + initializer + @"); System.Console.Write(t.c1.ToString()); System.Console.WriteLine(t.c2.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:0 format: value:2 alignment:0 format: "); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 104 (0x68) .maxstack 6 .locals init (System.ValueTuple<CustomHandler, CustomHandler> V_0, //t CustomHandler V_1) IL_0000: ldloca.s V_0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.0 IL_0005: ldc.i4.1 IL_0006: call ""CustomHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldc.i4.1 IL_000e: box ""int"" IL_0013: ldc.i4.0 IL_0014: ldnull IL_0015: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001a: ldloc.1 IL_001b: ldloca.s V_1 IL_001d: ldc.i4.0 IL_001e: ldc.i4.1 IL_001f: call ""CustomHandler..ctor(int, int)"" IL_0024: ldloca.s V_1 IL_0026: ldc.i4.2 IL_0027: box ""int"" IL_002c: ldc.i4.0 IL_002d: ldnull IL_002e: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0033: ldloc.1 IL_0034: call ""System.ValueTuple<CustomHandler, CustomHandler>..ctor(CustomHandler, CustomHandler)"" IL_0039: ldloca.s V_0 IL_003b: ldflda ""CustomHandler System.ValueTuple<CustomHandler, CustomHandler>.Item1"" IL_0040: constrained. ""CustomHandler"" IL_0046: callvirt ""string object.ToString()"" IL_004b: call ""void System.Console.Write(string)"" IL_0050: ldloca.s V_0 IL_0052: ldflda ""CustomHandler System.ValueTuple<CustomHandler, CustomHandler>.Item2"" IL_0057: constrained. ""CustomHandler"" IL_005d: callvirt ""string object.ToString()"" IL_0062: call ""void System.Console.WriteLine(string)"" IL_0067: ret } "); } [Theory, WorkItem(55609, "https://github.com/dotnet/roslyn/issues/55609")] [InlineData(@"$""{h1}{h2}""")] [InlineData(@"$""{h1}"" + $""{h2}""")] public void RefStructHandler_DynamicInHole(string expression) { var code = @" dynamic h1 = 1; dynamic h2 = 2; CustomHandler c = " + expression + ";"; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "ref struct", useBoolReturns: false); var comp = CreateCompilationWithCSharp(new[] { code, handler }); // Note: We don't give any errors when mixing dynamic and ref structs today. If that ever changes, we should get an // error here. This will crash at runtime because of this. comp.VerifyEmitDiagnostics(); } [Theory] [InlineData(@"$""Literal{1}""")] [InlineData(@"$""Literal"" + $""{1}""")] public void ConversionInParamsArguments(string expression) { var code = @" using System; using System.Linq; M(" + expression + ", " + expression + @"); void M(params CustomHandler[] handlers) { Console.WriteLine(string.Join(Environment.NewLine, handlers.Select(h => h.ToString()))); } "; var verifier = CompileAndVerify(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, expectedOutput: @" literal:Literal value:1 alignment:0 format: literal:Literal value:1 alignment:0 format: "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 100 (0x64) .maxstack 7 .locals init (CustomHandler V_0) IL_0000: ldc.i4.2 IL_0001: newarr ""CustomHandler"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldloca.s V_0 IL_000a: ldc.i4.7 IL_000b: ldc.i4.1 IL_000c: call ""CustomHandler..ctor(int, int)"" IL_0011: ldloca.s V_0 IL_0013: ldstr ""Literal"" IL_0018: call ""void CustomHandler.AppendLiteral(string)"" IL_001d: ldloca.s V_0 IL_001f: ldc.i4.1 IL_0020: box ""int"" IL_0025: ldc.i4.0 IL_0026: ldnull IL_0027: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_002c: ldloc.0 IL_002d: stelem ""CustomHandler"" IL_0032: dup IL_0033: ldc.i4.1 IL_0034: ldloca.s V_0 IL_0036: ldc.i4.7 IL_0037: ldc.i4.1 IL_0038: call ""CustomHandler..ctor(int, int)"" IL_003d: ldloca.s V_0 IL_003f: ldstr ""Literal"" IL_0044: call ""void CustomHandler.AppendLiteral(string)"" IL_0049: ldloca.s V_0 IL_004b: ldc.i4.1 IL_004c: box ""int"" IL_0051: ldc.i4.0 IL_0052: ldnull IL_0053: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0058: ldloc.0 IL_0059: stelem ""CustomHandler"" IL_005e: call ""void Program.<<Main>$>g__M|0_0(CustomHandler[])"" IL_0063: ret } "); } [Theory] [InlineData("static")] [InlineData("")] public void ArgumentsOnLocalFunctions_01(string mod) { var code = @" using System.Runtime.CompilerServices; M($""""); " + mod + @" void M([InterpolatedStringHandlerArgument("""")] CustomHandler c) { } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (4,3): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 3), // (6,10): error CS8944: 'M(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // void M([InterpolatedStringHandlerArgument("")] CustomHandler c) { } Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("M(CustomHandler)").WithLocation(6, 10 + mod.Length) ); } [Theory] [InlineData("static")] [InlineData("")] public void ArgumentsOnLocalFunctions_02(string mod) { var code = @" using System; using System.Runtime.CompilerServices; M(1, $""""); " + mod + @" void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) => _builder.Append(""i:"" + i.ToString()); } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: @"i:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 17 (0x11) .maxstack 4 .locals init (int V_0) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: call ""void Program.<<Main>$>g__M|0_0(int, CustomHandler)"" IL_0010: ret } "); } [Theory] [InlineData("static")] [InlineData("")] public void ArgumentsOnLambdas_01(string mod) { var code = @" using System.Runtime.CompilerServices; var a = " + mod + @" ([InterpolatedStringHandlerArgument("""")] CustomHandler c) => { }; a($""""); "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (4,12): warning CS8971: InterpolatedStringHandlerArgument has no effect when applied to lambda parameters and will be ignored at the call site. // var a = ([InterpolatedStringHandlerArgument("")] CustomHandler c) => { }; Diagnostic(ErrorCode.WRN_InterpolatedStringHandlerArgumentAttributeIgnoredOnLambdaParameters, @"InterpolatedStringHandlerArgument("""")").WithLocation(4, 12 + mod.Length), // (4,12): error CS8944: 'lambda expression' is not an instance method, the receiver cannot be an interpolated string handler argument. // var a = ([InterpolatedStringHandlerArgument("")] CustomHandler c) => { }; Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("lambda expression").WithLocation(4, 12 + mod.Length) ); } [Theory] [InlineData("static")] [InlineData("")] public void ArgumentsOnLambdas_02(string mod) { var code = @" using System; using System.Runtime.CompilerServices; var a = " + mod + @" (int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); a(1, $""""); partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) => throw null; } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: @""); verifier.VerifyDiagnostics( // (5,19): warning CS8971: InterpolatedStringHandlerArgument has no effect when applied to lambda parameters and will be ignored at the call site. // var a = (int i, [InterpolatedStringHandlerArgument("i")] CustomHandler c) => Console.WriteLine(c.ToString()); Diagnostic(ErrorCode.WRN_InterpolatedStringHandlerArgumentAttributeIgnoredOnLambdaParameters, @"InterpolatedStringHandlerArgument(""i"")").WithLocation(5, 19 + mod.Length) ); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 45 (0x2d) .maxstack 4 IL_0000: ldsfld ""System.Action<int, CustomHandler> Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<<Main>$>b__0_0(int, CustomHandler)"" IL_0014: newobj ""System.Action<int, CustomHandler>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Action<int, CustomHandler> Program.<>c.<>9__0_0"" IL_001f: ldc.i4.1 IL_0020: ldc.i4.0 IL_0021: ldc.i4.0 IL_0022: newobj ""CustomHandler..ctor(int, int)"" IL_0027: callvirt ""void System.Action<int, CustomHandler>.Invoke(int, CustomHandler)"" IL_002c: ret } "); } [Fact] public void ArgumentsOnDelegateTypes_01() { var code = @" using System.Runtime.CompilerServices; M m = null; m($""""); delegate void M([InterpolatedStringHandlerArgument("""")] CustomHandler c); "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (6,3): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // m($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(6, 3), // (8,18): error CS8944: 'M.Invoke(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // delegate void M([InterpolatedStringHandlerArgument("")] CustomHandler c); Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("M.Invoke(CustomHandler)").WithLocation(8, 18) ); } [Fact] public void ArgumentsOnDelegateTypes_02() { var vbCode = @" Imports System.Runtime.CompilerServices Public Delegate Sub M(<InterpolatedStringHandlerArgument("""")> c As CustomHandler) <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var code = @" M m = null; m($""""); "; var comp = CreateCompilation(code, references: new[] { vbComp.EmitToImageReference() }); comp.VerifyDiagnostics( // (4,3): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // m($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 3), // (4,3): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // m($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(4, 3), // (4,3): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // m($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(4, 3) ); } [Fact] public void ArgumentsOnDelegateTypes_03() { var code = @" using System; using System.Runtime.CompilerServices; M m = (i, c) => Console.WriteLine(c.ToString()); m(1, $""""); delegate void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c); partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) => _builder.Append(""i:"" + i.ToString()); } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: @"i:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 48 (0x30) .maxstack 5 .locals init (int V_0) IL_0000: ldsfld ""M Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<<Main>$>b__0_0(int, CustomHandler)"" IL_0014: newobj ""M..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""M Program.<>c.<>9__0_0"" IL_001f: ldc.i4.1 IL_0020: stloc.0 IL_0021: ldloc.0 IL_0022: ldc.i4.0 IL_0023: ldc.i4.0 IL_0024: ldloc.0 IL_0025: newobj ""CustomHandler..ctor(int, int, int)"" IL_002a: callvirt ""void M.Invoke(int, CustomHandler)"" IL_002f: ret } "); } [Fact] public void HandlerConstructorWithDefaultArgument_01() { var code = @" using System; using System.Runtime.CompilerServices; C.M($""""); class C { public static void M(CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] partial struct CustomHandler { private int _i = 0; public CustomHandler(int literalLength, int formattedCount, int i = 1) => _i = i; public override string ToString() => _i.ToString(); } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 14 (0xe) .maxstack 3 IL_0000: ldc.i4.0 IL_0001: ldc.i4.0 IL_0002: ldc.i4.1 IL_0003: newobj ""CustomHandler..ctor(int, int, int)"" IL_0008: call ""void C.M(CustomHandler)"" IL_000d: ret } "); } [Fact] public void HandlerConstructorWithDefaultArgument_02() { var code = @" using System; using System.Runtime.CompilerServices; C.M($""Literal""); class C { public static void M(CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] partial struct CustomHandler { private string _s = null; public CustomHandler(int literalLength, int formattedCount, out bool isValid, int i = 1) { _s = i.ToString(); isValid = false; } public void AppendLiteral(string s) => _s += s; public override string ToString() => _s; } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 38 (0x26) .maxstack 4 .locals init (CustomHandler V_0, bool V_1) IL_0000: ldc.i4.7 IL_0001: ldc.i4.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.1 IL_0005: newobj ""CustomHandler..ctor(int, int, out bool, int)"" IL_000a: stloc.0 IL_000b: ldloc.1 IL_000c: brfalse.s IL_001d IL_000e: ldloca.s V_0 IL_0010: ldstr ""Literal"" IL_0015: call ""void CustomHandler.AppendLiteral(string)"" IL_001a: ldc.i4.1 IL_001b: br.s IL_001e IL_001d: ldc.i4.0 IL_001e: pop IL_001f: ldloc.0 IL_0020: call ""void C.M(CustomHandler)"" IL_0025: ret } "); } [Fact] public void HandlerConstructorWithDefaultArgument_03() { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, $""""); class C { public static void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] partial struct CustomHandler { private string _s = null; public CustomHandler(int literalLength, int formattedCount, int i1, int i2 = 2) { _s = i1.ToString() + i2.ToString(); } public void AppendLiteral(string s) => _s += s; public override string ToString() => _s; } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"12"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 18 (0x12) .maxstack 5 .locals init (int V_0) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: ldc.i4.2 IL_0007: newobj ""CustomHandler..ctor(int, int, int, int)"" IL_000c: call ""void C.M(int, CustomHandler)"" IL_0011: ret } "); } [Fact] public void HandlerConstructorWithDefaultArgument_04() { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, $""Literal""); class C { public static void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] partial struct CustomHandler { private string _s = null; public CustomHandler(int literalLength, int formattedCount, int i1, out bool isValid, int i2 = 2) { _s = i1.ToString() + i2.ToString(); isValid = false; } public void AppendLiteral(string s) => _s += s; public override string ToString() => _s; } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"12"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 42 (0x2a) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.7 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: ldc.i4.2 IL_0009: newobj ""CustomHandler..ctor(int, int, int, out bool, int)"" IL_000e: stloc.1 IL_000f: ldloc.2 IL_0010: brfalse.s IL_0021 IL_0012: ldloca.s V_1 IL_0014: ldstr ""Literal"" IL_0019: call ""void CustomHandler.AppendLiteral(string)"" IL_001e: ldc.i4.1 IL_001f: br.s IL_0022 IL_0021: ldc.i4.0 IL_0022: pop IL_0023: ldloc.1 IL_0024: call ""void C.M(int, CustomHandler)"" IL_0029: ret } "); } [Fact] public void HandlerExtensionMethod_01() { var code = @" $""Test"".M(); public static class StringExt { public static void M(this CustomHandler handler) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (2,1): error CS1929: 'string' does not contain a definition for 'M' and the best extension method overload 'StringExt.M(CustomHandler)' requires a receiver of type 'CustomHandler' // $"Test".M(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, @"$""Test""").WithArguments("string", "M", "StringExt.M(CustomHandler)", "CustomHandler").WithLocation(2, 1) ); } [Fact] public void HandlerExtensionMethod_02() { var code = @" using System.Runtime.CompilerServices; var s = new S1(); s.M($""""); public struct S1 { public int Field = 1; } public static class S1Ext { public static void M(this S1 s, [InterpolatedStringHandlerArgument("""")] CustomHandler c) => throw null; } partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, S1 s) => throw null; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (5,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // s.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(5, 5), // (14,38): error CS8944: 'S1Ext.M(S1, CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // public static void M(this S1 s, [InterpolatedStringHandlerArgument("")] CustomHandler c) => throw null; Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("S1Ext.M(S1, CustomHandler)").WithLocation(14, 38) ); } [Fact] public void HandlerExtensionMethod_03() { var code = @" using System; using System.Runtime.CompilerServices; var s = new S1(); s.M($""""); public struct S1 { public int Field = 1; } public static class S1Ext { public static void M(this S1 s, [InterpolatedStringHandlerArgument(""s"")] CustomHandler c) => Console.WriteLine(c.ToString()); } partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, S1 s) : this(literalLength, formattedCount) => _builder.Append(""s.Field:"" + s.Field); } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: "s.Field:1"); verifier.VerifyDiagnostics(); } [Fact] public void NoStandaloneConstructor() { var code = @" using System.Runtime.CompilerServices; CustomHandler c = $""""; [InterpolatedStringHandler] struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s) {} } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }); comp.VerifyDiagnostics( // (4,19): error CS7036: There is no argument given that corresponds to the required formal parameter 's' of 'CustomHandler.CustomHandler(int, int, string)' // CustomHandler c = $""; Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, @"$""""").WithArguments("s", "CustomHandler.CustomHandler(int, int, string)").WithLocation(4, 19), // (4,19): error CS1615: Argument 3 may not be passed with the 'out' keyword // CustomHandler c = $""; Diagnostic(ErrorCode.ERR_BadArgExtraRef, @"$""""").WithArguments("3", "out").WithLocation(4, 19) ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using System.Collections.Immutable; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { public class InterpolationTests : CompilingTestBase { [Fact] public void TestSimpleInterp() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""Jenny don\'t change your number { number }.""); Console.WriteLine($""Jenny don\'t change your number { number , -12 }.""); Console.WriteLine($""Jenny don\'t change your number { number , 12 }.""); Console.WriteLine($""Jenny don\'t change your number { number :###-####}.""); Console.WriteLine($""Jenny don\'t change your number { number , -12 :###-####}.""); Console.WriteLine($""Jenny don\'t change your number { number , 12 :###-####}.""); Console.WriteLine($""{number}""); } }"; string expectedOutput = @"Jenny don't change your number 8675309. Jenny don't change your number 8675309 . Jenny don't change your number 8675309. Jenny don't change your number 867-5309. Jenny don't change your number 867-5309 . Jenny don't change your number 867-5309. 8675309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestOnlyInterp() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""{number}""); } }"; string expectedOutput = @"8675309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestDoubleInterp01() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""{number}{number}""); } }"; string expectedOutput = @"86753098675309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestDoubleInterp02() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""Jenny don\'t change your number { number :###-####} { number :###-####}.""); } }"; string expectedOutput = @"Jenny don't change your number 867-5309 867-5309."; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestEmptyInterp() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { /*trash*/ }.""); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,73): error CS1733: Expected expression // Console.WriteLine("Jenny don\'t change your number \{ /*trash*/ }."); Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(5, 73) ); } [Fact] public void TestHalfOpenInterp01() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { ""); } }"; // too many diagnostics perhaps, but it starts the right way. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,63): error CS1010: Newline in constant // Console.WriteLine($"Jenny don\'t change your number { "); Diagnostic(ErrorCode.ERR_NewlineInConst, "").WithLocation(5, 63), // (5,66): error CS8967: Newlines are not allowed inside a non-verbatim interpolated string // Console.WriteLine($"Jenny don\'t change your number { "); Diagnostic(ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, "").WithLocation(5, 66), // (6,6): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(6, 6), // (6,6): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 6), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2)); } [Fact] public void TestHalfOpenInterp02() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { 8675309 // ""); } }"; // too many diagnostics perhaps, but it starts the right way. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,71): error CS8077: A single-line comment may not be used in an interpolated string. // Console.WriteLine($"Jenny don\'t change your number { 8675309 // "); Diagnostic(ErrorCode.ERR_SingleLineCommentInExpressionHole, "//").WithLocation(5, 71), // (6,6): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(6, 6), // (6,6): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 6), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2)); } [Fact] public void TestHalfOpenInterp03() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { 8675309 /* ""); } }"; // too many diagnostics perhaps, but it starts the right way. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,71): error CS1035: End-of-file found, '*/' expected // Console.WriteLine($"Jenny don\'t change your number { 8675309 /* "); Diagnostic(ErrorCode.ERR_OpenEndedComment, "").WithLocation(5, 71), // (5,77): error CS8967: Newlines are not allowed inside a non-verbatim interpolated string // Console.WriteLine($"Jenny don\'t change your number { 8675309 /* "); Diagnostic(ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, "").WithLocation(5, 77), // (7,2): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 2), // (7,2): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 2), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2)); } [Fact] public void LambdaInInterp() { string source = @"using System; class Program { static void Main(string[] args) { //Console.WriteLine(""jenny {0:(408) ###-####}"", new object[] { ((Func<int>)(() => { return number; })).Invoke() }); Console.WriteLine($""jenny { ((Func<int>)(() => { return number; })).Invoke() :(408) ###-####}""); } static int number = 8675309; } "; string expectedOutput = @"jenny (408) 867-5309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OneLiteral() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""Hello"" ); } }"; string expectedOutput = @"Hello"; var verifier = CompileAndVerify(source, expectedOutput: expectedOutput); verifier.VerifyIL("Program.Main", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldstr ""Hello"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: ret } "); } [Fact] public void OneInsert() { string source = @"using System; class Program { static void Main(string[] args) { var hello = $""Hello""; Console.WriteLine( $""{hello}"" ); } }"; string expectedOutput = @"Hello"; var verifier = CompileAndVerify(source, expectedOutput: expectedOutput); verifier.VerifyIL("Program.Main", @" { // Code size 20 (0x14) .maxstack 2 IL_0000: ldstr ""Hello"" IL_0005: dup IL_0006: brtrue.s IL_000e IL_0008: pop IL_0009: ldstr """" IL_000e: call ""void System.Console.WriteLine(string)"" IL_0013: ret } "); } [Fact] public void TwoInserts() { string source = @"using System; class Program { static void Main(string[] args) { var hello = $""Hello""; var world = $""world"" ; Console.WriteLine( $""{hello}, { world }."" ); } }"; string expectedOutput = @"Hello, world."; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TwoInserts02() { string source = @"using System; class Program { static void Main(string[] args) { var hello = $""Hello""; var world = $""world"" ; Console.WriteLine( $@""{ hello }, { world }."" ); } }"; string expectedOutput = @"Hello, world."; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact, WorkItem(306, "https://github.com/dotnet/roslyn/issues/306"), WorkItem(308, "https://github.com/dotnet/roslyn/issues/308")] public void DynamicInterpolation() { string source = @"using System; using System.Linq.Expressions; class Program { static void Main(string[] args) { dynamic nil = null; dynamic a = new string[] {""Hello"", ""world""}; Console.WriteLine($""<{nil}>""); Console.WriteLine($""<{a}>""); } Expression<Func<string>> M(dynamic d) { return () => $""Dynamic: {d}""; } }"; string expectedOutput = @"<> <System.String[]>"; var verifier = CompileAndVerify(source, new[] { CSharpRef }, expectedOutput: expectedOutput).VerifyDiagnostics(); } [Fact] public void UnclosedInterpolation01() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,31): error CS1010: Newline in constant // Console.WriteLine( $"{" ); Diagnostic(ErrorCode.ERR_NewlineInConst, "").WithLocation(6, 31), // (6,35): error CS8958: Newlines are not allowed inside a non-verbatim interpolated string // Console.WriteLine( $"{" ); Diagnostic(ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, "").WithLocation(6, 35), // (7,6): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 6), // (7,6): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 6), // (8,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(8, 2)); } [Fact] public void UnclosedInterpolation02() { string source = @"class Program { static void Main(string[] args) { var x = $"";"; // The precise error messages are not important, but this must be an error. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,19): error CS1010: Newline in constant // var x = $"; Diagnostic(ErrorCode.ERR_NewlineInConst, ";").WithLocation(5, 19), // (5,20): error CS1002: ; expected // var x = $"; Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(5, 20), // (5,20): error CS1513: } expected // var x = $"; Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 20), // (5,20): error CS1513: } expected // var x = $"; Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 20) ); } [Fact] public void EmptyFormatSpecifier() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{3:}"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,32): error CS8089: Empty format specifier. // Console.WriteLine( $"{3:}" ); Diagnostic(ErrorCode.ERR_EmptyFormatSpecifier, ":").WithLocation(6, 32) ); } [Fact] public void TrailingSpaceInFormatSpecifier() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{3:d }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,32): error CS8088: A format specifier may not contain trailing whitespace. // Console.WriteLine( $"{3:d }" ); Diagnostic(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, ":d ").WithLocation(6, 32) ); } [Fact] public void TrailingSpaceInFormatSpecifier02() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $@""{3:d }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,33): error CS8088: A format specifier may not contain trailing whitespace. // Console.WriteLine( $@"{3:d Diagnostic(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, @":d ").WithLocation(6, 33) ); } [Fact] public void MissingInterpolationExpression01() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{ }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,32): error CS1733: Expected expression // Console.WriteLine( $"{ }" ); Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(6, 32) ); } [Fact] public void MissingInterpolationExpression02() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $@""{ }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,33): error CS1733: Expected expression // Console.WriteLine( $@"{ }" ); Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(6, 33) ); } [Fact] public void MissingInterpolationExpression03() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( "; var normal = "$\""; var verbat = "$@\""; // ensure reparsing of interpolated string token is precise in error scenarios (assertions do not fail) Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + " ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + "{").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + "{ ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + " ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + "{").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + "{ ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void MisplacedNewline01() { string source = @"using System; class Program { static void Main(string[] args) { var s = $""{ @"" "" } ""; } }"; // The precise error messages are not important, but this must be an error. Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void MisplacedNewline02() { string source = @"using System; class Program { static void Main(string[] args) { var s = $""{ @"" ""} ""; } }"; // The precise error messages are not important, but this must be an error. Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void PreprocessorInsideInterpolation() { string source = @"class Program { static void Main() { var s = $@""{ #region : #endregion 0 }""; } }"; // The precise error messages are not important, but this must be an error. Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void EscapedCurly() { string source = @"class Program { static void Main() { var s1 = $"" \u007B ""; var s2 = $"" \u007D""; } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,21): error CS8087: A '{' character may only be escaped by doubling '{{' in an interpolated string. // var s1 = $" \u007B "; Diagnostic(ErrorCode.ERR_EscapedCurly, @"\u007B").WithArguments("{").WithLocation(5, 21), // (6,21): error CS8087: A '}' character may only be escaped by doubling '}}' in an interpolated string. // var s2 = $" \u007D"; Diagnostic(ErrorCode.ERR_EscapedCurly, @"\u007D").WithArguments("}").WithLocation(6, 21) ); } [Fact, WorkItem(1119878, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119878")] public void NoFillIns01() { string source = @"class Program { static void Main() { System.Console.Write($""{{ x }}""); System.Console.WriteLine($@""This is a test""); } }"; string expectedOutput = @"{ x }This is a test"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BadAlignment() { string source = @"class Program { static void Main() { var s = $""{1,1E10}""; var t = $""{1,(int)1E10}""; } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,22): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // var s = $"{1,1E10}"; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1E10").WithArguments("double", "int").WithLocation(5, 22), // (5,22): error CS0150: A constant value is expected // var s = $"{1,1E10}"; Diagnostic(ErrorCode.ERR_ConstantExpected, "1E10").WithLocation(5, 22), // (6,22): error CS0221: Constant value '10000000000' cannot be converted to a 'int' (use 'unchecked' syntax to override) // var t = $"{1,(int)1E10}"; Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "(int)1E10").WithArguments("10000000000", "int").WithLocation(6, 22), // (6,22): error CS0150: A constant value is expected // var t = $"{1,(int)1E10}"; Diagnostic(ErrorCode.ERR_ConstantExpected, "(int)1E10").WithLocation(6, 22) ); } [Fact] public void NestedInterpolatedVerbatim() { string source = @"using System; class Program { static void Main(string[] args) { var s = $@""{$@""{1}""}""; Console.WriteLine(s); } }"; string expectedOutput = @"1"; CompileAndVerify(source, expectedOutput: expectedOutput); } // Since the platform type System.FormattableString is not yet in our platforms (at the // time of writing), we explicitly include the required platform types into the sources under test. private const string formattableString = @" /*============================================================ ** ** Class: FormattableString ** ** ** Purpose: implementation of the FormattableString ** class. ** ===========================================================*/ namespace System { /// <summary> /// A composite format string along with the arguments to be formatted. An instance of this /// type may result from the use of the C# or VB language primitive ""interpolated string"". /// </summary> public abstract class FormattableString : IFormattable { /// <summary> /// The composite format string. /// </summary> public abstract string Format { get; } /// <summary> /// Returns an object array that contains zero or more objects to format. Clients should not /// mutate the contents of the array. /// </summary> public abstract object[] GetArguments(); /// <summary> /// The number of arguments to be formatted. /// </summary> public abstract int ArgumentCount { get; } /// <summary> /// Returns one argument to be formatted from argument position <paramref name=""index""/>. /// </summary> public abstract object GetArgument(int index); /// <summary> /// Format to a string using the given culture. /// </summary> public abstract string ToString(IFormatProvider formatProvider); string IFormattable.ToString(string ignored, IFormatProvider formatProvider) { return ToString(formatProvider); } /// <summary> /// Format the given object in the invariant culture. This static method may be /// imported in C# by /// <code> /// using static System.FormattableString; /// </code>. /// Within the scope /// of that import directive an interpolated string may be formatted in the /// invariant culture by writing, for example, /// <code> /// Invariant($""{{ lat = {latitude}; lon = {longitude} }}"") /// </code> /// </summary> public static string Invariant(FormattableString formattable) { if (formattable == null) { throw new ArgumentNullException(""formattable""); } return formattable.ToString(Globalization.CultureInfo.InvariantCulture); } public override string ToString() { return ToString(Globalization.CultureInfo.CurrentCulture); } } } /*============================================================ ** ** Class: FormattableStringFactory ** ** ** Purpose: implementation of the FormattableStringFactory ** class. ** ===========================================================*/ namespace System.Runtime.CompilerServices { /// <summary> /// A factory type used by compilers to create instances of the type <see cref=""FormattableString""/>. /// </summary> public static class FormattableStringFactory { /// <summary> /// Create a <see cref=""FormattableString""/> from a composite format string and object /// array containing zero or more objects to format. /// </summary> public static FormattableString Create(string format, params object[] arguments) { if (format == null) { throw new ArgumentNullException(""format""); } if (arguments == null) { throw new ArgumentNullException(""arguments""); } return new ConcreteFormattableString(format, arguments); } private sealed class ConcreteFormattableString : FormattableString { private readonly string _format; private readonly object[] _arguments; internal ConcreteFormattableString(string format, object[] arguments) { _format = format; _arguments = arguments; } public override string Format { get { return _format; } } public override object[] GetArguments() { return _arguments; } public override int ArgumentCount { get { return _arguments.Length; } } public override object GetArgument(int index) { return _arguments[index]; } public override string ToString(IFormatProvider formatProvider) { return string.Format(formatProvider, Format, _arguments); } } } } "; [Fact] public void TargetType01() { string source = @"using System; class Program { public static void Main(string[] args) { IFormattable f = $""test""; Console.Write(f is System.FormattableString); } }"; CompileAndVerify(source + formattableString, expectedOutput: "True"); } [Fact] public void TargetType02() { string source = @"using System; interface I1 { void M(String s); } interface I2 { void M(FormattableString s); } interface I3 { void M(IFormattable s); } interface I4 : I1, I2 {} interface I5 : I1, I3 {} interface I6 : I2, I3 {} interface I7 : I1, I2, I3 {} class C : I1, I2, I3, I4, I5, I6, I7 { public void M(String s) { Console.Write(1); } public void M(FormattableString s) { Console.Write(2); } public void M(IFormattable s) { Console.Write(3); } } class Program { public static void Main(string[] args) { C c = new C(); ((I1)c).M($""""); ((I2)c).M($""""); ((I3)c).M($""""); ((I4)c).M($""""); ((I5)c).M($""""); ((I6)c).M($""""); ((I7)c).M($""""); ((C)c).M($""""); } }"; CompileAndVerify(source + formattableString, expectedOutput: "12311211"); } [Fact] public void MissingHelper() { string source = @"using System; class Program { public static void Main(string[] args) { IFormattable f = $""test""; } }"; CreateCompilationWithMscorlib40(source).VerifyEmitDiagnostics( // (5,26): error CS0518: Predefined type 'System.Runtime.CompilerServices.FormattableStringFactory' is not defined or imported // IFormattable f = $"test"; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"$""test""").WithArguments("System.Runtime.CompilerServices.FormattableStringFactory").WithLocation(5, 26) ); } [Fact] public void AsyncInterp() { string source = @"using System; using System.Threading.Tasks; class Program { public static void Main(string[] args) { Task<string> hello = Task.FromResult(""Hello""); Task<string> world = Task.FromResult(""world""); M(hello, world).Wait(); } public static async Task M(Task<string> hello, Task<string> world) { Console.WriteLine($""{ await hello }, { await world }!""); } }"; CompileAndVerify( source, references: new[] { MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929 }, expectedOutput: "Hello, world!", targetFramework: TargetFramework.Empty); } [Fact] public void AlignmentExpression() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { 123 , -(3+4) }.""); } }"; CompileAndVerify(source + formattableString, expectedOutput: "X = 123 ."); } [Fact] public void AlignmentMagnitude() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { 123 , (32768) }.""); Console.WriteLine($""X = { 123 , -(32768) }.""); Console.WriteLine($""X = { 123 , (32767) }.""); Console.WriteLine($""X = { 123 , -(32767) }.""); Console.WriteLine($""X = { 123 , int.MaxValue }.""); Console.WriteLine($""X = { 123 , int.MinValue }.""); } }"; CreateCompilation(source).VerifyDiagnostics( // (5,42): warning CS8094: Alignment value 32768 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , (32768) }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "32768").WithArguments("32768", "32767").WithLocation(5, 42), // (6,41): warning CS8094: Alignment value -32768 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , -(32768) }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "-(32768)").WithArguments("-32768", "32767").WithLocation(6, 41), // (9,41): warning CS8094: Alignment value 2147483647 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , int.MaxValue }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "int.MaxValue").WithArguments("2147483647", "32767").WithLocation(9, 41), // (10,41): warning CS8094: Alignment value -2147483648 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , int.MinValue }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "int.MinValue").WithArguments("-2147483648", "32767").WithLocation(10, 41) ); } [WorkItem(1097388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097388")] [Fact] public void InterpolationExpressionMustBeValue01() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { String }.""); Console.WriteLine($""X = { null }.""); } }"; CreateCompilation(source).VerifyDiagnostics( // (5,35): error CS0119: 'string' is a type, which is not valid in the given context // Console.WriteLine($"X = { String }."); Diagnostic(ErrorCode.ERR_BadSKunknown, "String").WithArguments("string", "type").WithLocation(5, 35) ); } [Fact] public void InterpolationExpressionMustBeValue02() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { x=>3 }.""); Console.WriteLine($""X = { Program.Main }.""); Console.WriteLine($""X = { Program.Main(null) }.""); } }"; CreateCompilation(source, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (5,35): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // Console.WriteLine($"X = { x=>3 }."); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x=>3").WithArguments("lambda expression", "object").WithLocation(5, 35), // (6,43): error CS0428: Cannot convert method group 'Main' to non-delegate type 'object'. Did you intend to invoke the method? // Console.WriteLine($"X = { Program.Main }."); Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "object").WithLocation(6, 43), // (7,35): error CS0029: Cannot implicitly convert type 'void' to 'object' // Console.WriteLine($"X = { Program.Main(null) }."); Diagnostic(ErrorCode.ERR_NoImplicitConv, "Program.Main(null)").WithArguments("void", "object").WithLocation(7, 35) ); CreateCompilation(source).VerifyDiagnostics( // (5,35): error CS8917: The delegate type could not be inferred. // Console.WriteLine($"X = { x=>3 }."); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x=>3").WithLocation(5, 35), // (7,35): error CS0029: Cannot implicitly convert type 'void' to 'object' // Console.WriteLine($"X = { Program.Main(null) }."); Diagnostic(ErrorCode.ERR_NoImplicitConv, "Program.Main(null)").WithArguments("void", "object").WithLocation(7, 35) ); } [WorkItem(1097428, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097428")] [Fact] public void BadCorelib01() { var text = @"namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } } public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } } public struct Char { } public class String { } internal class Program { public static void Main() { var s = $""X = { 1 } ""; } } }"; CreateEmptyCompilation(text, options: TestOptions.DebugExe) .VerifyEmitDiagnostics(new CodeAnalysis.Emit.EmitOptions(runtimeMetadataVersion: "x.y"), // (15,21): error CS0117: 'string' does not contain a definition for 'Format' // var s = $"X = { 1 } "; Diagnostic(ErrorCode.ERR_NoSuchMember, @"$""X = { 1 } """).WithArguments("string", "Format").WithLocation(15, 21) ); } [WorkItem(1097428, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097428")] [Fact] public void BadCorelib02() { var text = @"namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } } public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } } public struct Char { } public class String { public static Boolean Format(string format, int arg) { return true; } } internal class Program { public static void Main() { var s = $""X = { 1 } ""; } } }"; CreateEmptyCompilation(text, options: TestOptions.DebugExe) .VerifyEmitDiagnostics(new CodeAnalysis.Emit.EmitOptions(runtimeMetadataVersion: "x.y"), // (17,21): error CS0029: Cannot implicitly convert type 'bool' to 'string' // var s = $"X = { 1 } "; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""X = { 1 } """).WithArguments("bool", "string").WithLocation(17, 21) ); } [Fact] public void SillyCoreLib01() { var text = @"namespace System { interface IFormattable { } namespace Runtime.CompilerServices { public static class FormattableStringFactory { public static Bozo Create(string format, int arg) { return new Bozo(); } } } public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } } public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } } public struct Char { } public class String { public static Bozo Format(string format, int arg) { return new Bozo(); } } public class FormattableString { } public class Bozo { public static implicit operator string(Bozo bozo) { return ""zz""; } public static implicit operator FormattableString(Bozo bozo) { return new FormattableString(); } } internal class Program { public static void Main() { var s1 = $""X = { 1 } ""; FormattableString s2 = $""X = { 1 } ""; } } }"; var comp = CreateEmptyCompilation(text, options: Test.Utilities.TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); var compilation = CompileAndVerify(comp, verify: Verification.Fails); compilation.VerifyIL("System.Program.Main", @"{ // Code size 35 (0x23) .maxstack 2 IL_0000: ldstr ""X = {0} "" IL_0005: ldc.i4.1 IL_0006: call ""System.Bozo string.Format(string, int)"" IL_000b: call ""string System.Bozo.op_Implicit(System.Bozo)"" IL_0010: pop IL_0011: ldstr ""X = {0} "" IL_0016: ldc.i4.1 IL_0017: call ""System.Bozo System.Runtime.CompilerServices.FormattableStringFactory.Create(string, int)"" IL_001c: call ""System.FormattableString System.Bozo.op_Implicit(System.Bozo)"" IL_0021: pop IL_0022: ret }"); } [WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")] [Fact] public void Syntax01() { var text = @"using System; class Program { static void Main(string[] args) { var x = $""{ Math.Abs(value: 1):\}""; var y = x; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,40): error CS8087: A '}' character may only be escaped by doubling '}}' in an interpolated string. // var x = $"{ Math.Abs(value: 1):\}"; Diagnostic(ErrorCode.ERR_EscapedCurly, @"\").WithArguments("}").WithLocation(6, 40), // (6,40): error CS1009: Unrecognized escape sequence // var x = $"{ Math.Abs(value: 1):\}"; Diagnostic(ErrorCode.ERR_IllegalEscape, @"\}").WithLocation(6, 40) ); } [WorkItem(1097941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097941")] [Fact] public void Syntax02() { var text = @"using S = System; class C { void M() { var x = $""{ (S: } }"; // the precise diagnostics do not matter, as long as it is an error and not a crash. Assert.True(SyntaxFactory.ParseSyntaxTree(text).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")] [Fact] public void Syntax03() { var text = @"using System; class Program { static void Main(string[] args) { var x = $""{ Math.Abs(value: 1):}}""; var y = x; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,18): error CS8076: Missing close delimiter '}' for interpolated expression started with '{'. // var x = $"{ Math.Abs(value: 1):}}"; Diagnostic(ErrorCode.ERR_UnclosedExpressionHole, @"""{").WithLocation(6, 18) ); } [WorkItem(1099105, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1099105")] [Fact] public void NoUnexpandedForm() { string source = @"using System; class Program { public static void Main(string[] args) { string[] arr1 = new string[] { ""xyzzy"" }; object[] arr2 = arr1; Console.WriteLine($""-{null}-""); Console.WriteLine($""-{arr1}-""); Console.WriteLine($""-{arr2}-""); } }"; CompileAndVerify(source + formattableString, expectedOutput: @"-- -System.String[]- -System.String[]-"); } [WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")] [Fact] public void Dynamic01() { var text = @"class C { const dynamic a = a; string s = $""{0,a}""; }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (3,19): error CS0110: The evaluation of the constant value for 'C.a' involves a circular definition // const dynamic a = a; Diagnostic(ErrorCode.ERR_CircConstValue, "a").WithArguments("C.a").WithLocation(3, 19), // (3,23): error CS0134: 'C.a' is of type 'dynamic'. A const field of a reference type other than string can only be initialized with null. // const dynamic a = a; Diagnostic(ErrorCode.ERR_NotNullConstRefField, "a").WithArguments("C.a", "dynamic").WithLocation(3, 23), // (4,21): error CS0150: A constant value is expected // string s = $"{0,a}"; Diagnostic(ErrorCode.ERR_ConstantExpected, "a").WithLocation(4, 21) ); } [WorkItem(1099238, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1099238")] [Fact] public void Syntax04() { var text = @"using System; using System.Linq.Expressions; class Program { static void Main() { Expression<Func<string>> e = () => $""\u1{0:\u2}""; Console.WriteLine(e); } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (8,46): error CS1009: Unrecognized escape sequence // Expression<Func<string>> e = () => $"\u1{0:\u2}"; Diagnostic(ErrorCode.ERR_IllegalEscape, @"\u1").WithLocation(8, 46), // (8,52): error CS1009: Unrecognized escape sequence // Expression<Func<string>> e = () => $"\u1{0:\u2}"; Diagnostic(ErrorCode.ERR_IllegalEscape, @"\u2").WithLocation(8, 52) ); } [Fact, WorkItem(1098612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1098612")] public void MissingConversionFromFormattableStringToIFormattable() { var text = @"namespace System.Runtime.CompilerServices { public static class FormattableStringFactory { public static FormattableString Create(string format, params object[] arguments) { return null; } } } namespace System { public abstract class FormattableString { } } static class C { static void Main() { System.IFormattable i = $""{""""}""; } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyEmitDiagnostics( // (23,33): error CS0029: Cannot implicitly convert type 'FormattableString' to 'IFormattable' // System.IFormattable i = $"{""}"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{""""}""").WithArguments("System.FormattableString", "System.IFormattable").WithLocation(23, 33) ); } [Theory, WorkItem(54702, "https://github.com/dotnet/roslyn/issues/54702")] [InlineData(@"$""{s1}{s2}""", @"$""{s1}{s2}{s3}""", @"$""{s1}{s2}{s3}{s4}""", @"$""{s1}{s2}{s3}{s4}{s5}""")] [InlineData(@"$""{s1}"" + $""{s2}""", @"$""{s1}"" + $""{s2}"" + $""{s3}""", @"$""{s1}"" + $""{s2}"" + $""{s3}"" + $""{s4}""", @"$""{s1}"" + $""{s2}"" + $""{s3}"" + $""{s4}"" + $""{s5}""")] public void InterpolatedStringHandler_ConcatPreferencesForAllStringElements(string twoComponents, string threeComponents, string fourComponents, string fiveComponents) { var code = @" using System; Console.WriteLine(TwoComponents()); Console.WriteLine(ThreeComponents()); Console.WriteLine(FourComponents()); Console.WriteLine(FiveComponents()); string TwoComponents() { string s1 = ""1""; string s2 = ""2""; return " + twoComponents + @"; } string ThreeComponents() { string s1 = ""1""; string s2 = ""2""; string s3 = ""3""; return " + threeComponents + @"; } string FourComponents() { string s1 = ""1""; string s2 = ""2""; string s3 = ""3""; string s4 = ""4""; return " + fourComponents + @"; } string FiveComponents() { string s1 = ""1""; string s2 = ""2""; string s3 = ""3""; string s4 = ""4""; string s5 = ""5""; return " + fiveComponents + @"; } "; var handler = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { code, handler }, expectedOutput: @" 12 123 1234 value:1 value:2 value:3 value:4 value:5 "); verifier.VerifyIL("Program.<<Main>$>g__TwoComponents|0_0()", @" { // Code size 18 (0x12) .maxstack 2 .locals init (string V_0) //s2 IL_0000: ldstr ""1"" IL_0005: ldstr ""2"" IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: call ""string string.Concat(string, string)"" IL_0011: ret } "); verifier.VerifyIL("Program.<<Main>$>g__ThreeComponents|0_1()", @" { // Code size 25 (0x19) .maxstack 3 .locals init (string V_0, //s2 string V_1) //s3 IL_0000: ldstr ""1"" IL_0005: ldstr ""2"" IL_000a: stloc.0 IL_000b: ldstr ""3"" IL_0010: stloc.1 IL_0011: ldloc.0 IL_0012: ldloc.1 IL_0013: call ""string string.Concat(string, string, string)"" IL_0018: ret } "); verifier.VerifyIL("Program.<<Main>$>g__FourComponents|0_2()", @" { // Code size 32 (0x20) .maxstack 4 .locals init (string V_0, //s2 string V_1, //s3 string V_2) //s4 IL_0000: ldstr ""1"" IL_0005: ldstr ""2"" IL_000a: stloc.0 IL_000b: ldstr ""3"" IL_0010: stloc.1 IL_0011: ldstr ""4"" IL_0016: stloc.2 IL_0017: ldloc.0 IL_0018: ldloc.1 IL_0019: ldloc.2 IL_001a: call ""string string.Concat(string, string, string, string)"" IL_001f: ret } "); verifier.VerifyIL("Program.<<Main>$>g__FiveComponents|0_3()", @" { // Code size 89 (0x59) .maxstack 3 .locals init (string V_0, //s1 string V_1, //s2 string V_2, //s3 string V_3, //s4 string V_4, //s5 System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_5) IL_0000: ldstr ""1"" IL_0005: stloc.0 IL_0006: ldstr ""2"" IL_000b: stloc.1 IL_000c: ldstr ""3"" IL_0011: stloc.2 IL_0012: ldstr ""4"" IL_0017: stloc.3 IL_0018: ldstr ""5"" IL_001d: stloc.s V_4 IL_001f: ldloca.s V_5 IL_0021: ldc.i4.0 IL_0022: ldc.i4.5 IL_0023: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0028: ldloca.s V_5 IL_002a: ldloc.0 IL_002b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0030: ldloca.s V_5 IL_0032: ldloc.1 IL_0033: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0038: ldloca.s V_5 IL_003a: ldloc.2 IL_003b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0040: ldloca.s V_5 IL_0042: ldloc.3 IL_0043: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0048: ldloca.s V_5 IL_004a: ldloc.s V_4 IL_004c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0051: ldloca.s V_5 IL_0053: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0058: ret } "); } [Theory] [CombinatorialData] public void InterpolatedStringHandler_OverloadsAndBoolReturns( bool useDefaultParameters, bool useBoolReturns, bool constructorBoolArg, [CombinatorialValues(@"$""base{a}{a,1}{a:X}{a,2:Y}""", @"$""base"" + $""{a}"" + $""{a,1}"" + $""{a:X}"" + $""{a,2:Y}""")] string expression) { var source = @"int a = 1; System.Console.WriteLine(" + expression + @");"; string interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters, useBoolReturns, constructorBoolArg: constructorBoolArg); string expectedOutput = useDefaultParameters ? @"base value:1,alignment:0:format: value:1,alignment:1:format: value:1,alignment:0:format:X value:1,alignment:2:format:Y" : @"base value:1 value:1,alignment:1 value:1:format:X value:1,alignment:2:format:Y"; string expectedIl = getIl(); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: expectedOutput); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); var comp1 = CreateCompilation(interpolatedStringBuilder); foreach (var reference in new[] { comp1.EmitToImageReference(), comp1.ToMetadataReference() }) { var comp2 = CreateCompilation(source, new[] { reference }); verifier = CompileAndVerify(comp2, expectedOutput: expectedOutput); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); } string getIl() => (useDefaultParameters, useBoolReturns, constructorBoolArg) switch { (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 80 (0x50) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_1 IL_0019: ldloc.0 IL_001a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_001f: ldloca.s V_1 IL_0021: ldloc.0 IL_0022: ldc.i4.1 IL_0023: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_0028: ldloca.s V_1 IL_002a: ldloc.0 IL_002b: ldstr ""X"" IL_0030: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldloc.0 IL_0038: ldc.i4.2 IL_0039: ldstr ""Y"" IL_003e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0043: ldloca.s V_1 IL_0045: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_004a: call ""void System.Console.WriteLine(string)"" IL_004f: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 84 (0x54) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_1 IL_0019: ldloc.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0021: ldloca.s V_1 IL_0023: ldloc.0 IL_0024: ldc.i4.1 IL_0025: ldnull IL_0026: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_002b: ldloca.s V_1 IL_002d: ldloc.0 IL_002e: ldc.i4.0 IL_002f: ldstr ""X"" IL_0034: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0039: ldloca.s V_1 IL_003b: ldloc.0 IL_003c: ldc.i4.2 IL_003d: ldstr ""Y"" IL_0042: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0047: ldloca.s V_1 IL_0049: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_004e: call ""void System.Console.WriteLine(string)"" IL_0053: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 92 (0x5c) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: brfalse.s IL_004d IL_0019: ldloca.s V_1 IL_001b: ldloc.0 IL_001c: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0021: brfalse.s IL_004d IL_0023: ldloca.s V_1 IL_0025: ldloc.0 IL_0026: ldc.i4.1 IL_0027: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_002c: brfalse.s IL_004d IL_002e: ldloca.s V_1 IL_0030: ldloc.0 IL_0031: ldstr ""X"" IL_0036: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_003b: brfalse.s IL_004d IL_003d: ldloca.s V_1 IL_003f: ldloc.0 IL_0040: ldc.i4.2 IL_0041: ldstr ""Y"" IL_0046: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004b: br.s IL_004e IL_004d: ldc.i4.0 IL_004e: pop IL_004f: ldloca.s V_1 IL_0051: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0056: call ""void System.Console.WriteLine(string)"" IL_005b: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 96 (0x60) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: brfalse.s IL_0051 IL_0019: ldloca.s V_1 IL_001b: ldloc.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0023: brfalse.s IL_0051 IL_0025: ldloca.s V_1 IL_0027: ldloc.0 IL_0028: ldc.i4.1 IL_0029: ldnull IL_002a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_002f: brfalse.s IL_0051 IL_0031: ldloca.s V_1 IL_0033: ldloc.0 IL_0034: ldc.i4.0 IL_0035: ldstr ""X"" IL_003a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_003f: brfalse.s IL_0051 IL_0041: ldloca.s V_1 IL_0043: ldloc.0 IL_0044: ldc.i4.2 IL_0045: ldstr ""Y"" IL_004a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004f: br.s IL_0052 IL_0051: ldc.i4.0 IL_0052: pop IL_0053: ldloca.s V_1 IL_0055: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005a: call ""void System.Console.WriteLine(string)"" IL_005f: ret } ", (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 89 (0x59) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_004a IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: ldloca.s V_1 IL_001d: ldloc.0 IL_001e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0023: ldloca.s V_1 IL_0025: ldloc.0 IL_0026: ldc.i4.1 IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_002c: ldloca.s V_1 IL_002e: ldloc.0 IL_002f: ldstr ""X"" IL_0034: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_0039: ldloca.s V_1 IL_003b: ldloc.0 IL_003c: ldc.i4.2 IL_003d: ldstr ""Y"" IL_0042: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0047: ldc.i4.1 IL_0048: br.s IL_004b IL_004a: ldc.i4.0 IL_004b: pop IL_004c: ldloca.s V_1 IL_004e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0053: call ""void System.Console.WriteLine(string)"" IL_0058: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 93 (0x5d) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_004e IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: ldloca.s V_1 IL_001d: ldloc.0 IL_001e: ldc.i4.0 IL_001f: ldnull IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0025: ldloca.s V_1 IL_0027: ldloc.0 IL_0028: ldc.i4.1 IL_0029: ldnull IL_002a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_002f: ldloca.s V_1 IL_0031: ldloc.0 IL_0032: ldc.i4.0 IL_0033: ldstr ""X"" IL_0038: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_003d: ldloca.s V_1 IL_003f: ldloc.0 IL_0040: ldc.i4.2 IL_0041: ldstr ""Y"" IL_0046: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004b: ldc.i4.1 IL_004c: br.s IL_004f IL_004e: ldc.i4.0 IL_004f: pop IL_0050: ldloca.s V_1 IL_0052: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0057: call ""void System.Console.WriteLine(string)"" IL_005c: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 96 (0x60) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_0051 IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: brfalse.s IL_0051 IL_001d: ldloca.s V_1 IL_001f: ldloc.0 IL_0020: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0025: brfalse.s IL_0051 IL_0027: ldloca.s V_1 IL_0029: ldloc.0 IL_002a: ldc.i4.1 IL_002b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_0030: brfalse.s IL_0051 IL_0032: ldloca.s V_1 IL_0034: ldloc.0 IL_0035: ldstr ""X"" IL_003a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_003f: brfalse.s IL_0051 IL_0041: ldloca.s V_1 IL_0043: ldloc.0 IL_0044: ldc.i4.2 IL_0045: ldstr ""Y"" IL_004a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004f: br.s IL_0052 IL_0051: ldc.i4.0 IL_0052: pop IL_0053: ldloca.s V_1 IL_0055: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005a: call ""void System.Console.WriteLine(string)"" IL_005f: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 100 (0x64) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_0055 IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: brfalse.s IL_0055 IL_001d: ldloca.s V_1 IL_001f: ldloc.0 IL_0020: ldc.i4.0 IL_0021: ldnull IL_0022: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0027: brfalse.s IL_0055 IL_0029: ldloca.s V_1 IL_002b: ldloc.0 IL_002c: ldc.i4.1 IL_002d: ldnull IL_002e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0033: brfalse.s IL_0055 IL_0035: ldloca.s V_1 IL_0037: ldloc.0 IL_0038: ldc.i4.0 IL_0039: ldstr ""X"" IL_003e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0043: brfalse.s IL_0055 IL_0045: ldloca.s V_1 IL_0047: ldloc.0 IL_0048: ldc.i4.2 IL_0049: ldstr ""Y"" IL_004e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0053: br.s IL_0056 IL_0055: ldc.i4.0 IL_0056: pop IL_0057: ldloca.s V_1 IL_0059: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005e: call ""void System.Console.WriteLine(string)"" IL_0063: ret } ", }; } [Fact] public void UseOfSpanInInterpolationHole_CSharp9() { var source = @" using System; ReadOnlySpan<char> span = stackalloc char[1]; Console.WriteLine($""{span}"");"; var comp = CreateCompilation(new[] { source, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false) }, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,22): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // Console.WriteLine($"{span}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "span").WithArguments("interpolated string handlers", "10.0").WithLocation(4, 22) ); } [ConditionalTheory(typeof(MonoOrCoreClrOnly))] [CombinatorialData] public void UseOfSpanInInterpolationHole(bool useDefaultParameters, bool useBoolReturns, bool constructorBoolArg, [CombinatorialValues(@"$""base{a}{a,1}{a:X}{a,2:Y}""", @"$""base"" + $""{a}"" + $""{a,1}"" + $""{a:X}"" + $""{a,2:Y}""")] string expression) { var source = @" using System; ReadOnlySpan<char> a = ""1""; System.Console.WriteLine(" + expression + ");"; string interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters, useBoolReturns, constructorBoolArg: constructorBoolArg); string expectedOutput = useDefaultParameters ? @"base value:1,alignment:0:format: value:1,alignment:1:format: value:1,alignment:0:format:X value:1,alignment:2:format:Y" : @"base value:1 value:1,alignment:1 value:1:format:X value:1,alignment:2:format:Y"; string expectedIl = getIl(); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: expectedOutput, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular10); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); var comp1 = CreateCompilation(interpolatedStringBuilder, targetFramework: TargetFramework.NetCoreApp); foreach (var reference in new[] { comp1.EmitToImageReference(), comp1.ToMetadataReference() }) { var comp2 = CreateCompilation(source, new[] { reference }, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular10); verifier = CompileAndVerify(comp2, expectedOutput: expectedOutput); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); } string getIl() => (useDefaultParameters, useBoolReturns, constructorBoolArg) switch { (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 89 (0x59) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: ldloca.s V_1 IL_0022: ldloc.0 IL_0023: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_0028: ldloca.s V_1 IL_002a: ldloc.0 IL_002b: ldc.i4.1 IL_002c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0031: ldloca.s V_1 IL_0033: ldloc.0 IL_0034: ldstr ""X"" IL_0039: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_003e: ldloca.s V_1 IL_0040: ldloc.0 IL_0041: ldc.i4.2 IL_0042: ldstr ""Y"" IL_0047: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_004c: ldloca.s V_1 IL_004e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0053: call ""void System.Console.WriteLine(string)"" IL_0058: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 93 (0x5d) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: ldloca.s V_1 IL_0022: ldloc.0 IL_0023: ldc.i4.0 IL_0024: ldnull IL_0025: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_002a: ldloca.s V_1 IL_002c: ldloc.0 IL_002d: ldc.i4.1 IL_002e: ldnull IL_002f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0034: ldloca.s V_1 IL_0036: ldloc.0 IL_0037: ldc.i4.0 IL_0038: ldstr ""X"" IL_003d: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0042: ldloca.s V_1 IL_0044: ldloc.0 IL_0045: ldc.i4.2 IL_0046: ldstr ""Y"" IL_004b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0050: ldloca.s V_1 IL_0052: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0057: call ""void System.Console.WriteLine(string)"" IL_005c: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 101 (0x65) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: brfalse.s IL_0056 IL_0022: ldloca.s V_1 IL_0024: ldloc.0 IL_0025: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_002a: brfalse.s IL_0056 IL_002c: ldloca.s V_1 IL_002e: ldloc.0 IL_002f: ldc.i4.1 IL_0030: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0035: brfalse.s IL_0056 IL_0037: ldloca.s V_1 IL_0039: ldloc.0 IL_003a: ldstr ""X"" IL_003f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_0044: brfalse.s IL_0056 IL_0046: ldloca.s V_1 IL_0048: ldloc.0 IL_0049: ldc.i4.2 IL_004a: ldstr ""Y"" IL_004f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0054: br.s IL_0057 IL_0056: ldc.i4.0 IL_0057: pop IL_0058: ldloca.s V_1 IL_005a: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005f: call ""void System.Console.WriteLine(string)"" IL_0064: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 105 (0x69) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: brfalse.s IL_005a IL_0022: ldloca.s V_1 IL_0024: ldloc.0 IL_0025: ldc.i4.0 IL_0026: ldnull IL_0027: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_002c: brfalse.s IL_005a IL_002e: ldloca.s V_1 IL_0030: ldloc.0 IL_0031: ldc.i4.1 IL_0032: ldnull IL_0033: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0038: brfalse.s IL_005a IL_003a: ldloca.s V_1 IL_003c: ldloc.0 IL_003d: ldc.i4.0 IL_003e: ldstr ""X"" IL_0043: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0048: brfalse.s IL_005a IL_004a: ldloca.s V_1 IL_004c: ldloc.0 IL_004d: ldc.i4.2 IL_004e: ldstr ""Y"" IL_0053: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0058: br.s IL_005b IL_005a: ldc.i4.0 IL_005b: pop IL_005c: ldloca.s V_1 IL_005e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0063: call ""void System.Console.WriteLine(string)"" IL_0068: ret } ", (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 98 (0x62) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_0053 IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: ldloca.s V_1 IL_0026: ldloc.0 IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_002c: ldloca.s V_1 IL_002e: ldloc.0 IL_002f: ldc.i4.1 IL_0030: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0035: ldloca.s V_1 IL_0037: ldloc.0 IL_0038: ldstr ""X"" IL_003d: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_0042: ldloca.s V_1 IL_0044: ldloc.0 IL_0045: ldc.i4.2 IL_0046: ldstr ""Y"" IL_004b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0050: ldc.i4.1 IL_0051: br.s IL_0054 IL_0053: ldc.i4.0 IL_0054: pop IL_0055: ldloca.s V_1 IL_0057: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005c: call ""void System.Console.WriteLine(string)"" IL_0061: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 105 (0x69) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_005a IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: brfalse.s IL_005a IL_0026: ldloca.s V_1 IL_0028: ldloc.0 IL_0029: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_002e: brfalse.s IL_005a IL_0030: ldloca.s V_1 IL_0032: ldloc.0 IL_0033: ldc.i4.1 IL_0034: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0039: brfalse.s IL_005a IL_003b: ldloca.s V_1 IL_003d: ldloc.0 IL_003e: ldstr ""X"" IL_0043: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_0048: brfalse.s IL_005a IL_004a: ldloca.s V_1 IL_004c: ldloc.0 IL_004d: ldc.i4.2 IL_004e: ldstr ""Y"" IL_0053: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0058: br.s IL_005b IL_005a: ldc.i4.0 IL_005b: pop IL_005c: ldloca.s V_1 IL_005e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0063: call ""void System.Console.WriteLine(string)"" IL_0068: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 102 (0x66) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_0057 IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: ldloca.s V_1 IL_0026: ldloc.0 IL_0027: ldc.i4.0 IL_0028: ldnull IL_0029: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_002e: ldloca.s V_1 IL_0030: ldloc.0 IL_0031: ldc.i4.1 IL_0032: ldnull IL_0033: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0038: ldloca.s V_1 IL_003a: ldloc.0 IL_003b: ldc.i4.0 IL_003c: ldstr ""X"" IL_0041: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0046: ldloca.s V_1 IL_0048: ldloc.0 IL_0049: ldc.i4.2 IL_004a: ldstr ""Y"" IL_004f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0054: ldc.i4.1 IL_0055: br.s IL_0058 IL_0057: ldc.i4.0 IL_0058: pop IL_0059: ldloca.s V_1 IL_005b: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0060: call ""void System.Console.WriteLine(string)"" IL_0065: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 109 (0x6d) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_005e IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: brfalse.s IL_005e IL_0026: ldloca.s V_1 IL_0028: ldloc.0 IL_0029: ldc.i4.0 IL_002a: ldnull IL_002b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0030: brfalse.s IL_005e IL_0032: ldloca.s V_1 IL_0034: ldloc.0 IL_0035: ldc.i4.1 IL_0036: ldnull IL_0037: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_003c: brfalse.s IL_005e IL_003e: ldloca.s V_1 IL_0040: ldloc.0 IL_0041: ldc.i4.0 IL_0042: ldstr ""X"" IL_0047: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_004c: brfalse.s IL_005e IL_004e: ldloca.s V_1 IL_0050: ldloc.0 IL_0051: ldc.i4.2 IL_0052: ldstr ""Y"" IL_0057: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_005c: br.s IL_005f IL_005e: ldc.i4.0 IL_005f: pop IL_0060: ldloca.s V_1 IL_0062: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0067: call ""void System.Console.WriteLine(string)"" IL_006c: ret } ", }; } [Theory] [InlineData(@"$""base{Throw()}{a = 2}""")] [InlineData(@"$""base"" + $""{Throw()}"" + $""{a = 2}""")] public void BoolReturns_ShortCircuit(string expression) { var source = @" using System; int a = 1; Console.Write(" + expression + @"); Console.WriteLine(a); string Throw() => throw new Exception();"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true, returnExpression: "false"); CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" base 1"); } [Theory] [CombinatorialData] public void BoolOutParameter_ShortCircuits(bool useBoolReturns, [CombinatorialValues(@"$""{Throw()}{a = 2}""", @"$""{Throw()}"" + $""{a = 2}""")] string expression) { var source = @" using System; int a = 1; Console.WriteLine(a); Console.WriteLine(" + expression + @"); Console.WriteLine(a); string Throw() => throw new Exception(); "; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: useBoolReturns, constructorBoolArg: true, constructorSuccessResult: false); CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" 1 1"); } [Theory] [InlineData(@"$""base{await Hole()}""")] [InlineData(@"$""base"" + $""{await Hole()}""")] public void AwaitInHoles_UsesFormat(string expression) { var source = @" using System; using System.Threading.Tasks; Console.WriteLine(" + expression + @"); Task<int> Hole() => Task.FromResult(1);"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"base1"); verifier.VerifyIL("Program.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", !expression.Contains("+") ? @" { // Code size 164 (0xa4) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_003e IL_000a: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__Hole|0_0()"" IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0014: stloc.2 IL_0015: ldloca.s V_2 IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_001c: brtrue.s IL_005a IL_001e: ldarg.0 IL_001f: ldc.i4.0 IL_0020: dup IL_0021: stloc.0 IL_0022: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0027: ldarg.0 IL_0028: ldloc.2 IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_002e: ldarg.0 IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0034: ldloca.s V_2 IL_0036: ldarg.0 IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_003c: leave.s IL_00a3 IL_003e: ldarg.0 IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_0044: stloc.2 IL_0045: ldarg.0 IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0051: ldarg.0 IL_0052: ldc.i4.m1 IL_0053: dup IL_0054: stloc.0 IL_0055: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_005a: ldloca.s V_2 IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0061: stloc.1 IL_0062: ldstr ""base{0}"" IL_0067: ldloc.1 IL_0068: box ""int"" IL_006d: call ""string string.Format(string, object)"" IL_0072: call ""void System.Console.WriteLine(string)"" IL_0077: leave.s IL_0090 } catch System.Exception { IL_0079: stloc.3 IL_007a: ldarg.0 IL_007b: ldc.i4.s -2 IL_007d: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0082: ldarg.0 IL_0083: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0088: ldloc.3 IL_0089: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_008e: leave.s IL_00a3 } IL_0090: ldarg.0 IL_0091: ldc.i4.s -2 IL_0093: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0098: ldarg.0 IL_0099: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_009e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00a3: ret } " : @" { // Code size 174 (0xae) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_003e IL_000a: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__Hole|0_0()"" IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0014: stloc.2 IL_0015: ldloca.s V_2 IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_001c: brtrue.s IL_005a IL_001e: ldarg.0 IL_001f: ldc.i4.0 IL_0020: dup IL_0021: stloc.0 IL_0022: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0027: ldarg.0 IL_0028: ldloc.2 IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_002e: ldarg.0 IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0034: ldloca.s V_2 IL_0036: ldarg.0 IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_003c: leave.s IL_00ad IL_003e: ldarg.0 IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_0044: stloc.2 IL_0045: ldarg.0 IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0051: ldarg.0 IL_0052: ldc.i4.m1 IL_0053: dup IL_0054: stloc.0 IL_0055: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_005a: ldloca.s V_2 IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0061: stloc.1 IL_0062: ldstr ""base"" IL_0067: ldstr ""{0}"" IL_006c: ldloc.1 IL_006d: box ""int"" IL_0072: call ""string string.Format(string, object)"" IL_0077: call ""string string.Concat(string, string)"" IL_007c: call ""void System.Console.WriteLine(string)"" IL_0081: leave.s IL_009a } catch System.Exception { IL_0083: stloc.3 IL_0084: ldarg.0 IL_0085: ldc.i4.s -2 IL_0087: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_008c: ldarg.0 IL_008d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0092: ldloc.3 IL_0093: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_0098: leave.s IL_00ad } IL_009a: ldarg.0 IL_009b: ldc.i4.s -2 IL_009d: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_00a2: ldarg.0 IL_00a3: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_00a8: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00ad: ret }"); } [Theory] [InlineData(@"$""base{hole}""")] [InlineData(@"$""base"" + $""{hole}""")] public void NoAwaitInHoles_UsesBuilder(string expression) { var source = @" using System; using System.Threading.Tasks; var hole = await Hole(); Console.WriteLine(" + expression + @"); Task<int> Hole() => Task.FromResult(1);"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" base value:1"); verifier.VerifyIL("Program.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 185 (0xb9) .maxstack 3 .locals init (int V_0, int V_1, //hole System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_003e IL_000a: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__Hole|0_0()"" IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0014: stloc.2 IL_0015: ldloca.s V_2 IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_001c: brtrue.s IL_005a IL_001e: ldarg.0 IL_001f: ldc.i4.0 IL_0020: dup IL_0021: stloc.0 IL_0022: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0027: ldarg.0 IL_0028: ldloc.2 IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_002e: ldarg.0 IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0034: ldloca.s V_2 IL_0036: ldarg.0 IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_003c: leave.s IL_00b8 IL_003e: ldarg.0 IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_0044: stloc.2 IL_0045: ldarg.0 IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0051: ldarg.0 IL_0052: ldc.i4.m1 IL_0053: dup IL_0054: stloc.0 IL_0055: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_005a: ldloca.s V_2 IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0061: stloc.1 IL_0062: ldc.i4.4 IL_0063: ldc.i4.1 IL_0064: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0069: stloc.3 IL_006a: ldloca.s V_3 IL_006c: ldstr ""base"" IL_0071: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0076: ldloca.s V_3 IL_0078: ldloc.1 IL_0079: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_007e: ldloca.s V_3 IL_0080: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0085: call ""void System.Console.WriteLine(string)"" IL_008a: leave.s IL_00a5 } catch System.Exception { IL_008c: stloc.s V_4 IL_008e: ldarg.0 IL_008f: ldc.i4.s -2 IL_0091: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0096: ldarg.0 IL_0097: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_009c: ldloc.s V_4 IL_009e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00a3: leave.s IL_00b8 } IL_00a5: ldarg.0 IL_00a6: ldc.i4.s -2 IL_00a8: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_00ad: ldarg.0 IL_00ae: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_00b3: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00b8: ret } "); } [Theory] [InlineData(@"$""base{hole}""")] [InlineData(@"$""base"" + $""{hole}""")] public void NoAwaitInHoles_AwaitInExpression_UsesBuilder(string expression) { var source = @" using System; using System.Threading.Tasks; var hole = 2; Test(await M(1), " + expression + @", await M(3)); void Test(int i1, string s, int i2) => Console.WriteLine(s); Task<int> M(int i) { Console.WriteLine(i); return Task.FromResult(1); }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" 1 3 base value:2"); verifier.VerifyIL("Program.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 328 (0x148) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0050 IL_000a: ldloc.0 IL_000b: ldc.i4.1 IL_000c: beq IL_00dc IL_0011: ldarg.0 IL_0012: ldc.i4.2 IL_0013: stfld ""int Program.<<Main>$>d__0.<hole>5__2"" IL_0018: ldc.i4.1 IL_0019: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__M|0_1(int)"" IL_001e: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0023: stloc.2 IL_0024: ldloca.s V_2 IL_0026: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_002b: brtrue.s IL_006c IL_002d: ldarg.0 IL_002e: ldc.i4.0 IL_002f: dup IL_0030: stloc.0 IL_0031: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0036: ldarg.0 IL_0037: ldloc.2 IL_0038: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_003d: ldarg.0 IL_003e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0043: ldloca.s V_2 IL_0045: ldarg.0 IL_0046: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_004b: leave IL_0147 IL_0050: ldarg.0 IL_0051: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_0056: stloc.2 IL_0057: ldarg.0 IL_0058: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_005d: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0063: ldarg.0 IL_0064: ldc.i4.m1 IL_0065: dup IL_0066: stloc.0 IL_0067: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_006c: ldarg.0 IL_006d: ldloca.s V_2 IL_006f: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0074: stfld ""int Program.<<Main>$>d__0.<>7__wrap2"" IL_0079: ldarg.0 IL_007a: ldc.i4.4 IL_007b: ldc.i4.1 IL_007c: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0081: stloc.3 IL_0082: ldloca.s V_3 IL_0084: ldstr ""base"" IL_0089: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_008e: ldloca.s V_3 IL_0090: ldarg.0 IL_0091: ldfld ""int Program.<<Main>$>d__0.<hole>5__2"" IL_0096: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_009b: ldloca.s V_3 IL_009d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_00a2: stfld ""string Program.<<Main>$>d__0.<>7__wrap3"" IL_00a7: ldc.i4.3 IL_00a8: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__M|0_1(int)"" IL_00ad: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_00b2: stloc.2 IL_00b3: ldloca.s V_2 IL_00b5: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_00ba: brtrue.s IL_00f8 IL_00bc: ldarg.0 IL_00bd: ldc.i4.1 IL_00be: dup IL_00bf: stloc.0 IL_00c0: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_00c5: ldarg.0 IL_00c6: ldloc.2 IL_00c7: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_00cc: ldarg.0 IL_00cd: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_00d2: ldloca.s V_2 IL_00d4: ldarg.0 IL_00d5: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)"" IL_00da: leave.s IL_0147 IL_00dc: ldarg.0 IL_00dd: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_00e2: stloc.2 IL_00e3: ldarg.0 IL_00e4: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1"" IL_00e9: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_00ef: ldarg.0 IL_00f0: ldc.i4.m1 IL_00f1: dup IL_00f2: stloc.0 IL_00f3: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_00f8: ldloca.s V_2 IL_00fa: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_00ff: stloc.1 IL_0100: ldarg.0 IL_0101: ldfld ""int Program.<<Main>$>d__0.<>7__wrap2"" IL_0106: ldarg.0 IL_0107: ldfld ""string Program.<<Main>$>d__0.<>7__wrap3"" IL_010c: ldloc.1 IL_010d: call ""void Program.<<Main>$>g__Test|0_0(int, string, int)"" IL_0112: ldarg.0 IL_0113: ldnull IL_0114: stfld ""string Program.<<Main>$>d__0.<>7__wrap3"" IL_0119: leave.s IL_0134 } catch System.Exception { IL_011b: stloc.s V_4 IL_011d: ldarg.0 IL_011e: ldc.i4.s -2 IL_0120: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_0125: ldarg.0 IL_0126: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_012b: ldloc.s V_4 IL_012d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_0132: leave.s IL_0147 } IL_0134: ldarg.0 IL_0135: ldc.i4.s -2 IL_0137: stfld ""int Program.<<Main>$>d__0.<>1__state"" IL_013c: ldarg.0 IL_013d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder"" IL_0142: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_0147: ret } "); } [Theory, WorkItem(55609, "https://github.com/dotnet/roslyn/issues/55609")] [InlineData(@"$""base{hole}""")] [InlineData(@"$""base"" + $""{hole}""")] public void DynamicInHoles_UsesFormat(string expression) { var source = @" using System; using System.Threading.Tasks; dynamic hole = 1; Console.WriteLine(" + expression + @"); "; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerifyWithCSharp(new[] { source, interpolatedStringBuilder }, expectedOutput: @"base1"); verifier.VerifyIL("<top-level-statements-entry-point>", expression.Contains('+') ? @" { // Code size 34 (0x22) .maxstack 3 .locals init (object V_0) //hole IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldstr ""base"" IL_000c: ldstr ""{0}"" IL_0011: ldloc.0 IL_0012: call ""string string.Format(string, object)"" IL_0017: call ""string string.Concat(string, string)"" IL_001c: call ""void System.Console.WriteLine(string)"" IL_0021: ret } " : @" { // Code size 24 (0x18) .maxstack 2 .locals init (object V_0) //hole IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldstr ""base{0}"" IL_000c: ldloc.0 IL_000d: call ""string string.Format(string, object)"" IL_0012: call ""void System.Console.WriteLine(string)"" IL_0017: ret } "); } [Theory, WorkItem(55609, "https://github.com/dotnet/roslyn/issues/55609")] [InlineData(@"$""{hole}base""")] [InlineData(@"$""{hole}"" + $""base""")] public void DynamicInHoles_UsesFormat2(string expression) { var source = @" using System; using System.Threading.Tasks; dynamic hole = 1; Console.WriteLine(" + expression + @"); "; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerifyWithCSharp(new[] { source, interpolatedStringBuilder }, expectedOutput: @"1base"); verifier.VerifyIL("<top-level-statements-entry-point>", expression.Contains('+') ? @" { // Code size 34 (0x22) .maxstack 2 .locals init (object V_0) //hole IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldstr ""{0}"" IL_000c: ldloc.0 IL_000d: call ""string string.Format(string, object)"" IL_0012: ldstr ""base"" IL_0017: call ""string string.Concat(string, string)"" IL_001c: call ""void System.Console.WriteLine(string)"" IL_0021: ret } " : @" { // Code size 24 (0x18) .maxstack 2 .locals init (object V_0) //hole IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldstr ""{0}base"" IL_000c: ldloc.0 IL_000d: call ""string string.Format(string, object)"" IL_0012: call ""void System.Console.WriteLine(string)"" IL_0017: ret } "); } [Fact] public void ImplicitConversionsInConstructor() { var code = @" using System.Runtime.CompilerServices; CustomHandler c = $""""; [InterpolatedStringHandler] struct CustomHandler { public CustomHandler(object literalLength, object formattedCount) {} } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerAttribute }); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: box ""int"" IL_0006: ldc.i4.0 IL_0007: box ""int"" IL_000c: newobj ""CustomHandler..ctor(object, object)"" IL_0011: pop IL_0012: ret } "); } [Fact] public void MissingCreate_01() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public override string ToString() => throw null; public void Dispose() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 2 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 3 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "3").WithLocation(1, 5) ); } [Fact] public void MissingCreate_02() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength) => throw null; public override string ToString() => throw null; public void Dispose() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 2 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 3 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "3").WithLocation(1, 5) ); } [Fact] public void MissingCreate_03() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(ref int literalLength, int formattedCount) => throw null; public override string ToString() => throw null; public void Dispose() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS1620: Argument 1 must be passed with the 'ref' keyword // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadArgRef, @"$""{(object)1}""").WithArguments("1", "ref").WithLocation(1, 5) ); } [Theory] [InlineData(null)] [InlineData("public string ToStringAndClear(int literalLength) => throw null;")] [InlineData("public void ToStringAndClear() => throw null;")] [InlineData("public static string ToStringAndClear() => throw null;")] public void MissingWellKnownMethod_ToStringAndClear(string toStringAndClearMethod) { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; " + toStringAndClearMethod + @" public override string ToString() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( // (1,5): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear' // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "ToStringAndClear").WithLocation(1, 5) ); } [Fact] public void ObsoleteCreateMethod() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { [System.Obsolete(""Constructor is obsolete"", error: true)] public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; public void Dispose() => throw null; public override string ToString() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS0619: 'DefaultInterpolatedStringHandler.DefaultInterpolatedStringHandler(int, int)' is obsolete: 'Constructor is obsolete' // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.DefaultInterpolatedStringHandler(int, int)", "Constructor is obsolete").WithLocation(1, 5) ); } [Fact] public void ObsoleteAppendLiteralMethod() { var code = @"_ = $""base{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; public void Dispose() => throw null; public override string ToString() => throw null; [System.Obsolete(""AppendLiteral is obsolete"", error: true)] public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,7): error CS0619: 'DefaultInterpolatedStringHandler.AppendLiteral(string)' is obsolete: 'AppendLiteral is obsolete' // _ = $"base{(object)1}"; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "base").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "AppendLiteral is obsolete").WithLocation(1, 7) ); } [Fact] public void ObsoleteAppendFormattedMethod() { var code = @"_ = $""base{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; public void Dispose() => throw null; public override string ToString() => throw null; public void AppendLiteral(string value) => throw null; [System.Obsolete(""AppendFormatted is obsolete"", error: true)] public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,11): error CS0619: 'DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)' is obsolete: 'AppendFormatted is obsolete' // _ = $"base{(object)1}"; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "{(object)1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)", "AppendFormatted is obsolete").WithLocation(1, 11) ); } private const string UnmanagedCallersOnlyIl = @" .class public auto ansi sealed beforefieldinit System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute extends [mscorlib]System.Attribute { .custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = ( 01 00 40 00 00 00 01 00 54 02 09 49 6e 68 65 72 69 74 65 64 00 ) .field public class [mscorlib]System.Type[] CallConvs .field public string EntryPoint .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { ldarg.0 call instance void [mscorlib]System.Attribute::.ctor() ret } }"; [Fact] public void UnmanagedCallersOnlyAppendFormattedMethod() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" .class public sequential ansi sealed beforefieldinit System.Runtime.CompilerServices.DefaultInterpolatedStringHandler extends [mscorlib]System.ValueType { .custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [mscorlib]System.ObsoleteAttribute::.ctor(string, bool) = ( 01 00 52 54 79 70 65 73 20 77 69 74 68 20 65 6d 62 65 64 64 65 64 20 72 65 66 65 72 65 6e 63 65 73 20 61 72 65 20 6e 6f 74 20 73 75 70 70 6f 72 74 65 64 20 69 6e 20 74 68 69 73 20 76 65 72 73 69 6f 6e 20 6f 66 20 79 6f 75 72 20 63 6f 6d 70 69 6c 65 72 2e 01 00 00 ) .pack 0 .size 1 .method public hidebysig specialname rtspecialname instance void .ctor ( int32 literalLength, int32 formattedCount ) cil managed { ldnull throw } .method public hidebysig instance void Dispose () cil managed { ldnull throw } .method public hidebysig virtual instance string ToString () cil managed { ldnull throw } .method public hidebysig instance void AppendLiteral ( string 'value' ) cil managed { ldnull throw } .method public hidebysig instance void AppendFormatted<T> ( !!T hole, [opt] int32 'alignment', [opt] string format ) cil managed { .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) .param [2] = int32(0) .param [3] = nullref ldnull throw } } "; var comp = CreateCompilationWithIL(code, ilSource: interpolatedStringBuilder + UnmanagedCallersOnlyIl); comp.VerifyDiagnostics( // (1,7): error CS0570: 'DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)' is not supported by the language // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BindToBogus, "{(object)1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)").WithLocation(1, 7) ); } [Fact] public void UnmanagedCallersOnlyToStringMethod() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" .class public sequential ansi sealed beforefieldinit System.Runtime.CompilerServices.DefaultInterpolatedStringHandler extends [mscorlib]System.ValueType { .custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [mscorlib]System.ObsoleteAttribute::.ctor(string, bool) = ( 01 00 52 54 79 70 65 73 20 77 69 74 68 20 65 6d 62 65 64 64 65 64 20 72 65 66 65 72 65 6e 63 65 73 20 61 72 65 20 6e 6f 74 20 73 75 70 70 6f 72 74 65 64 20 69 6e 20 74 68 69 73 20 76 65 72 73 69 6f 6e 20 6f 66 20 79 6f 75 72 20 63 6f 6d 70 69 6c 65 72 2e 01 00 00 ) .pack 0 .size 1 .method public hidebysig specialname rtspecialname instance void .ctor ( int32 literalLength, int32 formattedCount ) cil managed { ldnull throw } .method public hidebysig instance string ToStringAndClear () cil managed { .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) ldnull throw } .method public hidebysig instance void AppendLiteral ( string 'value' ) cil managed { ldnull throw } .method public hidebysig instance void AppendFormatted<T> ( !!T hole, [opt] int32 'alignment', [opt] string format ) cil managed { .param [2] = int32(0) .param [3] = nullref ldnull throw } } "; var comp = CreateCompilationWithIL(code, ilSource: interpolatedStringBuilder + UnmanagedCallersOnlyIl); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( // (1,5): error CS0570: 'DefaultInterpolatedStringHandler.ToStringAndClear()' is not supported by the language // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BindToBogus, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()").WithLocation(1, 5) ); } [Theory] [InlineData(@"$""{i}{s}""")] [InlineData(@"$""{i}"" + $""{s}""")] public void UnsupportedArgumentType(string expression) { var source = @" unsafe { int* i = null; var s = new S(); _ = " + expression + @"; } ref struct S { }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: true, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, options: TestOptions.UnsafeReleaseExe, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (6,11): error CS0306: The type 'int*' may not be used as a type argument // _ = $"{i}{s}"; Diagnostic(ErrorCode.ERR_BadTypeArgument, "{i}").WithArguments("int*").WithLocation(6, 11), // (6,14): error CS0306: The type 'S' may not be used as a type argument // _ = $"{i}{s}"; Diagnostic(ErrorCode.ERR_BadTypeArgument, "{s}").WithArguments("S").WithLocation(6, 5 + expression.Length) ); } [Theory] [InlineData(@"$""{b switch { true => 1, false => null }}{(!b ? null : 2)}{default}{null}""")] [InlineData(@"$""{b switch { true => 1, false => null }}"" + $""{(!b ? null : 2)}"" + $""{default}"" + $""{null}""")] public void TargetTypedInterpolationHoles(string expression) { var source = @" bool b = true; System.Console.WriteLine(" + expression + @");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" value:1 value:2 value: value:"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 81 (0x51) .maxstack 3 .locals init (bool V_0, //b object V_1, System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_2 IL_0004: ldc.i4.0 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloc.0 IL_000c: brfalse.s IL_0017 IL_000e: ldc.i4.1 IL_000f: box ""int"" IL_0014: stloc.1 IL_0015: br.s IL_0019 IL_0017: ldnull IL_0018: stloc.1 IL_0019: ldloca.s V_2 IL_001b: ldloc.1 IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)"" IL_0021: ldloca.s V_2 IL_0023: ldloc.0 IL_0024: brfalse.s IL_002e IL_0026: ldc.i4.2 IL_0027: box ""int"" IL_002c: br.s IL_002f IL_002e: ldnull IL_002f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)"" IL_0034: ldloca.s V_2 IL_0036: ldnull IL_0037: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_003c: ldloca.s V_2 IL_003e: ldnull IL_003f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0044: ldloca.s V_2 IL_0046: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_004b: call ""void System.Console.WriteLine(string)"" IL_0050: ret } "); } [Theory] [InlineData(@"$""{(null, default)}{new()}""")] [InlineData(@"$""{(null, default)}"" + $""{new()}""")] public void TargetTypedInterpolationHoles_Errors(string expression) { var source = @"System.Console.WriteLine(" + expression + @");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,29): error CS1503: Argument 1: cannot convert from '(<null>, default)' to 'object' // System.Console.WriteLine($"{(null, default)}{new()}"); Diagnostic(ErrorCode.ERR_BadArgType, "(null, default)").WithArguments("1", "(<null>, default)", "object").WithLocation(1, 29), // (1,29): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // System.Console.WriteLine($"{(null, default)}{new()}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(null, default)").WithArguments("interpolated string handlers", "10.0").WithLocation(1, 29), // (1,46): error CS1729: 'string' does not contain a constructor that takes 0 arguments // System.Console.WriteLine($"{(null, default)}{new()}"); Diagnostic(ErrorCode.ERR_BadCtorArgCount, "new()").WithArguments("string", "0").WithLocation(1, 19 + expression.Length) ); } [Fact] public void RefTernary() { var source = @" bool b = true; int i = 1; System.Console.WriteLine($""{(!b ? ref i : ref i)}"");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"value:1"); } [Fact] public void NestedInterpolatedStrings_01() { var source = @" int i = 1; System.Console.WriteLine($""{$""{i}""}"");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"value:1"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 32 (0x20) .maxstack 3 .locals init (int V_0, //i System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.0 IL_0005: ldc.i4.1 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldloc.0 IL_000e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0013: ldloca.s V_1 IL_0015: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_001a: call ""void System.Console.WriteLine(string)"" IL_001f: ret } "); } [Theory] [InlineData(@"$""{$""{i1}""}{$""{i2}""}""")] [InlineData(@"$""{$""{i1}""}"" + $""{$""{i2}""}""")] public void NestedInterpolatedStrings_02(string expression) { var source = @" int i1 = 1; int i2 = 2; System.Console.WriteLine(" + expression + @");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" value:1 value:2"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 63 (0x3f) .maxstack 4 .locals init (int V_0, //i1 int V_1, //i2 System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.2 IL_0003: stloc.1 IL_0004: ldloca.s V_2 IL_0006: ldc.i4.0 IL_0007: ldc.i4.1 IL_0008: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000d: ldloca.s V_2 IL_000f: ldloc.0 IL_0010: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0015: ldloca.s V_2 IL_0017: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_001c: ldloca.s V_2 IL_001e: ldc.i4.0 IL_001f: ldc.i4.1 IL_0020: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0025: ldloca.s V_2 IL_0027: ldloc.1 IL_0028: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_002d: ldloca.s V_2 IL_002f: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0034: call ""string string.Concat(string, string)"" IL_0039: call ""void System.Console.WriteLine(string)"" IL_003e: ret } "); } [Fact] public void ExceptionFilter_01() { var source = @" using System; int i = 1; try { Console.WriteLine(""Starting try""); throw new MyException { Prop = i }; } // Test DefaultInterpolatedStringHandler renders specially, so we're actually comparing to ""value:Prop"" plus some whitespace catch (MyException e) when (e.ToString() == $""{i}"".Trim()) { Console.WriteLine(""Caught""); } class MyException : Exception { public int Prop { get; set; } public override string ToString() => ""value:"" + Prop.ToString(); }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" Starting try Caught"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 95 (0x5f) .maxstack 4 .locals init (int V_0, //i System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 .try { IL_0002: ldstr ""Starting try"" IL_0007: call ""void System.Console.WriteLine(string)"" IL_000c: newobj ""MyException..ctor()"" IL_0011: dup IL_0012: ldloc.0 IL_0013: callvirt ""void MyException.Prop.set"" IL_0018: throw } filter { IL_0019: isinst ""MyException"" IL_001e: dup IL_001f: brtrue.s IL_0025 IL_0021: pop IL_0022: ldc.i4.0 IL_0023: br.s IL_004f IL_0025: callvirt ""string object.ToString()"" IL_002a: ldloca.s V_1 IL_002c: ldc.i4.0 IL_002d: ldc.i4.1 IL_002e: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0033: ldloca.s V_1 IL_0035: ldloc.0 IL_0036: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_003b: ldloca.s V_1 IL_003d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0042: callvirt ""string string.Trim()"" IL_0047: call ""bool string.op_Equality(string, string)"" IL_004c: ldc.i4.0 IL_004d: cgt.un IL_004f: endfilter } // end filter { // handler IL_0051: pop IL_0052: ldstr ""Caught"" IL_0057: call ""void System.Console.WriteLine(string)"" IL_005c: leave.s IL_005e } IL_005e: ret } "); } [ConditionalFact(typeof(MonoOrCoreClrOnly), typeof(NoIOperationValidation))] public void ExceptionFilter_02() { var source = @" using System; ReadOnlySpan<char> s = new char[] { 'i' }; try { Console.WriteLine(""Starting try""); throw new MyException { Prop = s.ToString() }; } // Test DefaultInterpolatedStringHandler renders specially, so we're actually comparing to ""value:Prop"" plus some whitespace catch (MyException e) when (e.ToString() == $""{s}"".Trim()) { Console.WriteLine(""Caught""); } class MyException : Exception { public string Prop { get; set; } public override string ToString() => ""value:"" + Prop.ToString(); }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp, expectedOutput: @" Starting try Caught"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 122 (0x7a) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //s System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: newarr ""char"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 105 IL_000a: stelem.i2 IL_000b: call ""System.ReadOnlySpan<char> System.ReadOnlySpan<char>.op_Implicit(char[])"" IL_0010: stloc.0 .try { IL_0011: ldstr ""Starting try"" IL_0016: call ""void System.Console.WriteLine(string)"" IL_001b: newobj ""MyException..ctor()"" IL_0020: dup IL_0021: ldloca.s V_0 IL_0023: constrained. ""System.ReadOnlySpan<char>"" IL_0029: callvirt ""string object.ToString()"" IL_002e: callvirt ""void MyException.Prop.set"" IL_0033: throw } filter { IL_0034: isinst ""MyException"" IL_0039: dup IL_003a: brtrue.s IL_0040 IL_003c: pop IL_003d: ldc.i4.0 IL_003e: br.s IL_006a IL_0040: callvirt ""string object.ToString()"" IL_0045: ldloca.s V_1 IL_0047: ldc.i4.0 IL_0048: ldc.i4.1 IL_0049: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_004e: ldloca.s V_1 IL_0050: ldloc.0 IL_0051: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_0056: ldloca.s V_1 IL_0058: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005d: callvirt ""string string.Trim()"" IL_0062: call ""bool string.op_Equality(string, string)"" IL_0067: ldc.i4.0 IL_0068: cgt.un IL_006a: endfilter } // end filter { // handler IL_006c: pop IL_006d: ldstr ""Caught"" IL_0072: call ""void System.Console.WriteLine(string)"" IL_0077: leave.s IL_0079 } IL_0079: ret } "); } [ConditionalTheory(typeof(MonoOrCoreClrOnly), typeof(NoIOperationValidation))] [InlineData(@"$""{s}{c}""")] [InlineData(@"$""{s}"" + $""{c}""")] public void ImplicitUserDefinedConversionInHole(string expression) { var source = @" using System; S s = default; C c = new C(); Console.WriteLine(" + expression + @"); ref struct S { public static implicit operator ReadOnlySpan<char>(S s) => ""S converted""; } class C { public static implicit operator ReadOnlySpan<char>(C s) => ""C converted""; }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:S converted value:C"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 57 (0x39) .maxstack 3 .locals init (S V_0, //s C V_1, //c System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: newobj ""C..ctor()"" IL_000d: stloc.1 IL_000e: ldloca.s V_2 IL_0010: ldc.i4.0 IL_0011: ldc.i4.2 IL_0012: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0017: ldloca.s V_2 IL_0019: ldloc.0 IL_001a: call ""System.ReadOnlySpan<char> S.op_Implicit(S)"" IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_0024: ldloca.s V_2 IL_0026: ldloc.1 IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<C>(C)"" IL_002c: ldloca.s V_2 IL_002e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0033: call ""void System.Console.WriteLine(string)"" IL_0038: ret } "); } [Fact] public void ExplicitUserDefinedConversionInHole() { var source = @" using System; S s = default; Console.WriteLine($""{s}""); ref struct S { public static explicit operator ReadOnlySpan<char>(S s) => ""S converted""; } "; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (5,21): error CS0306: The type 'S' may not be used as a type argument // Console.WriteLine($"{s}"); Diagnostic(ErrorCode.ERR_BadTypeArgument, "{s}").WithArguments("S").WithLocation(5, 21) ); } [Theory] [InlineData(@"$""Text{1}""")] [InlineData(@"$""Text"" + $""{1}""")] public void ImplicitUserDefinedConversionInLiteral(string expression) { var source = @" using System; Console.WriteLine(" + expression + @"); public struct CustomStruct { public static implicit operator CustomStruct(string s) => new CustomStruct { S = s }; public string S { get; set; } public override string ToString() => ""literal:"" + S; } namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public void AppendLiteral(CustomStruct s) => _builder.AppendLine(s.ToString()); public void AppendFormatted(object o) => _builder.AppendLine(""value:"" + o.ToString()); } }"; var verifier = CompileAndVerify(source, expectedOutput: @" literal:Text value:1"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 52 (0x34) .maxstack 3 .locals init (System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.1 IL_0004: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldstr ""Text"" IL_0010: call ""CustomStruct CustomStruct.op_Implicit(string)"" IL_0015: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(CustomStruct)"" IL_001a: ldloca.s V_0 IL_001c: ldc.i4.1 IL_001d: box ""int"" IL_0022: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)"" IL_0027: ldloca.s V_0 IL_0029: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_002e: call ""void System.Console.WriteLine(string)"" IL_0033: ret } "); } [Theory] [InlineData(@"$""Text{1}""")] [InlineData(@"$""Text"" + $""{1}""")] public void ExplicitUserDefinedConversionInLiteral(string expression) { var source = @" using System; Console.WriteLine(" + expression + @"); public struct CustomStruct { public static explicit operator CustomStruct(string s) => new CustomStruct { S = s }; public string S { get; set; } public override string ToString() => ""literal:"" + S; } namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public void AppendLiteral(CustomStruct s) => _builder.AppendLine(s.ToString()); public void AppendFormatted(object o) => _builder.AppendLine(""value:"" + o.ToString()); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,21): error CS1503: Argument 1: cannot convert from 'string' to 'CustomStruct' // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_BadArgType, "Text").WithArguments("1", "string", "CustomStruct").WithLocation(4, 21) ); } [Theory] [InlineData(@"$""Text{1}""")] [InlineData(@"$""Text"" + $""{1}""")] public void InvalidBuilderReturnType(string expression) { var source = @" using System; Console.WriteLine(" + expression + @"); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public int AppendLiteral(string s) => 0; public int AppendFormatted(object o) => 0; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,21): error CS8941: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' is malformed. It does not return 'void' or 'bool'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)").WithLocation(4, 21), // (4,25): error CS8941: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' is malformed. It does not return 'void' or 'bool'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)").WithLocation(4, 15 + expression.Length) ); } [Fact] public void MissingAppendMethods() { var source = @" using System.Runtime.CompilerServices; CustomHandler c = $""Literal{1}""; [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } } "; var comp = CreateCompilation(new[] { source, InterpolatedStringHandlerAttribute }); comp.VerifyDiagnostics( // (4,21): error CS1061: 'CustomHandler' does not contain a definition for 'AppendLiteral' and no accessible extension method 'AppendLiteral' accepting a first argument of type 'CustomHandler' could be found (are you missing a using directive or an assembly reference?) // CustomHandler c = $"Literal{1}"; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Literal").WithArguments("CustomHandler", "AppendLiteral").WithLocation(4, 21), // (4,21): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. // CustomHandler c = $"Literal{1}"; Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "Literal").WithArguments("?.()").WithLocation(4, 21), // (4,28): error CS1061: 'CustomHandler' does not contain a definition for 'AppendFormatted' and no accessible extension method 'AppendFormatted' accepting a first argument of type 'CustomHandler' could be found (are you missing a using directive or an assembly reference?) // CustomHandler c = $"Literal{1}"; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "{1}").WithArguments("CustomHandler", "AppendFormatted").WithLocation(4, 28), // (4,28): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'. // CustomHandler c = $"Literal{1}"; Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{1}").WithArguments("?.()").WithLocation(4, 28) ); } [Fact] public void MissingBoolType() { var handlerSource = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var handlerRef = CreateCompilation(handlerSource).EmitToImageReference(); var source = @"CustomHandler c = $""Literal{1}"";"; var comp = CreateCompilation(source, references: new[] { handlerRef }); comp.MakeTypeMissing(SpecialType.System_Boolean); comp.VerifyDiagnostics( // (1,19): error CS0518: Predefined type 'System.Boolean' is not defined or imported // CustomHandler c = $"Literal{1}"; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"$""Literal{1}""").WithArguments("System.Boolean").WithLocation(1, 19) ); } [Fact] public void MissingVoidType() { var handlerSource = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var handlerRef = CreateCompilation(handlerSource).EmitToImageReference(); var source = @" class C { public bool M() { CustomHandler c = $""Literal{1}""; return true; } } "; var comp = CreateCompilation(source, references: new[] { handlerRef }); comp.MakeTypeMissing(SpecialType.System_Void); comp.VerifyEmitDiagnostics(); } [Theory] [InlineData(@"$""Text{1}""", @"$""{1}Text""")] [InlineData(@"$""Text"" + $""{1}""", @"$""{1}"" + $""Text""")] public void MixedBuilderReturnTypes_01(string expression1, string expression2) { var source = @" using System; Console.WriteLine(" + expression1 + @"); Console.WriteLine(" + expression2 + @"); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public bool AppendLiteral(string s) => true; public void AppendFormatted(object o) { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,25): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' has inconsistent return type. Expected to return 'bool'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)", "bool").WithLocation(4, 15 + expression1.Length), // (5,24): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' has inconsistent return type. Expected to return 'void'. // Console.WriteLine($"{1}Text"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "void").WithLocation(5, 14 + expression2.Length) ); } [Theory] [InlineData(@"$""Text{1}""", @"$""{1}Text""")] [InlineData(@"$""Text"" + $""{1}""", @"$""{1}"" + $""Text""")] public void MixedBuilderReturnTypes_02(string expression1, string expression2) { var source = @" using System; Console.WriteLine(" + expression1 + @"); Console.WriteLine(" + expression2 + @"); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public void AppendLiteral(string s) { } public bool AppendFormatted(object o) => true; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,25): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' has inconsistent return type. Expected to return 'void'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)", "void").WithLocation(4, 15 + expression1.Length), // (5,24): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' has inconsistent return type. Expected to return 'bool'. // Console.WriteLine($"{1}Text"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "bool").WithLocation(5, 14 + expression2.Length) ); } [Fact] public void MixedBuilderReturnTypes_03() { var source = @" using System; Console.WriteLine($""{1}""); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public bool AppendLiteral(string s) => true; public void AppendFormatted(object o) { _builder.AppendLine(""value:"" + o.ToString()); } } }"; CompileAndVerify(source, expectedOutput: "value:1"); } [Fact] public void MixedBuilderReturnTypes_04() { var source = @" using System; using System.Text; using System.Runtime.CompilerServices; Console.WriteLine((CustomHandler)$""l""); [InterpolatedStringHandler] public class CustomHandler { private readonly StringBuilder _builder; public CustomHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public override string ToString() => _builder.ToString(); public bool AppendFormatted(object o) => true; public void AppendLiteral(string s) { _builder.AppendLine(""literal:"" + s.ToString()); } } "; CompileAndVerify(new[] { source, InterpolatedStringHandlerAttribute }, expectedOutput: "literal:l"); } private static void VerifyInterpolatedStringExpression(CSharpCompilation comp, string handlerType = "CustomHandler") { var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var descendentNodes = tree.GetRoot().DescendantNodes(); var interpolatedString = (ExpressionSyntax)descendentNodes.OfType<BinaryExpressionSyntax>() .Where(b => b.DescendantNodes().OfType<InterpolatedStringExpressionSyntax>().Any()) .FirstOrDefault() ?? descendentNodes.OfType<InterpolatedStringExpressionSyntax>().Single(); var semanticInfo = model.GetSemanticInfoSummary(interpolatedString); Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType); Assert.Equal(handlerType, semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.InterpolatedStringHandler, semanticInfo.ImplicitConversion.Kind); Assert.True(semanticInfo.ImplicitConversion.Exists); Assert.True(semanticInfo.ImplicitConversion.IsValid); Assert.True(semanticInfo.ImplicitConversion.IsInterpolatedStringHandler); Assert.Null(semanticInfo.ImplicitConversion.Method); if (interpolatedString is BinaryExpressionSyntax) { Assert.False(semanticInfo.ConstantValue.HasValue); AssertEx.Equal("System.String System.String.op_Addition(System.String left, System.String right)", semanticInfo.Symbol.ToTestDisplayString()); } // https://github.com/dotnet/roslyn/issues/54505 Assert IConversionOperation.IsImplicit when IOperation is implemented for interpolated strings. } private CompilationVerifier CompileAndVerifyOnCorrectPlatforms(CSharpCompilation compilation, string expectedOutput) => CompileAndVerify( compilation, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expectedOutput : null, verify: ExecutionConditionUtil.IsMonoOrCoreClr ? Verification.Passes : Verification.Skipped); [Theory] [CombinatorialData] public void CustomHandlerLocal([CombinatorialValues("class", "struct")] string type, bool useBoolReturns, [CombinatorialValues(@"$""Literal{1,2:f}""", @"$""Literal"" + $""{1,2:f}""")] string expression) { var code = @" CustomHandler builder = " + expression + @"; System.Console.WriteLine(builder.ToString());"; var builder = GetInterpolatedStringCustomHandlerType("CustomHandler", type, useBoolReturns); var comp = CreateCompilation(new[] { code, builder }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" literal:Literal value:1 alignment:2 format:f"); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (type, useBoolReturns) switch { (type: "struct", useBoolReturns: true) => @" { // Code size 67 (0x43) .maxstack 4 .locals init (CustomHandler V_0, //builder CustomHandler V_1) IL_0000: ldloca.s V_1 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_1 IL_000b: ldstr ""Literal"" IL_0010: call ""bool CustomHandler.AppendLiteral(string)"" IL_0015: brfalse.s IL_002c IL_0017: ldloca.s V_1 IL_0019: ldc.i4.1 IL_001a: box ""int"" IL_001f: ldc.i4.2 IL_0020: ldstr ""f"" IL_0025: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_002a: br.s IL_002d IL_002c: ldc.i4.0 IL_002d: pop IL_002e: ldloc.1 IL_002f: stloc.0 IL_0030: ldloca.s V_0 IL_0032: constrained. ""CustomHandler"" IL_0038: callvirt ""string object.ToString()"" IL_003d: call ""void System.Console.WriteLine(string)"" IL_0042: ret } ", (type: "struct", useBoolReturns: false) => @" { // Code size 61 (0x3d) .maxstack 4 .locals init (CustomHandler V_0, //builder CustomHandler V_1) IL_0000: ldloca.s V_1 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_1 IL_000b: ldstr ""Literal"" IL_0010: call ""void CustomHandler.AppendLiteral(string)"" IL_0015: ldloca.s V_1 IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: ldc.i4.2 IL_001e: ldstr ""f"" IL_0023: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0028: ldloc.1 IL_0029: stloc.0 IL_002a: ldloca.s V_0 IL_002c: constrained. ""CustomHandler"" IL_0032: callvirt ""string object.ToString()"" IL_0037: call ""void System.Console.WriteLine(string)"" IL_003c: ret } ", (type: "class", useBoolReturns: true) => @" { // Code size 55 (0x37) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""Literal"" IL_000e: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0013: brfalse.s IL_0029 IL_0015: ldloc.0 IL_0016: ldc.i4.1 IL_0017: box ""int"" IL_001c: ldc.i4.2 IL_001d: ldstr ""f"" IL_0022: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: callvirt ""string object.ToString()"" IL_0031: call ""void System.Console.WriteLine(string)"" IL_0036: ret } ", (type: "class", useBoolReturns: false) => @" { // Code size 47 (0x2f) .maxstack 5 IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldstr ""Literal"" IL_000d: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0012: dup IL_0013: ldc.i4.1 IL_0014: box ""int"" IL_0019: ldc.i4.2 IL_001a: ldstr ""f"" IL_001f: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0024: callvirt ""string object.ToString()"" IL_0029: call ""void System.Console.WriteLine(string)"" IL_002e: ret } ", _ => throw ExceptionUtilities.Unreachable }; } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void CustomHandlerMethodArgument(string expression) { var code = @" M(" + expression + @"); void M(CustomHandler b) { System.Console.WriteLine(b.ToString()); }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"<top-level-statements-entry-point>", @" { // Code size 50 (0x32) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_0031: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"($""{1,2:f}"" + $""Literal"")")] public void ExplicitHandlerCast_InCode(string expression) { var code = @"System.Console.WriteLine((CustomHandler)" + expression + @");"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); SyntaxNode syntax = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().Single(); var semanticInfo = model.GetSemanticInfoSummary(syntax); Assert.Equal("CustomHandler", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(SpecialType.System_Object, semanticInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind); syntax = ((CastExpressionSyntax)syntax).Expression; Assert.Equal(expression, syntax.ToString()); semanticInfo = model.GetSemanticInfoSummary(syntax); Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType); Assert.Equal(SpecialType.System_String, semanticInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); // https://github.com/dotnet/roslyn/issues/54505 Assert cast is explicit after IOperation is implemented var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 42 (0x2a) .maxstack 5 IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldc.i4.1 IL_0009: box ""int"" IL_000e: ldc.i4.2 IL_000f: ldstr ""f"" IL_0014: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0019: dup IL_001a: ldstr ""Literal"" IL_001f: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0024: call ""void System.Console.WriteLine(object)"" IL_0029: ret } "); } [Theory, WorkItem(55345, "https://github.com/dotnet/roslyn/issues/55345")] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void HandlerConversionPreferredOverStringForNonConstant(string expression) { var code = @" CultureInfoNormalizer.Normalize(); C.M(" + expression + @"); class C { public static void M(CustomHandler b) { System.Console.WriteLine(b.ToString()); } public static void M(string s) { System.Console.WriteLine(s); } } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular10); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"<top-level-statements-entry-point>", @" { // Code size 55 (0x37) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.7 IL_0006: ldc.i4.1 IL_0007: newobj ""CustomHandler..ctor(int, int)"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: ldc.i4.1 IL_000f: box ""int"" IL_0014: ldc.i4.2 IL_0015: ldstr ""f"" IL_001a: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001f: brfalse.s IL_002e IL_0021: ldloc.0 IL_0022: ldstr ""Literal"" IL_0027: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_002c: br.s IL_002f IL_002e: ldc.i4.0 IL_002f: pop IL_0030: ldloc.0 IL_0031: call ""void C.M(CustomHandler)"" IL_0036: ret } "); comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular9); verifier = CompileAndVerify(comp, expectedOutput: @"1.00Literal"); verifier.VerifyIL(@"<top-level-statements-entry-point>", expression.Contains('+') ? @" { // Code size 37 (0x25) .maxstack 2 IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldstr ""{0,2:f}"" IL_000a: ldc.i4.1 IL_000b: box ""int"" IL_0010: call ""string string.Format(string, object)"" IL_0015: ldstr ""Literal"" IL_001a: call ""string string.Concat(string, string)"" IL_001f: call ""void C.M(string)"" IL_0024: ret } " : @" { // Code size 27 (0x1b) .maxstack 2 IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldstr ""{0,2:f}Literal"" IL_000a: ldc.i4.1 IL_000b: box ""int"" IL_0010: call ""string string.Format(string, object)"" IL_0015: call ""void C.M(string)"" IL_001a: ret } "); } [Theory] [InlineData(@"$""{""Literal""}""")] [InlineData(@"$""{""Lit""}"" + $""{""eral""}""")] public void StringPreferredOverHandlerConversionForConstant(string expression) { var code = @" C.M(" + expression + @"); class C { public static void M(CustomHandler b) { throw null; } public static void M(string s) { System.Console.WriteLine(s); } } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); var verifier = CompileAndVerify(comp, expectedOutput: @"Literal"); verifier.VerifyIL(@"<top-level-statements-entry-point>", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldstr ""Literal"" IL_0005: call ""void C.M(string)"" IL_000a: ret } "); } [Theory] [InlineData(@"$""{1}{2}""")] [InlineData(@"$""{1}"" + $""{2}""")] public void HandlerConversionPreferredOverStringForNonConstant_AttributeConstructor(string expression) { var code = @" using System; [Attr(" + expression + @")] class Attr : Attribute { public Attr(string s) {} public Attr(CustomHandler c) {} } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); comp.VerifyDiagnostics( // (4,2): error CS0181: Attribute constructor parameter 'c' has type 'CustomHandler', which is not a valid attribute parameter type // [Attr($"{1}{2}")] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "Attr").WithArguments("c", "CustomHandler").WithLocation(4, 2) ); VerifyInterpolatedStringExpression(comp); var attr = comp.SourceAssembly.SourceModule.GlobalNamespace.GetTypeMember("Attr"); Assert.Equal("Attr..ctor(CustomHandler c)", attr.GetAttributes().Single().AttributeConstructor.ToTestDisplayString()); } [Theory] [InlineData(@"$""{""Literal""}""")] [InlineData(@"$""{""Lit""}"" + $""{""eral""}""")] public void StringPreferredOverHandlerConversionForConstant_AttributeConstructor(string expression) { var code = @" using System; [Attr(" + expression + @")] class Attr : Attribute { public Attr(string s) {} public Attr(CustomHandler c) {} } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); CompileAndVerify(comp, symbolValidator: validate, sourceSymbolValidator: validate); void validate(ModuleSymbol m) { var attr = m.GlobalNamespace.GetTypeMember("Attr"); Assert.Equal("Attr..ctor(System.String s)", attr.GetAttributes().Single().AttributeConstructor.ToTestDisplayString()); } } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void MultipleBuilderTypes(string expression) { var code = @" C.M(" + expression + @"); class C { public static void M(CustomHandler1 c) => throw null; public static void M(CustomHandler2 c) => throw null; }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler1", "struct", useBoolReturns: false), GetInterpolatedStringCustomHandlerType("CustomHandler2", "struct", useBoolReturns: false, includeOneTimeHelpers: false) }); comp.VerifyDiagnostics( // (2,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(CustomHandler1)' and 'C.M(CustomHandler2)' // C.M($""); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(CustomHandler1)", "C.M(CustomHandler2)").WithLocation(2, 3) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericOverloadResolution_01(string expression) { var code = @" using System; C.M(" + expression + @"); class C { public static void M<T>(T t) => throw null; public static void M(CustomHandler c) => Console.WriteLine(c); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 50 (0x32) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: call ""void C.M(CustomHandler)"" IL_0031: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericOverloadResolution_02(string expression) { var code = @" using System; C.M(" + expression + @"); class C { public static void M<T>(T t) where T : CustomHandler => throw null; public static void M(CustomHandler c) => Console.WriteLine(c); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 50 (0x32) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: call ""void C.M(CustomHandler)"" IL_0031: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericOverloadResolution_03(string expression) { var code = @" C.M(" + expression + @"); class C { public static void M<T>(T t) where T : CustomHandler => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); comp.VerifyDiagnostics( // (2,3): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'C.M<T>(T)'. There is no implicit reference conversion from 'string' to 'CustomHandler'. // C.M($"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M").WithArguments("C.M<T>(T)", "CustomHandler", "T", "string").WithLocation(2, 3) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericInference_01(string expression) { var code = @" C.M(" + expression + @", default(CustomHandler)); C.M(default(CustomHandler), " + expression + @"); class C { public static void M<T>(T t1, T t2) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (2,3): error CS0411: The type arguments for method 'C.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // C.M($"{1,2:f}Literal", default(CustomHandler)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, T)").WithLocation(2, 3), // (3,3): error CS0411: The type arguments for method 'C.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // C.M(default(CustomHandler), $"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, T)").WithLocation(3, 3) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericInference_02(string expression) { var code = @" using System; C.M(default(CustomHandler), () => " + expression + @"); class C { public static void M<T>(T t1, Func<T> t2) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); comp.VerifyDiagnostics( // (3,3): error CS0411: The type arguments for method 'C.M<T>(T, Func<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // C.M(default(CustomHandler), () => $"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, System.Func<T>)").WithLocation(3, 3) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericInference_03(string expression) { var code = @" using System; C.M(" + expression + @", default(CustomHandler)); class C { public static void M<T>(T t1, T t2) => Console.WriteLine(t1); } partial class CustomHandler { public static implicit operator CustomHandler(string s) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 51 (0x33) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: ldnull IL_002d: call ""void C.M<CustomHandler>(CustomHandler, CustomHandler)"" IL_0032: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void GenericInference_04(string expression) { var code = @" using System; C.M(default(CustomHandler), () => " + expression + @"); class C { public static void M<T>(T t1, Func<T> t2) => Console.WriteLine(t2()); } partial class CustomHandler { public static implicit operator CustomHandler(string s) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("Program.<>c.<<Main>$>b__0_0()", @" { // Code size 45 (0x2d) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_01(string expression) { var code = @" using System; Func<CustomHandler> f = () => " + expression + @"; Console.WriteLine(f()); "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", @" { // Code size 45 (0x2d) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_02(string expression) { var code = @" using System; CultureInfoNormalizer.Normalize(); C.M(() => " + expression + @"); class C { public static void M(Func<string> f) => Console.WriteLine(f()); public static void M(Func<CustomHandler> f) => throw null; } "; // Interpolated string handler conversions are not considered when determining the natural type of an expression: the natural return type of this lambda is string, // so we don't even consider that there is a conversion from interpolated string expression to CustomHandler here (Sections 12.6.3.13 and 12.6.3.15 of the spec). var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); var verifier = CompileAndVerify(comp, expectedOutput: @"1.00Literal"); // No DefaultInterpolatedStringHandler was included in the compilation, so it falls back to string.Format verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", !expression.Contains('+') ? @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldstr ""{0,2:f}Literal"" IL_0005: ldc.i4.1 IL_0006: box ""int"" IL_000b: call ""string string.Format(string, object)"" IL_0010: ret } " : @" { // Code size 27 (0x1b) .maxstack 2 IL_0000: ldstr ""{0,2:f}"" IL_0005: ldc.i4.1 IL_0006: box ""int"" IL_000b: call ""string string.Format(string, object)"" IL_0010: ldstr ""Literal"" IL_0015: call ""string string.Concat(string, string)"" IL_001a: ret } "); } [Theory] [InlineData(@"$""{new S { Field = ""Field"" }}""")] [InlineData(@"$""{new S { Field = ""Field"" }}"" + $""""")] public void LambdaReturnInference_03(string expression) { // Same as 2, but using a type that isn't allowed in an interpolated string. There is an implicit conversion error on the ref struct // when converting to a string, because S cannot be a component of an interpolated string. This conversion error causes the lambda to // fail to bind as Func<string>, even though the natural return type is string, and the only successful bind is Func<CustomHandler>. var code = @" using System; C.M(() => " + expression + @"); static class C { public static void M(Func<string> f) => throw null; public static void M(Func<CustomHandler> f) => Console.WriteLine(f()); } public partial class CustomHandler { public void AppendFormatted(S value) => _builder.AppendLine(""value:"" + value.Field); } public ref struct S { public string Field { get; set; } } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"value:Field"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", @" { // Code size 35 (0x23) .maxstack 4 .locals init (S V_0) IL_0000: ldc.i4.0 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldloca.s V_0 IL_000a: initobj ""S"" IL_0010: ldloca.s V_0 IL_0012: ldstr ""Field"" IL_0017: call ""void S.Field.set"" IL_001c: ldloc.0 IL_001d: callvirt ""void CustomHandler.AppendFormatted(S)"" IL_0022: ret } "); } [Theory] [InlineData(@"$""{new S { Field = ""Field"" }}""")] [InlineData(@"$""{new S { Field = ""Field"" }}"" + $""""")] public void LambdaReturnInference_04(string expression) { // Same as 3, but with S added to DefaultInterpolatedStringHandler (which then allows the lambda to be bound as Func<string>, matching the natural return type) var code = @" using System; C.M(() => " + expression + @"); static class C { public static void M(Func<string> f) => Console.WriteLine(f()); public static void M(Func<CustomHandler> f) => throw null; } public partial class CustomHandler { public void AppendFormatted(S value) => throw null; } public ref struct S { public string Field { get; set; } } namespace System.Runtime.CompilerServices { public ref partial struct DefaultInterpolatedStringHandler { public void AppendFormatted(S value) => _builder.AppendLine(""value:"" + value.Field); } } "; string[] source = new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: false), GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: true, useBoolReturns: false) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (3,11): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // C.M(() => $"{new S { Field = "Field" }}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, expression).WithArguments("interpolated string handlers", "10.0").WithLocation(3, 11), // (3,14): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // C.M(() => $"{new S { Field = "Field" }}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, @"new S { Field = ""Field"" }").WithArguments("interpolated string handlers", "10.0").WithLocation(3, 14) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"value:Field"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", @" { // Code size 45 (0x2d) .maxstack 3 .locals init (System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_0, S V_1) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.1 IL_0004: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldloca.s V_1 IL_000d: initobj ""S"" IL_0013: ldloca.s V_1 IL_0015: ldstr ""Field"" IL_001a: call ""void S.Field.set"" IL_001f: ldloc.1 IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(S)"" IL_0025: ldloca.s V_0 IL_0027: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_002c: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_05(string expression) { var code = @" using System; C.M(b => { if (b) return default(CustomHandler); else return " + expression + @"; }); static class C { public static void M(Func<bool, string> f) => throw null; public static void M(Func<bool, CustomHandler> f) => Console.WriteLine(f(false)); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0(bool)", @" { // Code size 55 (0x37) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_000d IL_0003: ldloca.s V_0 IL_0005: initobj ""CustomHandler"" IL_000b: ldloc.0 IL_000c: ret IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_06(string expression) { // Same as 5, but with an implicit conversion from the builder type to string. This implicit conversion // means that a best common type can be inferred for all branches of the lambda expression (Section 12.6.3.15 of the spec) // and because there is a best common type, the inferred return type of the lambda is string. Since the inferred return type // has an identity conversion to the return type of Func<bool, string>, that is preferred. var code = @" using System; CultureInfoNormalizer.Normalize(); C.M(b => { if (b) return default(CustomHandler); else return " + expression + @"; }); static class C { public static void M(Func<bool, string> f) => Console.WriteLine(f(false)); public static void M(Func<bool, CustomHandler> f) => throw null; } public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0(bool)", !expression.Contains('+') ? @" { // Code size 35 (0x23) .maxstack 2 .locals init (CustomHandler V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_0012 IL_0003: ldloca.s V_0 IL_0005: initobj ""CustomHandler"" IL_000b: ldloc.0 IL_000c: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0011: ret IL_0012: ldstr ""{0,2:f}Literal"" IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: call ""string string.Format(string, object)"" IL_0022: ret } " : @" { // Code size 45 (0x2d) .maxstack 2 .locals init (CustomHandler V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_0012 IL_0003: ldloca.s V_0 IL_0005: initobj ""CustomHandler"" IL_000b: ldloc.0 IL_000c: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0011: ret IL_0012: ldstr ""{0,2:f}"" IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: call ""string string.Format(string, object)"" IL_0022: ldstr ""Literal"" IL_0027: call ""string string.Concat(string, string)"" IL_002c: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_07(string expression) { // Same as 5, but with an implicit conversion from string to the builder type. var code = @" using System; C.M(b => { if (b) return default(CustomHandler); else return " + expression + @"; }); static class C { public static void M(Func<bool, string> f) => Console.WriteLine(f(false)); public static void M(Func<bool, CustomHandler> f) => Console.WriteLine(f(false)); } public partial struct CustomHandler { public static implicit operator CustomHandler(string s) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0(bool)", @" { // Code size 55 (0x37) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_000d IL_0003: ldloca.s V_0 IL_0005: initobj ""CustomHandler"" IL_000b: ldloc.0 IL_000c: ret IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void LambdaReturnInference_08(string expression) { // Same as 5, but with an implicit conversion from the builder type to string and from string to the builder type. var code = @" using System; C.M(b => { if (b) return default(CustomHandler); else return " + expression + @"; }); static class C { public static void M(Func<bool, string> f) => Console.WriteLine(f(false)); public static void M(Func<bool, CustomHandler> f) => throw null; } public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; public static implicit operator CustomHandler(string c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (3,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Func<bool, string>)' and 'C.M(Func<bool, CustomHandler>)' // C.M(b => Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Func<bool, string>)", "C.M(System.Func<bool, CustomHandler>)").WithLocation(3, 3) ); } [Theory] [InlineData(@"$""{1}""")] [InlineData(@"$""{1}"" + $""{2}""")] public void LambdaInference_AmbiguousInOlderLangVersions(string expression) { var code = @" using System; C.M(param => { param = " + expression + @"; }); static class C { public static void M(Action<string> f) => throw null; public static void M(Action<CustomHandler> f) => throw null; } "; var source = new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); // This successful emit is being caused by https://github.com/dotnet/roslyn/issues/53761, along with the duplicate diagnostics in LambdaReturnInference_04 // We should not be changing binding behavior based on LangVersion. comp.VerifyEmitDiagnostics(); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (3,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Action<string>)' and 'C.M(Action<CustomHandler>)' // C.M(param => Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Action<string>)", "C.M(System.Action<CustomHandler>)").WithLocation(3, 3) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_01(string expression) { var code = @" using System; var x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 76 (0x4c) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brtrue.s IL_0038 IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: br.s IL_0041 IL_0038: ldloca.s V_0 IL_003a: initobj ""CustomHandler"" IL_0040: ldloc.0 IL_0041: box ""CustomHandler"" IL_0046: call ""void System.Console.WriteLine(object)"" IL_004b: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_02(string expression) { // Same as 01, but with a conversion from CustomHandler to string. The rules here are similar to LambdaReturnInference_06 var code = @" using System; CultureInfoNormalizer.Normalize(); var x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", !expression.Contains('+') ? @" { // Code size 56 (0x38) .maxstack 2 .locals init (CustomHandler V_0) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.0 IL_0006: box ""bool"" IL_000b: unbox.any ""bool"" IL_0010: brtrue.s IL_0024 IL_0012: ldstr ""{0,2:f}Literal"" IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: call ""string string.Format(string, object)"" IL_0022: br.s IL_0032 IL_0024: ldloca.s V_0 IL_0026: initobj ""CustomHandler"" IL_002c: ldloc.0 IL_002d: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0032: call ""void System.Console.WriteLine(string)"" IL_0037: ret } " : @" { // Code size 66 (0x42) .maxstack 2 .locals init (CustomHandler V_0) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.0 IL_0006: box ""bool"" IL_000b: unbox.any ""bool"" IL_0010: brtrue.s IL_002e IL_0012: ldstr ""{0,2:f}"" IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: call ""string string.Format(string, object)"" IL_0022: ldstr ""Literal"" IL_0027: call ""string string.Concat(string, string)"" IL_002c: br.s IL_003c IL_002e: ldloca.s V_0 IL_0030: initobj ""CustomHandler"" IL_0036: ldloc.0 IL_0037: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_003c: call ""void System.Console.WriteLine(string)"" IL_0041: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_03(string expression) { // Same as 02, but with a target-type var code = @" using System; CustomHandler x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,19): error CS0029: Cannot implicitly convert type 'string' to 'CustomHandler' // CustomHandler x = (bool)(object)false ? default(CustomHandler) : $"{1,2:f}Literal"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"(bool)(object)false ? default(CustomHandler) : " + expression).WithArguments("string", "CustomHandler").WithLocation(4, 19) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_04(string expression) { // Same 01, but with a conversion from string to CustomHandler. The rules here are similar to LambdaReturnInference_07 var code = @" using System; var x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 76 (0x4c) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brtrue.s IL_0038 IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: br.s IL_0041 IL_0038: ldloca.s V_0 IL_003a: initobj ""CustomHandler"" IL_0040: ldloc.0 IL_0041: box ""CustomHandler"" IL_0046: call ""void System.Console.WriteLine(object)"" IL_004b: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_05(string expression) { // Same 01, but with a conversion from string to CustomHandler and CustomHandler to string. var code = @" using System; var x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,9): error CS0172: Type of conditional expression cannot be determined because 'CustomHandler' and 'string' implicitly convert to one another // var x = (bool)(object)false ? default(CustomHandler) : $"{1,2:f}Literal"; Diagnostic(ErrorCode.ERR_AmbigQM, @"(bool)(object)false ? default(CustomHandler) : " + expression).WithArguments("CustomHandler", "string").WithLocation(4, 9) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void TernaryTypes_06(string expression) { // Same 05, but with a target type var code = @" using System; CustomHandler x = (bool)(object)false ? default(CustomHandler) : " + expression + @"; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => c.ToString(); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 76 (0x4c) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brtrue.s IL_0038 IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: br.s IL_0041 IL_0038: ldloca.s V_0 IL_003a: initobj ""CustomHandler"" IL_0040: ldloc.0 IL_0041: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0046: call ""void System.Console.WriteLine(string)"" IL_004b: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_01(string expression) { // Switch expressions infer a best type based on _types_, not based on expressions (section 12.6.3.15 of the spec). Because this is based on types // and not on expression conversions, no best type can be found for this switch expression. var code = @" using System; var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,29): error CS8506: No best type was found for the switch expression. // var x = (bool)(object)false switch { true => default(CustomHandler), false => $"{1,2:f}Literal" }; Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(4, 29) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_02(string expression) { // Same as 01, but with a conversion from CustomHandler. This allows the switch expression to infer a best-common type, which is string. var code = @" using System; CultureInfoNormalizer.Normalize(); var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", !expression.Contains('+') ? @" { // Code size 59 (0x3b) .maxstack 2 .locals init (string V_0, CustomHandler V_1) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.0 IL_0006: box ""bool"" IL_000b: unbox.any ""bool"" IL_0010: brfalse.s IL_0023 IL_0012: ldloca.s V_1 IL_0014: initobj ""CustomHandler"" IL_001a: ldloc.1 IL_001b: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0020: stloc.0 IL_0021: br.s IL_0034 IL_0023: ldstr ""{0,2:f}Literal"" IL_0028: ldc.i4.1 IL_0029: box ""int"" IL_002e: call ""string string.Format(string, object)"" IL_0033: stloc.0 IL_0034: ldloc.0 IL_0035: call ""void System.Console.WriteLine(string)"" IL_003a: ret } " : @" { // Code size 69 (0x45) .maxstack 2 .locals init (string V_0, CustomHandler V_1) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.0 IL_0006: box ""bool"" IL_000b: unbox.any ""bool"" IL_0010: brfalse.s IL_0023 IL_0012: ldloca.s V_1 IL_0014: initobj ""CustomHandler"" IL_001a: ldloc.1 IL_001b: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0020: stloc.0 IL_0021: br.s IL_003e IL_0023: ldstr ""{0,2:f}"" IL_0028: ldc.i4.1 IL_0029: box ""int"" IL_002e: call ""string string.Format(string, object)"" IL_0033: ldstr ""Literal"" IL_0038: call ""string string.Concat(string, string)"" IL_003d: stloc.0 IL_003e: ldloc.0 IL_003f: call ""void System.Console.WriteLine(string)"" IL_0044: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_03(string expression) { // Same 02, but with a target-type. The natural type will fail to compile, so the switch will use a target type (unlike TernaryTypes_03, which fails to compile). var code = @" using System; CustomHandler x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => c.ToString(); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 79 (0x4f) .maxstack 4 .locals init (CustomHandler V_0, CustomHandler V_1) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brfalse.s IL_0019 IL_000d: ldloca.s V_1 IL_000f: initobj ""CustomHandler"" IL_0015: ldloc.1 IL_0016: stloc.0 IL_0017: br.s IL_0043 IL_0019: ldloca.s V_1 IL_001b: ldc.i4.7 IL_001c: ldc.i4.1 IL_001d: call ""CustomHandler..ctor(int, int)"" IL_0022: ldloca.s V_1 IL_0024: ldc.i4.1 IL_0025: box ""int"" IL_002a: ldc.i4.2 IL_002b: ldstr ""f"" IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldstr ""Literal"" IL_003c: call ""void CustomHandler.AppendLiteral(string)"" IL_0041: ldloc.1 IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0049: call ""void System.Console.WriteLine(string)"" IL_004e: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_04(string expression) { // Same as 01, but with a conversion to CustomHandler. This allows the switch expression to infer a best-common type, which is CustomHandler. var code = @" using System; var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 79 (0x4f) .maxstack 4 .locals init (CustomHandler V_0, CustomHandler V_1) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brfalse.s IL_0019 IL_000d: ldloca.s V_1 IL_000f: initobj ""CustomHandler"" IL_0015: ldloc.1 IL_0016: stloc.0 IL_0017: br.s IL_0043 IL_0019: ldloca.s V_1 IL_001b: ldc.i4.7 IL_001c: ldc.i4.1 IL_001d: call ""CustomHandler..ctor(int, int)"" IL_0022: ldloca.s V_1 IL_0024: ldc.i4.1 IL_0025: box ""int"" IL_002a: ldc.i4.2 IL_002b: ldstr ""f"" IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldstr ""Literal"" IL_003c: call ""void CustomHandler.AppendLiteral(string)"" IL_0041: ldloc.1 IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: box ""CustomHandler"" IL_0049: call ""void System.Console.WriteLine(object)"" IL_004e: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_05(string expression) { // Same as 01, but with conversions in both directions. No best common type can be found. var code = @" using System; var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,29): error CS8506: No best type was found for the switch expression. // var x = (bool)(object)false switch { true => default(CustomHandler), false => $"{1,2:f}Literal" }; Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(4, 29) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void SwitchTypes_06(string expression) { // Same as 05, but with a target type. var code = @" using System; CustomHandler x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => c.ToString(); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 79 (0x4f) .maxstack 4 .locals init (CustomHandler V_0, CustomHandler V_1) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brfalse.s IL_0019 IL_000d: ldloca.s V_1 IL_000f: initobj ""CustomHandler"" IL_0015: ldloc.1 IL_0016: stloc.0 IL_0017: br.s IL_0043 IL_0019: ldloca.s V_1 IL_001b: ldc.i4.7 IL_001c: ldc.i4.1 IL_001d: call ""CustomHandler..ctor(int, int)"" IL_0022: ldloca.s V_1 IL_0024: ldc.i4.1 IL_0025: box ""int"" IL_002a: ldc.i4.2 IL_002b: ldstr ""f"" IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldstr ""Literal"" IL_003c: call ""void CustomHandler.AppendLiteral(string)"" IL_0041: ldloc.1 IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0049: call ""void System.Console.WriteLine(string)"" IL_004e: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void PassAsRefWithoutKeyword_01(string expression) { var code = @" M(" + expression + @"); void M(ref CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 48 (0x30) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_0 IL_002a: call ""void Program.<<Main>$>g__M|0_0(ref CustomHandler)"" IL_002f: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void PassAsRefWithoutKeyword_02(string expression) { var code = @" M(" + expression + @"); M(ref " + expression + @"); void M(ref CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (2,3): error CS1620: Argument 1 must be passed with the 'ref' keyword // M($"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("1", "ref").WithLocation(2, 3), // (3,7): error CS1510: A ref or out value must be an assignable variable // M(ref $"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_RefLvalueExpected, expression).WithLocation(3, 7) ); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void PassAsRefWithoutKeyword_03(string expression) { var code = @" M(" + expression + @"); void M(in CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 45 (0x2d) .maxstack 5 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldc.i4.1 IL_0009: box ""int"" IL_000e: ldc.i4.2 IL_000f: ldstr ""f"" IL_0014: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0019: dup IL_001a: ldstr ""Literal"" IL_001f: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0024: stloc.0 IL_0025: ldloca.s V_0 IL_0027: call ""void Program.<<Main>$>g__M|0_0(in CustomHandler)"" IL_002c: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void PassAsRefWithoutKeyword_04(string expression) { var code = @" M(" + expression + @"); void M(in CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 48 (0x30) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_0 IL_002a: call ""void Program.<<Main>$>g__M|0_0(in CustomHandler)"" IL_002f: ret } "); } [Theory] [CombinatorialData] public void RefOverloadResolution_Struct([CombinatorialValues("in", "ref")] string refKind, [CombinatorialValues(@"$""{1,2:f}Literal""", @"$""{1,2:f}"" + $""Literal""")] string expression) { var code = @" C.M(" + expression + @"); class C { public static void M(CustomHandler c) => System.Console.WriteLine(c); public static void M(" + refKind + @" CustomHandler c) => throw null; }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloc.0 IL_0029: call ""void C.M(CustomHandler)"" IL_002e: ret } "); } [Theory] [CombinatorialData] public void RefOverloadResolution_Class([CombinatorialValues("in", "ref")] string refKind, [CombinatorialValues(@"$""{1,2:f}Literal""", @"$""{1,2:f}"" + $""Literal""")] string expression) { var code = @" C.M(" + expression + @"); class C { public static void M(CustomHandler c) => System.Console.WriteLine(c); public static void M(" + refKind + @" CustomHandler c) => System.Console.WriteLine(c); }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloc.0 IL_0029: call ""void C.M(CustomHandler)"" IL_002e: ret } "); } [Theory] [InlineData(@"$""{1,2:f}Literal""")] [InlineData(@"$""{1,2:f}"" + $""Literal""")] public void RefOverloadResolution_MultipleBuilderTypes(string expression) { var code = @" C.M(" + expression + @"); class C { public static void M(CustomHandler1 c) => System.Console.WriteLine(c); public static void M(ref CustomHandler2 c) => throw null; }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler1", "struct", useBoolReturns: false), GetInterpolatedStringCustomHandlerType("CustomHandler2", "struct", useBoolReturns: false, includeOneTimeHelpers: false) }); VerifyInterpolatedStringExpression(comp, "CustomHandler1"); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (CustomHandler1 V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler1..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler1.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler1.AppendLiteral(string)"" IL_0028: ldloc.0 IL_0029: call ""void C.M(CustomHandler1)"" IL_002e: ret } "); } private const string InterpolatedStringHandlerAttributesVB = @" Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Class Or AttributeTargets.Struct, AllowMultiple:=False, Inherited:=False)> Public NotInheritable Class InterpolatedStringHandlerAttribute Inherits Attribute End Class <AttributeUsage(AttributeTargets.Parameter, AllowMultiple:=False, Inherited:=False)> Public NotInheritable Class InterpolatedStringHandlerArgumentAttribute Inherits Attribute Public Sub New(argument As String) Arguments = { argument } End Sub Public Sub New(ParamArray arguments() as String) Me.Arguments = arguments End Sub Public ReadOnly Property Arguments As String() End Class End Namespace "; [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_NonHandlerType(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); class C { public static void M([InterpolatedStringHandlerArgumentAttribute] string s) {} } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute }); comp.VerifyDiagnostics( // (8,27): error CS8946: 'string' is not an interpolated string handler type. // public static void M([InterpolatedStringHandlerArgumentAttribute] string s) {} Diagnostic(ErrorCode.ERR_TypeIsNotAnInterpolatedStringHandlerType, "InterpolatedStringHandlerArgumentAttribute").WithArguments("string").WithLocation(8, 27) ); var sParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", sParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(sParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(sParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NonHandlerType_Metadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i as Integer, <InterpolatedStringHandlerArgument(""i"")> c As String) End Sub End Class "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); // Note: there is no compilation error here because the natural type of a string is still string, and // we just bind to that method without checking the handler attribute. var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics(); var sParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", sParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(sParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(sParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_InvalidArgument(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); class C { public static void M([InterpolatedStringHandlerArgumentAttribute(1)] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (8,70): error CS1503: Argument 1: cannot convert from 'int' to 'string' // public static void M([InterpolatedStringHandlerArgumentAttribute(1)] CustomHandler c) {} Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "string").WithLocation(8, 70) ); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_01(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""NonExistant"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 5), // (8,27): error CS8945: 'NonExistant' is not a valid parameter name from 'C.M(CustomHandler)'. // public static void M([InterpolatedStringHandlerArgumentAttribute("NonExistant")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant"")").WithArguments("NonExistant", "C.M(CustomHandler)").WithLocation(8, 27) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_01_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(""NonExistant"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_02(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(1, " + expression + @"); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"", ""NonExistant"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8945: 'NonExistant' is not a valid parameter name from 'C.M(int, CustomHandler)'. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("i", "NonExistant")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""i"", ""NonExistant"")").WithArguments("NonExistant", "C.M(int, CustomHandler)").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_02_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(""i"", ""NonExistant"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_03(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(1, " + expression + @"); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8945: 'NonExistant1' is not a valid parameter name from 'C.M(int, CustomHandler)'. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("NonExistant1", "NonExistant2")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")").WithArguments("NonExistant1", "C.M(int, CustomHandler)").WithLocation(8, 34), // (8,34): error CS8945: 'NonExistant2' is not a valid parameter name from 'C.M(int, CustomHandler)'. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("NonExistant1", "NonExistant2")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")").WithArguments("NonExistant2", "C.M(int, CustomHandler)").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_03_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(""NonExistant1"", ""NonExistant2"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_ReferenceSelf(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(1, " + expression + @"); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""c"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8948: InterpolatedStringHandlerArgumentAttribute arguments cannot refer to the parameter the attribute is used on. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("c")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_CannotUseSelfAsInterpolatedStringHandlerArgument, @"InterpolatedStringHandlerArgumentAttribute(""c"")").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_ReferencesSelf_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(""c"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(1, " + expression + @"); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(new string[] { null })] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8943: null is not a valid parameter name. To get access to the receiver of an instance method, use the empty string as the parameter name. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(new string[] { null })] CustomHandler c) {} Diagnostic(ErrorCode.ERR_NullInvalidInterpolatedStringHandlerArgumentName, "InterpolatedStringHandlerArgumentAttribute(new string[] { null })").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_01() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument({ Nothing })> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_02() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument({ Nothing, ""i"" })> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_03() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(CStr(Nothing))> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnStaticMethod(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); class C { public static void M([InterpolatedStringHandlerArgumentAttribute("""")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 5), // (8,27): error CS8944: 'C.M(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // public static void M([InterpolatedStringHandlerArgumentAttribute("")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute("""")").WithArguments("C.M(CustomHandler)").WithLocation(8, 27) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"{""""}")] [InlineData(@"""""")] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnStaticMethod_FromMetadata(string arg) { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(" + arg + @")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnConstructor(string expression) { var code = @" using System.Runtime.CompilerServices; _ = new C(" + expression + @"); class C { public C([InterpolatedStringHandlerArgumentAttribute("""")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,11): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // _ = new C($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 11), // (8,15): error CS8944: 'C.C(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // public C([InterpolatedStringHandlerArgumentAttribute("")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute("""")").WithArguments("C.C(CustomHandler)").WithLocation(8, 15) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod(".ctor").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"{""""}")] [InlineData(@"""""")] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnConstructor_FromMetadata(string arg) { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Sub New(<InterpolatedStringHandlerArgument(" + arg + @")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"_ = new C($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,11): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // _ = new C($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 11), // (1,11): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // _ = new C($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 11), // (1,11): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // _ = new C($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 11) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod(".ctor").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerAttributeArgumentError_SubstitutedTypeSymbol(string expression) { var code = @" using System.Runtime.CompilerServices; C<CustomHandler>.M(" + expression + @"); public class C<T> { public static void M([InterpolatedStringHandlerArgumentAttribute] T t) { } } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler }); comp.VerifyDiagnostics( // (4,20): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 20), // (8,27): error CS8946: 'T' is not an interpolated string handler type. // public static void M([InterpolatedStringHandlerArgumentAttribute] T t) { } Diagnostic(ErrorCode.ERR_TypeIsNotAnInterpolatedStringHandlerType, "InterpolatedStringHandlerArgumentAttribute").WithArguments("T").WithLocation(8, 27) ); var c = comp.SourceModule.GlobalNamespace.GetTypeMember("C"); var handler = comp.SourceModule.GlobalNamespace.GetTypeMember("CustomHandler"); var substitutedC = c.WithTypeArguments(ImmutableArray.Create(TypeWithAnnotations.Create(handler))); var cParam = substitutedC.GetMethod("M").Parameters.Single(); Assert.IsType<SubstitutedParameterSymbol>(cParam); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_SubstitutedTypeSymbol_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C(Of T) Public Shared Sub M(<InterpolatedStringHandlerArgument()> c As T) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C<CustomHandler>.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,20): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 20), // (1,20): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 20), // (1,20): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 20) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C`1").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttributeWarn_ParameterAfterHandler([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""text""", @"$""text"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; public class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, int i) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var goodCode = @" int i = 10; C.M(i: i, c: " + expression + @"); "; var comp = CreateCompilation(new[] { code, goodCode, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate, expectedOutput: @" i:10 literal:text "); verifier.VerifyDiagnostics( // (6,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller // to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, int i) => Console.WriteLine(c.ToString()); Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(6, 27) ); verifyIL(verifier); var badCode = @"C.M(" + expression + @", 1);"; comp = CreateCompilation(new[] { code, badCode, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (1,10): error CS8950: Parameter 'i' is an argument to the interpolated string handler conversion on parameter 'c', but is specified after the interpolated string constant. Reorder the arguments to move 'i' before 'c'. // C.M($"", 1); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString, "1").WithArguments("i", "c").WithLocation(1, 7 + expression.Length), // (6,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller // to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, int i) => Console.WriteLine(c.ToString()); Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(6, 27) ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.First(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(1, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } void verifyIL(CompilationVerifier verifier) { verifier.VerifyIL("<top-level-statements-entry-point>", extraConstructorArg == "" ? @" { // Code size 36 (0x24) .maxstack 4 .locals init (int V_0, int V_1, CustomHandler V_2) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: stloc.1 IL_0005: ldloca.s V_2 IL_0007: ldc.i4.4 IL_0008: ldc.i4.0 IL_0009: ldloc.0 IL_000a: call ""CustomHandler..ctor(int, int, int)"" IL_000f: ldloca.s V_2 IL_0011: ldstr ""text"" IL_0016: call ""bool CustomHandler.AppendLiteral(string)"" IL_001b: pop IL_001c: ldloc.2 IL_001d: ldloc.1 IL_001e: call ""void C.M(CustomHandler, int)"" IL_0023: ret } " : @" { // Code size 43 (0x2b) .maxstack 4 .locals init (int V_0, int V_1, CustomHandler V_2, bool V_3) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: stloc.1 IL_0005: ldc.i4.4 IL_0006: ldc.i4.0 IL_0007: ldloc.0 IL_0008: ldloca.s V_3 IL_000a: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000f: stloc.2 IL_0010: ldloc.3 IL_0011: brfalse.s IL_0021 IL_0013: ldloca.s V_2 IL_0015: ldstr ""text"" IL_001a: call ""bool CustomHandler.AppendLiteral(string)"" IL_001f: br.s IL_0022 IL_0021: ldc.i4.0 IL_0022: pop IL_0023: ldloc.2 IL_0024: ldloc.1 IL_0025: call ""void C.M(CustomHandler, int)"" IL_002a: ret } "); } } [Fact] public void InterpolatedStringHandlerArgumentAttributeWarn_ParameterAfterHandler_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(""i"")> c As CustomHandler, i As Integer) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation("", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics(); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.First(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(1, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_OptionalNotSpecifiedAtCallsite(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); public class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, int i = 0) { } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) { } } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler }); comp.VerifyDiagnostics( // (4,5): error CS8951: Parameter 'i' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter 'c'. Specify the value of 'i' before 'c'. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, expression).WithArguments("i", "c").WithLocation(4, 5), // (8,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, params int[] i) { } Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(8, 27) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttributeError_ParamsNotSpecifiedAtCallsite(string expression) { var code = @" using System.Runtime.CompilerServices; C.M(" + expression + @"); public class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, params int[] i) { } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int[] i) : this(literalLength, formattedCount) { } } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler }); comp.VerifyDiagnostics( // (4,5): error CS8951: Parameter 'i' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter 'c'. Specify the value of 'i' before 'c'. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, expression).WithArguments("i", "c").WithLocation(4, 5), // (8,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, params int[] i) { } Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(8, 27) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MissingConstructor(string expression) { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate).VerifyDiagnostics(); CreateCompilation(@"C.M(1, " + expression + @");", new[] { comp.ToMetadataReference() }).VerifyDiagnostics( // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "3").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 4 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "4").WithLocation(1, 8) ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_InaccessibleConstructor_01(string expression) { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {} } public partial struct CustomHandler { private CustomHandler(int literalLength, int formattedCount, int i) : this() {} static void InCustomHandler() { C.M(1, " + expression + @"); } } "; var executableCode = @"C.M(1, " + expression + @");"; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (1,8): error CS0122: 'CustomHandler.CustomHandler(int, int, int)' is inaccessible due to its protection level // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadAccess, expression).WithArguments("CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 8) ); var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. CompileAndVerify(dependency, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics(); comp = CreateCompilation(executableCode, new[] { dependency.EmitToImageReference() }); comp.VerifyDiagnostics( // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 4 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "4").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "3").WithLocation(1, 8) ); comp = CreateCompilation(executableCode, new[] { dependency.ToMetadataReference() }); comp.VerifyDiagnostics( // (1,8): error CS0122: 'CustomHandler.CustomHandler(int, int, int)' is inaccessible due to its protection level // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadAccess, expression).WithArguments("CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 8) ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } } private void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes(string mRef, string customHandlerRef, string expression, params DiagnosticDescription[] expectedDiagnostics) { var code = @" using System.Runtime.CompilerServices; int i = 0; C.M(" + mRef + @" i, " + expression + @"); public class C { public static void M(" + mRef + @" int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) { " + (mRef == "out" ? "i = 0;" : "") + @" } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, " + customHandlerRef + @" int i) : this() { " + (customHandlerRef == "out" ? "i = 0;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics(expectedDiagnostics); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefNone(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "", expression, // (5,9): error CS1615: Argument 3 may not be passed with the 'ref' keyword // C.M(ref i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "ref").WithLocation(5, 9)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefOut(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "out", expression, // (5,9): error CS1620: Argument 3 must be passed with the 'out' keyword // C.M(ref i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 9)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefIn(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "in", expression, // (5,9): error CS1615: Argument 3 may not be passed with the 'ref' keyword // C.M(ref i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "ref").WithLocation(5, 9)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InNone(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "", expression, // (5,8): error CS1615: Argument 3 may not be passed with the 'in' keyword // C.M(in i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "in").WithLocation(5, 8)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InOut(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "out", expression, // (5,8): error CS1620: Argument 3 must be passed with the 'out' keyword // C.M(in i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 8)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InRef(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "ref", expression, // (5,8): error CS1620: Argument 3 must be passed with the 'ref' keyword // C.M(in i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 8)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_OutNone(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("out", "", expression, // (5,9): error CS1615: Argument 3 may not be passed with the 'out' keyword // C.M(out i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "out").WithLocation(5, 9)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_OutRef(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("out", "ref", expression, // (5,9): error CS1620: Argument 3 must be passed with the 'ref' keyword // C.M(out i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 9)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_NoneRef(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("", "ref", expression, // (5,6): error CS1620: Argument 3 must be passed with the 'ref' keyword // C.M( i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 6)); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_NoneOut(string expression) { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("", "out", expression, // (5,6): error CS1620: Argument 3 must be passed with the 'out' keyword // C.M( i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 6)); } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_MismatchedType([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression) { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {} } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s" + extraConstructorArg + @") : this() { " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var executableCode = @"C.M(1, " + expression + @");"; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var expectedDiagnostics = extraConstructorArg == "" ? new DiagnosticDescription[] { // (1,5): error CS1503: Argument 3: cannot convert from 'int' to 'string' // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("3", "int", "string").WithLocation(1, 5) } : new DiagnosticDescription[] { // (1,5): error CS1503: Argument 3: cannot convert from 'int' to 'string' // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("3", "int", "string").WithLocation(1, 5), // (1,8): error CS7036: There is no argument given that corresponds to the required formal parameter 'success' of 'CustomHandler.CustomHandler(int, int, string, out bool)' // C.M(1, $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("success", "CustomHandler.CustomHandler(int, int, string, out bool)").WithLocation(1, 8) }; var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics(expectedDiagnostics); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); CompileAndVerify(dependency, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics(); foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() }) { comp = CreateCompilation(executableCode, new[] { d }); comp.VerifyDiagnostics(expectedDiagnostics); } static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_SingleArg([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""2""", @"$""2"" + $""""")] string expression) { var code = @" using System.Runtime.CompilerServices; public class C { public static string M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) => c.ToString(); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var executableCode = @" using System; int i = 10; Console.WriteLine(C.M(i, " + expression + @")); "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i:10 literal:2"); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() }) { verifier = CompileAndVerify(executableCode, new[] { d }, expectedOutput: @" i:10 literal:2"); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); } static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } static void verifyIL(string extraConstructorArg, CompilationVerifier verifier) { verifier.VerifyIL("<top-level-statements-entry-point>", extraConstructorArg == "" ? @" { // Code size 39 (0x27) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldloca.s V_1 IL_0006: ldc.i4.1 IL_0007: ldc.i4.0 IL_0008: ldloc.0 IL_0009: call ""CustomHandler..ctor(int, int, int)"" IL_000e: ldloca.s V_1 IL_0010: ldstr ""2"" IL_0015: call ""bool CustomHandler.AppendLiteral(string)"" IL_001a: pop IL_001b: ldloc.1 IL_001c: call ""string C.M(int, CustomHandler)"" IL_0021: call ""void System.Console.WriteLine(string)"" IL_0026: ret } " : @" { // Code size 46 (0x2e) .maxstack 5 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldc.i4.1 IL_0005: ldc.i4.0 IL_0006: ldloc.0 IL_0007: ldloca.s V_2 IL_0009: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000e: stloc.1 IL_000f: ldloc.2 IL_0010: brfalse.s IL_0020 IL_0012: ldloca.s V_1 IL_0014: ldstr ""2"" IL_0019: call ""bool CustomHandler.AppendLiteral(string)"" IL_001e: br.s IL_0021 IL_0020: ldc.i4.0 IL_0021: pop IL_0022: ldloc.1 IL_0023: call ""string C.M(int, CustomHandler)"" IL_0028: call ""void System.Console.WriteLine(string)"" IL_002d: ret } "); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_MultipleArgs([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var executableCode = @" int i = 10; string s = ""arg""; C.M(i, s, " + expression + @"); "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); string expectedOutput = @" i:10 s:arg literal:literal "; var verifier = base.CompileAndVerify((Compilation)comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() }) { verifier = CompileAndVerify(executableCode, new[] { d }, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); } static void validator(ModuleSymbol verifier) { var cParam = verifier.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } static void verifyIL(string extraConstructorArg, CompilationVerifier verifier) { verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 44 (0x2c) .maxstack 7 .locals init (string V_0, //s int V_1, string V_2, CustomHandler V_3) IL_0000: ldc.i4.s 10 IL_0002: ldstr ""arg"" IL_0007: stloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldloc.0 IL_000b: stloc.2 IL_000c: ldloc.2 IL_000d: ldloca.s V_3 IL_000f: ldc.i4.7 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: ldloc.2 IL_0013: call ""CustomHandler..ctor(int, int, int, string)"" IL_0018: ldloca.s V_3 IL_001a: ldstr ""literal"" IL_001f: call ""bool CustomHandler.AppendLiteral(string)"" IL_0024: pop IL_0025: ldloc.3 IL_0026: call ""void C.M(int, string, CustomHandler)"" IL_002b: ret } " : @" { // Code size 52 (0x34) .maxstack 7 .locals init (string V_0, //s int V_1, string V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.s 10 IL_0002: ldstr ""arg"" IL_0007: stloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldloc.0 IL_000b: stloc.2 IL_000c: ldloc.2 IL_000d: ldc.i4.7 IL_000e: ldc.i4.0 IL_000f: ldloc.1 IL_0010: ldloc.2 IL_0011: ldloca.s V_4 IL_0013: newobj ""CustomHandler..ctor(int, int, int, string, out bool)"" IL_0018: stloc.3 IL_0019: ldloc.s V_4 IL_001b: brfalse.s IL_002b IL_001d: ldloca.s V_3 IL_001f: ldstr ""literal"" IL_0024: call ""bool CustomHandler.AppendLiteral(string)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.0 IL_002c: pop IL_002d: ldloc.3 IL_002e: call ""void C.M(int, string, CustomHandler)"" IL_0033: ret } "); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_RefKindsMatch([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; int i = 1; string s = null; object o; C.M(i, ref s, out o, " + expression + @"); Console.WriteLine(s); Console.WriteLine(o); public class C { public static void M(in int i, ref string s, out object o, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"", ""o"")] CustomHandler c) { Console.WriteLine(s); o = ""o in M""; s = ""s in M""; Console.Write(c.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, in int i, ref string s, out object o" + extraConstructorArg + @") : this(literalLength, formattedCount) { o = null; s = ""s in constructor""; _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" s in constructor i:1 literal:literal s in M o in M "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 67 (0x43) .maxstack 8 .locals init (int V_0, //i string V_1, //s object V_2, //o int& V_3, string& V_4, object& V_5, CustomHandler V_6) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldnull IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: stloc.3 IL_0007: ldloc.3 IL_0008: ldloca.s V_1 IL_000a: stloc.s V_4 IL_000c: ldloc.s V_4 IL_000e: ldloca.s V_2 IL_0010: stloc.s V_5 IL_0012: ldloc.s V_5 IL_0014: ldc.i4.7 IL_0015: ldc.i4.0 IL_0016: ldloc.3 IL_0017: ldloc.s V_4 IL_0019: ldloc.s V_5 IL_001b: newobj ""CustomHandler..ctor(int, int, in int, ref string, out object)"" IL_0020: stloc.s V_6 IL_0022: ldloca.s V_6 IL_0024: ldstr ""literal"" IL_0029: call ""bool CustomHandler.AppendLiteral(string)"" IL_002e: pop IL_002f: ldloc.s V_6 IL_0031: call ""void C.M(in int, ref string, out object, CustomHandler)"" IL_0036: ldloc.1 IL_0037: call ""void System.Console.WriteLine(string)"" IL_003c: ldloc.2 IL_003d: call ""void System.Console.WriteLine(object)"" IL_0042: ret } " : @" { // Code size 76 (0x4c) .maxstack 9 .locals init (int V_0, //i string V_1, //s object V_2, //o int& V_3, string& V_4, object& V_5, CustomHandler V_6, bool V_7) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldnull IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: stloc.3 IL_0007: ldloc.3 IL_0008: ldloca.s V_1 IL_000a: stloc.s V_4 IL_000c: ldloc.s V_4 IL_000e: ldloca.s V_2 IL_0010: stloc.s V_5 IL_0012: ldloc.s V_5 IL_0014: ldc.i4.7 IL_0015: ldc.i4.0 IL_0016: ldloc.3 IL_0017: ldloc.s V_4 IL_0019: ldloc.s V_5 IL_001b: ldloca.s V_7 IL_001d: newobj ""CustomHandler..ctor(int, int, in int, ref string, out object, out bool)"" IL_0022: stloc.s V_6 IL_0024: ldloc.s V_7 IL_0026: brfalse.s IL_0036 IL_0028: ldloca.s V_6 IL_002a: ldstr ""literal"" IL_002f: call ""bool CustomHandler.AppendLiteral(string)"" IL_0034: br.s IL_0037 IL_0036: ldc.i4.0 IL_0037: pop IL_0038: ldloc.s V_6 IL_003a: call ""void C.M(in int, ref string, out object, CustomHandler)"" IL_003f: ldloc.1 IL_0040: call ""void System.Console.WriteLine(string)"" IL_0045: ldloc.2 IL_0046: call ""void System.Console.WriteLine(object)"" IL_004b: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(3).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1, 2 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_ReorderedAttributePositions([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(GetInt(), GetString(), " + expression + @"); int GetInt() { Console.WriteLine(""GetInt""); return 10; } string GetString() { Console.WriteLine(""GetString""); return ""str""; } public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""s"", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""s:"" + s); _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" GetInt GetString s:str i:10 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 45 (0x2d) .maxstack 7 .locals init (string V_0, int V_1, CustomHandler V_2) IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string Program.<<Main>$>g__GetString|0_1()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: ldloca.s V_2 IL_0010: ldc.i4.7 IL_0011: ldc.i4.0 IL_0012: ldloc.0 IL_0013: ldloc.1 IL_0014: call ""CustomHandler..ctor(int, int, string, int)"" IL_0019: ldloca.s V_2 IL_001b: ldstr ""literal"" IL_0020: call ""bool CustomHandler.AppendLiteral(string)"" IL_0025: pop IL_0026: ldloc.2 IL_0027: call ""void C.M(int, string, CustomHandler)"" IL_002c: ret } " : @" { // Code size 52 (0x34) .maxstack 7 .locals init (string V_0, int V_1, CustomHandler V_2, bool V_3) IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string Program.<<Main>$>g__GetString|0_1()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: ldc.i4.7 IL_000f: ldc.i4.0 IL_0010: ldloc.0 IL_0011: ldloc.1 IL_0012: ldloca.s V_3 IL_0014: newobj ""CustomHandler..ctor(int, int, string, int, out bool)"" IL_0019: stloc.2 IL_001a: ldloc.3 IL_001b: brfalse.s IL_002b IL_001d: ldloca.s V_2 IL_001f: ldstr ""literal"" IL_0024: call ""bool CustomHandler.AppendLiteral(string)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.0 IL_002c: pop IL_002d: ldloc.2 IL_002e: call ""void C.M(int, string, CustomHandler)"" IL_0033: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 1, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_ParametersReordered([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; GetC().M(s: GetString(), i: GetInt(), c: " + expression + @"); C GetC() { Console.WriteLine(""GetC""); return new C { Field = 5 }; } int GetInt() { Console.WriteLine(""GetInt""); return 10; } string GetString() { Console.WriteLine(""GetString""); return ""str""; } public class C { public int Field; public void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""s"", """", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s, C c, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""s:"" + s); _builder.AppendLine(""c.Field:"" + c.Field.ToString()); _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" GetC GetString GetInt s:str c.Field:5 i:10 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 56 (0x38) .maxstack 9 .locals init (string V_0, C V_1, int V_2, string V_3, CustomHandler V_4) IL_0000: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string Program.<<Main>$>g__GetString|0_2()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: stloc.3 IL_000f: call ""int Program.<<Main>$>g__GetInt|0_1()"" IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: ldloc.3 IL_0017: ldloca.s V_4 IL_0019: ldc.i4.7 IL_001a: ldc.i4.0 IL_001b: ldloc.0 IL_001c: ldloc.1 IL_001d: ldloc.2 IL_001e: call ""CustomHandler..ctor(int, int, string, C, int)"" IL_0023: ldloca.s V_4 IL_0025: ldstr ""literal"" IL_002a: call ""bool CustomHandler.AppendLiteral(string)"" IL_002f: pop IL_0030: ldloc.s V_4 IL_0032: callvirt ""void C.M(int, string, CustomHandler)"" IL_0037: ret } " : @" { // Code size 65 (0x41) .maxstack 9 .locals init (string V_0, C V_1, int V_2, string V_3, CustomHandler V_4, bool V_5) IL_0000: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string Program.<<Main>$>g__GetString|0_2()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: stloc.3 IL_000f: call ""int Program.<<Main>$>g__GetInt|0_1()"" IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: ldloc.3 IL_0017: ldc.i4.7 IL_0018: ldc.i4.0 IL_0019: ldloc.0 IL_001a: ldloc.1 IL_001b: ldloc.2 IL_001c: ldloca.s V_5 IL_001e: newobj ""CustomHandler..ctor(int, int, string, C, int, out bool)"" IL_0023: stloc.s V_4 IL_0025: ldloc.s V_5 IL_0027: brfalse.s IL_0037 IL_0029: ldloca.s V_4 IL_002b: ldstr ""literal"" IL_0030: call ""bool CustomHandler.AppendLiteral(string)"" IL_0035: br.s IL_0038 IL_0037: ldc.i4.0 IL_0038: pop IL_0039: ldloc.s V_4 IL_003b: callvirt ""void C.M(int, string, CustomHandler)"" IL_0040: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 1, -1, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_Duplicated([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(GetInt(), """", " + expression + @"); int GetInt() { Console.WriteLine(""GetInt""); return 10; } public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, int i2" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""i2:"" + i2.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" GetInt i1:10 i2:10 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 43 (0x2b) .maxstack 7 .locals init (int V_0, CustomHandler V_1) IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr """" IL_000c: ldloca.s V_1 IL_000e: ldc.i4.7 IL_000f: ldc.i4.0 IL_0010: ldloc.0 IL_0011: ldloc.0 IL_0012: call ""CustomHandler..ctor(int, int, int, int)"" IL_0017: ldloca.s V_1 IL_0019: ldstr ""literal"" IL_001e: call ""bool CustomHandler.AppendLiteral(string)"" IL_0023: pop IL_0024: ldloc.1 IL_0025: call ""void C.M(int, string, CustomHandler)"" IL_002a: ret } " : @" { // Code size 50 (0x32) .maxstack 7 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr """" IL_000c: ldc.i4.7 IL_000d: ldc.i4.0 IL_000e: ldloc.0 IL_000f: ldloc.0 IL_0010: ldloca.s V_2 IL_0012: newobj ""CustomHandler..ctor(int, int, int, int, out bool)"" IL_0017: stloc.1 IL_0018: ldloc.2 IL_0019: brfalse.s IL_0029 IL_001b: ldloca.s V_1 IL_001d: ldstr ""literal"" IL_0022: call ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.1 IL_002c: call ""void C.M(int, string, CustomHandler)"" IL_0031: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_EmptyWithMatchingConstructor([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, """", " + expression + @"); public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute()] CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount" + extraConstructorArg + @") { " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: "CustomHandler").VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 19 (0x13) .maxstack 4 IL_0000: ldc.i4.1 IL_0001: ldstr """" IL_0006: ldc.i4.0 IL_0007: ldc.i4.0 IL_0008: newobj ""CustomHandler..ctor(int, int)"" IL_000d: call ""void C.M(int, string, CustomHandler)"" IL_0012: ret } " : @" { // Code size 21 (0x15) .maxstack 5 .locals init (bool V_0) IL_0000: ldc.i4.1 IL_0001: ldstr """" IL_0006: ldc.i4.0 IL_0007: ldc.i4.0 IL_0008: ldloca.s V_0 IL_000a: newobj ""CustomHandler..ctor(int, int, out bool)"" IL_000f: call ""void C.M(int, string, CustomHandler)"" IL_0014: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_EmptyWithoutMatchingConstructor([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression) { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute()] CustomHandler c) { } } [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") { " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. CompileAndVerify(comp, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics(); CreateCompilation(@"C.M(1, """", " + expression + @");", new[] { comp.EmitToImageReference() }).VerifyDiagnostics( (extraConstructorArg == "") ? new[] { // (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'CustomHandler.CustomHandler(int, int, int)' // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("i", "CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 12), // (1,12): error CS1615: Argument 3 may not be passed with the 'out' keyword // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, expression).WithArguments("3", "out").WithLocation(1, 12) } : new[] { // (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'CustomHandler.CustomHandler(int, int, int, out bool)' // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("i", "CustomHandler.CustomHandler(int, int, int, out bool)").WithLocation(1, 12), // (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'success' of 'CustomHandler.CustomHandler(int, int, int, out bool)' // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("success", "CustomHandler.CustomHandler(int, int, int, out bool)").WithLocation(1, 12) } ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_OnIndexerRvalue([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; var c = new C(); Console.WriteLine(c[10, ""str"", " + expression + @"]); public class C { public string this[int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c] { get => c.ToString(); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i1:10 s:str literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 52 (0x34) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldloca.s V_2 IL_0012: ldc.i4.7 IL_0013: ldc.i4.0 IL_0014: ldloc.0 IL_0015: ldloc.1 IL_0016: call ""CustomHandler..ctor(int, int, int, string)"" IL_001b: ldloca.s V_2 IL_001d: ldstr ""literal"" IL_0022: call ""bool CustomHandler.AppendLiteral(string)"" IL_0027: pop IL_0028: ldloc.2 IL_0029: callvirt ""string C.this[int, string, CustomHandler].get"" IL_002e: call ""void System.Console.WriteLine(string)"" IL_0033: ret } " : @" { // Code size 59 (0x3b) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2, bool V_3) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldc.i4.7 IL_0011: ldc.i4.0 IL_0012: ldloc.0 IL_0013: ldloc.1 IL_0014: ldloca.s V_3 IL_0016: newobj ""CustomHandler..ctor(int, int, int, string, out bool)"" IL_001b: stloc.2 IL_001c: ldloc.3 IL_001d: brfalse.s IL_002d IL_001f: ldloca.s V_2 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: pop IL_002f: ldloc.2 IL_0030: callvirt ""string C.this[int, string, CustomHandler].get"" IL_0035: call ""void System.Console.WriteLine(string)"" IL_003a: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetIndexer<PropertySymbol>("Item").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_OnIndexerLvalue([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; var c = new C(); c[10, ""str"", " + expression + @"] = """"; public class C { public string this[int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c] { set => Console.WriteLine(c.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i1:10 s:str literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 52 (0x34) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldloca.s V_2 IL_0012: ldc.i4.7 IL_0013: ldc.i4.0 IL_0014: ldloc.0 IL_0015: ldloc.1 IL_0016: call ""CustomHandler..ctor(int, int, int, string)"" IL_001b: ldloca.s V_2 IL_001d: ldstr ""literal"" IL_0022: call ""bool CustomHandler.AppendLiteral(string)"" IL_0027: pop IL_0028: ldloc.2 IL_0029: ldstr """" IL_002e: callvirt ""void C.this[int, string, CustomHandler].set"" IL_0033: ret } " : @" { // Code size 59 (0x3b) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2, bool V_3) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldc.i4.7 IL_0011: ldc.i4.0 IL_0012: ldloc.0 IL_0013: ldloc.1 IL_0014: ldloca.s V_3 IL_0016: newobj ""CustomHandler..ctor(int, int, int, string, out bool)"" IL_001b: stloc.2 IL_001c: ldloc.3 IL_001d: brfalse.s IL_002d IL_001f: ldloca.s V_2 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: pop IL_002f: ldloc.2 IL_0030: ldstr """" IL_0035: callvirt ""void C.this[int, string, CustomHandler].set"" IL_003a: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetIndexer<PropertySymbol>("Item").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_ThisParameter([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; (new C(5)).M((int)10, ""str"", " + expression + @"); public class C { public int Prop { get; } public C(int i) => Prop = i; public void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", """", ""s"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, C c, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""c.Prop:"" + c.Prop.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i1:10 c.Prop:5 s:str literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 51 (0x33) .maxstack 9 .locals init (int V_0, C V_1, string V_2, CustomHandler V_3) IL_0000: ldc.i4.5 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.1 IL_0007: ldloc.1 IL_0008: ldc.i4.s 10 IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: ldstr ""str"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldloca.s V_3 IL_0015: ldc.i4.7 IL_0016: ldc.i4.0 IL_0017: ldloc.0 IL_0018: ldloc.1 IL_0019: ldloc.2 IL_001a: call ""CustomHandler..ctor(int, int, int, C, string)"" IL_001f: ldloca.s V_3 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: pop IL_002c: ldloc.3 IL_002d: callvirt ""void C.M(int, string, CustomHandler)"" IL_0032: ret } " : @" { // Code size 59 (0x3b) .maxstack 9 .locals init (int V_0, C V_1, string V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.5 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.1 IL_0007: ldloc.1 IL_0008: ldc.i4.s 10 IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: ldstr ""str"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldc.i4.7 IL_0014: ldc.i4.0 IL_0015: ldloc.0 IL_0016: ldloc.1 IL_0017: ldloc.2 IL_0018: ldloca.s V_4 IL_001a: newobj ""CustomHandler..ctor(int, int, int, C, string, out bool)"" IL_001f: stloc.3 IL_0020: ldloc.s V_4 IL_0022: brfalse.s IL_0032 IL_0024: ldloca.s V_3 IL_0026: ldstr ""literal"" IL_002b: call ""bool CustomHandler.AppendLiteral(string)"" IL_0030: br.s IL_0033 IL_0032: ldc.i4.0 IL_0033: pop IL_0034: ldloc.3 IL_0035: callvirt ""void C.M(int, string, CustomHandler)"" IL_003a: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, -1, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [InlineData(@"$""literal""")] [InlineData(@"$"""" + $""literal""")] public void InterpolatedStringHandlerArgumentAttribute_OnConstructor(string expression) { var code = @" using System; using System.Runtime.CompilerServices; _ = new C(5, " + expression + @"); public class C { public int Prop { get; } public C(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")]CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" i:5 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 34 (0x22) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.5 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldloca.s V_1 IL_0005: ldc.i4.7 IL_0006: ldc.i4.0 IL_0007: ldloc.0 IL_0008: call ""CustomHandler..ctor(int, int, int)"" IL_000d: ldloca.s V_1 IL_000f: ldstr ""literal"" IL_0014: call ""bool CustomHandler.AppendLiteral(string)"" IL_0019: pop IL_001a: ldloc.1 IL_001b: newobj ""C..ctor(int, CustomHandler)"" IL_0020: pop IL_0021: ret } "); } [Theory] [CombinatorialData] public void RefReturningMethodAsReceiver_Success([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C c = new C(1); GetC(ref c).M(" + expression + @"); Console.WriteLine(c.I); ref C GetC(ref C c) { Console.WriteLine(""GetC""); return ref c; } public class C { public int I; public C(int i) { I = i; } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref C c" + extraConstructorArg + @") : this(literalLength, formattedCount) { c = new C(2); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, verify: ExecutionConditionUtil.IsWindowsDesktop ? Verification.Skipped : Verification.Passes, expectedOutput: @" GetC literal:literal 2 "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 57 (0x39) .maxstack 4 .locals init (C V_0, //c C& V_1, CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: call ""ref C Program.<<Main>$>g__GetC|0_0(ref C)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldind.ref IL_0011: ldc.i4.7 IL_0012: ldc.i4.0 IL_0013: ldloc.1 IL_0014: newobj ""CustomHandler..ctor(int, int, ref C)"" IL_0019: stloc.2 IL_001a: ldloca.s V_2 IL_001c: ldstr ""literal"" IL_0021: call ""bool CustomHandler.AppendLiteral(string)"" IL_0026: pop IL_0027: ldloc.2 IL_0028: callvirt ""void C.M(CustomHandler)"" IL_002d: ldloc.0 IL_002e: ldfld ""int C.I"" IL_0033: call ""void System.Console.WriteLine(int)"" IL_0038: ret } " : @" { // Code size 65 (0x41) .maxstack 5 .locals init (C V_0, //c C& V_1, CustomHandler V_2, bool V_3) IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: call ""ref C Program.<<Main>$>g__GetC|0_0(ref C)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldind.ref IL_0011: ldc.i4.7 IL_0012: ldc.i4.0 IL_0013: ldloc.1 IL_0014: ldloca.s V_3 IL_0016: newobj ""CustomHandler..ctor(int, int, ref C, out bool)"" IL_001b: stloc.2 IL_001c: ldloc.3 IL_001d: brfalse.s IL_002d IL_001f: ldloca.s V_2 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: pop IL_002f: ldloc.2 IL_0030: callvirt ""void C.M(CustomHandler)"" IL_0035: ldloc.0 IL_0036: ldfld ""int C.I"" IL_003b: call ""void System.Console.WriteLine(int)"" IL_0040: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { -1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void RefReturningMethodAsReceiver_Success_StructReceiver([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C c = new C(1); GetC(ref c).M(" + expression + @"); Console.WriteLine(c.I); ref C GetC(ref C c) { Console.WriteLine(""GetC""); return ref c; } public struct C { public int I; public C(int i) { I = i; } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref C c" + extraConstructorArg + @") : this(literalLength, formattedCount) { c = new C(2); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, verify: ExecutionConditionUtil.IsWindowsDesktop ? Verification.Skipped : Verification.Passes, expectedOutput: @" GetC literal:literal 2 "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 57 (0x39) .maxstack 4 .locals init (C V_0, //c C& V_1, CustomHandler V_2) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: call ""C..ctor(int)"" IL_0008: ldloca.s V_0 IL_000a: call ""ref C Program.<<Main>$>g__GetC|0_0(ref C)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.0 IL_0013: ldloc.1 IL_0014: newobj ""CustomHandler..ctor(int, int, ref C)"" IL_0019: stloc.2 IL_001a: ldloca.s V_2 IL_001c: ldstr ""literal"" IL_0021: call ""bool CustomHandler.AppendLiteral(string)"" IL_0026: pop IL_0027: ldloc.2 IL_0028: call ""void C.M(CustomHandler)"" IL_002d: ldloc.0 IL_002e: ldfld ""int C.I"" IL_0033: call ""void System.Console.WriteLine(int)"" IL_0038: ret } " : @" { // Code size 65 (0x41) .maxstack 5 .locals init (C V_0, //c C& V_1, CustomHandler V_2, bool V_3) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: call ""C..ctor(int)"" IL_0008: ldloca.s V_0 IL_000a: call ""ref C Program.<<Main>$>g__GetC|0_0(ref C)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.0 IL_0013: ldloc.1 IL_0014: ldloca.s V_3 IL_0016: newobj ""CustomHandler..ctor(int, int, ref C, out bool)"" IL_001b: stloc.2 IL_001c: ldloc.3 IL_001d: brfalse.s IL_002d IL_001f: ldloca.s V_2 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: pop IL_002f: ldloc.2 IL_0030: call ""void C.M(CustomHandler)"" IL_0035: ldloc.0 IL_0036: ldfld ""int C.I"" IL_003b: call ""void System.Console.WriteLine(int)"" IL_0040: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { -1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void RefReturningMethodAsReceiver_MismatchedRefness_01([CombinatorialValues("ref readonly", "")] string refness, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System.Runtime.CompilerServices; C c = new C(1); GetC().M(" + expression + @"); " + refness + @" C GetC() => throw null; public class C { public C(int i) { } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) { } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref C c) : this(literalLength, formattedCount) { } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (5,10): error CS1620: Argument 3 must be passed with the 'ref' keyword // GetC().M($"literal"); Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("3", "ref").WithLocation(5, 10) ); } [Theory] [CombinatorialData] public void RefReturningMethodAsReceiver_MismatchedRefness_02([CombinatorialValues("in", "")] string refness, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression) { var code = @" using System.Runtime.CompilerServices; C c = new C(1); GetC(ref c).M(" + expression + @"); ref C GetC(ref C c) => ref c; public class C { public C(int i) { } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) { } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount," + refness + @" C c) : this(literalLength, formattedCount) { } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (5,15): error CS1615: Argument 3 may not be passed with the 'ref' keyword // GetC(ref c).M($"literal"); Diagnostic(ErrorCode.ERR_BadArgExtraRef, expression).WithArguments("3", "ref").WithLocation(5, 15) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void StructReceiver_Rvalue(string expression) { var code = @" using System; using System.Runtime.CompilerServices; S s1 = new S { I = 1 }; S s2 = new S { I = 2 }; s1.M(s2, " + expression + @"); public struct S { public int I; public void M(S s2, [InterpolatedStringHandlerArgument("""", ""s2"")]CustomHandler handler) { Console.WriteLine(""s1.I:"" + this.I.ToString()); Console.WriteLine(""s2.I:"" + s2.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, S s1, S s2) : this(literalLength, formattedCount) { s1.I = 3; s2.I = 4; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" s1.I:1 s2.I:2"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 56 (0x38) .maxstack 6 .locals init (S V_0, //s2 S V_1, S V_2) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: stfld ""int S.I"" IL_0010: ldloc.1 IL_0011: ldloca.s V_1 IL_0013: initobj ""S"" IL_0019: ldloca.s V_1 IL_001b: ldc.i4.2 IL_001c: stfld ""int S.I"" IL_0021: ldloc.1 IL_0022: stloc.0 IL_0023: stloc.1 IL_0024: ldloca.s V_1 IL_0026: ldloc.0 IL_0027: stloc.2 IL_0028: ldloc.2 IL_0029: ldc.i4.0 IL_002a: ldc.i4.0 IL_002b: ldloc.1 IL_002c: ldloc.2 IL_002d: newobj ""CustomHandler..ctor(int, int, S, S)"" IL_0032: call ""void S.M(S, CustomHandler)"" IL_0037: ret } "); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void StructReceiver_Lvalue(string expression) { var code = @" using System; using System.Runtime.CompilerServices; S s1 = new S { I = 1 }; S s2 = new S { I = 2 }; s1.M(ref s2, " + expression + @"); public struct S { public int I; public void M(ref S s2, [InterpolatedStringHandlerArgument("""", ""s2"")]CustomHandler handler) { Console.WriteLine(""s1.I:"" + this.I.ToString()); Console.WriteLine(""s2.I:"" + s2.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref S s1, ref S s2) : this(literalLength, formattedCount) { s1.I = 3; s2.I = 4; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (8,14): error CS1620: Argument 3 must be passed with the 'ref' keyword // s1.M(ref s2, $""); Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("3", "ref").WithLocation(8, 14) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void StructParameter_ByVal(string expression) { var code = @" using System; using System.Runtime.CompilerServices; S s = new S { I = 1 }; S.M(s, " + expression + @"); public struct S { public int I; public static void M(S s, [InterpolatedStringHandlerArgument(""s"")]CustomHandler handler) { Console.WriteLine(""s.I:"" + s.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, S s) : this(literalLength, formattedCount) { s.I = 2; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @"s.I:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 33 (0x21) .maxstack 4 .locals init (S V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloca.s V_0 IL_000a: ldc.i4.1 IL_000b: stfld ""int S.I"" IL_0010: ldloc.0 IL_0011: stloc.0 IL_0012: ldloc.0 IL_0013: ldc.i4.0 IL_0014: ldc.i4.0 IL_0015: ldloc.0 IL_0016: newobj ""CustomHandler..ctor(int, int, S)"" IL_001b: call ""void S.M(S, CustomHandler)"" IL_0020: ret } "); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void StructParameter_ByRef(string expression) { var code = @" using System; using System.Runtime.CompilerServices; S s = new S { I = 1 }; S.M(ref s, " + expression + @"); public struct S { public int I; public static void M(ref S s, [InterpolatedStringHandlerArgument(""s"")]CustomHandler handler) { Console.WriteLine(""s.I:"" + s.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref S s) : this(literalLength, formattedCount) { s.I = 2; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @"s.I:2"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 36 (0x24) .maxstack 4 .locals init (S V_0, //s S V_1, S& V_2) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: stfld ""int S.I"" IL_0010: ldloc.1 IL_0011: stloc.0 IL_0012: ldloca.s V_0 IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: ldc.i4.0 IL_0017: ldc.i4.0 IL_0018: ldloc.2 IL_0019: newobj ""CustomHandler..ctor(int, int, ref S)"" IL_001e: call ""void S.M(ref S, CustomHandler)"" IL_0023: ret } "); } [Theory] [CombinatorialData] public void SideEffects(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal""", @"$"""" + $""literal""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; GetReceiver().M( GetArg(""Unrelated parameter 1""), GetArg(""Second value""), GetArg(""Unrelated parameter 2""), GetArg(""First value""), " + expression + @", GetArg(""Unrelated parameter 4"")); C GetReceiver() { Console.WriteLine(""GetReceiver""); return new C() { Prop = ""Prop"" }; } string GetArg(string s) { Console.WriteLine(s); return s; } public class C { public string Prop { get; set; } public void M(string param1, string param2, string param3, string param4, [InterpolatedStringHandlerArgument(""param4"", """", ""param2"")] CustomHandler c, string param6) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s1, C c, string s2" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""s1:"" + s1); _builder.AppendLine(""c.Prop:"" + c.Prop); _builder.AppendLine(""s2:"" + s2); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns); var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }, expectedOutput: @" GetReceiver Unrelated parameter 1 Second value Unrelated parameter 2 First value Handler constructor Unrelated parameter 4 s1:First value c.Prop:Prop s2:Second value literal:literal "); verifier.VerifyDiagnostics(); } [Theory] [InlineData(@"$""literal""")] [InlineData(@"$""literal"" + $""""")] public void InterpolatedStringHandlerArgumentsAttribute_ConversionFromArgumentType(string expression) { var code = @" using System; using System.Globalization; using System.Runtime.CompilerServices; int i = 1; C.M(i, " + expression + @"); public class C { public static implicit operator C(int i) => throw null; public static implicit operator C(double d) { Console.WriteLine(d.ToString(""G"", CultureInfo.InvariantCulture)); return new C(); } public override string ToString() => ""C""; public static void M(double d, [InterpolatedStringHandlerArgument(""d"")] CustomHandler handler) => Console.WriteLine(handler.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount) { } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" 1 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 39 (0x27) .maxstack 5 .locals init (double V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: conv.r8 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldloca.s V_1 IL_0006: ldc.i4.7 IL_0007: ldc.i4.0 IL_0008: ldloc.0 IL_0009: call ""C C.op_Implicit(double)"" IL_000e: call ""CustomHandler..ctor(int, int, C)"" IL_0013: ldloca.s V_1 IL_0015: ldstr ""literal"" IL_001a: call ""bool CustomHandler.AppendLiteral(string)"" IL_001f: pop IL_0020: ldloc.1 IL_0021: call ""void C.M(double, CustomHandler)"" IL_0026: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_Indexer_01(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal{i}""", @"$""literal"" + $""{i}""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; int i = 3; GetC()[GetInt(1), " + expression + @"] += GetInt(2); static C GetC() { Console.WriteLine(""GetC""); return new C() { Prop = 2 }; } static int GetInt(int i) { Console.WriteLine(""GetInt"" + i.ToString()); return 1; } public class C { public int Prop { get; set; } public int this[int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c] { get { Console.WriteLine(""Indexer getter""); return 0; } set { Console.WriteLine(""Indexer setter""); Console.WriteLine(c.ToString()); } } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""arg1:"" + arg1); _builder.AppendLine(""C.Prop:"" + c.Prop.ToString()); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" GetC GetInt1 Handler constructor Indexer getter GetInt2 Indexer setter arg1:1 C.Prop:2 literal:literal value:3 alignment:0 format: "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 85 (0x55) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, CustomHandler V_5) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: stloc.3 IL_0011: ldloca.s V_5 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_5 IL_001e: ldstr ""literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_5 IL_002a: ldloc.0 IL_002b: box ""int"" IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0037: ldloc.s V_5 IL_0039: stloc.s V_4 IL_003b: ldloc.2 IL_003c: ldloc.3 IL_003d: ldloc.s V_4 IL_003f: ldloc.2 IL_0040: ldloc.3 IL_0041: ldloc.s V_4 IL_0043: callvirt ""int C.this[int, CustomHandler].get"" IL_0048: ldc.i4.2 IL_0049: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_004e: add IL_004f: callvirt ""void C.this[int, CustomHandler].set"" IL_0054: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 96 (0x60) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, CustomHandler V_5, bool V_6) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: stloc.3 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_6 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.s V_5 IL_001e: ldloc.s V_6 IL_0020: brfalse.s IL_0040 IL_0022: ldloca.s V_5 IL_0024: ldstr ""literal"" IL_0029: call ""void CustomHandler.AppendLiteral(string)"" IL_002e: ldloca.s V_5 IL_0030: ldloc.0 IL_0031: box ""int"" IL_0036: ldc.i4.0 IL_0037: ldnull IL_0038: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_003d: ldc.i4.1 IL_003e: br.s IL_0041 IL_0040: ldc.i4.0 IL_0041: pop IL_0042: ldloc.s V_5 IL_0044: stloc.s V_4 IL_0046: ldloc.2 IL_0047: ldloc.3 IL_0048: ldloc.s V_4 IL_004a: ldloc.2 IL_004b: ldloc.3 IL_004c: ldloc.s V_4 IL_004e: callvirt ""int C.this[int, CustomHandler].get"" IL_0053: ldc.i4.2 IL_0054: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0059: add IL_005a: callvirt ""void C.this[int, CustomHandler].set"" IL_005f: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 91 (0x5b) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, CustomHandler V_5) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: stloc.3 IL_0011: ldloca.s V_5 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_5 IL_001e: ldstr ""literal"" IL_0023: call ""bool CustomHandler.AppendLiteral(string)"" IL_0028: brfalse.s IL_003b IL_002a: ldloca.s V_5 IL_002c: ldloc.0 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.s V_5 IL_003f: stloc.s V_4 IL_0041: ldloc.2 IL_0042: ldloc.3 IL_0043: ldloc.s V_4 IL_0045: ldloc.2 IL_0046: ldloc.3 IL_0047: ldloc.s V_4 IL_0049: callvirt ""int C.this[int, CustomHandler].get"" IL_004e: ldc.i4.2 IL_004f: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0054: add IL_0055: callvirt ""void C.this[int, CustomHandler].set"" IL_005a: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 97 (0x61) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, CustomHandler V_5, bool V_6) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: stloc.3 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_6 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.s V_5 IL_001e: ldloc.s V_6 IL_0020: brfalse.s IL_0041 IL_0022: ldloca.s V_5 IL_0024: ldstr ""literal"" IL_0029: call ""bool CustomHandler.AppendLiteral(string)"" IL_002e: brfalse.s IL_0041 IL_0030: ldloca.s V_5 IL_0032: ldloc.0 IL_0033: box ""int"" IL_0038: ldc.i4.0 IL_0039: ldnull IL_003a: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_003f: br.s IL_0042 IL_0041: ldc.i4.0 IL_0042: pop IL_0043: ldloc.s V_5 IL_0045: stloc.s V_4 IL_0047: ldloc.2 IL_0048: ldloc.3 IL_0049: ldloc.s V_4 IL_004b: ldloc.2 IL_004c: ldloc.3 IL_004d: ldloc.s V_4 IL_004f: callvirt ""int C.this[int, CustomHandler].get"" IL_0054: ldc.i4.2 IL_0055: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_005a: add IL_005b: callvirt ""void C.this[int, CustomHandler].set"" IL_0060: ret } ", }; } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_Indexer_02(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal{i}""", @"$""literal"" + $""{i}""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; int i = 3; GetC()[GetInt(1), " + expression + @"] += GetInt(2); static C GetC() { Console.WriteLine(""GetC""); return new C() { Prop = 2 }; } static int GetInt(int i) { Console.WriteLine(""GetInt"" + i.ToString()); return 1; } public class C { private int field; public int Prop { get; set; } public ref int this[int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c] { get { Console.WriteLine(""Indexer getter""); Console.WriteLine(c.ToString()); return ref field; } } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""arg1:"" + arg1); _builder.AppendLine(""C.Prop:"" + c.Prop.ToString()); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" GetC GetInt1 Handler constructor Indexer getter arg1:1 C.Prop:2 literal:literal value:3 alignment:0 format: GetInt2 "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 72 (0x48) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_3 IL_002a: ldloc.0 IL_002b: box ""int"" IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0037: ldloc.3 IL_0038: callvirt ""ref int C.this[int, CustomHandler].get"" IL_003d: dup IL_003e: ldind.i4 IL_003f: ldc.i4.2 IL_0040: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0045: add IL_0046: stind.i4 IL_0047: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 82 (0x52) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_4 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.3 IL_001d: ldloc.s V_4 IL_001f: brfalse.s IL_003f IL_0021: ldloca.s V_3 IL_0023: ldstr ""literal"" IL_0028: call ""void CustomHandler.AppendLiteral(string)"" IL_002d: ldloca.s V_3 IL_002f: ldloc.0 IL_0030: box ""int"" IL_0035: ldc.i4.0 IL_0036: ldnull IL_0037: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_003c: ldc.i4.1 IL_003d: br.s IL_0040 IL_003f: ldc.i4.0 IL_0040: pop IL_0041: ldloc.3 IL_0042: callvirt ""ref int C.this[int, CustomHandler].get"" IL_0047: dup IL_0048: ldind.i4 IL_0049: ldc.i4.2 IL_004a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_004f: add IL_0050: stind.i4 IL_0051: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 78 (0x4e) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""bool CustomHandler.AppendLiteral(string)"" IL_0028: brfalse.s IL_003b IL_002a: ldloca.s V_3 IL_002c: ldloc.0 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.3 IL_003e: callvirt ""ref int C.this[int, CustomHandler].get"" IL_0043: dup IL_0044: ldind.i4 IL_0045: ldc.i4.2 IL_0046: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_004b: add IL_004c: stind.i4 IL_004d: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 83 (0x53) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_4 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.3 IL_001d: ldloc.s V_4 IL_001f: brfalse.s IL_0040 IL_0021: ldloca.s V_3 IL_0023: ldstr ""literal"" IL_0028: call ""bool CustomHandler.AppendLiteral(string)"" IL_002d: brfalse.s IL_0040 IL_002f: ldloca.s V_3 IL_0031: ldloc.0 IL_0032: box ""int"" IL_0037: ldc.i4.0 IL_0038: ldnull IL_0039: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_003e: br.s IL_0041 IL_0040: ldc.i4.0 IL_0041: pop IL_0042: ldloc.3 IL_0043: callvirt ""ref int C.this[int, CustomHandler].get"" IL_0048: dup IL_0049: ldind.i4 IL_004a: ldc.i4.2 IL_004b: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0050: add IL_0051: stind.i4 IL_0052: ret } ", }; } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_RefReturningMethod(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal{i}""", @"$""literal"" + $""{i}""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; int i = 3; GetC().M(GetInt(1), " + expression + @") += GetInt(2); static C GetC() { Console.WriteLine(""GetC""); return new C() { Prop = 2 }; } static int GetInt(int i) { Console.WriteLine(""GetInt"" + i.ToString()); return 1; } public class C { private int field; public int Prop { get; set; } public ref int M(int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c) { Console.WriteLine(""M""); Console.WriteLine(c.ToString()); return ref field; } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""arg1:"" + arg1); _builder.AppendLine(""C.Prop:"" + c.Prop.ToString()); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" GetC GetInt1 Handler constructor M arg1:1 C.Prop:2 literal:literal value:3 alignment:0 format: GetInt2 "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 72 (0x48) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_3 IL_002a: ldloc.0 IL_002b: box ""int"" IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0037: ldloc.3 IL_0038: callvirt ""ref int C.M(int, CustomHandler)"" IL_003d: dup IL_003e: ldind.i4 IL_003f: ldc.i4.2 IL_0040: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0045: add IL_0046: stind.i4 IL_0047: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 82 (0x52) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_4 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.3 IL_001d: ldloc.s V_4 IL_001f: brfalse.s IL_003f IL_0021: ldloca.s V_3 IL_0023: ldstr ""literal"" IL_0028: call ""void CustomHandler.AppendLiteral(string)"" IL_002d: ldloca.s V_3 IL_002f: ldloc.0 IL_0030: box ""int"" IL_0035: ldc.i4.0 IL_0036: ldnull IL_0037: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_003c: ldc.i4.1 IL_003d: br.s IL_0040 IL_003f: ldc.i4.0 IL_0040: pop IL_0041: ldloc.3 IL_0042: callvirt ""ref int C.M(int, CustomHandler)"" IL_0047: dup IL_0048: ldind.i4 IL_0049: ldc.i4.2 IL_004a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_004f: add IL_0050: stind.i4 IL_0051: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 78 (0x4e) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""bool CustomHandler.AppendLiteral(string)"" IL_0028: brfalse.s IL_003b IL_002a: ldloca.s V_3 IL_002c: ldloc.0 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.3 IL_003e: callvirt ""ref int C.M(int, CustomHandler)"" IL_0043: dup IL_0044: ldind.i4 IL_0045: ldc.i4.2 IL_0046: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_004b: add IL_004c: stind.i4 IL_004d: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 83 (0x53) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_4 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.3 IL_001d: ldloc.s V_4 IL_001f: brfalse.s IL_0040 IL_0021: ldloca.s V_3 IL_0023: ldstr ""literal"" IL_0028: call ""bool CustomHandler.AppendLiteral(string)"" IL_002d: brfalse.s IL_0040 IL_002f: ldloca.s V_3 IL_0031: ldloc.0 IL_0032: box ""int"" IL_0037: ldc.i4.0 IL_0038: ldnull IL_0039: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_003e: br.s IL_0041 IL_0040: ldc.i4.0 IL_0041: pop IL_0042: ldloc.3 IL_0043: callvirt ""ref int C.M(int, CustomHandler)"" IL_0048: dup IL_0049: ldind.i4 IL_004a: ldc.i4.2 IL_004b: call ""int Program.<<Main>$>g__GetInt|0_1(int)"" IL_0050: add IL_0051: stind.i4 IL_0052: ret } ", }; } [Theory] [InlineData(@"$""literal""")] [InlineData(@"$"""" + $""literal""")] public void InterpolatedStringHandlerArgumentsAttribute_CollectionInitializerAdd(string expression) { var code = @" using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; _ = new C(1) { " + expression + @" }; public class C : IEnumerable<int> { public int Field; public C(int i) { Field = i; } public void Add([InterpolatedStringHandlerArgument("""")] CustomHandler c) { Console.WriteLine(c.ToString()); } public IEnumerator<int> GetEnumerator() => throw null; IEnumerator IEnumerable.GetEnumerator() => throw null; } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount) { _builder.AppendLine(""c.Field:"" + c.Field.ToString()); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" c.Field:1 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 37 (0x25) .maxstack 5 .locals init (C V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldloca.s V_1 IL_000a: ldc.i4.7 IL_000b: ldc.i4.0 IL_000c: ldloc.0 IL_000d: call ""CustomHandler..ctor(int, int, C)"" IL_0012: ldloca.s V_1 IL_0014: ldstr ""literal"" IL_0019: call ""void CustomHandler.AppendLiteral(string)"" IL_001e: ldloc.1 IL_001f: callvirt ""void C.Add(CustomHandler)"" IL_0024: ret } "); } [Theory] [InlineData(@"$""literal""")] [InlineData(@"$"""" + $""literal""")] public void InterpolatedStringHandlerArgumentsAttribute_DictionaryInitializer(string expression) { var code = @" using System; using System.Runtime.CompilerServices; _ = new C(1) { [" + expression + @"] = 1 }; public class C { public int Field; public C(int i) { Field = i; } public int this[[InterpolatedStringHandlerArgument("""")] CustomHandler c] { set => Console.WriteLine(c.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount) { _builder.AppendLine(""c.Field:"" + c.Field.ToString()); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" c.Field:1 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 40 (0x28) .maxstack 4 .locals init (C V_0, CustomHandler V_1, CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.0 IL_0007: ldloca.s V_2 IL_0009: ldc.i4.7 IL_000a: ldc.i4.0 IL_000b: ldloc.0 IL_000c: call ""CustomHandler..ctor(int, int, C)"" IL_0011: ldloca.s V_2 IL_0013: ldstr ""literal"" IL_0018: call ""void CustomHandler.AppendLiteral(string)"" IL_001d: ldloc.2 IL_001e: stloc.1 IL_001f: ldloc.0 IL_0020: ldloc.1 IL_0021: ldc.i4.1 IL_0022: callvirt ""void C.this[CustomHandler].set"" IL_0027: ret } "); } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_AttributeOnAppendFormatCall(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""{$""Inner string""}{2}""", @"$""{$""Inner string""}"" + $""{2}""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, " + expression + @"); class C { public static void M(int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler handler) { Console.WriteLine(handler.ToString()); } } public partial class CustomHandler { private int I = 0; public CustomHandler(int literalLength, int formattedCount, int i" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""int constructor""); I = i; " + (validityParameter ? "success = true;" : "") + @" } public CustomHandler(int literalLength, int formattedCount, CustomHandler c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""CustomHandler constructor""); _builder.AppendLine(""c.I:"" + c.I.ToString()); " + (validityParameter ? "success = true;" : "") + @" } public " + (useBoolReturns ? "bool" : "void") + @" AppendFormatted([InterpolatedStringHandlerArgument("""")]CustomHandler c) { _builder.AppendLine(""CustomHandler AppendFormatted""); _builder.Append(c.ToString()); " + (useBoolReturns ? "return true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" int constructor CustomHandler constructor CustomHandler AppendFormatted c.I:1 literal:Inner string value:2 alignment:0 format: "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 59 (0x3b) .maxstack 6 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: dup IL_000c: stloc.1 IL_000d: ldloc.1 IL_000e: ldc.i4.s 12 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0017: dup IL_0018: ldstr ""Inner string"" IL_001d: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0022: callvirt ""void CustomHandler.AppendFormatted(CustomHandler)"" IL_0027: dup IL_0028: ldc.i4.2 IL_0029: box ""int"" IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: call ""void C.M(int, CustomHandler)"" IL_003a: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 87 (0x57) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2, CustomHandler V_3, CustomHandler V_4, bool V_5) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.2 IL_000f: brfalse.s IL_004e IL_0011: ldloc.1 IL_0012: stloc.3 IL_0013: ldloc.3 IL_0014: ldc.i4.s 12 IL_0016: ldc.i4.0 IL_0017: ldloc.3 IL_0018: ldloca.s V_5 IL_001a: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_001f: stloc.s V_4 IL_0021: ldloc.s V_5 IL_0023: brfalse.s IL_0034 IL_0025: ldloc.s V_4 IL_0027: ldstr ""Inner string"" IL_002c: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0031: ldc.i4.1 IL_0032: br.s IL_0035 IL_0034: ldc.i4.0 IL_0035: pop IL_0036: ldloc.s V_4 IL_0038: callvirt ""void CustomHandler.AppendFormatted(CustomHandler)"" IL_003d: ldloc.1 IL_003e: ldc.i4.2 IL_003f: box ""int"" IL_0044: ldc.i4.0 IL_0045: ldnull IL_0046: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_004b: ldc.i4.1 IL_004c: br.s IL_004f IL_004e: ldc.i4.0 IL_004f: pop IL_0050: ldloc.1 IL_0051: call ""void C.M(int, CustomHandler)"" IL_0056: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 68 (0x44) .maxstack 5 .locals init (int V_0, CustomHandler V_1, CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: stloc.2 IL_000e: ldloc.2 IL_000f: ldc.i4.s 12 IL_0011: ldc.i4.0 IL_0012: ldloc.2 IL_0013: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0018: dup IL_0019: ldstr ""Inner string"" IL_001e: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0023: pop IL_0024: callvirt ""bool CustomHandler.AppendFormatted(CustomHandler)"" IL_0029: brfalse.s IL_003b IL_002b: ldloc.1 IL_002c: ldc.i4.2 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.1 IL_003e: call ""void C.M(int, CustomHandler)"" IL_0043: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 87 (0x57) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2, CustomHandler V_3, CustomHandler V_4, bool V_5) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.2 IL_000f: brfalse.s IL_004e IL_0011: ldloc.1 IL_0012: stloc.3 IL_0013: ldloc.3 IL_0014: ldc.i4.s 12 IL_0016: ldc.i4.0 IL_0017: ldloc.3 IL_0018: ldloca.s V_5 IL_001a: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_001f: stloc.s V_4 IL_0021: ldloc.s V_5 IL_0023: brfalse.s IL_0033 IL_0025: ldloc.s V_4 IL_0027: ldstr ""Inner string"" IL_002c: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0031: br.s IL_0034 IL_0033: ldc.i4.0 IL_0034: pop IL_0035: ldloc.s V_4 IL_0037: callvirt ""bool CustomHandler.AppendFormatted(CustomHandler)"" IL_003c: brfalse.s IL_004e IL_003e: ldloc.1 IL_003f: ldc.i4.2 IL_0040: box ""int"" IL_0045: ldc.i4.0 IL_0046: ldnull IL_0047: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_004c: br.s IL_004f IL_004e: ldc.i4.0 IL_004f: pop IL_0050: ldloc.1 IL_0051: call ""void C.M(int, CustomHandler)"" IL_0056: ret } ", }; } [Theory] [InlineData(@"$""literal""")] [InlineData(@"$"""" + $""literal""")] public void DiscardsUsedAsParameters(string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(out _, " + expression + @"); public class C { public static void M(out int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler c) { i = 0; Console.WriteLine(c.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, out int i) : this(literalLength, formattedCount) { i = 1; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @"literal:literal"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 31 (0x1f) .maxstack 4 .locals init (int V_0, CustomHandler V_1) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.0 IL_0004: ldloca.s V_0 IL_0006: newobj ""CustomHandler..ctor(int, int, out int)"" IL_000b: stloc.1 IL_000c: ldloca.s V_1 IL_000e: ldstr ""literal"" IL_0013: call ""void CustomHandler.AppendLiteral(string)"" IL_0018: ldloc.1 IL_0019: call ""void C.M(out int, CustomHandler)"" IL_001e: ret } "); } [Fact] public void DiscardsUsedAsParameters_DefinedInVB() { var vb = @" Imports System Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Public Class C Public Shared Sub M(<Out> ByRef i As Integer, <InterpolatedStringHandlerArgument(""i"")>c As CustomHandler) Console.WriteLine(i) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler Public Sub New(literalLength As Integer, formattedCount As Integer, <Out> ByRef i As Integer) i = 1 End Sub End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vb, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var code = @"C.M(out _, $"""");"; var comp = CreateCompilation(code, new[] { vbComp.EmitToImageReference() }); var verifier = CompileAndVerify(comp, expectedOutput: @"1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 17 (0x11) .maxstack 4 .locals init (int V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.0 IL_0004: ldloca.s V_0 IL_0006: newobj ""CustomHandler..ctor(int, int, out int)"" IL_000b: call ""void C.M(out int, CustomHandler)"" IL_0010: ret } "); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DisallowedInExpressionTrees(string expression) { var code = @" using System; using System.Linq.Expressions; Expression<Func<CustomHandler>> expr = () => " + expression + @"; "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, handler }); comp.VerifyDiagnostics( // (5,46): error CS8952: An expression tree may not contain an interpolated string handler conversion. // Expression<Func<CustomHandler>> expr = () => $""; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsInterpolatedStringHandlerConversion, expression).WithLocation(5, 46) ); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_01() { var code = @" using System; using System.Linq.Expressions; Expression<Func<string, string>> e = o => $""{o.Length}"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 127 (0x7f) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldc.i4.1 IL_006f: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0074: dup IL_0075: ldc.i4.0 IL_0076: ldloc.0 IL_0077: stelem.ref IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_007d: pop IL_007e: ret } "); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_02() { var code = @" using System.Linq.Expressions; Expression e = (string o) => $""{o.Length}"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 127 (0x7f) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldc.i4.1 IL_006f: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0074: dup IL_0075: ldc.i4.0 IL_0076: ldloc.0 IL_0077: stelem.ref IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_007d: pop IL_007e: ret } "); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_03() { var code = @" using System; using System.Linq.Expressions; Expression<Func<Func<string, string>>> e = () => o => $""{o.Length}"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 137 (0x89) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldc.i4.1 IL_006f: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0074: dup IL_0075: ldc.i4.0 IL_0076: ldloc.0 IL_0077: stelem.ref IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_007d: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()"" IL_0082: call ""System.Linq.Expressions.Expression<System.Func<System.Func<string, string>>> System.Linq.Expressions.Expression.Lambda<System.Func<System.Func<string, string>>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0087: pop IL_0088: ret } "); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_04() { var code = @" using System; using System.Linq.Expressions; Expression e = Func<string, string> () => (string o) => $""{o.Length}"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 137 (0x89) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldc.i4.1 IL_006f: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0074: dup IL_0075: ldc.i4.0 IL_0076: ldloc.0 IL_0077: stelem.ref IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_007d: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()"" IL_0082: call ""System.Linq.Expressions.Expression<System.Func<System.Func<string, string>>> System.Linq.Expressions.Expression.Lambda<System.Func<System.Func<string, string>>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0087: pop IL_0088: ret } "); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_05() { var code = @" using System; using System.Linq.Expressions; Expression<Func<string, string>> e = o => $""{o.Length}"" + $""literal"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 167 (0xa7) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldstr ""literal"" IL_0073: ldtoken ""string"" IL_0078: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_007d: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0082: ldtoken ""string string.Concat(string, string)"" IL_0087: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_008c: castclass ""System.Reflection.MethodInfo"" IL_0091: call ""System.Linq.Expressions.BinaryExpression System.Linq.Expressions.Expression.Add(System.Linq.Expressions.Expression, System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0096: ldc.i4.1 IL_0097: newarr ""System.Linq.Expressions.ParameterExpression"" IL_009c: dup IL_009d: ldc.i4.0 IL_009e: ldloc.0 IL_009f: stelem.ref IL_00a0: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_00a5: pop IL_00a6: ret } "); } [Theory] [CombinatorialData] public void CustomHandlerUsedAsArgumentToCustomHandler(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression) { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, " + expression + @", " + expression + @"); public class C { public static void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c1, [InterpolatedStringHandlerArgument(""c1"")] CustomHandler c2) => Console.WriteLine(c2.ToString()); } public partial class CustomHandler { private int i; public CustomHandler(int literalLength, int formattedCount, int i" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); this.i = i; " + (validityParameter ? "success = true;" : "") + @" } public CustomHandler(int literalLength, int formattedCount, CustomHandler c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { _builder.AppendLine(""c.i:"" + c.i.ToString()); " + (validityParameter ? "success = true;" : "") + @" } }"; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: "c.i:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 27 (0x1b) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: ldc.i4.0 IL_000e: ldc.i4.0 IL_000f: ldloc.1 IL_0010: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0015: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001a: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 31 (0x1f) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.1 IL_000f: ldc.i4.0 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: ldloca.s V_2 IL_0014: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_0019: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001e: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 27 (0x1b) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: ldc.i4.0 IL_000e: ldc.i4.0 IL_000f: ldloc.1 IL_0010: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0015: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001a: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 31 (0x1f) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.1 IL_000f: ldc.i4.0 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: ldloca.s V_2 IL_0014: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_0019: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001e: ret } ", }; } [Fact, WorkItem(1370647, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647")] public void AsFormattableString() { var code = @" M($""{1}"" + $""literal""); System.FormattableString s = $""{1}"" + $""literal""; void M(System.FormattableString s) { } "; var comp = CreateCompilation(code); comp.VerifyDiagnostics( // (2,3): error CS1503: Argument 1: cannot convert from 'string' to 'System.FormattableString' // M($"{1}" + $"literal"); Diagnostic(ErrorCode.ERR_BadArgType, @"$""{1}"" + $""literal""").WithArguments("1", "string", "System.FormattableString").WithLocation(2, 3), // (3,30): error CS0029: Cannot implicitly convert type 'string' to 'System.FormattableString' // System.FormattableString s = $"{1}" + $"literal"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{1}"" + $""literal""").WithArguments("string", "System.FormattableString").WithLocation(3, 30) ); } [Fact, WorkItem(1370647, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647")] public void AsIFormattable() { var code = @" M($""{1}"" + $""literal""); System.IFormattable s = $""{1}"" + $""literal""; void M(System.IFormattable s) { } "; var comp = CreateCompilation(code); comp.VerifyDiagnostics( // (2,3): error CS1503: Argument 1: cannot convert from 'string' to 'System.IFormattable' // M($"{1}" + $"literal"); Diagnostic(ErrorCode.ERR_BadArgType, @"$""{1}"" + $""literal""").WithArguments("1", "string", "System.IFormattable").WithLocation(2, 3), // (3,25): error CS0029: Cannot implicitly convert type 'string' to 'System.IFormattable' // System.IFormattable s = $"{1}" + $"literal"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{1}"" + $""literal""").WithArguments("string", "System.IFormattable").WithLocation(3, 25) ); } [Theory] [CombinatorialData] public void DefiniteAssignment_01(bool useBoolReturns, bool trailingOutParameter, [CombinatorialValues(@"$""{i = 1}{M(out var o)}{s = o.ToString()}""", @"$""{i = 1}"" + $""{M(out var o)}"" + $""{s = o.ToString()}""")] string expression) { var code = @" int i; string s; CustomHandler c = " + expression + @"; _ = i.ToString(); _ = o.ToString(); _ = s.ToString(); string M(out object o) { o = null; return null; } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns, includeTrailingOutConstructorParameter: trailingOutParameter); var comp = CreateCompilation(new[] { code, customHandler }); if (trailingOutParameter) { comp.VerifyDiagnostics( // (6,5): error CS0165: Use of unassigned local variable 'i' // _ = i.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(6, 5), // (7,5): error CS0165: Use of unassigned local variable 'o' // _ = o.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "o").WithArguments("o").WithLocation(7, 5), // (8,5): error CS0165: Use of unassigned local variable 's' // _ = s.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s").WithLocation(8, 5) ); } else if (useBoolReturns) { comp.VerifyDiagnostics( // (7,5): error CS0165: Use of unassigned local variable 'o' // _ = o.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "o").WithArguments("o").WithLocation(7, 5), // (8,5): error CS0165: Use of unassigned local variable 's' // _ = s.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s").WithLocation(8, 5) ); } else { comp.VerifyDiagnostics(); } } [Theory] [CombinatorialData] public void DefiniteAssignment_02(bool useBoolReturns, bool trailingOutParameter, [CombinatorialValues(@"$""{i = 1}""", @"$"""" + $""{i = 1}""", @"$""{i = 1}"" + $""""")] string expression) { var code = @" int i; CustomHandler c = " + expression + @"; _ = i.ToString(); "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns, includeTrailingOutConstructorParameter: trailingOutParameter); var comp = CreateCompilation(new[] { code, customHandler }); if (trailingOutParameter) { comp.VerifyDiagnostics( // (5,5): error CS0165: Use of unassigned local variable 'i' // _ = i.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(5, 5) ); } else { comp.VerifyDiagnostics(); } } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DynamicConstruction_01(string expression) { var code = @" using System.Runtime.CompilerServices; dynamic d = 1; M(d, " + expression + @"); void M(dynamic d, [InterpolatedStringHandlerArgument(""d"")]CustomHandler c) {} public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, dynamic d) : this() {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute }); comp.VerifyDiagnostics( // (4,6): error CS8953: An interpolated string handler construction cannot use dynamic. Manually construct an instance of 'CustomHandler'. // M(d, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, expression).WithArguments("CustomHandler").WithLocation(4, 6) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DynamicConstruction_02(string expression) { var code = @" using System.Runtime.CompilerServices; int i = 1; M(i, " + expression + @"); void M(dynamic d, [InterpolatedStringHandlerArgument(""d"")]CustomHandler c) {} public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, dynamic d) : this() {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute }); comp.VerifyDiagnostics( // (4,6): error CS8953: An interpolated string handler construction cannot use dynamic. Manually construct an instance of 'CustomHandler'. // M(d, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, expression).WithArguments("CustomHandler").WithLocation(4, 6) ); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DynamicConstruction_03(string expression) { var code = @" using System; using System.Runtime.CompilerServices; int i = 1; M(i, " + expression + @"); void M(int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler c) {} public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, dynamic d) : this(literalLength, formattedCount) { Console.WriteLine(""d:"" + d.ToString()); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false, includeOneTimeHelpers: false); var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "d:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 22 (0x16) .maxstack 4 .locals init (int V_0) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: box ""int"" IL_000b: newobj ""CustomHandler..ctor(int, int, dynamic)"" IL_0010: call ""void Program.<<Main>$>g__M|0_0(int, CustomHandler)"" IL_0015: ret } "); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DynamicConstruction_04(string expression) { var code = @" using System; using System.Runtime.CompilerServices; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(dynamic literalLength, int formattedCount) { Console.WriteLine(""ctor""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "ctor"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 18 (0x12) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: box ""int"" IL_0006: ldc.i4.0 IL_0007: newobj ""CustomHandler..ctor(dynamic, int)"" IL_000c: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_0011: ret } "); } [Theory] [InlineData(@"$""""")] [InlineData(@"$"""" + $""""")] public void DynamicConstruction_05(string expression) { var code = @" using System; using System.Runtime.CompilerServices; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { Console.WriteLine(""ctor""); } public CustomHandler(dynamic literalLength, int formattedCount) { throw null; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "ctor"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: ldc.i4.0 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_000c: ret } "); } [Theory] [InlineData(@"$""Literal""")] [InlineData(@"$"""" + $""Literal""")] public void DynamicConstruction_06(string expression) { var code = @" using System; using System.Runtime.CompilerServices; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public void AppendLiteral(dynamic d) { Console.WriteLine(""AppendLiteral""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "AppendLiteral"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 28 (0x1c) .maxstack 3 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.0 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldstr ""Literal"" IL_0010: call ""void CustomHandler.AppendLiteral(dynamic)"" IL_0015: ldloc.0 IL_0016: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_001b: ret } "); } [Theory] [InlineData(@"$""{1}""")] [InlineData(@"$""{1}"" + $""""")] public void DynamicConstruction_07(string expression) { var code = @" using System; using System.Runtime.CompilerServices; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public void AppendFormatted(dynamic d) { Console.WriteLine(""AppendFormatted""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "AppendFormatted"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 29 (0x1d) .maxstack 3 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: call ""void CustomHandler.AppendFormatted(dynamic)"" IL_0016: ldloc.0 IL_0017: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_001c: ret } "); } [Theory] [InlineData(@"$""literal{d}""")] [InlineData(@"$""literal"" + $""{d}""")] public void DynamicConstruction_08(string expression) { var code = @" using System; using System.Runtime.CompilerServices; dynamic d = 1; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public void AppendLiteral(dynamic d) { Console.WriteLine(""AppendLiteral""); } public void AppendFormatted(dynamic d) { Console.WriteLine(""AppendFormatted""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: @" AppendLiteral AppendFormatted"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 128 (0x80) .maxstack 9 .locals init (object V_0, //d CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldloca.s V_1 IL_0009: ldc.i4.7 IL_000a: ldc.i4.1 IL_000b: call ""CustomHandler..ctor(int, int)"" IL_0010: ldloca.s V_1 IL_0012: ldstr ""literal"" IL_0017: call ""void CustomHandler.AppendLiteral(dynamic)"" IL_001c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0"" IL_0021: brtrue.s IL_0062 IL_0023: ldc.i4 0x100 IL_0028: ldstr ""AppendFormatted"" IL_002d: ldnull IL_002e: ldtoken ""Program"" IL_0033: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0038: ldc.i4.2 IL_0039: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_003e: dup IL_003f: ldc.i4.0 IL_0040: ldc.i4.s 9 IL_0042: ldnull IL_0043: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0048: stelem.ref IL_0049: dup IL_004a: ldc.i4.1 IL_004b: ldc.i4.0 IL_004c: ldnull IL_004d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0052: stelem.ref IL_0053: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0058: call ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_005d: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0"" IL_0062: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0"" IL_0067: ldfld ""<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>>.Target"" IL_006c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0"" IL_0071: ldloca.s V_1 IL_0073: ldloc.0 IL_0074: callvirt ""void <>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, ref CustomHandler, dynamic)"" IL_0079: ldloc.1 IL_007a: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_007f: ret } "); } [Theory] [InlineData(@"$""literal{d}""")] [InlineData(@"$""literal"" + $""{d}""")] public void DynamicConstruction_09(string expression) { var code = @" using System; using System.Runtime.CompilerServices; dynamic d = 1; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public bool AppendLiteral(dynamic d) { Console.WriteLine(""AppendLiteral""); return true; } public bool AppendFormatted(dynamic d) { Console.WriteLine(""AppendFormatted""); return true; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: @" AppendLiteral AppendFormatted"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 196 (0xc4) .maxstack 11 .locals init (object V_0, //d CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldloca.s V_1 IL_0009: ldc.i4.7 IL_000a: ldc.i4.1 IL_000b: call ""CustomHandler..ctor(int, int)"" IL_0010: ldloca.s V_1 IL_0012: ldstr ""literal"" IL_0017: call ""bool CustomHandler.AppendLiteral(dynamic)"" IL_001c: brfalse IL_00bb IL_0021: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1"" IL_0026: brtrue.s IL_004c IL_0028: ldc.i4.0 IL_0029: ldtoken ""bool"" IL_002e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0033: ldtoken ""Program"" IL_0038: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0042: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0047: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1"" IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1"" IL_0051: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Target"" IL_0056: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1"" IL_005b: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0"" IL_0060: brtrue.s IL_009d IL_0062: ldc.i4.0 IL_0063: ldstr ""AppendFormatted"" IL_0068: ldnull IL_0069: ldtoken ""Program"" IL_006e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0073: ldc.i4.2 IL_0074: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0079: dup IL_007a: ldc.i4.0 IL_007b: ldc.i4.s 9 IL_007d: ldnull IL_007e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0083: stelem.ref IL_0084: dup IL_0085: ldc.i4.1 IL_0086: ldc.i4.0 IL_0087: ldnull IL_0088: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008d: stelem.ref IL_008e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0093: call ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0098: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0"" IL_009d: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0"" IL_00a2: ldfld ""<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>>.Target"" IL_00a7: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0"" IL_00ac: ldloca.s V_1 IL_00ae: ldloc.0 IL_00af: callvirt ""dynamic <>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, ref CustomHandler, dynamic)"" IL_00b4: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00b9: br.s IL_00bc IL_00bb: ldc.i4.0 IL_00bc: pop IL_00bd: ldloc.1 IL_00be: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)"" IL_00c3: ret } "); } [Theory] [InlineData(@"$""{s}""")] [InlineData(@"$""{s}"" + $""""")] public void RefEscape_01(string expression) { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount) : this() {} public void AppendFormatted(Span<char> s) => this.s = s; public static CustomHandler M() { Span<char> s = stackalloc char[10]; return " + expression + @"; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,19): error CS8352: Cannot use local 's' in this context because it may expose referenced variables outside of their declaration scope // return $"{s}"; Diagnostic(ErrorCode.ERR_EscapeLocal, "s").WithArguments("s").WithLocation(17, 19) ); } [Theory] [InlineData(@"$""{s}""")] [InlineData(@"$""{s}"" + $""""")] public void RefEscape_02(string expression) { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount) : this() {} public void AppendFormatted(Span<char> s) => this.s = s; public static ref CustomHandler M() { Span<char> s = stackalloc char[10]; return " + expression + @"; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,9): error CS8150: By-value returns may only be used in methods that return by value // return $"{s}"; Diagnostic(ErrorCode.ERR_MustHaveRefReturn, "return").WithLocation(17, 9) ); } [Theory] [InlineData(@"$""{s}""")] [InlineData(@"$""{s}"" + $""""")] public void RefEscape_03(string expression) { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount) : this() {} public void AppendFormatted(Span<char> s) => this.s = s; public static ref CustomHandler M() { Span<char> s = stackalloc char[10]; return ref " + expression + @"; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,20): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // return ref $"{s}"; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, expression).WithLocation(17, 20) ); } [Theory] [InlineData(@"$""{s}""")] [InlineData(@"$""{s}"" + $""""")] public void RefEscape_04(string expression) { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { S1 s1; public CustomHandler(int literalLength, int formattedCount, ref S1 s1) : this() { this.s1 = s1; } public void AppendFormatted(Span<char> s) => this.s1.s = s; public static void M(ref S1 s1) { Span<char> s = stackalloc char[10]; M2(ref s1, " + expression + @"); } public static void M2(ref S1 s1, [InterpolatedStringHandlerArgument(""s1"")] ref CustomHandler handler) {} } public ref struct S1 { public Span<char> s; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,9): error CS8350: This combination of arguments to 'CustomHandler.M2(ref S1, ref CustomHandler)' is disallowed because it may expose variables referenced by parameter 'handler' outside of their declaration scope // M2(ref s1, $"{s}"); Diagnostic(ErrorCode.ERR_CallArgMixing, @"M2(ref s1, " + expression + @")").WithArguments("CustomHandler.M2(ref S1, ref CustomHandler)", "handler").WithLocation(17, 9), // (17,23): error CS8352: Cannot use local 's' in this context because it may expose referenced variables outside of their declaration scope // M2(ref s1, $"{s}"); Diagnostic(ErrorCode.ERR_EscapeLocal, "s").WithArguments("s").WithLocation(17, 23) ); } [Theory] [InlineData(@"$""{s1}""")] [InlineData(@"$""{s1}"" + $""""")] public void RefEscape_05(string expression) { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount, ref Span<char> s) : this() { this.s = s; } public void AppendFormatted(S1 s1) => s1.s = this.s; public static void M(ref S1 s1) { Span<char> s = stackalloc char[10]; M2(ref s, " + expression + @"); } public static void M2(ref Span<char> s, [InterpolatedStringHandlerArgument(""s"")] CustomHandler handler) {} } public ref struct S1 { public Span<char> s; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics(); } [Theory] [InlineData(@"$""{s2}""")] [InlineData(@"$""{s2}"" + $""""")] public void RefEscape_06(string expression) { var code = @" using System; using System.Runtime.CompilerServices; Span<char> s = stackalloc char[5]; Span<char> s2 = stackalloc char[10]; s.TryWrite(" + expression + @"); public static class MemoryExtensions { public static bool TryWrite(this Span<char> span, [InterpolatedStringHandlerArgument(""span"")] CustomHandler builder) => true; } [InterpolatedStringHandler] public ref struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, Span<char> s) : this() { } public bool AppendFormatted(Span<char> s) => true; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics(); } [Theory] [InlineData(@"$""{s2}""")] [InlineData(@"$""{s2}"" + $""""")] public void RefEscape_07(string expression) { var code = @" using System; using System.Runtime.CompilerServices; Span<char> s = stackalloc char[5]; Span<char> s2 = stackalloc char[10]; s.TryWrite(" + expression + @"); public static class MemoryExtensions { public static bool TryWrite(this Span<char> span, [InterpolatedStringHandlerArgument(""span"")] ref CustomHandler builder) => true; } [InterpolatedStringHandler] public ref struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, Span<char> s) : this() { } public bool AppendFormatted(Span<char> s) => true; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics(); } [Fact] public void RefEscape_08() { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount, ref Span<char> s) : this() { this.s = s; } public static CustomHandler M() { Span<char> s = stackalloc char[10]; ref CustomHandler c = ref M2(ref s, $""""); return c; } public static ref CustomHandler M2(ref Span<char> s, [InterpolatedStringHandlerArgument(""s"")] ref CustomHandler handler) { return ref handler; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (16,16): error CS8352: Cannot use local 'c' in this context because it may expose referenced variables outside of their declaration scope // return c; Diagnostic(ErrorCode.ERR_EscapeLocal, "c").WithArguments("c").WithLocation(16, 16) ); } [Fact] public void RefEscape_09() { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount, ref S1 s1) : this() { s1.Handler = this; } public static void M(ref S1 s1) { Span<char> s2 = stackalloc char[10]; M2(ref s1, $""{s2}""); } public static void M2(ref S1 s1, [InterpolatedStringHandlerArgument(""s1"")] CustomHandler handler) { } public void AppendFormatted(Span<char> s) { this.s = s; } } public ref struct S1 { public CustomHandler Handler; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (15,9): error CS8350: This combination of arguments to 'CustomHandler.M2(ref S1, CustomHandler)' is disallowed because it may expose variables referenced by parameter 'handler' outside of their declaration scope // M2(ref s1, $"{s2}"); Diagnostic(ErrorCode.ERR_CallArgMixing, @"M2(ref s1, $""{s2}"")").WithArguments("CustomHandler.M2(ref S1, CustomHandler)", "handler").WithLocation(15, 9), // (15,23): error CS8352: Cannot use local 's2' in this context because it may expose referenced variables outside of their declaration scope // M2(ref s1, $"{s2}"); Diagnostic(ErrorCode.ERR_EscapeLocal, "s2").WithArguments("s2").WithLocation(15, 23) ); } [Theory, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")] [InlineData(@"$""{{ {i} }}""")] [InlineData(@"$""{{ "" + $""{i}"" + $"" }}""")] public void BracesAreEscaped_01(string expression) { var code = @" int i = 1; System.Console.WriteLine(" + expression + @");"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" { value:1 }"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 56 (0x38) .maxstack 3 .locals init (int V_0, //i System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.1 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""{ "" IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_1 IL_0019: ldloc.0 IL_001a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_001f: ldloca.s V_1 IL_0021: ldstr "" }"" IL_0026: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_002b: ldloca.s V_1 IL_002d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0032: call ""void System.Console.WriteLine(string)"" IL_0037: ret } "); } [Theory, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")] [InlineData(@"$""{{ {i} }}""")] [InlineData(@"$""{{ "" + $""{i}"" + $"" }}""")] public void BracesAreEscaped_02(string expression) { var code = @" int i = 1; CustomHandler c = " + expression + @"; System.Console.WriteLine(c.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" literal:{ value:1 alignment:0 format: literal: }"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 71 (0x47) .maxstack 4 .locals init (int V_0, //i CustomHandler V_1, //c CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_2 IL_0004: ldc.i4.4 IL_0005: ldc.i4.1 IL_0006: call ""CustomHandler..ctor(int, int)"" IL_000b: ldloca.s V_2 IL_000d: ldstr ""{ "" IL_0012: call ""void CustomHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_2 IL_0019: ldloc.0 IL_001a: box ""int"" IL_001f: ldc.i4.0 IL_0020: ldnull IL_0021: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0026: ldloca.s V_2 IL_0028: ldstr "" }"" IL_002d: call ""void CustomHandler.AppendLiteral(string)"" IL_0032: ldloc.2 IL_0033: stloc.1 IL_0034: ldloca.s V_1 IL_0036: constrained. ""CustomHandler"" IL_003c: callvirt ""string object.ToString()"" IL_0041: call ""void System.Console.WriteLine(string)"" IL_0046: ret } "); } [Fact] public void InterpolatedStringsAddedUnderObjectAddition() { var code = @" int i1 = 1; int i2 = 2; int i3 = 3; int i4 = 4; System.Console.WriteLine($""{i1}"" + $""{i2}"" + $""{i3}"" + i4);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 value:2 value:3 4 "); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 66 (0x42) .maxstack 3 .locals init (int V_0, //i1 int V_1, //i2 int V_2, //i3 int V_3, //i4 System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_4) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.2 IL_0003: stloc.1 IL_0004: ldc.i4.3 IL_0005: stloc.2 IL_0006: ldc.i4.4 IL_0007: stloc.3 IL_0008: ldloca.s V_4 IL_000a: ldc.i4.0 IL_000b: ldc.i4.3 IL_000c: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0011: ldloca.s V_4 IL_0013: ldloc.0 IL_0014: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0019: ldloca.s V_4 IL_001b: ldloc.1 IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0021: ldloca.s V_4 IL_0023: ldloc.2 IL_0024: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0029: ldloca.s V_4 IL_002b: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0030: ldloca.s V_3 IL_0032: call ""string int.ToString()"" IL_0037: call ""string string.Concat(string, string)"" IL_003c: call ""void System.Console.WriteLine(string)"" IL_0041: ret } "); } [Theory] [InlineData(@"$""({i1}),"" + $""[{i2}],"" + $""{{{i3}}}""")] [InlineData(@"($""({i1}),"" + $""[{i2}],"") + $""{{{i3}}}""")] [InlineData(@"$""({i1}),"" + ($""[{i2}],"" + $""{{{i3}}}"")")] public void InterpolatedStringsAddedUnderObjectAddition2(string expression) { var code = $@" int i1 = 1; int i2 = 2; int i3 = 3; System.Console.WriteLine({expression});"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); CompileAndVerify(comp, expectedOutput: @" ( value:1 ), [ value:2 ], { value:3 } "); } [Fact] public void InterpolatedStringsAddedUnderObjectAddition3() { var code = @" #nullable enable using System; try { var s = string.Empty; Console.WriteLine($""{s = null}{s.Length}"" + $""""); } catch (NullReferenceException) { Console.WriteLine(""Null reference exception caught.""); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); CompileAndVerify(comp, expectedOutput: "Null reference exception caught.").VerifyIL("<top-level-statements-entry-point>", @" { // Code size 65 (0x41) .maxstack 3 .locals init (string V_0, //s System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) .try { IL_0000: ldsfld ""string string.Empty"" IL_0005: stloc.0 IL_0006: ldc.i4.0 IL_0007: ldc.i4.2 IL_0008: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000d: stloc.1 IL_000e: ldloca.s V_1 IL_0010: ldnull IL_0011: dup IL_0012: stloc.0 IL_0013: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0018: ldloca.s V_1 IL_001a: ldloc.0 IL_001b: callvirt ""int string.Length.get"" IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0025: ldloca.s V_1 IL_0027: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_002c: call ""void System.Console.WriteLine(string)"" IL_0031: leave.s IL_0040 } catch System.NullReferenceException { IL_0033: pop IL_0034: ldstr ""Null reference exception caught."" IL_0039: call ""void System.Console.WriteLine(string)"" IL_003e: leave.s IL_0040 } IL_0040: ret } ").VerifyDiagnostics( // (9,36): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine($"{s = null}{s.Length}" + $""); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 36) ); } [Fact] public void InterpolatedStringsAddedUnderObjectAddition_DefiniteAssignment() { var code = @" object o1; object o2; object o3; _ = $""{o1 = null}"" + $""{o2 = null}"" + $""{o3 = null}"" + 1; o1.ToString(); o2.ToString(); o3.ToString(); "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true) }); comp.VerifyDiagnostics( // (7,1): error CS0165: Use of unassigned local variable 'o2' // o2.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "o2").WithArguments("o2").WithLocation(7, 1), // (8,1): error CS0165: Use of unassigned local variable 'o3' // o3.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "o3").WithArguments("o3").WithLocation(8, 1) ); } [Fact] public void ParenthesizedAdditiveExpression_01() { var code = @" int i1 = 1; int i2 = 2; int i3 = 3; CustomHandler c = ($""{i1}"" + $""{i2}"") + $""{i3}""; System.Console.WriteLine(c.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:0 format: value:2 alignment:0 format: value:3 alignment:0 format: "); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 82 (0x52) .maxstack 4 .locals init (int V_0, //i1 int V_1, //i2 int V_2, //i3 CustomHandler V_3, //c CustomHandler V_4) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.2 IL_0003: stloc.1 IL_0004: ldc.i4.3 IL_0005: stloc.2 IL_0006: ldloca.s V_4 IL_0008: ldc.i4.0 IL_0009: ldc.i4.3 IL_000a: call ""CustomHandler..ctor(int, int)"" IL_000f: ldloca.s V_4 IL_0011: ldloc.0 IL_0012: box ""int"" IL_0017: ldc.i4.0 IL_0018: ldnull IL_0019: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001e: ldloca.s V_4 IL_0020: ldloc.1 IL_0021: box ""int"" IL_0026: ldc.i4.0 IL_0027: ldnull IL_0028: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_002d: ldloca.s V_4 IL_002f: ldloc.2 IL_0030: box ""int"" IL_0035: ldc.i4.0 IL_0036: ldnull IL_0037: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_003c: ldloc.s V_4 IL_003e: stloc.3 IL_003f: ldloca.s V_3 IL_0041: constrained. ""CustomHandler"" IL_0047: callvirt ""string object.ToString()"" IL_004c: call ""void System.Console.WriteLine(string)"" IL_0051: ret }"); } [Fact] public void ParenthesizedAdditiveExpression_02() { var code = @" int i1 = 1; int i2 = 2; int i3 = 3; CustomHandler c = $""{i1}"" + ($""{i2}"" + $""{i3}""); System.Console.WriteLine(c.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (6,19): error CS0029: Cannot implicitly convert type 'string' to 'CustomHandler' // CustomHandler c = $"{i1}" + ($"{i2}" + $"{i3}"); Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{i1}"" + ($""{i2}"" + $""{i3}"")").WithArguments("string", "CustomHandler").WithLocation(6, 19) ); } [Theory] [InlineData(@"$""{1}"", $""{2}""")] [InlineData(@"$""{1}"" + $"""", $""{2}"" + $""""")] public void TupleDeclaration_01(string initializer) { var code = @" (CustomHandler c1, CustomHandler c2) = (" + initializer + @"); System.Console.Write(c1.ToString()); System.Console.WriteLine(c2.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:0 format: value:2 alignment:0 format: "); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 91 (0x5b) .maxstack 4 .locals init (CustomHandler V_0, //c1 CustomHandler V_1, //c2 CustomHandler V_2, CustomHandler V_3) IL_0000: ldloca.s V_3 IL_0002: ldc.i4.0 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_3 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.0 IL_0012: ldnull IL_0013: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0018: ldloc.3 IL_0019: stloc.2 IL_001a: ldloca.s V_3 IL_001c: ldc.i4.0 IL_001d: ldc.i4.1 IL_001e: call ""CustomHandler..ctor(int, int)"" IL_0023: ldloca.s V_3 IL_0025: ldc.i4.2 IL_0026: box ""int"" IL_002b: ldc.i4.0 IL_002c: ldnull IL_002d: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0032: ldloc.3 IL_0033: ldloc.2 IL_0034: stloc.0 IL_0035: stloc.1 IL_0036: ldloca.s V_0 IL_0038: constrained. ""CustomHandler"" IL_003e: callvirt ""string object.ToString()"" IL_0043: call ""void System.Console.Write(string)"" IL_0048: ldloca.s V_1 IL_004a: constrained. ""CustomHandler"" IL_0050: callvirt ""string object.ToString()"" IL_0055: call ""void System.Console.WriteLine(string)"" IL_005a: ret } "); } [Theory] [InlineData(@"$""{1}"", $""{2}""")] [InlineData(@"$""{1}"" + $"""", $""{2}"" + $""""")] public void TupleDeclaration_02(string initializer) { var code = @" (CustomHandler c1, CustomHandler c2) t = (" + initializer + @"); System.Console.Write(t.c1.ToString()); System.Console.WriteLine(t.c2.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:0 format: value:2 alignment:0 format: "); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 104 (0x68) .maxstack 6 .locals init (System.ValueTuple<CustomHandler, CustomHandler> V_0, //t CustomHandler V_1) IL_0000: ldloca.s V_0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.0 IL_0005: ldc.i4.1 IL_0006: call ""CustomHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldc.i4.1 IL_000e: box ""int"" IL_0013: ldc.i4.0 IL_0014: ldnull IL_0015: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001a: ldloc.1 IL_001b: ldloca.s V_1 IL_001d: ldc.i4.0 IL_001e: ldc.i4.1 IL_001f: call ""CustomHandler..ctor(int, int)"" IL_0024: ldloca.s V_1 IL_0026: ldc.i4.2 IL_0027: box ""int"" IL_002c: ldc.i4.0 IL_002d: ldnull IL_002e: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0033: ldloc.1 IL_0034: call ""System.ValueTuple<CustomHandler, CustomHandler>..ctor(CustomHandler, CustomHandler)"" IL_0039: ldloca.s V_0 IL_003b: ldflda ""CustomHandler System.ValueTuple<CustomHandler, CustomHandler>.Item1"" IL_0040: constrained. ""CustomHandler"" IL_0046: callvirt ""string object.ToString()"" IL_004b: call ""void System.Console.Write(string)"" IL_0050: ldloca.s V_0 IL_0052: ldflda ""CustomHandler System.ValueTuple<CustomHandler, CustomHandler>.Item2"" IL_0057: constrained. ""CustomHandler"" IL_005d: callvirt ""string object.ToString()"" IL_0062: call ""void System.Console.WriteLine(string)"" IL_0067: ret } "); } [Theory, WorkItem(55609, "https://github.com/dotnet/roslyn/issues/55609")] [InlineData(@"$""{h1}{h2}""")] [InlineData(@"$""{h1}"" + $""{h2}""")] public void RefStructHandler_DynamicInHole(string expression) { var code = @" dynamic h1 = 1; dynamic h2 = 2; CustomHandler c = " + expression + ";"; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "ref struct", useBoolReturns: false); var comp = CreateCompilationWithCSharp(new[] { code, handler }); // Note: We don't give any errors when mixing dynamic and ref structs today. If that ever changes, we should get an // error here. This will crash at runtime because of this. comp.VerifyEmitDiagnostics(); } [Theory] [InlineData(@"$""Literal{1}""")] [InlineData(@"$""Literal"" + $""{1}""")] public void ConversionInParamsArguments(string expression) { var code = @" using System; using System.Linq; M(" + expression + ", " + expression + @"); void M(params CustomHandler[] handlers) { Console.WriteLine(string.Join(Environment.NewLine, handlers.Select(h => h.ToString()))); } "; var verifier = CompileAndVerify(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, expectedOutput: @" literal:Literal value:1 alignment:0 format: literal:Literal value:1 alignment:0 format: "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 100 (0x64) .maxstack 7 .locals init (CustomHandler V_0) IL_0000: ldc.i4.2 IL_0001: newarr ""CustomHandler"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldloca.s V_0 IL_000a: ldc.i4.7 IL_000b: ldc.i4.1 IL_000c: call ""CustomHandler..ctor(int, int)"" IL_0011: ldloca.s V_0 IL_0013: ldstr ""Literal"" IL_0018: call ""void CustomHandler.AppendLiteral(string)"" IL_001d: ldloca.s V_0 IL_001f: ldc.i4.1 IL_0020: box ""int"" IL_0025: ldc.i4.0 IL_0026: ldnull IL_0027: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_002c: ldloc.0 IL_002d: stelem ""CustomHandler"" IL_0032: dup IL_0033: ldc.i4.1 IL_0034: ldloca.s V_0 IL_0036: ldc.i4.7 IL_0037: ldc.i4.1 IL_0038: call ""CustomHandler..ctor(int, int)"" IL_003d: ldloca.s V_0 IL_003f: ldstr ""Literal"" IL_0044: call ""void CustomHandler.AppendLiteral(string)"" IL_0049: ldloca.s V_0 IL_004b: ldc.i4.1 IL_004c: box ""int"" IL_0051: ldc.i4.0 IL_0052: ldnull IL_0053: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0058: ldloc.0 IL_0059: stelem ""CustomHandler"" IL_005e: call ""void Program.<<Main>$>g__M|0_0(CustomHandler[])"" IL_0063: ret } "); } [Theory] [InlineData("static")] [InlineData("")] public void ArgumentsOnLocalFunctions_01(string mod) { var code = @" using System.Runtime.CompilerServices; M($""""); " + mod + @" void M([InterpolatedStringHandlerArgument("""")] CustomHandler c) { } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (4,3): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 3), // (6,10): error CS8944: 'M(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // void M([InterpolatedStringHandlerArgument("")] CustomHandler c) { } Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("M(CustomHandler)").WithLocation(6, 10 + mod.Length) ); } [Theory] [InlineData("static")] [InlineData("")] public void ArgumentsOnLocalFunctions_02(string mod) { var code = @" using System; using System.Runtime.CompilerServices; M(1, $""""); " + mod + @" void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) => _builder.Append(""i:"" + i.ToString()); } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: @"i:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 17 (0x11) .maxstack 4 .locals init (int V_0) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: call ""void Program.<<Main>$>g__M|0_0(int, CustomHandler)"" IL_0010: ret } "); } [Theory] [InlineData("static")] [InlineData("")] public void ArgumentsOnLambdas_01(string mod) { var code = @" using System.Runtime.CompilerServices; var a = " + mod + @" ([InterpolatedStringHandlerArgument("""")] CustomHandler c) => { }; a($""""); "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (4,12): warning CS8971: InterpolatedStringHandlerArgument has no effect when applied to lambda parameters and will be ignored at the call site. // var a = ([InterpolatedStringHandlerArgument("")] CustomHandler c) => { }; Diagnostic(ErrorCode.WRN_InterpolatedStringHandlerArgumentAttributeIgnoredOnLambdaParameters, @"InterpolatedStringHandlerArgument("""")").WithLocation(4, 12 + mod.Length), // (4,12): error CS8944: 'lambda expression' is not an instance method, the receiver cannot be an interpolated string handler argument. // var a = ([InterpolatedStringHandlerArgument("")] CustomHandler c) => { }; Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("lambda expression").WithLocation(4, 12 + mod.Length) ); } [Theory] [InlineData("static")] [InlineData("")] public void ArgumentsOnLambdas_02(string mod) { var code = @" using System; using System.Runtime.CompilerServices; var a = " + mod + @" (int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); a(1, $""""); partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) => throw null; } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: @""); verifier.VerifyDiagnostics( // (5,19): warning CS8971: InterpolatedStringHandlerArgument has no effect when applied to lambda parameters and will be ignored at the call site. // var a = (int i, [InterpolatedStringHandlerArgument("i")] CustomHandler c) => Console.WriteLine(c.ToString()); Diagnostic(ErrorCode.WRN_InterpolatedStringHandlerArgumentAttributeIgnoredOnLambdaParameters, @"InterpolatedStringHandlerArgument(""i"")").WithLocation(5, 19 + mod.Length) ); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 45 (0x2d) .maxstack 4 IL_0000: ldsfld ""System.Action<int, CustomHandler> Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<<Main>$>b__0_0(int, CustomHandler)"" IL_0014: newobj ""System.Action<int, CustomHandler>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Action<int, CustomHandler> Program.<>c.<>9__0_0"" IL_001f: ldc.i4.1 IL_0020: ldc.i4.0 IL_0021: ldc.i4.0 IL_0022: newobj ""CustomHandler..ctor(int, int)"" IL_0027: callvirt ""void System.Action<int, CustomHandler>.Invoke(int, CustomHandler)"" IL_002c: ret } "); } [Fact] public void ArgumentsOnDelegateTypes_01() { var code = @" using System.Runtime.CompilerServices; M m = null; m($""""); delegate void M([InterpolatedStringHandlerArgument("""")] CustomHandler c); "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (6,3): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // m($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(6, 3), // (8,18): error CS8944: 'M.Invoke(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // delegate void M([InterpolatedStringHandlerArgument("")] CustomHandler c); Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("M.Invoke(CustomHandler)").WithLocation(8, 18) ); } [Fact] public void ArgumentsOnDelegateTypes_02() { var vbCode = @" Imports System.Runtime.CompilerServices Public Delegate Sub M(<InterpolatedStringHandlerArgument("""")> c As CustomHandler) <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var code = @" M m = null; m($""""); "; var comp = CreateCompilation(code, references: new[] { vbComp.EmitToImageReference() }); comp.VerifyDiagnostics( // (4,3): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // m($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 3), // (4,3): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // m($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(4, 3), // (4,3): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // m($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(4, 3) ); } [Fact] public void ArgumentsOnDelegateTypes_03() { var code = @" using System; using System.Runtime.CompilerServices; M m = (i, c) => Console.WriteLine(c.ToString()); m(1, $""""); delegate void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c); partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) => _builder.Append(""i:"" + i.ToString()); } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: @"i:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 48 (0x30) .maxstack 5 .locals init (int V_0) IL_0000: ldsfld ""M Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<<Main>$>b__0_0(int, CustomHandler)"" IL_0014: newobj ""M..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""M Program.<>c.<>9__0_0"" IL_001f: ldc.i4.1 IL_0020: stloc.0 IL_0021: ldloc.0 IL_0022: ldc.i4.0 IL_0023: ldc.i4.0 IL_0024: ldloc.0 IL_0025: newobj ""CustomHandler..ctor(int, int, int)"" IL_002a: callvirt ""void M.Invoke(int, CustomHandler)"" IL_002f: ret } "); } [Fact] public void HandlerConstructorWithDefaultArgument_01() { var code = @" using System; using System.Runtime.CompilerServices; C.M($""""); class C { public static void M(CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] partial struct CustomHandler { private int _i = 0; public CustomHandler(int literalLength, int formattedCount, int i = 1) => _i = i; public override string ToString() => _i.ToString(); } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 14 (0xe) .maxstack 3 IL_0000: ldc.i4.0 IL_0001: ldc.i4.0 IL_0002: ldc.i4.1 IL_0003: newobj ""CustomHandler..ctor(int, int, int)"" IL_0008: call ""void C.M(CustomHandler)"" IL_000d: ret } "); } [Fact] public void HandlerConstructorWithDefaultArgument_02() { var code = @" using System; using System.Runtime.CompilerServices; C.M($""Literal""); class C { public static void M(CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] partial struct CustomHandler { private string _s = null; public CustomHandler(int literalLength, int formattedCount, out bool isValid, int i = 1) { _s = i.ToString(); isValid = false; } public void AppendLiteral(string s) => _s += s; public override string ToString() => _s; } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 38 (0x26) .maxstack 4 .locals init (CustomHandler V_0, bool V_1) IL_0000: ldc.i4.7 IL_0001: ldc.i4.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.1 IL_0005: newobj ""CustomHandler..ctor(int, int, out bool, int)"" IL_000a: stloc.0 IL_000b: ldloc.1 IL_000c: brfalse.s IL_001d IL_000e: ldloca.s V_0 IL_0010: ldstr ""Literal"" IL_0015: call ""void CustomHandler.AppendLiteral(string)"" IL_001a: ldc.i4.1 IL_001b: br.s IL_001e IL_001d: ldc.i4.0 IL_001e: pop IL_001f: ldloc.0 IL_0020: call ""void C.M(CustomHandler)"" IL_0025: ret } "); } [Fact] public void HandlerConstructorWithDefaultArgument_03() { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, $""""); class C { public static void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] partial struct CustomHandler { private string _s = null; public CustomHandler(int literalLength, int formattedCount, int i1, int i2 = 2) { _s = i1.ToString() + i2.ToString(); } public void AppendLiteral(string s) => _s += s; public override string ToString() => _s; } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"12"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 18 (0x12) .maxstack 5 .locals init (int V_0) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: ldc.i4.2 IL_0007: newobj ""CustomHandler..ctor(int, int, int, int)"" IL_000c: call ""void C.M(int, CustomHandler)"" IL_0011: ret } "); } [Fact] public void HandlerConstructorWithDefaultArgument_04() { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, $""Literal""); class C { public static void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] partial struct CustomHandler { private string _s = null; public CustomHandler(int literalLength, int formattedCount, int i1, out bool isValid, int i2 = 2) { _s = i1.ToString() + i2.ToString(); isValid = false; } public void AppendLiteral(string s) => _s += s; public override string ToString() => _s; } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"12"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 42 (0x2a) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.7 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: ldc.i4.2 IL_0009: newobj ""CustomHandler..ctor(int, int, int, out bool, int)"" IL_000e: stloc.1 IL_000f: ldloc.2 IL_0010: brfalse.s IL_0021 IL_0012: ldloca.s V_1 IL_0014: ldstr ""Literal"" IL_0019: call ""void CustomHandler.AppendLiteral(string)"" IL_001e: ldc.i4.1 IL_001f: br.s IL_0022 IL_0021: ldc.i4.0 IL_0022: pop IL_0023: ldloc.1 IL_0024: call ""void C.M(int, CustomHandler)"" IL_0029: ret } "); } [Fact] public void HandlerExtensionMethod_01() { var code = @" $""Test"".M(); public static class StringExt { public static void M(this CustomHandler handler) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (2,1): error CS1929: 'string' does not contain a definition for 'M' and the best extension method overload 'StringExt.M(CustomHandler)' requires a receiver of type 'CustomHandler' // $"Test".M(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, @"$""Test""").WithArguments("string", "M", "StringExt.M(CustomHandler)", "CustomHandler").WithLocation(2, 1) ); } [Fact] public void HandlerExtensionMethod_02() { var code = @" using System.Runtime.CompilerServices; var s = new S1(); s.M($""""); public struct S1 { public int Field = 1; } public static class S1Ext { public static void M(this S1 s, [InterpolatedStringHandlerArgument("""")] CustomHandler c) => throw null; } partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, S1 s) => throw null; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }); comp.VerifyDiagnostics( // (5,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // s.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(5, 5), // (14,38): error CS8944: 'S1Ext.M(S1, CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // public static void M(this S1 s, [InterpolatedStringHandlerArgument("")] CustomHandler c) => throw null; Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("S1Ext.M(S1, CustomHandler)").WithLocation(14, 38) ); } [Fact] public void HandlerExtensionMethod_03() { var code = @" using System; using System.Runtime.CompilerServices; var s = new S1(); s.M($""""); public struct S1 { public int Field = 1; } public static class S1Ext { public static void M(this S1 s, [InterpolatedStringHandlerArgument(""s"")] CustomHandler c) => Console.WriteLine(c.ToString()); } partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, S1 s) : this(literalLength, formattedCount) => _builder.Append(""s.Field:"" + s.Field); } "; var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: "s.Field:1"); verifier.VerifyDiagnostics(); } [Fact] public void NoStandaloneConstructor() { var code = @" using System.Runtime.CompilerServices; CustomHandler c = $""""; [InterpolatedStringHandler] struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s) {} } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }); comp.VerifyDiagnostics( // (4,19): error CS7036: There is no argument given that corresponds to the required formal parameter 's' of 'CustomHandler.CustomHandler(int, int, string)' // CustomHandler c = $""; Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, @"$""""").WithArguments("s", "CustomHandler.CustomHandler(int, int, string)").WithLocation(4, 19), // (4,19): error CS1615: Argument 3 may not be passed with the 'out' keyword // CustomHandler c = $""; Diagnostic(ErrorCode.ERR_BadArgExtraRef, @"$""""").WithArguments("3", "out").WithLocation(4, 19) ); } } }
-1