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
timestamp[ns, tz=UTC] | date_merged
timestamp[ns, tz=UTC] | 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 | 55,530 | Ignore modules with bad metadata in function resolver | Fixes https://github.com/dotnet/roslyn/issues/55475 | tmat | 2021-08-10T18:56:37Z | 2021-08-11T18:37:09Z | cd0c0464c069a2b80774d70f071c29333d9fa23c | bc874ebc5111a2a33221409f895953b1536f6612 | Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475 | ./src/Scripting/CoreTest/NuGetPackageResolverTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Scripting.Hosting;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Scripting.Test
{
public class NuGetPackageResolverTests : TestBase
{
[Fact]
public void ParsePackageNameAndVersion()
{
ParseInvalidPackageReference("A");
ParseInvalidPackageReference("A/1");
ParseInvalidPackageReference("nuget");
ParseInvalidPackageReference("nuget:");
ParseInvalidPackageReference("NUGET:");
ParseInvalidPackageReference("nugetA/1");
ParseValidPackageReference("nuget:A", "A", "");
ParseValidPackageReference("nuget:A.B", "A.B", "");
ParseValidPackageReference("nuget: ", " ", "");
ParseInvalidPackageReference("nuget:A/");
ParseInvalidPackageReference("nuget:A//1.0");
ParseInvalidPackageReference("nuget:/1.0.0");
ParseInvalidPackageReference("nuget:A/B/2.0.0");
ParseValidPackageReference("nuget::nuget/1", ":nuget", "1");
ParseValidPackageReference("nuget:A/1", "A", "1");
ParseValidPackageReference("nuget:A.B/1.0.0", "A.B", "1.0.0");
ParseValidPackageReference("nuget:A/B.C", "A", "B.C");
ParseValidPackageReference("nuget: /1", " ", "1");
ParseValidPackageReference("nuget:A\t/\n1.0\r ", "A\t", "\n1.0\r ");
}
private static void ParseValidPackageReference(string reference, string expectedName, string expectedVersion)
{
string name;
string version;
Assert.True(NuGetPackageResolver.TryParsePackageReference(reference, out name, out version));
Assert.Equal(expectedName, name);
Assert.Equal(expectedVersion, version);
}
private static void ParseInvalidPackageReference(string reference)
{
string name;
string version;
Assert.False(NuGetPackageResolver.TryParsePackageReference(reference, out name, out version));
Assert.Null(name);
Assert.Null(version);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Scripting.Hosting;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Scripting.Test
{
public class NuGetPackageResolverTests : TestBase
{
[Fact]
public void ParsePackageNameAndVersion()
{
ParseInvalidPackageReference("A");
ParseInvalidPackageReference("A/1");
ParseInvalidPackageReference("nuget");
ParseInvalidPackageReference("nuget:");
ParseInvalidPackageReference("NUGET:");
ParseInvalidPackageReference("nugetA/1");
ParseValidPackageReference("nuget:A", "A", "");
ParseValidPackageReference("nuget:A.B", "A.B", "");
ParseValidPackageReference("nuget: ", " ", "");
ParseInvalidPackageReference("nuget:A/");
ParseInvalidPackageReference("nuget:A//1.0");
ParseInvalidPackageReference("nuget:/1.0.0");
ParseInvalidPackageReference("nuget:A/B/2.0.0");
ParseValidPackageReference("nuget::nuget/1", ":nuget", "1");
ParseValidPackageReference("nuget:A/1", "A", "1");
ParseValidPackageReference("nuget:A.B/1.0.0", "A.B", "1.0.0");
ParseValidPackageReference("nuget:A/B.C", "A", "B.C");
ParseValidPackageReference("nuget: /1", " ", "1");
ParseValidPackageReference("nuget:A\t/\n1.0\r ", "A\t", "\n1.0\r ");
}
private static void ParseValidPackageReference(string reference, string expectedName, string expectedVersion)
{
string name;
string version;
Assert.True(NuGetPackageResolver.TryParsePackageReference(reference, out name, out version));
Assert.Equal(expectedName, name);
Assert.Equal(expectedVersion, version);
}
private static void ParseInvalidPackageReference(string reference)
{
string name;
string version;
Assert.False(NuGetPackageResolver.TryParsePackageReference(reference, out name, out version));
Assert.Null(name);
Assert.Null(version);
}
}
}
| -1 |
dotnet/roslyn | 55,530 | Ignore modules with bad metadata in function resolver | Fixes https://github.com/dotnet/roslyn/issues/55475 | tmat | 2021-08-10T18:56:37Z | 2021-08-11T18:37:09Z | cd0c0464c069a2b80774d70f071c29333d9fa23c | bc874ebc5111a2a33221409f895953b1536f6612 | Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475 | ./src/EditorFeatures/VisualBasicTest/EndConstructGeneration/SelectBlockTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration
<[UseExportProvider]>
Public Class SelectBlockTests
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestApplyAfterSelectKeyword()
VerifyStatementEndConstructApplied(
before:="Class c1
Sub goo()
Select goo
End Sub
End Class",
beforeCaret:={2, -1},
after:="Class c1
Sub goo()
Select goo
Case
End Select
End Sub
End Class",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestApplyAfterSelectCaseKeyword()
VerifyStatementEndConstructApplied(
before:="Class c1
Sub goo()
Select Case goo
End Sub
End Class",
beforeCaret:={2, -1},
after:="Class c1
Sub goo()
Select Case goo
Case
End Select
End Sub
End Class",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyNestedDo()
VerifyStatementEndConstructApplied(
before:="Class C
Sub S
Select Case 1
Case 1
Select 1
End Select
End Sub
End Class",
beforeCaret:={4, -1},
after:="Class C
Sub S
Select Case 1
Case 1
Select 1
Case
End Select
End Select
End Sub
End Class",
afterCaret:={5, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyInvalidSelectBlock()
VerifyStatementEndConstructNotApplied(
text:="Class C
Sub S
dim x = Select 1
End Sub
End Class",
caret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyInvalidSelectBlock01()
VerifyStatementEndConstructNotApplied(
text:="Class EC
Sub T
Select 1
Case 1
End Sub
End Class",
caret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyInvalidSelectBlock02()
VerifyStatementEndConstructNotApplied(
text:="Class EC
Select 1
End Class",
caret:={1, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyReCommitSelectBlock()
VerifyStatementEndConstructNotApplied(
text:="Class C
Sub S
Select Case 1
Case 1
End Select
End Sub
End Class",
caret:={2, -1})
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.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration
<[UseExportProvider]>
Public Class SelectBlockTests
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestApplyAfterSelectKeyword()
VerifyStatementEndConstructApplied(
before:="Class c1
Sub goo()
Select goo
End Sub
End Class",
beforeCaret:={2, -1},
after:="Class c1
Sub goo()
Select goo
Case
End Select
End Sub
End Class",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestApplyAfterSelectCaseKeyword()
VerifyStatementEndConstructApplied(
before:="Class c1
Sub goo()
Select Case goo
End Sub
End Class",
beforeCaret:={2, -1},
after:="Class c1
Sub goo()
Select Case goo
Case
End Select
End Sub
End Class",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyNestedDo()
VerifyStatementEndConstructApplied(
before:="Class C
Sub S
Select Case 1
Case 1
Select 1
End Select
End Sub
End Class",
beforeCaret:={4, -1},
after:="Class C
Sub S
Select Case 1
Case 1
Select 1
Case
End Select
End Select
End Sub
End Class",
afterCaret:={5, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyInvalidSelectBlock()
VerifyStatementEndConstructNotApplied(
text:="Class C
Sub S
dim x = Select 1
End Sub
End Class",
caret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyInvalidSelectBlock01()
VerifyStatementEndConstructNotApplied(
text:="Class EC
Sub T
Select 1
Case 1
End Sub
End Class",
caret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyInvalidSelectBlock02()
VerifyStatementEndConstructNotApplied(
text:="Class EC
Select 1
End Class",
caret:={1, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyReCommitSelectBlock()
VerifyStatementEndConstructNotApplied(
text:="Class C
Sub S
Select Case 1
Case 1
End Select
End Sub
End Class",
caret:={2, -1})
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,530 | Ignore modules with bad metadata in function resolver | Fixes https://github.com/dotnet/roslyn/issues/55475 | tmat | 2021-08-10T18:56:37Z | 2021-08-11T18:37:09Z | cd0c0464c069a2b80774d70f071c29333d9fa23c | bc874ebc5111a2a33221409f895953b1536f6612 | Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475 | ./src/Compilers/Core/Portable/Operations/ControlFlowGraphBuilder.RegionBuilder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.FlowAnalysis
{
internal sealed partial class ControlFlowGraphBuilder
{
private class RegionBuilder
{
public ControlFlowRegionKind Kind;
public RegionBuilder? Enclosing { get; private set; } = null;
public readonly ITypeSymbol? ExceptionType;
public BasicBlockBuilder? FirstBlock = null;
public BasicBlockBuilder? LastBlock = null;
public ArrayBuilder<RegionBuilder>? Regions = null;
public ImmutableArray<ILocalSymbol> Locals;
public ArrayBuilder<(IMethodSymbol, ILocalFunctionOperation)>? LocalFunctions = null;
public ArrayBuilder<CaptureId>? CaptureIds = null;
public readonly bool IsStackSpillRegion;
#if DEBUG
private bool _aboutToFree = false;
#endif
public RegionBuilder(ControlFlowRegionKind kind, ITypeSymbol? exceptionType = null, ImmutableArray<ILocalSymbol> locals = default, bool isStackSpillRegion = false)
{
Debug.Assert(!isStackSpillRegion || (kind == ControlFlowRegionKind.LocalLifetime && locals.IsDefaultOrEmpty));
Kind = kind;
ExceptionType = exceptionType;
Locals = locals.NullToEmpty();
IsStackSpillRegion = isStackSpillRegion;
}
[MemberNotNullWhen(false, nameof(FirstBlock), nameof(LastBlock))]
public bool IsEmpty
{
get
{
Debug.Assert((FirstBlock == null) == (LastBlock == null));
#pragma warning disable CS8775 // LastBlock is null when exiting, verified equivalent to FirstBlock above
return FirstBlock == null;
#pragma warning restore CS8775
}
}
[MemberNotNullWhen(true, nameof(Regions))]
public bool HasRegions => Regions?.Count > 0;
[MemberNotNullWhen(true, nameof(LocalFunctions))]
public bool HasLocalFunctions => LocalFunctions?.Count > 0;
[MemberNotNullWhen(true, nameof(CaptureIds))]
public bool HasCaptureIds => CaptureIds?.Count > 0;
#if DEBUG
public void AboutToFree() => _aboutToFree = true;
#endif
[MemberNotNull(nameof(CaptureIds))]
public void AddCaptureId(int captureId)
{
Debug.Assert(Kind != ControlFlowRegionKind.Root);
if (CaptureIds == null)
{
CaptureIds = ArrayBuilder<CaptureId>.GetInstance();
}
CaptureIds.Add(new CaptureId(captureId));
}
public void AddCaptureIds(ArrayBuilder<CaptureId>? others)
{
Debug.Assert(Kind != ControlFlowRegionKind.Root);
if (others == null)
{
return;
}
if (CaptureIds == null)
{
CaptureIds = ArrayBuilder<CaptureId>.GetInstance();
}
CaptureIds.AddRange(others);
}
[MemberNotNull(nameof(LocalFunctions))]
public void Add(IMethodSymbol symbol, ILocalFunctionOperation operation)
{
Debug.Assert(!IsStackSpillRegion);
Debug.Assert(Kind != ControlFlowRegionKind.Root);
Debug.Assert(symbol.MethodKind == MethodKind.LocalFunction);
if (LocalFunctions == null)
{
LocalFunctions = ArrayBuilder<(IMethodSymbol, ILocalFunctionOperation)>.GetInstance();
}
LocalFunctions.Add((symbol, operation));
}
public void AddRange(ArrayBuilder<(IMethodSymbol, ILocalFunctionOperation)>? others)
{
Debug.Assert(Kind != ControlFlowRegionKind.Root);
if (others == null)
{
return;
}
Debug.Assert(others.All(((IMethodSymbol m, ILocalFunctionOperation _) tuple) => tuple.m.MethodKind == MethodKind.LocalFunction));
if (LocalFunctions == null)
{
LocalFunctions = ArrayBuilder<(IMethodSymbol, ILocalFunctionOperation)>.GetInstance();
}
LocalFunctions.AddRange(others);
}
[MemberNotNull(nameof(Regions))]
public void Add(RegionBuilder region)
{
if (Regions == null)
{
Regions = ArrayBuilder<RegionBuilder>.GetInstance();
}
#if DEBUG
Debug.Assert(region.Enclosing == null || (region.Enclosing._aboutToFree && region.Enclosing.Enclosing == this));
#endif
region.Enclosing = this;
Regions.Add(region);
#if DEBUG
ControlFlowRegionKind lastKind = Regions.Last().Kind;
switch (Kind)
{
case ControlFlowRegionKind.FilterAndHandler:
Debug.Assert(Regions.Count <= 2);
Debug.Assert(lastKind == (Regions.Count < 2 ? ControlFlowRegionKind.Filter : ControlFlowRegionKind.Catch));
break;
case ControlFlowRegionKind.TryAndCatch:
if (Regions.Count == 1)
{
Debug.Assert(lastKind == ControlFlowRegionKind.Try);
}
else
{
Debug.Assert(lastKind == ControlFlowRegionKind.Catch || lastKind == ControlFlowRegionKind.FilterAndHandler);
}
break;
case ControlFlowRegionKind.TryAndFinally:
Debug.Assert(Regions.Count <= 2);
if (Regions.Count == 1)
{
Debug.Assert(lastKind == ControlFlowRegionKind.Try);
}
else
{
Debug.Assert(lastKind == ControlFlowRegionKind.Finally);
}
break;
default:
Debug.Assert(lastKind != ControlFlowRegionKind.Filter);
Debug.Assert(lastKind != ControlFlowRegionKind.Catch);
Debug.Assert(lastKind != ControlFlowRegionKind.Finally);
Debug.Assert(lastKind != ControlFlowRegionKind.Try);
break;
}
#endif
}
public void Remove(RegionBuilder region)
{
Debug.Assert(region.Enclosing == this);
Debug.Assert(Regions != null);
if (Regions.Count == 1)
{
Debug.Assert(Regions[0] == region);
Regions.Clear();
}
else
{
Regions.RemoveAt(Regions.IndexOf(region));
}
region.Enclosing = null;
}
public void ReplaceRegion(RegionBuilder toReplace, ArrayBuilder<RegionBuilder> replaceWith)
{
Debug.Assert(toReplace.Enclosing == this);
Debug.Assert(toReplace.FirstBlock!.Ordinal <= replaceWith.First().FirstBlock!.Ordinal);
Debug.Assert(toReplace.LastBlock!.Ordinal >= replaceWith.Last().LastBlock!.Ordinal);
Debug.Assert(Regions != null);
int insertAt;
if (Regions.Count == 1)
{
Debug.Assert(Regions[0] == toReplace);
insertAt = 0;
}
else
{
insertAt = Regions.IndexOf(toReplace);
}
int replaceWithCount = replaceWith.Count;
if (replaceWithCount == 1)
{
RegionBuilder single = replaceWith[0];
single.Enclosing = this;
Regions[insertAt] = single;
}
else
{
int originalCount = Regions.Count;
Regions.Count = replaceWithCount - 1 + originalCount;
for (int i = originalCount - 1, j = Regions.Count - 1; i > insertAt; i--, j--)
{
Regions[j] = Regions[i];
}
foreach (RegionBuilder region in replaceWith)
{
region.Enclosing = this;
Regions[insertAt++] = region;
}
}
toReplace.Enclosing = null;
}
[MemberNotNull(nameof(FirstBlock), nameof(LastBlock))]
public void ExtendToInclude(BasicBlockBuilder block)
{
Debug.Assert(block != null);
Debug.Assert((Kind != ControlFlowRegionKind.FilterAndHandler &&
Kind != ControlFlowRegionKind.TryAndCatch &&
Kind != ControlFlowRegionKind.TryAndFinally) ||
Regions!.Last().LastBlock == block);
if (FirstBlock == null)
{
Debug.Assert(LastBlock == null);
if (!HasRegions)
{
FirstBlock = block;
LastBlock = block;
return;
}
FirstBlock = Regions.First().FirstBlock;
Debug.Assert(FirstBlock != null);
Debug.Assert(Regions.Count == 1 && Regions.First().LastBlock == block);
}
else
{
Debug.Assert(LastBlock!.Ordinal < block.Ordinal);
Debug.Assert(!HasRegions || Regions.Last().LastBlock!.Ordinal <= block.Ordinal);
}
LastBlock = block;
}
public void Free()
{
#if DEBUG
Debug.Assert(_aboutToFree);
#endif
Enclosing = null;
FirstBlock = null;
LastBlock = null;
Regions?.Free();
Regions = null;
LocalFunctions?.Free();
LocalFunctions = null;
CaptureIds?.Free();
CaptureIds = null;
}
public ControlFlowRegion ToImmutableRegionAndFree(ArrayBuilder<BasicBlockBuilder> blocks,
ArrayBuilder<IMethodSymbol> localFunctions,
ImmutableDictionary<IMethodSymbol, (ControlFlowRegion region, ILocalFunctionOperation operation, int ordinal)>.Builder localFunctionsMap,
ImmutableDictionary<IFlowAnonymousFunctionOperation, (ControlFlowRegion region, int ordinal)>.Builder? anonymousFunctionsMapOpt,
ControlFlowRegion? enclosing)
{
#if DEBUG
Debug.Assert(!_aboutToFree);
#endif
Debug.Assert(!IsEmpty);
int localFunctionsBefore = localFunctions.Count;
if (HasLocalFunctions)
{
foreach ((IMethodSymbol method, IOperation _) in LocalFunctions)
{
localFunctions.Add(method);
}
}
ImmutableArray<ControlFlowRegion> subRegions;
if (HasRegions)
{
var builder = ArrayBuilder<ControlFlowRegion>.GetInstance(Regions.Count);
foreach (RegionBuilder region in Regions)
{
builder.Add(region.ToImmutableRegionAndFree(blocks, localFunctions, localFunctionsMap, anonymousFunctionsMapOpt, enclosing: null));
}
subRegions = builder.ToImmutableAndFree();
}
else
{
subRegions = ImmutableArray<ControlFlowRegion>.Empty;
}
CaptureIds?.Sort((x, y) => x.Value.CompareTo(y.Value));
var result = new ControlFlowRegion(Kind, FirstBlock.Ordinal, LastBlock.Ordinal, subRegions,
Locals,
LocalFunctions?.SelectAsArray(((IMethodSymbol, ILocalFunctionOperation) tuple) => tuple.Item1) ?? default,
CaptureIds?.ToImmutable() ?? default,
ExceptionType,
enclosing);
if (HasLocalFunctions)
{
foreach ((IMethodSymbol method, ILocalFunctionOperation operation) in LocalFunctions)
{
localFunctionsMap.Add(method, (result, operation, localFunctionsBefore++));
}
}
int firstBlockWithoutRegion = FirstBlock.Ordinal;
foreach (ControlFlowRegion region in subRegions)
{
for (int i = firstBlockWithoutRegion; i < region.FirstBlockOrdinal; i++)
{
setRegion(blocks[i]);
}
firstBlockWithoutRegion = region.LastBlockOrdinal + 1;
}
for (int i = firstBlockWithoutRegion; i <= LastBlock.Ordinal; i++)
{
setRegion(blocks[i]);
}
#if DEBUG
AboutToFree();
#endif
Free();
return result;
void setRegion(BasicBlockBuilder block)
{
Debug.Assert(block.Region == null);
block.Region = result;
// Populate the map of IFlowAnonymousFunctionOperation nodes, if we have any
if (anonymousFunctionsMapOpt != null)
{
(ImmutableDictionary<IFlowAnonymousFunctionOperation, (ControlFlowRegion region, int ordinal)>.Builder map, ControlFlowRegion region) argument = (anonymousFunctionsMapOpt, result);
if (block.HasStatements)
{
foreach (IOperation o in block.StatementsOpt)
{
AnonymousFunctionsMapBuilder.Instance.Visit(o, argument);
}
}
AnonymousFunctionsMapBuilder.Instance.Visit(block.BranchValue, argument);
}
}
}
private sealed class AnonymousFunctionsMapBuilder :
OperationVisitor<(ImmutableDictionary<IFlowAnonymousFunctionOperation, (ControlFlowRegion region, int ordinal)>.Builder map, ControlFlowRegion region), IOperation>
{
public static readonly AnonymousFunctionsMapBuilder Instance = new AnonymousFunctionsMapBuilder();
public override IOperation? VisitFlowAnonymousFunction(
IFlowAnonymousFunctionOperation operation,
(ImmutableDictionary<IFlowAnonymousFunctionOperation, (ControlFlowRegion region, int ordinal)>.Builder map, ControlFlowRegion region) argument)
{
argument.map.Add(operation, (argument.region, argument.map.Count));
return base.VisitFlowAnonymousFunction(operation, argument);
}
internal override IOperation? VisitNoneOperation(IOperation operation, (ImmutableDictionary<IFlowAnonymousFunctionOperation, (ControlFlowRegion region, int ordinal)>.Builder map, ControlFlowRegion region) argument)
{
return DefaultVisit(operation, argument);
}
public override IOperation? DefaultVisit(
IOperation operation,
(ImmutableDictionary<IFlowAnonymousFunctionOperation, (ControlFlowRegion region, int ordinal)>.Builder map, ControlFlowRegion region) argument)
{
foreach (IOperation child in ((Operation)operation).ChildOperations)
{
Visit(child, argument);
}
return null;
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.FlowAnalysis
{
internal sealed partial class ControlFlowGraphBuilder
{
private class RegionBuilder
{
public ControlFlowRegionKind Kind;
public RegionBuilder? Enclosing { get; private set; } = null;
public readonly ITypeSymbol? ExceptionType;
public BasicBlockBuilder? FirstBlock = null;
public BasicBlockBuilder? LastBlock = null;
public ArrayBuilder<RegionBuilder>? Regions = null;
public ImmutableArray<ILocalSymbol> Locals;
public ArrayBuilder<(IMethodSymbol, ILocalFunctionOperation)>? LocalFunctions = null;
public ArrayBuilder<CaptureId>? CaptureIds = null;
public readonly bool IsStackSpillRegion;
#if DEBUG
private bool _aboutToFree = false;
#endif
public RegionBuilder(ControlFlowRegionKind kind, ITypeSymbol? exceptionType = null, ImmutableArray<ILocalSymbol> locals = default, bool isStackSpillRegion = false)
{
Debug.Assert(!isStackSpillRegion || (kind == ControlFlowRegionKind.LocalLifetime && locals.IsDefaultOrEmpty));
Kind = kind;
ExceptionType = exceptionType;
Locals = locals.NullToEmpty();
IsStackSpillRegion = isStackSpillRegion;
}
[MemberNotNullWhen(false, nameof(FirstBlock), nameof(LastBlock))]
public bool IsEmpty
{
get
{
Debug.Assert((FirstBlock == null) == (LastBlock == null));
#pragma warning disable CS8775 // LastBlock is null when exiting, verified equivalent to FirstBlock above
return FirstBlock == null;
#pragma warning restore CS8775
}
}
[MemberNotNullWhen(true, nameof(Regions))]
public bool HasRegions => Regions?.Count > 0;
[MemberNotNullWhen(true, nameof(LocalFunctions))]
public bool HasLocalFunctions => LocalFunctions?.Count > 0;
[MemberNotNullWhen(true, nameof(CaptureIds))]
public bool HasCaptureIds => CaptureIds?.Count > 0;
#if DEBUG
public void AboutToFree() => _aboutToFree = true;
#endif
[MemberNotNull(nameof(CaptureIds))]
public void AddCaptureId(int captureId)
{
Debug.Assert(Kind != ControlFlowRegionKind.Root);
if (CaptureIds == null)
{
CaptureIds = ArrayBuilder<CaptureId>.GetInstance();
}
CaptureIds.Add(new CaptureId(captureId));
}
public void AddCaptureIds(ArrayBuilder<CaptureId>? others)
{
Debug.Assert(Kind != ControlFlowRegionKind.Root);
if (others == null)
{
return;
}
if (CaptureIds == null)
{
CaptureIds = ArrayBuilder<CaptureId>.GetInstance();
}
CaptureIds.AddRange(others);
}
[MemberNotNull(nameof(LocalFunctions))]
public void Add(IMethodSymbol symbol, ILocalFunctionOperation operation)
{
Debug.Assert(!IsStackSpillRegion);
Debug.Assert(Kind != ControlFlowRegionKind.Root);
Debug.Assert(symbol.MethodKind == MethodKind.LocalFunction);
if (LocalFunctions == null)
{
LocalFunctions = ArrayBuilder<(IMethodSymbol, ILocalFunctionOperation)>.GetInstance();
}
LocalFunctions.Add((symbol, operation));
}
public void AddRange(ArrayBuilder<(IMethodSymbol, ILocalFunctionOperation)>? others)
{
Debug.Assert(Kind != ControlFlowRegionKind.Root);
if (others == null)
{
return;
}
Debug.Assert(others.All(((IMethodSymbol m, ILocalFunctionOperation _) tuple) => tuple.m.MethodKind == MethodKind.LocalFunction));
if (LocalFunctions == null)
{
LocalFunctions = ArrayBuilder<(IMethodSymbol, ILocalFunctionOperation)>.GetInstance();
}
LocalFunctions.AddRange(others);
}
[MemberNotNull(nameof(Regions))]
public void Add(RegionBuilder region)
{
if (Regions == null)
{
Regions = ArrayBuilder<RegionBuilder>.GetInstance();
}
#if DEBUG
Debug.Assert(region.Enclosing == null || (region.Enclosing._aboutToFree && region.Enclosing.Enclosing == this));
#endif
region.Enclosing = this;
Regions.Add(region);
#if DEBUG
ControlFlowRegionKind lastKind = Regions.Last().Kind;
switch (Kind)
{
case ControlFlowRegionKind.FilterAndHandler:
Debug.Assert(Regions.Count <= 2);
Debug.Assert(lastKind == (Regions.Count < 2 ? ControlFlowRegionKind.Filter : ControlFlowRegionKind.Catch));
break;
case ControlFlowRegionKind.TryAndCatch:
if (Regions.Count == 1)
{
Debug.Assert(lastKind == ControlFlowRegionKind.Try);
}
else
{
Debug.Assert(lastKind == ControlFlowRegionKind.Catch || lastKind == ControlFlowRegionKind.FilterAndHandler);
}
break;
case ControlFlowRegionKind.TryAndFinally:
Debug.Assert(Regions.Count <= 2);
if (Regions.Count == 1)
{
Debug.Assert(lastKind == ControlFlowRegionKind.Try);
}
else
{
Debug.Assert(lastKind == ControlFlowRegionKind.Finally);
}
break;
default:
Debug.Assert(lastKind != ControlFlowRegionKind.Filter);
Debug.Assert(lastKind != ControlFlowRegionKind.Catch);
Debug.Assert(lastKind != ControlFlowRegionKind.Finally);
Debug.Assert(lastKind != ControlFlowRegionKind.Try);
break;
}
#endif
}
public void Remove(RegionBuilder region)
{
Debug.Assert(region.Enclosing == this);
Debug.Assert(Regions != null);
if (Regions.Count == 1)
{
Debug.Assert(Regions[0] == region);
Regions.Clear();
}
else
{
Regions.RemoveAt(Regions.IndexOf(region));
}
region.Enclosing = null;
}
public void ReplaceRegion(RegionBuilder toReplace, ArrayBuilder<RegionBuilder> replaceWith)
{
Debug.Assert(toReplace.Enclosing == this);
Debug.Assert(toReplace.FirstBlock!.Ordinal <= replaceWith.First().FirstBlock!.Ordinal);
Debug.Assert(toReplace.LastBlock!.Ordinal >= replaceWith.Last().LastBlock!.Ordinal);
Debug.Assert(Regions != null);
int insertAt;
if (Regions.Count == 1)
{
Debug.Assert(Regions[0] == toReplace);
insertAt = 0;
}
else
{
insertAt = Regions.IndexOf(toReplace);
}
int replaceWithCount = replaceWith.Count;
if (replaceWithCount == 1)
{
RegionBuilder single = replaceWith[0];
single.Enclosing = this;
Regions[insertAt] = single;
}
else
{
int originalCount = Regions.Count;
Regions.Count = replaceWithCount - 1 + originalCount;
for (int i = originalCount - 1, j = Regions.Count - 1; i > insertAt; i--, j--)
{
Regions[j] = Regions[i];
}
foreach (RegionBuilder region in replaceWith)
{
region.Enclosing = this;
Regions[insertAt++] = region;
}
}
toReplace.Enclosing = null;
}
[MemberNotNull(nameof(FirstBlock), nameof(LastBlock))]
public void ExtendToInclude(BasicBlockBuilder block)
{
Debug.Assert(block != null);
Debug.Assert((Kind != ControlFlowRegionKind.FilterAndHandler &&
Kind != ControlFlowRegionKind.TryAndCatch &&
Kind != ControlFlowRegionKind.TryAndFinally) ||
Regions!.Last().LastBlock == block);
if (FirstBlock == null)
{
Debug.Assert(LastBlock == null);
if (!HasRegions)
{
FirstBlock = block;
LastBlock = block;
return;
}
FirstBlock = Regions.First().FirstBlock;
Debug.Assert(FirstBlock != null);
Debug.Assert(Regions.Count == 1 && Regions.First().LastBlock == block);
}
else
{
Debug.Assert(LastBlock!.Ordinal < block.Ordinal);
Debug.Assert(!HasRegions || Regions.Last().LastBlock!.Ordinal <= block.Ordinal);
}
LastBlock = block;
}
public void Free()
{
#if DEBUG
Debug.Assert(_aboutToFree);
#endif
Enclosing = null;
FirstBlock = null;
LastBlock = null;
Regions?.Free();
Regions = null;
LocalFunctions?.Free();
LocalFunctions = null;
CaptureIds?.Free();
CaptureIds = null;
}
public ControlFlowRegion ToImmutableRegionAndFree(ArrayBuilder<BasicBlockBuilder> blocks,
ArrayBuilder<IMethodSymbol> localFunctions,
ImmutableDictionary<IMethodSymbol, (ControlFlowRegion region, ILocalFunctionOperation operation, int ordinal)>.Builder localFunctionsMap,
ImmutableDictionary<IFlowAnonymousFunctionOperation, (ControlFlowRegion region, int ordinal)>.Builder? anonymousFunctionsMapOpt,
ControlFlowRegion? enclosing)
{
#if DEBUG
Debug.Assert(!_aboutToFree);
#endif
Debug.Assert(!IsEmpty);
int localFunctionsBefore = localFunctions.Count;
if (HasLocalFunctions)
{
foreach ((IMethodSymbol method, IOperation _) in LocalFunctions)
{
localFunctions.Add(method);
}
}
ImmutableArray<ControlFlowRegion> subRegions;
if (HasRegions)
{
var builder = ArrayBuilder<ControlFlowRegion>.GetInstance(Regions.Count);
foreach (RegionBuilder region in Regions)
{
builder.Add(region.ToImmutableRegionAndFree(blocks, localFunctions, localFunctionsMap, anonymousFunctionsMapOpt, enclosing: null));
}
subRegions = builder.ToImmutableAndFree();
}
else
{
subRegions = ImmutableArray<ControlFlowRegion>.Empty;
}
CaptureIds?.Sort((x, y) => x.Value.CompareTo(y.Value));
var result = new ControlFlowRegion(Kind, FirstBlock.Ordinal, LastBlock.Ordinal, subRegions,
Locals,
LocalFunctions?.SelectAsArray(((IMethodSymbol, ILocalFunctionOperation) tuple) => tuple.Item1) ?? default,
CaptureIds?.ToImmutable() ?? default,
ExceptionType,
enclosing);
if (HasLocalFunctions)
{
foreach ((IMethodSymbol method, ILocalFunctionOperation operation) in LocalFunctions)
{
localFunctionsMap.Add(method, (result, operation, localFunctionsBefore++));
}
}
int firstBlockWithoutRegion = FirstBlock.Ordinal;
foreach (ControlFlowRegion region in subRegions)
{
for (int i = firstBlockWithoutRegion; i < region.FirstBlockOrdinal; i++)
{
setRegion(blocks[i]);
}
firstBlockWithoutRegion = region.LastBlockOrdinal + 1;
}
for (int i = firstBlockWithoutRegion; i <= LastBlock.Ordinal; i++)
{
setRegion(blocks[i]);
}
#if DEBUG
AboutToFree();
#endif
Free();
return result;
void setRegion(BasicBlockBuilder block)
{
Debug.Assert(block.Region == null);
block.Region = result;
// Populate the map of IFlowAnonymousFunctionOperation nodes, if we have any
if (anonymousFunctionsMapOpt != null)
{
(ImmutableDictionary<IFlowAnonymousFunctionOperation, (ControlFlowRegion region, int ordinal)>.Builder map, ControlFlowRegion region) argument = (anonymousFunctionsMapOpt, result);
if (block.HasStatements)
{
foreach (IOperation o in block.StatementsOpt)
{
AnonymousFunctionsMapBuilder.Instance.Visit(o, argument);
}
}
AnonymousFunctionsMapBuilder.Instance.Visit(block.BranchValue, argument);
}
}
}
private sealed class AnonymousFunctionsMapBuilder :
OperationVisitor<(ImmutableDictionary<IFlowAnonymousFunctionOperation, (ControlFlowRegion region, int ordinal)>.Builder map, ControlFlowRegion region), IOperation>
{
public static readonly AnonymousFunctionsMapBuilder Instance = new AnonymousFunctionsMapBuilder();
public override IOperation? VisitFlowAnonymousFunction(
IFlowAnonymousFunctionOperation operation,
(ImmutableDictionary<IFlowAnonymousFunctionOperation, (ControlFlowRegion region, int ordinal)>.Builder map, ControlFlowRegion region) argument)
{
argument.map.Add(operation, (argument.region, argument.map.Count));
return base.VisitFlowAnonymousFunction(operation, argument);
}
internal override IOperation? VisitNoneOperation(IOperation operation, (ImmutableDictionary<IFlowAnonymousFunctionOperation, (ControlFlowRegion region, int ordinal)>.Builder map, ControlFlowRegion region) argument)
{
return DefaultVisit(operation, argument);
}
public override IOperation? DefaultVisit(
IOperation operation,
(ImmutableDictionary<IFlowAnonymousFunctionOperation, (ControlFlowRegion region, int ordinal)>.Builder map, ControlFlowRegion region) argument)
{
foreach (IOperation child in ((Operation)operation).ChildOperations)
{
Visit(child, argument);
}
return null;
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,530 | Ignore modules with bad metadata in function resolver | Fixes https://github.com/dotnet/roslyn/issues/55475 | tmat | 2021-08-10T18:56:37Z | 2021-08-11T18:37:09Z | cd0c0464c069a2b80774d70f071c29333d9fa23c | bc874ebc5111a2a33221409f895953b1536f6612 | Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475 | ./src/EditorFeatures/Core/Shared/Options/InternalFeatureOnOffOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
using Microsoft.CodeAnalysis.Storage;
namespace Microsoft.CodeAnalysis.Editor.Shared.Options
{
internal static class InternalFeatureOnOffOptions
{
internal const string LocalRegistryPath = StorageOptions.LocalRegistryPath;
public static readonly Option2<bool> BraceMatching = new(nameof(InternalFeatureOnOffOptions), nameof(BraceMatching), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Brace Matching"));
public static readonly Option2<bool> Classification = new(nameof(InternalFeatureOnOffOptions), nameof(Classification), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Classification"));
public static readonly Option2<bool> SemanticColorizer = new(nameof(InternalFeatureOnOffOptions), nameof(SemanticColorizer), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Semantic Colorizer"));
public static readonly Option2<bool> SyntacticColorizer = new(nameof(InternalFeatureOnOffOptions), nameof(SyntacticColorizer), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Syntactic Colorizer"));
public static readonly Option2<bool> AutomaticPairCompletion = new(nameof(InternalFeatureOnOffOptions), nameof(AutomaticPairCompletion), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Automatic Pair Completion"));
public static readonly Option2<bool> AutomaticLineEnder = new(nameof(InternalFeatureOnOffOptions), nameof(AutomaticLineEnder), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Automatic Line Ender"));
public static readonly Option2<bool> SmartIndenter = new(nameof(InternalFeatureOnOffOptions), nameof(SmartIndenter), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Smart Indenter"));
public static readonly Option2<bool> CompletionSet = new(nameof(InternalFeatureOnOffOptions), nameof(CompletionSet), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Completion Set"));
public static readonly Option2<bool> KeywordHighlight = new(nameof(InternalFeatureOnOffOptions), nameof(KeywordHighlight), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Keyword Highlight"));
public static readonly Option2<bool> QuickInfo = new(nameof(InternalFeatureOnOffOptions), nameof(QuickInfo), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Quick Info"));
public static readonly Option2<bool> Squiggles = new(nameof(InternalFeatureOnOffOptions), nameof(Squiggles), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Squiggles"));
public static readonly Option2<bool> FormatOnSave = new(nameof(InternalFeatureOnOffOptions), nameof(FormatOnSave), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "FormatOnSave"));
public static readonly Option2<bool> RenameTracking = new(nameof(InternalFeatureOnOffOptions), nameof(RenameTracking), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Rename Tracking"));
public static readonly Option2<bool> EventHookup = new(nameof(InternalFeatureOnOffOptions), nameof(EventHookup), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Event Hookup"));
/// Due to https://github.com/dotnet/roslyn/issues/5393, the name "Snippets" is unusable for serialization.
/// (Summary: Some builds incorrectly set it without providing a way to clear it so it exists in many registries.)
public static readonly Option2<bool> Snippets = new(nameof(InternalFeatureOnOffOptions), nameof(Snippets), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Snippets2"));
public static readonly Option2<bool> TodoComments = new(nameof(InternalFeatureOnOffOptions), nameof(TodoComments), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Todo Comments"));
public static readonly Option2<bool> DesignerAttributes = new(nameof(InternalFeatureOnOffOptions), nameof(DesignerAttributes), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Designer Attribute"));
public static readonly Option2<bool> BackgroundAnalysisMemoryMonitor = new(nameof(InternalFeatureOnOffOptions), "FullSolutionAnalysisMemoryMonitor", defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Full Solution Analysis Memory Monitor"));
public static readonly Option2<bool> ProjectReferenceConversion = new(nameof(InternalFeatureOnOffOptions), nameof(ProjectReferenceConversion), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Project Reference Conversion"));
}
[ExportOptionProvider, Shared]
internal class InternalFeatureOnOffOptionsProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public InternalFeatureOnOffOptionsProvider()
{
}
public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(
InternalFeatureOnOffOptions.BraceMatching,
InternalFeatureOnOffOptions.Classification,
InternalFeatureOnOffOptions.SemanticColorizer,
InternalFeatureOnOffOptions.SyntacticColorizer,
InternalFeatureOnOffOptions.AutomaticPairCompletion,
InternalFeatureOnOffOptions.AutomaticLineEnder,
InternalFeatureOnOffOptions.SmartIndenter,
InternalFeatureOnOffOptions.CompletionSet,
InternalFeatureOnOffOptions.KeywordHighlight,
InternalFeatureOnOffOptions.QuickInfo,
InternalFeatureOnOffOptions.Squiggles,
InternalFeatureOnOffOptions.FormatOnSave,
InternalFeatureOnOffOptions.RenameTracking,
InternalFeatureOnOffOptions.EventHookup,
InternalFeatureOnOffOptions.Snippets,
InternalFeatureOnOffOptions.TodoComments,
InternalFeatureOnOffOptions.DesignerAttributes,
InternalFeatureOnOffOptions.BackgroundAnalysisMemoryMonitor,
InternalFeatureOnOffOptions.ProjectReferenceConversion);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
using Microsoft.CodeAnalysis.Storage;
namespace Microsoft.CodeAnalysis.Editor.Shared.Options
{
internal static class InternalFeatureOnOffOptions
{
internal const string LocalRegistryPath = StorageOptions.LocalRegistryPath;
public static readonly Option2<bool> BraceMatching = new(nameof(InternalFeatureOnOffOptions), nameof(BraceMatching), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Brace Matching"));
public static readonly Option2<bool> Classification = new(nameof(InternalFeatureOnOffOptions), nameof(Classification), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Classification"));
public static readonly Option2<bool> SemanticColorizer = new(nameof(InternalFeatureOnOffOptions), nameof(SemanticColorizer), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Semantic Colorizer"));
public static readonly Option2<bool> SyntacticColorizer = new(nameof(InternalFeatureOnOffOptions), nameof(SyntacticColorizer), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Syntactic Colorizer"));
public static readonly Option2<bool> AutomaticPairCompletion = new(nameof(InternalFeatureOnOffOptions), nameof(AutomaticPairCompletion), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Automatic Pair Completion"));
public static readonly Option2<bool> AutomaticLineEnder = new(nameof(InternalFeatureOnOffOptions), nameof(AutomaticLineEnder), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Automatic Line Ender"));
public static readonly Option2<bool> SmartIndenter = new(nameof(InternalFeatureOnOffOptions), nameof(SmartIndenter), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Smart Indenter"));
public static readonly Option2<bool> CompletionSet = new(nameof(InternalFeatureOnOffOptions), nameof(CompletionSet), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Completion Set"));
public static readonly Option2<bool> KeywordHighlight = new(nameof(InternalFeatureOnOffOptions), nameof(KeywordHighlight), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Keyword Highlight"));
public static readonly Option2<bool> QuickInfo = new(nameof(InternalFeatureOnOffOptions), nameof(QuickInfo), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Quick Info"));
public static readonly Option2<bool> Squiggles = new(nameof(InternalFeatureOnOffOptions), nameof(Squiggles), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Squiggles"));
public static readonly Option2<bool> FormatOnSave = new(nameof(InternalFeatureOnOffOptions), nameof(FormatOnSave), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "FormatOnSave"));
public static readonly Option2<bool> RenameTracking = new(nameof(InternalFeatureOnOffOptions), nameof(RenameTracking), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Rename Tracking"));
public static readonly Option2<bool> EventHookup = new(nameof(InternalFeatureOnOffOptions), nameof(EventHookup), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Event Hookup"));
/// Due to https://github.com/dotnet/roslyn/issues/5393, the name "Snippets" is unusable for serialization.
/// (Summary: Some builds incorrectly set it without providing a way to clear it so it exists in many registries.)
public static readonly Option2<bool> Snippets = new(nameof(InternalFeatureOnOffOptions), nameof(Snippets), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Snippets2"));
public static readonly Option2<bool> TodoComments = new(nameof(InternalFeatureOnOffOptions), nameof(TodoComments), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Todo Comments"));
public static readonly Option2<bool> DesignerAttributes = new(nameof(InternalFeatureOnOffOptions), nameof(DesignerAttributes), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Designer Attribute"));
public static readonly Option2<bool> BackgroundAnalysisMemoryMonitor = new(nameof(InternalFeatureOnOffOptions), "FullSolutionAnalysisMemoryMonitor", defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Full Solution Analysis Memory Monitor"));
public static readonly Option2<bool> ProjectReferenceConversion = new(nameof(InternalFeatureOnOffOptions), nameof(ProjectReferenceConversion), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Project Reference Conversion"));
}
[ExportOptionProvider, Shared]
internal class InternalFeatureOnOffOptionsProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public InternalFeatureOnOffOptionsProvider()
{
}
public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(
InternalFeatureOnOffOptions.BraceMatching,
InternalFeatureOnOffOptions.Classification,
InternalFeatureOnOffOptions.SemanticColorizer,
InternalFeatureOnOffOptions.SyntacticColorizer,
InternalFeatureOnOffOptions.AutomaticPairCompletion,
InternalFeatureOnOffOptions.AutomaticLineEnder,
InternalFeatureOnOffOptions.SmartIndenter,
InternalFeatureOnOffOptions.CompletionSet,
InternalFeatureOnOffOptions.KeywordHighlight,
InternalFeatureOnOffOptions.QuickInfo,
InternalFeatureOnOffOptions.Squiggles,
InternalFeatureOnOffOptions.FormatOnSave,
InternalFeatureOnOffOptions.RenameTracking,
InternalFeatureOnOffOptions.EventHookup,
InternalFeatureOnOffOptions.Snippets,
InternalFeatureOnOffOptions.TodoComments,
InternalFeatureOnOffOptions.DesignerAttributes,
InternalFeatureOnOffOptions.BackgroundAnalysisMemoryMonitor,
InternalFeatureOnOffOptions.ProjectReferenceConversion);
}
}
| -1 |
dotnet/roslyn | 55,530 | Ignore modules with bad metadata in function resolver | Fixes https://github.com/dotnet/roslyn/issues/55475 | tmat | 2021-08-10T18:56:37Z | 2021-08-11T18:37:09Z | cd0c0464c069a2b80774d70f071c29333d9fa23c | bc874ebc5111a2a33221409f895953b1536f6612 | Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475 | ./src/Features/Core/Portable/SignatureHelp/AbstractSignatureHelpProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SignatureHelp
{
internal abstract partial class AbstractSignatureHelpProvider : ISignatureHelpProvider
{
protected static readonly SymbolDisplayFormat MinimallyQualifiedWithoutParametersFormat =
SymbolDisplayFormat.MinimallyQualifiedFormat.WithMemberOptions(
SymbolDisplayFormat.MinimallyQualifiedFormat.MemberOptions & ~SymbolDisplayMemberOptions.IncludeParameters);
protected static readonly SymbolDisplayFormat MinimallyQualifiedWithoutTypeParametersFormat =
SymbolDisplayFormat.MinimallyQualifiedFormat.WithGenericsOptions(
SymbolDisplayFormat.MinimallyQualifiedFormat.GenericsOptions & ~SymbolDisplayGenericsOptions.IncludeTypeParameters);
protected AbstractSignatureHelpProvider()
{
}
public abstract bool IsTriggerCharacter(char ch);
public abstract bool IsRetriggerCharacter(char ch);
public abstract SignatureHelpState? GetCurrentArgumentState(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, TextSpan currentSpan, CancellationToken cancellationToken);
protected abstract Task<SignatureHelpItems?> GetItemsWorkerAsync(Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken);
/// <remarks>
/// This overload is required for compatibility with existing extensions.
/// </remarks>
protected static SignatureHelpItems? CreateSignatureHelpItems(
IList<SignatureHelpItem> items, TextSpan applicableSpan, SignatureHelpState state)
{
return CreateSignatureHelpItems(items, applicableSpan, state, selectedItem: null);
}
protected static SignatureHelpItems? CreateSignatureHelpItems(
IList<SignatureHelpItem>? items, TextSpan applicableSpan, SignatureHelpState? state, int? selectedItem)
{
if (items == null || !items.Any() || state == null)
{
return null;
}
if (selectedItem < 0)
{
selectedItem = null;
}
(items, selectedItem) = Filter(items, state.ArgumentNames, selectedItem);
return new SignatureHelpItems(items, applicableSpan, state.ArgumentIndex, state.ArgumentCount, state.ArgumentName, selectedItem);
}
protected static SignatureHelpItems? CreateCollectionInitializerSignatureHelpItems(
IList<SignatureHelpItem> items, TextSpan applicableSpan, SignatureHelpState? state)
{
// We will have added all the accessible '.Add' methods that take at least one
// arguments. However, in general the one-arg Add method is the least likely for the
// user to invoke. For example, say there is:
//
// new JObject { { $$ } }
//
// Technically, the user could be calling the `.Add(object)` overload in this case.
// However, normally in that case, they would just supply the value directly like so:
//
// new JObject { new JProperty(...), new JProperty(...) }
//
// So, it's a strong signal when they're inside another `{ $$ }` that they want to call
// the .Add methods that take multiple args, like so:
//
// new JObject { { propName, propValue }, { propName, propValue } }
//
// So, we include all the .Add methods, but we prefer selecting the first that has
// at least two parameters.
return CreateSignatureHelpItems(
items, applicableSpan, state, items.IndexOf(i => i.Parameters.Length >= 2));
}
private static (IList<SignatureHelpItem> items, int? selectedItem) Filter(IList<SignatureHelpItem> items, IEnumerable<string>? parameterNames, int? selectedItem)
{
if (parameterNames == null)
{
return (items.ToList(), selectedItem);
}
var filteredList = items.Where(i => Include(i, parameterNames)).ToList();
var isEmpty = filteredList.Count == 0;
if (!selectedItem.HasValue || isEmpty)
{
return (isEmpty ? items.ToList() : filteredList, selectedItem);
}
// adjust the selected item
var selection = items[selectedItem.Value];
selectedItem = filteredList.IndexOf(selection);
return (filteredList, selectedItem);
}
private static bool Include(SignatureHelpItem item, IEnumerable<string> parameterNames)
{
var itemParameterNames = item.Parameters.Select(p => p.Name).ToSet();
return parameterNames.All(itemParameterNames.Contains);
}
public async Task<SignatureHelpState?> GetCurrentArgumentStateAsync(Document document, int position, TextSpan currentSpan, CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
return GetCurrentArgumentState(root, position, document.GetRequiredLanguageService<ISyntaxFactsService>(), currentSpan, cancellationToken);
}
// TODO: remove once Pythia moves to ExternalAccess APIs
[Obsolete("Use overload without ISymbolDisplayService")]
#pragma warning disable CA1822 // Mark members as static - see obsolete comment above.
protected SignatureHelpItem CreateItem(
#pragma warning restore CA1822 // Mark members as static
ISymbol orderSymbol,
SemanticModel semanticModel,
int position,
ISymbolDisplayService symbolDisplayService,
IAnonymousTypeDisplayService anonymousTypeDisplayService,
bool isVariadic,
Func<CancellationToken, IEnumerable<TaggedText>> documentationFactory,
IList<SymbolDisplayPart> prefixParts,
IList<SymbolDisplayPart> separatorParts,
IList<SymbolDisplayPart> suffixParts,
IList<SignatureHelpSymbolParameter> parameters,
IList<SymbolDisplayPart>? descriptionParts = null)
{
return CreateItem(orderSymbol, semanticModel, position, anonymousTypeDisplayService,
isVariadic, documentationFactory, prefixParts, separatorParts, suffixParts, parameters, descriptionParts);
}
protected static SignatureHelpItem CreateItem(
ISymbol orderSymbol,
SemanticModel semanticModel,
int position,
IAnonymousTypeDisplayService anonymousTypeDisplayService,
bool isVariadic,
Func<CancellationToken, IEnumerable<TaggedText>>? documentationFactory,
IList<SymbolDisplayPart> prefixParts,
IList<SymbolDisplayPart> separatorParts,
IList<SymbolDisplayPart> suffixParts,
IList<SignatureHelpSymbolParameter> parameters,
IList<SymbolDisplayPart>? descriptionParts = null)
{
return CreateItemImpl(orderSymbol, semanticModel, position, anonymousTypeDisplayService,
isVariadic, documentationFactory, prefixParts, separatorParts, suffixParts, parameters, descriptionParts);
}
protected static SignatureHelpItem CreateItemImpl(
ISymbol orderSymbol,
SemanticModel semanticModel,
int position,
IAnonymousTypeDisplayService anonymousTypeDisplayService,
bool isVariadic,
Func<CancellationToken, IEnumerable<TaggedText>>? documentationFactory,
IList<SymbolDisplayPart> prefixParts,
IList<SymbolDisplayPart> separatorParts,
IList<SymbolDisplayPart> suffixParts,
IList<SignatureHelpSymbolParameter> parameters,
IList<SymbolDisplayPart>? descriptionParts)
{
prefixParts = anonymousTypeDisplayService.InlineDelegateAnonymousTypes(prefixParts, semanticModel, position);
separatorParts = anonymousTypeDisplayService.InlineDelegateAnonymousTypes(separatorParts, semanticModel, position);
suffixParts = anonymousTypeDisplayService.InlineDelegateAnonymousTypes(suffixParts, semanticModel, position);
parameters = parameters.Select(p => InlineDelegateAnonymousTypes(p, semanticModel, position, anonymousTypeDisplayService)).ToList();
descriptionParts = descriptionParts == null
? SpecializedCollections.EmptyList<SymbolDisplayPart>()
: descriptionParts;
var allParts = prefixParts.Concat(separatorParts)
.Concat(suffixParts)
.Concat(parameters.SelectMany(p => p.GetAllParts()))
.Concat(descriptionParts);
var directAnonymousTypeReferences =
from part in allParts
where part.Symbol.IsNormalAnonymousType()
select (INamedTypeSymbol)part.Symbol!;
var info = anonymousTypeDisplayService.GetNormalAnonymousTypeDisplayInfo(
orderSymbol, directAnonymousTypeReferences, semanticModel, position);
if (info.AnonymousTypesParts.Count > 0)
{
var anonymousTypeParts = new List<SymbolDisplayPart>
{
new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, "\r\n\r\n")
};
anonymousTypeParts.AddRange(info.AnonymousTypesParts);
return new SymbolKeySignatureHelpItem(
orderSymbol,
isVariadic,
documentationFactory,
info.ReplaceAnonymousTypes(prefixParts).ToTaggedText(),
info.ReplaceAnonymousTypes(separatorParts).ToTaggedText(),
info.ReplaceAnonymousTypes(suffixParts).ToTaggedText(),
parameters.Select(p => ReplaceAnonymousTypes(p, info)).Select(p => (SignatureHelpParameter)p),
anonymousTypeParts.ToTaggedText());
}
return new SymbolKeySignatureHelpItem(
orderSymbol,
isVariadic,
documentationFactory,
prefixParts.ToTaggedText(),
separatorParts.ToTaggedText(),
suffixParts.ToTaggedText(),
parameters.Select(p => (SignatureHelpParameter)p),
descriptionParts.ToTaggedText());
}
private static SignatureHelpSymbolParameter ReplaceAnonymousTypes(
SignatureHelpSymbolParameter parameter,
AnonymousTypeDisplayInfo info)
{
return new SignatureHelpSymbolParameter(
parameter.Name,
parameter.IsOptional,
parameter.DocumentationFactory,
info.ReplaceAnonymousTypes(parameter.DisplayParts),
info.ReplaceAnonymousTypes(parameter.SelectedDisplayParts));
}
private static SignatureHelpSymbolParameter InlineDelegateAnonymousTypes(
SignatureHelpSymbolParameter parameter,
SemanticModel semanticModel,
int position,
IAnonymousTypeDisplayService anonymousTypeDisplayService)
{
return new SignatureHelpSymbolParameter(
parameter.Name,
parameter.IsOptional,
parameter.DocumentationFactory,
anonymousTypeDisplayService.InlineDelegateAnonymousTypes(parameter.DisplayParts, semanticModel, position),
anonymousTypeDisplayService.InlineDelegateAnonymousTypes(parameter.PrefixDisplayParts, semanticModel, position),
anonymousTypeDisplayService.InlineDelegateAnonymousTypes(parameter.SuffixDisplayParts, semanticModel, position),
anonymousTypeDisplayService.InlineDelegateAnonymousTypes(parameter.SelectedDisplayParts, semanticModel, position));
}
public async Task<SignatureHelpItems?> GetItemsAsync(
Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken)
{
var itemsForCurrentDocument = await GetItemsWorkerAsync(document, position, triggerInfo, cancellationToken).ConfigureAwait(false);
if (itemsForCurrentDocument == null)
{
return itemsForCurrentDocument;
}
var relatedDocuments = await FindActiveRelatedDocumentsAsync(position, document, cancellationToken).ConfigureAwait(false);
if (relatedDocuments.IsEmpty)
{
return itemsForCurrentDocument;
}
var totalProjects = relatedDocuments.Select(d => d.Project.Id).Concat(document.Project.Id);
var semanticModel = await document.ReuseExistingSpeculativeModelAsync(position, cancellationToken).ConfigureAwait(false);
var compilation = semanticModel.Compilation;
var finalItems = new List<SignatureHelpItem>();
foreach (var item in itemsForCurrentDocument.Items)
{
if (item is not SymbolKeySignatureHelpItem symbolKeyItem ||
symbolKeyItem.SymbolKey is not SymbolKey symbolKey ||
symbolKey.Resolve(compilation, ignoreAssemblyKey: true, cancellationToken).Symbol is not ISymbol symbol)
{
finalItems.Add(item);
continue;
}
// If the symbol is an instantiated generic method, ensure we use its original
// definition for symbol key resolution in related compilations.
if (symbol is IMethodSymbol methodSymbol && methodSymbol.IsGenericMethod && methodSymbol != methodSymbol.OriginalDefinition)
{
symbolKey = SymbolKey.Create(methodSymbol.OriginalDefinition, cancellationToken);
}
var invalidProjectsForCurrentSymbol = new List<ProjectId>();
foreach (var relatedDocument in relatedDocuments)
{
// Try to resolve symbolKey in each related compilation,
// unresolvable key means the symbol is unavailable in the corresponding project.
var relatedSemanticModel = await relatedDocument.ReuseExistingSpeculativeModelAsync(position, cancellationToken).ConfigureAwait(false);
if (symbolKey.Resolve(relatedSemanticModel.Compilation, ignoreAssemblyKey: true, cancellationToken).Symbol == null)
{
invalidProjectsForCurrentSymbol.Add(relatedDocument.Project.Id);
}
}
var platformData = new SupportedPlatformData(invalidProjectsForCurrentSymbol, totalProjects, document.Project.Solution.Workspace);
finalItems.Add(UpdateItem(item, platformData));
}
return new SignatureHelpItems(
finalItems, itemsForCurrentDocument.ApplicableSpan,
itemsForCurrentDocument.ArgumentIndex,
itemsForCurrentDocument.ArgumentCount,
itemsForCurrentDocument.ArgumentName,
itemsForCurrentDocument.SelectedItemIndex);
}
private static async Task<ImmutableArray<Document>> FindActiveRelatedDocumentsAsync(int position, Document document, CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<Document>.GetInstance(out var builder);
foreach (var relatedDocument in document.GetLinkedDocuments())
{
var syntaxTree = await relatedDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
if (!relatedDocument.GetRequiredLanguageService<ISyntaxFactsService>().IsInInactiveRegion(syntaxTree, position, cancellationToken))
{
builder.Add(relatedDocument);
}
}
return builder.ToImmutable();
}
private static SignatureHelpItem UpdateItem(SignatureHelpItem item, SupportedPlatformData platformData)
{
var platformParts = platformData.ToDisplayParts().ToTaggedText();
if (platformParts.Length == 0)
{
return item;
}
var startingNewLine = new List<TaggedText>();
startingNewLine.AddLineBreak();
var concatted = startingNewLine.Concat(platformParts);
var updatedDescription = item.DescriptionParts.IsDefault
? concatted
: item.DescriptionParts.Concat(concatted);
item.DescriptionParts = updatedDescription.ToImmutableArrayOrEmpty();
return item;
}
protected static int? TryGetSelectedIndex<TSymbol>(ImmutableArray<TSymbol> candidates, ISymbol? currentSymbol) where TSymbol : class, ISymbol
{
if (currentSymbol is TSymbol matched)
{
var found = candidates.IndexOf(matched);
if (found >= 0)
{
return found;
}
}
return null;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SignatureHelp
{
internal abstract partial class AbstractSignatureHelpProvider : ISignatureHelpProvider
{
protected static readonly SymbolDisplayFormat MinimallyQualifiedWithoutParametersFormat =
SymbolDisplayFormat.MinimallyQualifiedFormat.WithMemberOptions(
SymbolDisplayFormat.MinimallyQualifiedFormat.MemberOptions & ~SymbolDisplayMemberOptions.IncludeParameters);
protected static readonly SymbolDisplayFormat MinimallyQualifiedWithoutTypeParametersFormat =
SymbolDisplayFormat.MinimallyQualifiedFormat.WithGenericsOptions(
SymbolDisplayFormat.MinimallyQualifiedFormat.GenericsOptions & ~SymbolDisplayGenericsOptions.IncludeTypeParameters);
protected AbstractSignatureHelpProvider()
{
}
public abstract bool IsTriggerCharacter(char ch);
public abstract bool IsRetriggerCharacter(char ch);
public abstract SignatureHelpState? GetCurrentArgumentState(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, TextSpan currentSpan, CancellationToken cancellationToken);
protected abstract Task<SignatureHelpItems?> GetItemsWorkerAsync(Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken);
/// <remarks>
/// This overload is required for compatibility with existing extensions.
/// </remarks>
protected static SignatureHelpItems? CreateSignatureHelpItems(
IList<SignatureHelpItem> items, TextSpan applicableSpan, SignatureHelpState state)
{
return CreateSignatureHelpItems(items, applicableSpan, state, selectedItem: null);
}
protected static SignatureHelpItems? CreateSignatureHelpItems(
IList<SignatureHelpItem>? items, TextSpan applicableSpan, SignatureHelpState? state, int? selectedItem)
{
if (items == null || !items.Any() || state == null)
{
return null;
}
if (selectedItem < 0)
{
selectedItem = null;
}
(items, selectedItem) = Filter(items, state.ArgumentNames, selectedItem);
return new SignatureHelpItems(items, applicableSpan, state.ArgumentIndex, state.ArgumentCount, state.ArgumentName, selectedItem);
}
protected static SignatureHelpItems? CreateCollectionInitializerSignatureHelpItems(
IList<SignatureHelpItem> items, TextSpan applicableSpan, SignatureHelpState? state)
{
// We will have added all the accessible '.Add' methods that take at least one
// arguments. However, in general the one-arg Add method is the least likely for the
// user to invoke. For example, say there is:
//
// new JObject { { $$ } }
//
// Technically, the user could be calling the `.Add(object)` overload in this case.
// However, normally in that case, they would just supply the value directly like so:
//
// new JObject { new JProperty(...), new JProperty(...) }
//
// So, it's a strong signal when they're inside another `{ $$ }` that they want to call
// the .Add methods that take multiple args, like so:
//
// new JObject { { propName, propValue }, { propName, propValue } }
//
// So, we include all the .Add methods, but we prefer selecting the first that has
// at least two parameters.
return CreateSignatureHelpItems(
items, applicableSpan, state, items.IndexOf(i => i.Parameters.Length >= 2));
}
private static (IList<SignatureHelpItem> items, int? selectedItem) Filter(IList<SignatureHelpItem> items, IEnumerable<string>? parameterNames, int? selectedItem)
{
if (parameterNames == null)
{
return (items.ToList(), selectedItem);
}
var filteredList = items.Where(i => Include(i, parameterNames)).ToList();
var isEmpty = filteredList.Count == 0;
if (!selectedItem.HasValue || isEmpty)
{
return (isEmpty ? items.ToList() : filteredList, selectedItem);
}
// adjust the selected item
var selection = items[selectedItem.Value];
selectedItem = filteredList.IndexOf(selection);
return (filteredList, selectedItem);
}
private static bool Include(SignatureHelpItem item, IEnumerable<string> parameterNames)
{
var itemParameterNames = item.Parameters.Select(p => p.Name).ToSet();
return parameterNames.All(itemParameterNames.Contains);
}
public async Task<SignatureHelpState?> GetCurrentArgumentStateAsync(Document document, int position, TextSpan currentSpan, CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
return GetCurrentArgumentState(root, position, document.GetRequiredLanguageService<ISyntaxFactsService>(), currentSpan, cancellationToken);
}
// TODO: remove once Pythia moves to ExternalAccess APIs
[Obsolete("Use overload without ISymbolDisplayService")]
#pragma warning disable CA1822 // Mark members as static - see obsolete comment above.
protected SignatureHelpItem CreateItem(
#pragma warning restore CA1822 // Mark members as static
ISymbol orderSymbol,
SemanticModel semanticModel,
int position,
ISymbolDisplayService symbolDisplayService,
IAnonymousTypeDisplayService anonymousTypeDisplayService,
bool isVariadic,
Func<CancellationToken, IEnumerable<TaggedText>> documentationFactory,
IList<SymbolDisplayPart> prefixParts,
IList<SymbolDisplayPart> separatorParts,
IList<SymbolDisplayPart> suffixParts,
IList<SignatureHelpSymbolParameter> parameters,
IList<SymbolDisplayPart>? descriptionParts = null)
{
return CreateItem(orderSymbol, semanticModel, position, anonymousTypeDisplayService,
isVariadic, documentationFactory, prefixParts, separatorParts, suffixParts, parameters, descriptionParts);
}
protected static SignatureHelpItem CreateItem(
ISymbol orderSymbol,
SemanticModel semanticModel,
int position,
IAnonymousTypeDisplayService anonymousTypeDisplayService,
bool isVariadic,
Func<CancellationToken, IEnumerable<TaggedText>>? documentationFactory,
IList<SymbolDisplayPart> prefixParts,
IList<SymbolDisplayPart> separatorParts,
IList<SymbolDisplayPart> suffixParts,
IList<SignatureHelpSymbolParameter> parameters,
IList<SymbolDisplayPart>? descriptionParts = null)
{
return CreateItemImpl(orderSymbol, semanticModel, position, anonymousTypeDisplayService,
isVariadic, documentationFactory, prefixParts, separatorParts, suffixParts, parameters, descriptionParts);
}
protected static SignatureHelpItem CreateItemImpl(
ISymbol orderSymbol,
SemanticModel semanticModel,
int position,
IAnonymousTypeDisplayService anonymousTypeDisplayService,
bool isVariadic,
Func<CancellationToken, IEnumerable<TaggedText>>? documentationFactory,
IList<SymbolDisplayPart> prefixParts,
IList<SymbolDisplayPart> separatorParts,
IList<SymbolDisplayPart> suffixParts,
IList<SignatureHelpSymbolParameter> parameters,
IList<SymbolDisplayPart>? descriptionParts)
{
prefixParts = anonymousTypeDisplayService.InlineDelegateAnonymousTypes(prefixParts, semanticModel, position);
separatorParts = anonymousTypeDisplayService.InlineDelegateAnonymousTypes(separatorParts, semanticModel, position);
suffixParts = anonymousTypeDisplayService.InlineDelegateAnonymousTypes(suffixParts, semanticModel, position);
parameters = parameters.Select(p => InlineDelegateAnonymousTypes(p, semanticModel, position, anonymousTypeDisplayService)).ToList();
descriptionParts = descriptionParts == null
? SpecializedCollections.EmptyList<SymbolDisplayPart>()
: descriptionParts;
var allParts = prefixParts.Concat(separatorParts)
.Concat(suffixParts)
.Concat(parameters.SelectMany(p => p.GetAllParts()))
.Concat(descriptionParts);
var directAnonymousTypeReferences =
from part in allParts
where part.Symbol.IsNormalAnonymousType()
select (INamedTypeSymbol)part.Symbol!;
var info = anonymousTypeDisplayService.GetNormalAnonymousTypeDisplayInfo(
orderSymbol, directAnonymousTypeReferences, semanticModel, position);
if (info.AnonymousTypesParts.Count > 0)
{
var anonymousTypeParts = new List<SymbolDisplayPart>
{
new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, "\r\n\r\n")
};
anonymousTypeParts.AddRange(info.AnonymousTypesParts);
return new SymbolKeySignatureHelpItem(
orderSymbol,
isVariadic,
documentationFactory,
info.ReplaceAnonymousTypes(prefixParts).ToTaggedText(),
info.ReplaceAnonymousTypes(separatorParts).ToTaggedText(),
info.ReplaceAnonymousTypes(suffixParts).ToTaggedText(),
parameters.Select(p => ReplaceAnonymousTypes(p, info)).Select(p => (SignatureHelpParameter)p),
anonymousTypeParts.ToTaggedText());
}
return new SymbolKeySignatureHelpItem(
orderSymbol,
isVariadic,
documentationFactory,
prefixParts.ToTaggedText(),
separatorParts.ToTaggedText(),
suffixParts.ToTaggedText(),
parameters.Select(p => (SignatureHelpParameter)p),
descriptionParts.ToTaggedText());
}
private static SignatureHelpSymbolParameter ReplaceAnonymousTypes(
SignatureHelpSymbolParameter parameter,
AnonymousTypeDisplayInfo info)
{
return new SignatureHelpSymbolParameter(
parameter.Name,
parameter.IsOptional,
parameter.DocumentationFactory,
info.ReplaceAnonymousTypes(parameter.DisplayParts),
info.ReplaceAnonymousTypes(parameter.SelectedDisplayParts));
}
private static SignatureHelpSymbolParameter InlineDelegateAnonymousTypes(
SignatureHelpSymbolParameter parameter,
SemanticModel semanticModel,
int position,
IAnonymousTypeDisplayService anonymousTypeDisplayService)
{
return new SignatureHelpSymbolParameter(
parameter.Name,
parameter.IsOptional,
parameter.DocumentationFactory,
anonymousTypeDisplayService.InlineDelegateAnonymousTypes(parameter.DisplayParts, semanticModel, position),
anonymousTypeDisplayService.InlineDelegateAnonymousTypes(parameter.PrefixDisplayParts, semanticModel, position),
anonymousTypeDisplayService.InlineDelegateAnonymousTypes(parameter.SuffixDisplayParts, semanticModel, position),
anonymousTypeDisplayService.InlineDelegateAnonymousTypes(parameter.SelectedDisplayParts, semanticModel, position));
}
public async Task<SignatureHelpItems?> GetItemsAsync(
Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken)
{
var itemsForCurrentDocument = await GetItemsWorkerAsync(document, position, triggerInfo, cancellationToken).ConfigureAwait(false);
if (itemsForCurrentDocument == null)
{
return itemsForCurrentDocument;
}
var relatedDocuments = await FindActiveRelatedDocumentsAsync(position, document, cancellationToken).ConfigureAwait(false);
if (relatedDocuments.IsEmpty)
{
return itemsForCurrentDocument;
}
var totalProjects = relatedDocuments.Select(d => d.Project.Id).Concat(document.Project.Id);
var semanticModel = await document.ReuseExistingSpeculativeModelAsync(position, cancellationToken).ConfigureAwait(false);
var compilation = semanticModel.Compilation;
var finalItems = new List<SignatureHelpItem>();
foreach (var item in itemsForCurrentDocument.Items)
{
if (item is not SymbolKeySignatureHelpItem symbolKeyItem ||
symbolKeyItem.SymbolKey is not SymbolKey symbolKey ||
symbolKey.Resolve(compilation, ignoreAssemblyKey: true, cancellationToken).Symbol is not ISymbol symbol)
{
finalItems.Add(item);
continue;
}
// If the symbol is an instantiated generic method, ensure we use its original
// definition for symbol key resolution in related compilations.
if (symbol is IMethodSymbol methodSymbol && methodSymbol.IsGenericMethod && methodSymbol != methodSymbol.OriginalDefinition)
{
symbolKey = SymbolKey.Create(methodSymbol.OriginalDefinition, cancellationToken);
}
var invalidProjectsForCurrentSymbol = new List<ProjectId>();
foreach (var relatedDocument in relatedDocuments)
{
// Try to resolve symbolKey in each related compilation,
// unresolvable key means the symbol is unavailable in the corresponding project.
var relatedSemanticModel = await relatedDocument.ReuseExistingSpeculativeModelAsync(position, cancellationToken).ConfigureAwait(false);
if (symbolKey.Resolve(relatedSemanticModel.Compilation, ignoreAssemblyKey: true, cancellationToken).Symbol == null)
{
invalidProjectsForCurrentSymbol.Add(relatedDocument.Project.Id);
}
}
var platformData = new SupportedPlatformData(invalidProjectsForCurrentSymbol, totalProjects, document.Project.Solution.Workspace);
finalItems.Add(UpdateItem(item, platformData));
}
return new SignatureHelpItems(
finalItems, itemsForCurrentDocument.ApplicableSpan,
itemsForCurrentDocument.ArgumentIndex,
itemsForCurrentDocument.ArgumentCount,
itemsForCurrentDocument.ArgumentName,
itemsForCurrentDocument.SelectedItemIndex);
}
private static async Task<ImmutableArray<Document>> FindActiveRelatedDocumentsAsync(int position, Document document, CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<Document>.GetInstance(out var builder);
foreach (var relatedDocument in document.GetLinkedDocuments())
{
var syntaxTree = await relatedDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
if (!relatedDocument.GetRequiredLanguageService<ISyntaxFactsService>().IsInInactiveRegion(syntaxTree, position, cancellationToken))
{
builder.Add(relatedDocument);
}
}
return builder.ToImmutable();
}
private static SignatureHelpItem UpdateItem(SignatureHelpItem item, SupportedPlatformData platformData)
{
var platformParts = platformData.ToDisplayParts().ToTaggedText();
if (platformParts.Length == 0)
{
return item;
}
var startingNewLine = new List<TaggedText>();
startingNewLine.AddLineBreak();
var concatted = startingNewLine.Concat(platformParts);
var updatedDescription = item.DescriptionParts.IsDefault
? concatted
: item.DescriptionParts.Concat(concatted);
item.DescriptionParts = updatedDescription.ToImmutableArrayOrEmpty();
return item;
}
protected static int? TryGetSelectedIndex<TSymbol>(ImmutableArray<TSymbol> candidates, ISymbol? currentSymbol) where TSymbol : class, ISymbol
{
if (currentSymbol is TSymbol matched)
{
var found = candidates.IndexOf(matched);
if (found >= 0)
{
return found;
}
}
return null;
}
}
}
| -1 |
dotnet/roslyn | 55,530 | Ignore modules with bad metadata in function resolver | Fixes https://github.com/dotnet/roslyn/issues/55475 | tmat | 2021-08-10T18:56:37Z | 2021-08-11T18:37:09Z | cd0c0464c069a2b80774d70f071c29333d9fa23c | bc874ebc5111a2a33221409f895953b1536f6612 | Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475 | ./src/EditorFeatures/TestUtilities2/Intellisense/EmptyFeatureController.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.VisualStudio.Utilities
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense
Friend NotInheritable Class EmptyFeatureController
Implements IFeatureController
Friend Shared ReadOnly Instance As EmptyFeatureController = New EmptyFeatureController()
Private Sub New()
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.VisualStudio.Utilities
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense
Friend NotInheritable Class EmptyFeatureController
Implements IFeatureController
Friend Shared ReadOnly Instance As EmptyFeatureController = New EmptyFeatureController()
Private Sub New()
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,530 | Ignore modules with bad metadata in function resolver | Fixes https://github.com/dotnet/roslyn/issues/55475 | tmat | 2021-08-10T18:56:37Z | 2021-08-11T18:37:09Z | cd0c0464c069a2b80774d70f071c29333d9fa23c | bc874ebc5111a2a33221409f895953b1536f6612 | Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475 | ./src/Compilers/VisualBasic/Portable/CodeGen/EmitOperators.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.Reflection.Metadata
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGen
Partial Friend Class CodeGenerator
Private Sub EmitUnaryOperatorExpression(expression As BoundUnaryOperator, used As Boolean)
Debug.Assert((expression.OperatorKind And Not UnaryOperatorKind.IntrinsicOpMask) = 0 AndAlso expression.OperatorKind <> 0)
If Not used AndAlso Not OperatorHasSideEffects(expression) Then
EmitExpression(expression.Operand, used:=False)
Return
End If
Select Case expression.OperatorKind
Case UnaryOperatorKind.Minus
' If overflow checking is on, we must subtract from zero because Neg doesn't
' check for overflow.
Dim targetPrimitiveType = expression.Type.PrimitiveTypeCode
Dim useCheckedSubtraction As Boolean = (expression.Checked AndAlso
(targetPrimitiveType = Cci.PrimitiveTypeCode.Int32 OrElse
targetPrimitiveType = Cci.PrimitiveTypeCode.Int64))
If useCheckedSubtraction Then
' Generate the zero const first.
_builder.EmitOpCode(ILOpCode.Ldc_i4_0)
If targetPrimitiveType = Cci.PrimitiveTypeCode.Int64 Then
_builder.EmitOpCode(ILOpCode.Conv_i8)
End If
End If
EmitExpression(expression.Operand, used:=True)
If useCheckedSubtraction Then
_builder.EmitOpCode(ILOpCode.Sub_ovf)
Else
_builder.EmitOpCode(ILOpCode.Neg)
End If
' The result of the math operation has either 4 or 8 byte width.
' For 1 and 2 byte widths, convert the value back to the original type.
DowncastResultOfArithmeticOperation(targetPrimitiveType, expression.Checked)
Case UnaryOperatorKind.Not
If expression.Type.IsBooleanType() Then
' ISSUE: Will this emit 0 for false and 1 for true or can it leave non-zero on the stack without mapping it to 1?
' Dev10 code gen made sure there is either 0 or 1 on the stack after this operation.
EmitCondExpr(expression.Operand, sense:=False)
Else
EmitExpression(expression.Operand, used:=True)
_builder.EmitOpCode(ILOpCode.Not)
' Since the CLR will generate a 4-byte result from the Not operation, we
' need to convert back to ui1 or ui2 because they are unsigned
' CONSIDER cambecc (8-2-2000): no need to generate a Convert for each of n consecutive
' Not operations
Dim targetPrimitiveType = expression.Type.PrimitiveTypeCode
If targetPrimitiveType = Cci.PrimitiveTypeCode.UInt8 OrElse
targetPrimitiveType = Cci.PrimitiveTypeCode.UInt16 Then
_builder.EmitNumericConversion(Cci.PrimitiveTypeCode.UInt32,
targetPrimitiveType, False)
End If
End If
Case UnaryOperatorKind.Plus
EmitExpression(expression.Operand, used:=True)
Case Else
Throw ExceptionUtilities.UnexpectedValue(expression.OperatorKind)
End Select
EmitPopIfUnused(used)
End Sub
Private Shared Function OperatorHasSideEffects(expression As BoundUnaryOperator) As Boolean
If expression.Checked AndAlso
expression.OperatorKind = UnaryOperatorKind.Minus AndAlso
expression.Type.IsIntegralType() Then
Return True
End If
Return False
End Function
Private Sub EmitBinaryOperatorExpression(expression As BoundBinaryOperator, used As Boolean)
Dim operationKind = expression.OperatorKind And BinaryOperatorKind.OpMask
Dim shortCircuit As Boolean = operationKind = BinaryOperatorKind.AndAlso OrElse operationKind = BinaryOperatorKind.OrElse
If Not used AndAlso Not shortCircuit AndAlso Not OperatorHasSideEffects(expression) Then
EmitExpression(expression.Left, False)
EmitExpression(expression.Right, False)
Return
End If
If IsCondOperator(operationKind) Then
EmitBinaryCondOperator(expression, True)
Else
EmitBinaryOperator(expression)
End If
EmitPopIfUnused(used)
End Sub
Private Function IsCondOperator(operationKind As BinaryOperatorKind) As Boolean
Select Case (operationKind And BinaryOperatorKind.OpMask)
Case BinaryOperatorKind.OrElse,
BinaryOperatorKind.AndAlso,
BinaryOperatorKind.Equals,
BinaryOperatorKind.NotEquals,
BinaryOperatorKind.LessThanOrEqual,
BinaryOperatorKind.GreaterThanOrEqual,
BinaryOperatorKind.LessThan,
BinaryOperatorKind.GreaterThan,
BinaryOperatorKind.Is,
BinaryOperatorKind.IsNot
Return True
Case Else
Return False
End Select
End Function
Private Sub EmitBinaryOperator(expression As BoundBinaryOperator)
' Do not blow the stack due to a deep recursion on the left.
Dim child As BoundExpression = expression.Left
If child.Kind <> BoundKind.BinaryOperator OrElse child.ConstantValueOpt IsNot Nothing Then
EmitBinaryOperatorSimple(expression)
Return
End If
Dim binary As BoundBinaryOperator = DirectCast(child, BoundBinaryOperator)
If IsCondOperator(binary.OperatorKind) Then
EmitBinaryOperatorSimple(expression)
Return
End If
Dim stack = ArrayBuilder(Of BoundBinaryOperator).GetInstance()
stack.Push(expression)
Do
stack.Push(binary)
child = binary.Left
If child.Kind <> BoundKind.BinaryOperator OrElse child.ConstantValueOpt IsNot Nothing Then
Exit Do
End If
binary = DirectCast(child, BoundBinaryOperator)
If IsCondOperator(binary.OperatorKind) Then
Exit Do
End If
Loop
EmitExpression(child, True)
Do
binary = stack.Pop()
EmitExpression(binary.Right, True)
Select Case (binary.OperatorKind And BinaryOperatorKind.OpMask)
Case BinaryOperatorKind.And
_builder.EmitOpCode(ILOpCode.And)
Case BinaryOperatorKind.Xor
_builder.EmitOpCode(ILOpCode.Xor)
Case BinaryOperatorKind.Or
_builder.EmitOpCode(ILOpCode.Or)
Case Else
EmitBinaryArithOperatorInstructionAndDowncast(binary)
End Select
Loop While binary IsNot expression
Debug.Assert(stack.Count = 0)
stack.Free()
End Sub
Private Sub EmitBinaryOperatorSimple(expression As BoundBinaryOperator)
Select Case (expression.OperatorKind And BinaryOperatorKind.OpMask)
Case BinaryOperatorKind.And
EmitExpression(expression.Left, True)
EmitExpression(expression.Right, True)
_builder.EmitOpCode(ILOpCode.And)
Case BinaryOperatorKind.Xor
EmitExpression(expression.Left, True)
EmitExpression(expression.Right, True)
_builder.EmitOpCode(ILOpCode.Xor)
Case BinaryOperatorKind.Or
EmitExpression(expression.Left, True)
EmitExpression(expression.Right, True)
_builder.EmitOpCode(ILOpCode.Or)
Case Else
EmitBinaryArithOperator(expression)
End Select
End Sub
Private Function OperatorHasSideEffects(expression As BoundBinaryOperator) As Boolean
Dim type = expression.OperatorKind And BinaryOperatorKind.OpMask
Select Case type
Case BinaryOperatorKind.Divide,
BinaryOperatorKind.Modulo,
BinaryOperatorKind.IntegerDivide
Return True
Case BinaryOperatorKind.Multiply,
BinaryOperatorKind.Add,
BinaryOperatorKind.Subtract
Return expression.Checked AndAlso expression.Type.IsIntegralType()
Case Else
Return False
End Select
End Function
Private Sub EmitBinaryArithOperator(expression As BoundBinaryOperator)
EmitExpression(expression.Left, True)
EmitExpression(expression.Right, True)
EmitBinaryArithOperatorInstructionAndDowncast(expression)
End Sub
Private Sub EmitBinaryArithOperatorInstructionAndDowncast(expression As BoundBinaryOperator)
Dim targetPrimitiveType = expression.Type.PrimitiveTypeCode
Dim opKind = expression.OperatorKind And BinaryOperatorKind.OpMask
Select Case opKind
Case BinaryOperatorKind.Multiply
If expression.Checked AndAlso
(targetPrimitiveType = Cci.PrimitiveTypeCode.Int32 OrElse targetPrimitiveType = Cci.PrimitiveTypeCode.Int64) Then
_builder.EmitOpCode(ILOpCode.Mul_ovf)
ElseIf expression.Checked AndAlso
(targetPrimitiveType = Cci.PrimitiveTypeCode.UInt32 OrElse targetPrimitiveType = Cci.PrimitiveTypeCode.UInt64) Then
_builder.EmitOpCode(ILOpCode.Mul_ovf_un)
Else
_builder.EmitOpCode(ILOpCode.Mul)
End If
Case BinaryOperatorKind.Modulo
If targetPrimitiveType.IsUnsigned() Then
_builder.EmitOpCode(ILOpCode.Rem_un)
Else
_builder.EmitOpCode(ILOpCode.[Rem])
End If
Case BinaryOperatorKind.Add
If expression.Checked AndAlso
(targetPrimitiveType = Cci.PrimitiveTypeCode.Int32 OrElse targetPrimitiveType = Cci.PrimitiveTypeCode.Int64) Then
_builder.EmitOpCode(ILOpCode.Add_ovf)
ElseIf expression.Checked AndAlso
(targetPrimitiveType = Cci.PrimitiveTypeCode.UInt32 OrElse targetPrimitiveType = Cci.PrimitiveTypeCode.UInt64) Then
_builder.EmitOpCode(ILOpCode.Add_ovf_un)
Else
_builder.EmitOpCode(ILOpCode.Add)
End If
Case BinaryOperatorKind.Subtract
If expression.Checked AndAlso
(targetPrimitiveType = Cci.PrimitiveTypeCode.Int32 OrElse targetPrimitiveType = Cci.PrimitiveTypeCode.Int64) Then
_builder.EmitOpCode(ILOpCode.Sub_ovf)
ElseIf expression.Checked AndAlso
(targetPrimitiveType = Cci.PrimitiveTypeCode.UInt32 OrElse targetPrimitiveType = Cci.PrimitiveTypeCode.UInt64) Then
_builder.EmitOpCode(ILOpCode.Sub_ovf_un)
Else
_builder.EmitOpCode(ILOpCode.Sub)
End If
Case BinaryOperatorKind.Divide,
BinaryOperatorKind.IntegerDivide
If targetPrimitiveType.IsUnsigned() Then
_builder.EmitOpCode(ILOpCode.Div_un)
Else
_builder.EmitOpCode(ILOpCode.Div)
End If
Case BinaryOperatorKind.LeftShift
' And the right operand with mask corresponding the left operand type
Debug.Assert(expression.Right.Type.PrimitiveTypeCode = Cci.PrimitiveTypeCode.Int32)
'mask RHS if not a constant or too large
Dim shiftMax = GetShiftSizeMask(expression.Left.Type)
Dim shiftConst = expression.Right.ConstantValueOpt
If shiftConst Is Nothing OrElse shiftConst.UInt32Value > shiftMax Then
_builder.EmitConstantValue(ConstantValue.Create(shiftMax))
_builder.EmitOpCode(ILOpCode.And)
End If
_builder.EmitOpCode(ILOpCode.Shl)
Case BinaryOperatorKind.RightShift
' And the right operand with mask corresponding the left operand type
Debug.Assert(expression.Right.Type.PrimitiveTypeCode = Cci.PrimitiveTypeCode.Int32)
'mask RHS if not a constant or too large
Dim shiftMax = GetShiftSizeMask(expression.Left.Type)
Dim shiftConst = expression.Right.ConstantValueOpt
If shiftConst Is Nothing OrElse shiftConst.UInt32Value > shiftMax Then
_builder.EmitConstantValue(ConstantValue.Create(shiftMax))
_builder.EmitOpCode(ILOpCode.And)
End If
If targetPrimitiveType.IsUnsigned() Then
_builder.EmitOpCode(ILOpCode.Shr_un)
Else
_builder.EmitOpCode(ILOpCode.Shr)
End If
Case Else
' BinaryOperatorKind.Power, BinaryOperatorKind.Like and BinaryOperatorKind.Concatenate should go here.
Throw ExceptionUtilities.UnexpectedValue(opKind)
End Select
' The result of the math operation has either 4 or 8 byte width.
' For 1 and 2 byte widths, convert the value back to the original type.
DowncastResultOfArithmeticOperation(targetPrimitiveType, expression.Checked AndAlso
opKind <> BinaryOperatorKind.LeftShift AndAlso
opKind <> BinaryOperatorKind.RightShift)
End Sub
Private Sub DowncastResultOfArithmeticOperation(
targetPrimitiveType As Cci.PrimitiveTypeCode,
isChecked As Boolean
)
' The result of the math operation has either 4 or 8 byte width.
' For 1 and 2 byte widths, convert the value back to the original type.
If targetPrimitiveType = Cci.PrimitiveTypeCode.Int8 OrElse
targetPrimitiveType = Cci.PrimitiveTypeCode.UInt8 OrElse
targetPrimitiveType = Cci.PrimitiveTypeCode.Int16 OrElse
targetPrimitiveType = Cci.PrimitiveTypeCode.UInt16 Then
_builder.EmitNumericConversion(If(targetPrimitiveType.IsUnsigned(), Cci.PrimitiveTypeCode.UInt32, Cci.PrimitiveTypeCode.Int32),
targetPrimitiveType,
isChecked)
End If
End Sub
Public Shared Function GetShiftSizeMask(leftOperandType As TypeSymbol) As Integer
Return leftOperandType.GetEnumUnderlyingTypeOrSelf.SpecialType.GetShiftSizeMask()
End Function
Private Sub EmitShortCircuitingOperator(condition As BoundBinaryOperator, sense As Boolean, stopSense As Boolean, stopValue As Boolean)
' we generate:
'
' gotoif (a == stopSense) fallThrough
' b == sense
' goto labEnd
' fallThrough:
' stopValue
' labEnd:
' AND OR
' +- ------ -----
' stopSense | !sense sense
' stopValue | 0 1
Dim fallThrough As Object = Nothing
EmitCondBranch(condition.Left, fallThrough, stopSense)
EmitCondExpr(condition.Right, sense)
' if fall-through was not initialized, no-one is going to take that branch
' and we are done with Right on the stack
If fallThrough Is Nothing Then
Return
End If
Dim labEnd = New Object
_builder.EmitBranch(ILOpCode.Br, labEnd)
' if we get to FallThrough we should not have Right on the stack. Adjust for that.
_builder.AdjustStack(-1)
_builder.MarkLabel(fallThrough)
_builder.EmitBoolConstant(stopValue)
_builder.MarkLabel(labEnd)
End Sub
'NOTE: odd positions assume inverted sense
Private Shared ReadOnly s_compOpCodes As ILOpCode() = New ILOpCode() {ILOpCode.Clt, ILOpCode.Cgt, ILOpCode.Cgt, ILOpCode.Clt, ILOpCode.Clt_un, ILOpCode.Cgt_un, ILOpCode.Cgt_un, ILOpCode.Clt_un, ILOpCode.Clt, ILOpCode.Cgt_un, ILOpCode.Cgt, ILOpCode.Clt_un}
'NOTE: The result of this should be a boolean on the stack.
Private Sub EmitBinaryCondOperator(binOp As BoundBinaryOperator, sense As Boolean)
Dim andOrSense As Boolean = sense
Dim opIdx As Integer
Dim opKind = (binOp.OperatorKind And BinaryOperatorKind.OpMask)
Dim operandType = binOp.Left.Type
Debug.Assert(operandType IsNot Nothing OrElse (binOp.Left.IsNothingLiteral() AndAlso (opKind = BinaryOperatorKind.Is OrElse opKind = BinaryOperatorKind.IsNot)))
If operandType IsNot Nothing AndAlso operandType.IsBooleanType() Then
' Since VB True is -1 but is stored as 1 in IL, relational operations on Boolean must
' be reversed to yield the correct results. Note that = and <> do not need reversal.
Select Case opKind
Case BinaryOperatorKind.LessThan
opKind = BinaryOperatorKind.GreaterThan
Case BinaryOperatorKind.LessThanOrEqual
opKind = BinaryOperatorKind.GreaterThanOrEqual
Case BinaryOperatorKind.GreaterThan
opKind = BinaryOperatorKind.LessThan
Case BinaryOperatorKind.GreaterThanOrEqual
opKind = BinaryOperatorKind.LessThanOrEqual
End Select
End If
Select Case opKind
Case BinaryOperatorKind.OrElse
andOrSense = Not andOrSense
GoTo BinaryOperatorKindLogicalAnd
Case BinaryOperatorKind.AndAlso
BinaryOperatorKindLogicalAnd:
Debug.Assert(binOp.Left.Type.SpecialType = SpecialType.System_Boolean)
Debug.Assert(binOp.Right.Type.SpecialType = SpecialType.System_Boolean)
If Not andOrSense Then
EmitShortCircuitingOperator(binOp, sense, sense, True)
Else
EmitShortCircuitingOperator(binOp, sense, Not sense, False)
End If
Return
Case BinaryOperatorKind.IsNot
ValidateReferenceEqualityOperands(binOp)
GoTo BinaryOperatorKindNotEqual
Case BinaryOperatorKind.Is
ValidateReferenceEqualityOperands(binOp)
GoTo BinaryOperatorKindEqual
Case BinaryOperatorKind.NotEquals
BinaryOperatorKindNotEqual:
sense = Not sense
GoTo BinaryOperatorKindEqual
Case BinaryOperatorKind.Equals
BinaryOperatorKindEqual:
Dim constant = binOp.Left.ConstantValueOpt
Dim comparand = binOp.Right
If constant Is Nothing Then
constant = comparand.ConstantValueOpt
comparand = binOp.Left
End If
If constant IsNot Nothing Then
If constant.IsDefaultValue Then
If Not constant.IsFloating Then
If sense Then
EmitIsNullOrZero(comparand, constant)
Else
' obj != null/0 for pointers and integral numerics is emitted as cgt.un
EmitIsNotNullOrZero(comparand, constant)
End If
Return
End If
ElseIf constant.IsBoolean Then
' treat "x = True" ==> "x"
EmitExpression(comparand, True)
EmitIsSense(sense)
Return
End If
End If
EmitBinaryCondOperatorHelper(ILOpCode.Ceq, binOp.Left, binOp.Right, sense)
Return
Case BinaryOperatorKind.Or
Debug.Assert(binOp.Left.Type.SpecialType = SpecialType.System_Boolean)
Debug.Assert(binOp.Right.Type.SpecialType = SpecialType.System_Boolean)
EmitBinaryCondOperatorHelper(ILOpCode.Or, binOp.Left, binOp.Right, sense)
Return
Case BinaryOperatorKind.And
Debug.Assert(binOp.Left.Type.SpecialType = SpecialType.System_Boolean)
Debug.Assert(binOp.Right.Type.SpecialType = SpecialType.System_Boolean)
EmitBinaryCondOperatorHelper(ILOpCode.And, binOp.Left, binOp.Right, sense)
Return
Case BinaryOperatorKind.Xor
Debug.Assert(binOp.Left.Type.SpecialType = SpecialType.System_Boolean)
Debug.Assert(binOp.Right.Type.SpecialType = SpecialType.System_Boolean)
' Xor is equivalent to not equal.
If (sense) Then
EmitBinaryCondOperatorHelper(ILOpCode.Xor, binOp.Left, binOp.Right, True)
Else
EmitBinaryCondOperatorHelper(ILOpCode.Ceq, binOp.Left, binOp.Right, True)
End If
Return
Case BinaryOperatorKind.LessThan
opIdx = 0
Case BinaryOperatorKind.LessThanOrEqual
opIdx = 1
sense = Not sense
Case BinaryOperatorKind.GreaterThan
opIdx = 2
Case BinaryOperatorKind.GreaterThanOrEqual
opIdx = 3
sense = Not sense
Case Else
Throw ExceptionUtilities.UnexpectedValue(opKind)
End Select
If operandType IsNot Nothing Then
If operandType.IsUnsignedIntegralType() Then
opIdx += 4
Else
If operandType.IsFloatingType() Then
opIdx += 8
End If
End If
End If
EmitBinaryCondOperatorHelper(s_compOpCodes(opIdx), binOp.Left, binOp.Right, sense)
Return
End Sub
Private Sub EmitIsNotNullOrZero(comparand As BoundExpression, nullOrZero As ConstantValue)
EmitExpression(comparand, True)
Dim comparandType = comparand.Type
If comparandType.IsReferenceType AndAlso Not IsVerifierReference(comparandType) Then
EmitBox(comparandType, comparand.Syntax)
End If
_builder.EmitConstantValue(nullOrZero)
_builder.EmitOpCode(ILOpCode.Cgt_un)
End Sub
Private Sub EmitIsNullOrZero(comparand As BoundExpression, nullOrZero As ConstantValue)
EmitExpression(comparand, True)
Dim comparandType = comparand.Type
If comparandType.IsReferenceType AndAlso Not IsVerifierReference(comparandType) Then
EmitBox(comparandType, comparand.Syntax)
End If
_builder.EmitConstantValue(nullOrZero)
_builder.EmitOpCode(ILOpCode.Ceq)
End Sub
Private Sub EmitBinaryCondOperatorHelper(opCode As ILOpCode,
left As BoundExpression,
right As BoundExpression,
sense As Boolean)
EmitExpression(left, True)
EmitExpression(right, True)
_builder.EmitOpCode(opCode)
EmitIsSense(sense)
End Sub
' generate a conditional (ie, boolean) expression...
' this will leave a value on the stack which conforms to sense, ie:(condition == sense)
Private Function EmitCondExpr(condition As BoundExpression, sense As Boolean) As ConstResKind
While condition.Kind = BoundKind.UnaryOperator
Dim unOp = DirectCast(condition, BoundUnaryOperator)
Debug.Assert(unOp.OperatorKind = UnaryOperatorKind.Not AndAlso unOp.Type.IsBooleanType())
condition = unOp.Operand
sense = Not sense
End While
Debug.Assert(condition.Type.SpecialType = SpecialType.System_Boolean)
If _ilEmitStyle = ILEmitStyle.Release AndAlso condition.IsConstant Then
Dim constValue = condition.ConstantValueOpt
Debug.Assert(constValue.IsBoolean)
Dim constant = constValue.BooleanValue
_builder.EmitBoolConstant(constant = sense)
Return (If(constant = sense, ConstResKind.ConstTrue, ConstResKind.ConstFalse))
End If
If condition.Kind = BoundKind.BinaryOperator Then
Dim binOp = DirectCast(condition, BoundBinaryOperator)
EmitBinaryCondOperator(binOp, sense)
Return ConstResKind.NotAConst
End If
EmitExpression(condition, True)
EmitIsSense(sense)
Return ConstResKind.NotAConst
End Function
' emits IsTrue/IsFalse according to the sense
' IsTrue actually does nothing
Private Sub EmitIsSense(sense As Boolean)
If Not sense Then
_builder.EmitOpCode(ILOpCode.Ldc_i4_0)
_builder.EmitOpCode(ILOpCode.Ceq)
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.Reflection.Metadata
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGen
Partial Friend Class CodeGenerator
Private Sub EmitUnaryOperatorExpression(expression As BoundUnaryOperator, used As Boolean)
Debug.Assert((expression.OperatorKind And Not UnaryOperatorKind.IntrinsicOpMask) = 0 AndAlso expression.OperatorKind <> 0)
If Not used AndAlso Not OperatorHasSideEffects(expression) Then
EmitExpression(expression.Operand, used:=False)
Return
End If
Select Case expression.OperatorKind
Case UnaryOperatorKind.Minus
' If overflow checking is on, we must subtract from zero because Neg doesn't
' check for overflow.
Dim targetPrimitiveType = expression.Type.PrimitiveTypeCode
Dim useCheckedSubtraction As Boolean = (expression.Checked AndAlso
(targetPrimitiveType = Cci.PrimitiveTypeCode.Int32 OrElse
targetPrimitiveType = Cci.PrimitiveTypeCode.Int64))
If useCheckedSubtraction Then
' Generate the zero const first.
_builder.EmitOpCode(ILOpCode.Ldc_i4_0)
If targetPrimitiveType = Cci.PrimitiveTypeCode.Int64 Then
_builder.EmitOpCode(ILOpCode.Conv_i8)
End If
End If
EmitExpression(expression.Operand, used:=True)
If useCheckedSubtraction Then
_builder.EmitOpCode(ILOpCode.Sub_ovf)
Else
_builder.EmitOpCode(ILOpCode.Neg)
End If
' The result of the math operation has either 4 or 8 byte width.
' For 1 and 2 byte widths, convert the value back to the original type.
DowncastResultOfArithmeticOperation(targetPrimitiveType, expression.Checked)
Case UnaryOperatorKind.Not
If expression.Type.IsBooleanType() Then
' ISSUE: Will this emit 0 for false and 1 for true or can it leave non-zero on the stack without mapping it to 1?
' Dev10 code gen made sure there is either 0 or 1 on the stack after this operation.
EmitCondExpr(expression.Operand, sense:=False)
Else
EmitExpression(expression.Operand, used:=True)
_builder.EmitOpCode(ILOpCode.Not)
' Since the CLR will generate a 4-byte result from the Not operation, we
' need to convert back to ui1 or ui2 because they are unsigned
' CONSIDER cambecc (8-2-2000): no need to generate a Convert for each of n consecutive
' Not operations
Dim targetPrimitiveType = expression.Type.PrimitiveTypeCode
If targetPrimitiveType = Cci.PrimitiveTypeCode.UInt8 OrElse
targetPrimitiveType = Cci.PrimitiveTypeCode.UInt16 Then
_builder.EmitNumericConversion(Cci.PrimitiveTypeCode.UInt32,
targetPrimitiveType, False)
End If
End If
Case UnaryOperatorKind.Plus
EmitExpression(expression.Operand, used:=True)
Case Else
Throw ExceptionUtilities.UnexpectedValue(expression.OperatorKind)
End Select
EmitPopIfUnused(used)
End Sub
Private Shared Function OperatorHasSideEffects(expression As BoundUnaryOperator) As Boolean
If expression.Checked AndAlso
expression.OperatorKind = UnaryOperatorKind.Minus AndAlso
expression.Type.IsIntegralType() Then
Return True
End If
Return False
End Function
Private Sub EmitBinaryOperatorExpression(expression As BoundBinaryOperator, used As Boolean)
Dim operationKind = expression.OperatorKind And BinaryOperatorKind.OpMask
Dim shortCircuit As Boolean = operationKind = BinaryOperatorKind.AndAlso OrElse operationKind = BinaryOperatorKind.OrElse
If Not used AndAlso Not shortCircuit AndAlso Not OperatorHasSideEffects(expression) Then
EmitExpression(expression.Left, False)
EmitExpression(expression.Right, False)
Return
End If
If IsCondOperator(operationKind) Then
EmitBinaryCondOperator(expression, True)
Else
EmitBinaryOperator(expression)
End If
EmitPopIfUnused(used)
End Sub
Private Function IsCondOperator(operationKind As BinaryOperatorKind) As Boolean
Select Case (operationKind And BinaryOperatorKind.OpMask)
Case BinaryOperatorKind.OrElse,
BinaryOperatorKind.AndAlso,
BinaryOperatorKind.Equals,
BinaryOperatorKind.NotEquals,
BinaryOperatorKind.LessThanOrEqual,
BinaryOperatorKind.GreaterThanOrEqual,
BinaryOperatorKind.LessThan,
BinaryOperatorKind.GreaterThan,
BinaryOperatorKind.Is,
BinaryOperatorKind.IsNot
Return True
Case Else
Return False
End Select
End Function
Private Sub EmitBinaryOperator(expression As BoundBinaryOperator)
' Do not blow the stack due to a deep recursion on the left.
Dim child As BoundExpression = expression.Left
If child.Kind <> BoundKind.BinaryOperator OrElse child.ConstantValueOpt IsNot Nothing Then
EmitBinaryOperatorSimple(expression)
Return
End If
Dim binary As BoundBinaryOperator = DirectCast(child, BoundBinaryOperator)
If IsCondOperator(binary.OperatorKind) Then
EmitBinaryOperatorSimple(expression)
Return
End If
Dim stack = ArrayBuilder(Of BoundBinaryOperator).GetInstance()
stack.Push(expression)
Do
stack.Push(binary)
child = binary.Left
If child.Kind <> BoundKind.BinaryOperator OrElse child.ConstantValueOpt IsNot Nothing Then
Exit Do
End If
binary = DirectCast(child, BoundBinaryOperator)
If IsCondOperator(binary.OperatorKind) Then
Exit Do
End If
Loop
EmitExpression(child, True)
Do
binary = stack.Pop()
EmitExpression(binary.Right, True)
Select Case (binary.OperatorKind And BinaryOperatorKind.OpMask)
Case BinaryOperatorKind.And
_builder.EmitOpCode(ILOpCode.And)
Case BinaryOperatorKind.Xor
_builder.EmitOpCode(ILOpCode.Xor)
Case BinaryOperatorKind.Or
_builder.EmitOpCode(ILOpCode.Or)
Case Else
EmitBinaryArithOperatorInstructionAndDowncast(binary)
End Select
Loop While binary IsNot expression
Debug.Assert(stack.Count = 0)
stack.Free()
End Sub
Private Sub EmitBinaryOperatorSimple(expression As BoundBinaryOperator)
Select Case (expression.OperatorKind And BinaryOperatorKind.OpMask)
Case BinaryOperatorKind.And
EmitExpression(expression.Left, True)
EmitExpression(expression.Right, True)
_builder.EmitOpCode(ILOpCode.And)
Case BinaryOperatorKind.Xor
EmitExpression(expression.Left, True)
EmitExpression(expression.Right, True)
_builder.EmitOpCode(ILOpCode.Xor)
Case BinaryOperatorKind.Or
EmitExpression(expression.Left, True)
EmitExpression(expression.Right, True)
_builder.EmitOpCode(ILOpCode.Or)
Case Else
EmitBinaryArithOperator(expression)
End Select
End Sub
Private Function OperatorHasSideEffects(expression As BoundBinaryOperator) As Boolean
Dim type = expression.OperatorKind And BinaryOperatorKind.OpMask
Select Case type
Case BinaryOperatorKind.Divide,
BinaryOperatorKind.Modulo,
BinaryOperatorKind.IntegerDivide
Return True
Case BinaryOperatorKind.Multiply,
BinaryOperatorKind.Add,
BinaryOperatorKind.Subtract
Return expression.Checked AndAlso expression.Type.IsIntegralType()
Case Else
Return False
End Select
End Function
Private Sub EmitBinaryArithOperator(expression As BoundBinaryOperator)
EmitExpression(expression.Left, True)
EmitExpression(expression.Right, True)
EmitBinaryArithOperatorInstructionAndDowncast(expression)
End Sub
Private Sub EmitBinaryArithOperatorInstructionAndDowncast(expression As BoundBinaryOperator)
Dim targetPrimitiveType = expression.Type.PrimitiveTypeCode
Dim opKind = expression.OperatorKind And BinaryOperatorKind.OpMask
Select Case opKind
Case BinaryOperatorKind.Multiply
If expression.Checked AndAlso
(targetPrimitiveType = Cci.PrimitiveTypeCode.Int32 OrElse targetPrimitiveType = Cci.PrimitiveTypeCode.Int64) Then
_builder.EmitOpCode(ILOpCode.Mul_ovf)
ElseIf expression.Checked AndAlso
(targetPrimitiveType = Cci.PrimitiveTypeCode.UInt32 OrElse targetPrimitiveType = Cci.PrimitiveTypeCode.UInt64) Then
_builder.EmitOpCode(ILOpCode.Mul_ovf_un)
Else
_builder.EmitOpCode(ILOpCode.Mul)
End If
Case BinaryOperatorKind.Modulo
If targetPrimitiveType.IsUnsigned() Then
_builder.EmitOpCode(ILOpCode.Rem_un)
Else
_builder.EmitOpCode(ILOpCode.[Rem])
End If
Case BinaryOperatorKind.Add
If expression.Checked AndAlso
(targetPrimitiveType = Cci.PrimitiveTypeCode.Int32 OrElse targetPrimitiveType = Cci.PrimitiveTypeCode.Int64) Then
_builder.EmitOpCode(ILOpCode.Add_ovf)
ElseIf expression.Checked AndAlso
(targetPrimitiveType = Cci.PrimitiveTypeCode.UInt32 OrElse targetPrimitiveType = Cci.PrimitiveTypeCode.UInt64) Then
_builder.EmitOpCode(ILOpCode.Add_ovf_un)
Else
_builder.EmitOpCode(ILOpCode.Add)
End If
Case BinaryOperatorKind.Subtract
If expression.Checked AndAlso
(targetPrimitiveType = Cci.PrimitiveTypeCode.Int32 OrElse targetPrimitiveType = Cci.PrimitiveTypeCode.Int64) Then
_builder.EmitOpCode(ILOpCode.Sub_ovf)
ElseIf expression.Checked AndAlso
(targetPrimitiveType = Cci.PrimitiveTypeCode.UInt32 OrElse targetPrimitiveType = Cci.PrimitiveTypeCode.UInt64) Then
_builder.EmitOpCode(ILOpCode.Sub_ovf_un)
Else
_builder.EmitOpCode(ILOpCode.Sub)
End If
Case BinaryOperatorKind.Divide,
BinaryOperatorKind.IntegerDivide
If targetPrimitiveType.IsUnsigned() Then
_builder.EmitOpCode(ILOpCode.Div_un)
Else
_builder.EmitOpCode(ILOpCode.Div)
End If
Case BinaryOperatorKind.LeftShift
' And the right operand with mask corresponding the left operand type
Debug.Assert(expression.Right.Type.PrimitiveTypeCode = Cci.PrimitiveTypeCode.Int32)
'mask RHS if not a constant or too large
Dim shiftMax = GetShiftSizeMask(expression.Left.Type)
Dim shiftConst = expression.Right.ConstantValueOpt
If shiftConst Is Nothing OrElse shiftConst.UInt32Value > shiftMax Then
_builder.EmitConstantValue(ConstantValue.Create(shiftMax))
_builder.EmitOpCode(ILOpCode.And)
End If
_builder.EmitOpCode(ILOpCode.Shl)
Case BinaryOperatorKind.RightShift
' And the right operand with mask corresponding the left operand type
Debug.Assert(expression.Right.Type.PrimitiveTypeCode = Cci.PrimitiveTypeCode.Int32)
'mask RHS if not a constant or too large
Dim shiftMax = GetShiftSizeMask(expression.Left.Type)
Dim shiftConst = expression.Right.ConstantValueOpt
If shiftConst Is Nothing OrElse shiftConst.UInt32Value > shiftMax Then
_builder.EmitConstantValue(ConstantValue.Create(shiftMax))
_builder.EmitOpCode(ILOpCode.And)
End If
If targetPrimitiveType.IsUnsigned() Then
_builder.EmitOpCode(ILOpCode.Shr_un)
Else
_builder.EmitOpCode(ILOpCode.Shr)
End If
Case Else
' BinaryOperatorKind.Power, BinaryOperatorKind.Like and BinaryOperatorKind.Concatenate should go here.
Throw ExceptionUtilities.UnexpectedValue(opKind)
End Select
' The result of the math operation has either 4 or 8 byte width.
' For 1 and 2 byte widths, convert the value back to the original type.
DowncastResultOfArithmeticOperation(targetPrimitiveType, expression.Checked AndAlso
opKind <> BinaryOperatorKind.LeftShift AndAlso
opKind <> BinaryOperatorKind.RightShift)
End Sub
Private Sub DowncastResultOfArithmeticOperation(
targetPrimitiveType As Cci.PrimitiveTypeCode,
isChecked As Boolean
)
' The result of the math operation has either 4 or 8 byte width.
' For 1 and 2 byte widths, convert the value back to the original type.
If targetPrimitiveType = Cci.PrimitiveTypeCode.Int8 OrElse
targetPrimitiveType = Cci.PrimitiveTypeCode.UInt8 OrElse
targetPrimitiveType = Cci.PrimitiveTypeCode.Int16 OrElse
targetPrimitiveType = Cci.PrimitiveTypeCode.UInt16 Then
_builder.EmitNumericConversion(If(targetPrimitiveType.IsUnsigned(), Cci.PrimitiveTypeCode.UInt32, Cci.PrimitiveTypeCode.Int32),
targetPrimitiveType,
isChecked)
End If
End Sub
Public Shared Function GetShiftSizeMask(leftOperandType As TypeSymbol) As Integer
Return leftOperandType.GetEnumUnderlyingTypeOrSelf.SpecialType.GetShiftSizeMask()
End Function
Private Sub EmitShortCircuitingOperator(condition As BoundBinaryOperator, sense As Boolean, stopSense As Boolean, stopValue As Boolean)
' we generate:
'
' gotoif (a == stopSense) fallThrough
' b == sense
' goto labEnd
' fallThrough:
' stopValue
' labEnd:
' AND OR
' +- ------ -----
' stopSense | !sense sense
' stopValue | 0 1
Dim fallThrough As Object = Nothing
EmitCondBranch(condition.Left, fallThrough, stopSense)
EmitCondExpr(condition.Right, sense)
' if fall-through was not initialized, no-one is going to take that branch
' and we are done with Right on the stack
If fallThrough Is Nothing Then
Return
End If
Dim labEnd = New Object
_builder.EmitBranch(ILOpCode.Br, labEnd)
' if we get to FallThrough we should not have Right on the stack. Adjust for that.
_builder.AdjustStack(-1)
_builder.MarkLabel(fallThrough)
_builder.EmitBoolConstant(stopValue)
_builder.MarkLabel(labEnd)
End Sub
'NOTE: odd positions assume inverted sense
Private Shared ReadOnly s_compOpCodes As ILOpCode() = New ILOpCode() {ILOpCode.Clt, ILOpCode.Cgt, ILOpCode.Cgt, ILOpCode.Clt, ILOpCode.Clt_un, ILOpCode.Cgt_un, ILOpCode.Cgt_un, ILOpCode.Clt_un, ILOpCode.Clt, ILOpCode.Cgt_un, ILOpCode.Cgt, ILOpCode.Clt_un}
'NOTE: The result of this should be a boolean on the stack.
Private Sub EmitBinaryCondOperator(binOp As BoundBinaryOperator, sense As Boolean)
Dim andOrSense As Boolean = sense
Dim opIdx As Integer
Dim opKind = (binOp.OperatorKind And BinaryOperatorKind.OpMask)
Dim operandType = binOp.Left.Type
Debug.Assert(operandType IsNot Nothing OrElse (binOp.Left.IsNothingLiteral() AndAlso (opKind = BinaryOperatorKind.Is OrElse opKind = BinaryOperatorKind.IsNot)))
If operandType IsNot Nothing AndAlso operandType.IsBooleanType() Then
' Since VB True is -1 but is stored as 1 in IL, relational operations on Boolean must
' be reversed to yield the correct results. Note that = and <> do not need reversal.
Select Case opKind
Case BinaryOperatorKind.LessThan
opKind = BinaryOperatorKind.GreaterThan
Case BinaryOperatorKind.LessThanOrEqual
opKind = BinaryOperatorKind.GreaterThanOrEqual
Case BinaryOperatorKind.GreaterThan
opKind = BinaryOperatorKind.LessThan
Case BinaryOperatorKind.GreaterThanOrEqual
opKind = BinaryOperatorKind.LessThanOrEqual
End Select
End If
Select Case opKind
Case BinaryOperatorKind.OrElse
andOrSense = Not andOrSense
GoTo BinaryOperatorKindLogicalAnd
Case BinaryOperatorKind.AndAlso
BinaryOperatorKindLogicalAnd:
Debug.Assert(binOp.Left.Type.SpecialType = SpecialType.System_Boolean)
Debug.Assert(binOp.Right.Type.SpecialType = SpecialType.System_Boolean)
If Not andOrSense Then
EmitShortCircuitingOperator(binOp, sense, sense, True)
Else
EmitShortCircuitingOperator(binOp, sense, Not sense, False)
End If
Return
Case BinaryOperatorKind.IsNot
ValidateReferenceEqualityOperands(binOp)
GoTo BinaryOperatorKindNotEqual
Case BinaryOperatorKind.Is
ValidateReferenceEqualityOperands(binOp)
GoTo BinaryOperatorKindEqual
Case BinaryOperatorKind.NotEquals
BinaryOperatorKindNotEqual:
sense = Not sense
GoTo BinaryOperatorKindEqual
Case BinaryOperatorKind.Equals
BinaryOperatorKindEqual:
Dim constant = binOp.Left.ConstantValueOpt
Dim comparand = binOp.Right
If constant Is Nothing Then
constant = comparand.ConstantValueOpt
comparand = binOp.Left
End If
If constant IsNot Nothing Then
If constant.IsDefaultValue Then
If Not constant.IsFloating Then
If sense Then
EmitIsNullOrZero(comparand, constant)
Else
' obj != null/0 for pointers and integral numerics is emitted as cgt.un
EmitIsNotNullOrZero(comparand, constant)
End If
Return
End If
ElseIf constant.IsBoolean Then
' treat "x = True" ==> "x"
EmitExpression(comparand, True)
EmitIsSense(sense)
Return
End If
End If
EmitBinaryCondOperatorHelper(ILOpCode.Ceq, binOp.Left, binOp.Right, sense)
Return
Case BinaryOperatorKind.Or
Debug.Assert(binOp.Left.Type.SpecialType = SpecialType.System_Boolean)
Debug.Assert(binOp.Right.Type.SpecialType = SpecialType.System_Boolean)
EmitBinaryCondOperatorHelper(ILOpCode.Or, binOp.Left, binOp.Right, sense)
Return
Case BinaryOperatorKind.And
Debug.Assert(binOp.Left.Type.SpecialType = SpecialType.System_Boolean)
Debug.Assert(binOp.Right.Type.SpecialType = SpecialType.System_Boolean)
EmitBinaryCondOperatorHelper(ILOpCode.And, binOp.Left, binOp.Right, sense)
Return
Case BinaryOperatorKind.Xor
Debug.Assert(binOp.Left.Type.SpecialType = SpecialType.System_Boolean)
Debug.Assert(binOp.Right.Type.SpecialType = SpecialType.System_Boolean)
' Xor is equivalent to not equal.
If (sense) Then
EmitBinaryCondOperatorHelper(ILOpCode.Xor, binOp.Left, binOp.Right, True)
Else
EmitBinaryCondOperatorHelper(ILOpCode.Ceq, binOp.Left, binOp.Right, True)
End If
Return
Case BinaryOperatorKind.LessThan
opIdx = 0
Case BinaryOperatorKind.LessThanOrEqual
opIdx = 1
sense = Not sense
Case BinaryOperatorKind.GreaterThan
opIdx = 2
Case BinaryOperatorKind.GreaterThanOrEqual
opIdx = 3
sense = Not sense
Case Else
Throw ExceptionUtilities.UnexpectedValue(opKind)
End Select
If operandType IsNot Nothing Then
If operandType.IsUnsignedIntegralType() Then
opIdx += 4
Else
If operandType.IsFloatingType() Then
opIdx += 8
End If
End If
End If
EmitBinaryCondOperatorHelper(s_compOpCodes(opIdx), binOp.Left, binOp.Right, sense)
Return
End Sub
Private Sub EmitIsNotNullOrZero(comparand As BoundExpression, nullOrZero As ConstantValue)
EmitExpression(comparand, True)
Dim comparandType = comparand.Type
If comparandType.IsReferenceType AndAlso Not IsVerifierReference(comparandType) Then
EmitBox(comparandType, comparand.Syntax)
End If
_builder.EmitConstantValue(nullOrZero)
_builder.EmitOpCode(ILOpCode.Cgt_un)
End Sub
Private Sub EmitIsNullOrZero(comparand As BoundExpression, nullOrZero As ConstantValue)
EmitExpression(comparand, True)
Dim comparandType = comparand.Type
If comparandType.IsReferenceType AndAlso Not IsVerifierReference(comparandType) Then
EmitBox(comparandType, comparand.Syntax)
End If
_builder.EmitConstantValue(nullOrZero)
_builder.EmitOpCode(ILOpCode.Ceq)
End Sub
Private Sub EmitBinaryCondOperatorHelper(opCode As ILOpCode,
left As BoundExpression,
right As BoundExpression,
sense As Boolean)
EmitExpression(left, True)
EmitExpression(right, True)
_builder.EmitOpCode(opCode)
EmitIsSense(sense)
End Sub
' generate a conditional (ie, boolean) expression...
' this will leave a value on the stack which conforms to sense, ie:(condition == sense)
Private Function EmitCondExpr(condition As BoundExpression, sense As Boolean) As ConstResKind
While condition.Kind = BoundKind.UnaryOperator
Dim unOp = DirectCast(condition, BoundUnaryOperator)
Debug.Assert(unOp.OperatorKind = UnaryOperatorKind.Not AndAlso unOp.Type.IsBooleanType())
condition = unOp.Operand
sense = Not sense
End While
Debug.Assert(condition.Type.SpecialType = SpecialType.System_Boolean)
If _ilEmitStyle = ILEmitStyle.Release AndAlso condition.IsConstant Then
Dim constValue = condition.ConstantValueOpt
Debug.Assert(constValue.IsBoolean)
Dim constant = constValue.BooleanValue
_builder.EmitBoolConstant(constant = sense)
Return (If(constant = sense, ConstResKind.ConstTrue, ConstResKind.ConstFalse))
End If
If condition.Kind = BoundKind.BinaryOperator Then
Dim binOp = DirectCast(condition, BoundBinaryOperator)
EmitBinaryCondOperator(binOp, sense)
Return ConstResKind.NotAConst
End If
EmitExpression(condition, True)
EmitIsSense(sense)
Return ConstResKind.NotAConst
End Function
' emits IsTrue/IsFalse according to the sense
' IsTrue actually does nothing
Private Sub EmitIsSense(sense As Boolean)
If Not sense Then
_builder.EmitOpCode(ILOpCode.Ldc_i4_0)
_builder.EmitOpCode(ILOpCode.Ceq)
End If
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,530 | Ignore modules with bad metadata in function resolver | Fixes https://github.com/dotnet/roslyn/issues/55475 | tmat | 2021-08-10T18:56:37Z | 2021-08-11T18:37:09Z | cd0c0464c069a2b80774d70f071c29333d9fa23c | bc874ebc5111a2a33221409f895953b1536f6612 | Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475 | ./src/Features/LanguageServer/ProtocolUnitTests/Completion/CompletionResolveTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Microsoft.VisualStudio.Text.Adornments;
using Newtonsoft.Json;
using Roslyn.Test.Utilities;
using Xunit;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Completion
{
public class CompletionResolveTests : AbstractLanguageServerProtocolTests
{
[Fact]
public async Task TestResolveCompletionItemFromListAsync()
{
var markup =
@"class A
{
void M()
{
{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var clientCapabilities = new LSP.VSInternalClientCapabilities
{
SupportsVisualStudioExtensions = true,
TextDocument = new TextDocumentClientCapabilities()
{
Completion = new VSInternalCompletionSetting()
{
CompletionList = new VSInternalCompletionListSetting()
{
Data = true,
}
}
}
};
var clientCompletionItem = await GetCompletionItemToResolveAsync<LSP.VSInternalCompletionItem>(
testLspServer,
locations,
label: "A",
clientCapabilities).ConfigureAwait(false);
var description = new ClassifiedTextElement(CreateClassifiedTextRunForClass("A"));
var expected = CreateResolvedCompletionItem(clientCompletionItem, description, "class A", null);
var results = (LSP.VSInternalCompletionItem)await RunResolveCompletionItemAsync(
testLspServer, clientCompletionItem, clientCapabilities).ConfigureAwait(false);
AssertJsonEquals(expected, results);
}
[Fact]
public async Task TestResolveCompletionItemAsync()
{
var markup =
@"class A
{
void M()
{
{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var clientCompletionItem = await GetCompletionItemToResolveAsync<LSP.VSInternalCompletionItem>(testLspServer, locations, label: "A").ConfigureAwait(false);
var description = new ClassifiedTextElement(CreateClassifiedTextRunForClass("A"));
var expected = CreateResolvedCompletionItem(clientCompletionItem, description, "class A", null);
var results = (LSP.VSInternalCompletionItem)await RunResolveCompletionItemAsync(
testLspServer, clientCompletionItem).ConfigureAwait(false);
AssertJsonEquals(expected, results);
}
[Fact]
[WorkItem(51125, "https://github.com/dotnet/roslyn/issues/51125")]
public async Task TestResolveOverridesCompletionItemAsync()
{
var markup =
@"abstract class A
{
public abstract void M();
}
class B : A
{
override {|caret:|}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var clientCompletionItem = await GetCompletionItemToResolveAsync<LSP.VSInternalCompletionItem>(testLspServer, locations, label: "M()").ConfigureAwait(false);
var results = (LSP.VSInternalCompletionItem)await RunResolveCompletionItemAsync(
testLspServer, clientCompletionItem).ConfigureAwait(false);
Assert.NotNull(results.TextEdit);
Assert.Null(results.InsertText);
Assert.Equal(@"public override void M()
{
throw new System.NotImplementedException();
}", results.TextEdit.NewText);
}
[Fact]
[WorkItem(51125, "https://github.com/dotnet/roslyn/issues/51125")]
public async Task TestResolveOverridesCompletionItem_SnippetsEnabledAsync()
{
var markup =
@"abstract class A
{
public abstract void M();
}
class B : A
{
override {|caret:|}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
// Explicitly enable snippets. This allows us to set the cursor with $0. Currently only applies to C# in Razor docs.
var clientCapabilities = new LSP.VSInternalClientCapabilities
{
SupportsVisualStudioExtensions = true,
TextDocument = new LSP.TextDocumentClientCapabilities
{
Completion = new CompletionSetting
{
CompletionItem = new CompletionItemSetting
{
SnippetSupport = true
}
}
}
};
var clientCompletionItem = await GetCompletionItemToResolveAsync<LSP.VSInternalCompletionItem>(
testLspServer,
locations,
label: "M()",
clientCapabilities).ConfigureAwait(false);
var results = (LSP.VSInternalCompletionItem)await RunResolveCompletionItemAsync(
testLspServer, clientCompletionItem, clientCapabilities).ConfigureAwait(false);
Assert.NotNull(results.TextEdit);
Assert.Null(results.InsertText);
Assert.Equal(@"public override void M()
{
throw new System.NotImplementedException();$0
}", results.TextEdit.NewText);
}
[Fact]
[WorkItem(51125, "https://github.com/dotnet/roslyn/issues/51125")]
public async Task TestResolveOverridesCompletionItem_SnippetsEnabled_CaretOutOfSnippetScopeAsync()
{
var markup =
@"abstract class A
{
public abstract void M();
}
class B : A
{
override {|caret:|}
}";
using var testLspServer = CreateTestLspServer(markup, out _);
var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First();
var selectedItem = CodeAnalysis.Completion.CompletionItem.Create(displayText: "M");
var textEdit = await CompletionResolveHandler.GenerateTextEditAsync(
document, new TestCaretOutOfScopeCompletionService(), selectedItem, snippetsSupported: true, CancellationToken.None).ConfigureAwait(false);
Assert.Equal(@"public override void M()
{
throw new System.NotImplementedException();
}", textEdit.NewText);
}
[Fact]
public async Task TestResolveCompletionItemWithMarkupContentAsync()
{
var markup =
@"
class A
{
/// <summary>
/// A cref <see cref=""AMethod""/>
/// <br/>
/// <strong>strong text</strong>
/// <br/>
/// <em>italic text</em>
/// <br/>
/// <u>underline text</u>
/// <para>
/// <list type='bullet'>
/// <item>
/// <description>Item 1.</description>
/// </item>
/// <item>
/// <description>Item 2.</description>
/// </item>
/// </list>
/// <a href = ""https://google.com"" > link text</a>
/// </para>
/// </summary>
void AMethod(int i)
{
}
void M()
{
AMet{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var clientCompletionItem = await GetCompletionItemToResolveAsync<LSP.CompletionItem>(
testLspServer,
locations,
label: "AMethod",
new ClientCapabilities()).ConfigureAwait(false);
Assert.True(clientCompletionItem is not VSInternalCompletionItem);
var expected = @"```csharp
void A.AMethod(int i)
```
A cref A\.AMethod\(int\)
**strong text**
_italic text_
<u>underline text</u>
• Item 1\.
• Item 2\.
[link text](https://google.com)";
var results = await RunResolveCompletionItemAsync(
testLspServer,
clientCompletionItem,
new ClientCapabilities
{
TextDocument = new TextDocumentClientCapabilities
{
Completion = new CompletionSetting
{
CompletionItem = new CompletionItemSetting
{
DocumentationFormat = new MarkupKind[] { MarkupKind.Markdown }
}
}
}
}).ConfigureAwait(false);
Assert.Equal(expected, results.Documentation.Value.Second.Value);
}
[Fact]
public async Task TestResolveCompletionItemWithPlainTextAsync()
{
var markup =
@"
class A
{
/// <summary>
/// A cref <see cref=""AMethod""/>
/// <br/>
/// <strong>strong text</strong>
/// <br/>
/// <em>italic text</em>
/// <br/>
/// <u>underline text</u>
/// <para>
/// <list type='bullet'>
/// <item>
/// <description>Item 1.</description>
/// </item>
/// <item>
/// <description>Item 2.</description>
/// </item>
/// </list>
/// <a href = ""https://google.com"" > link text</a>
/// </para>
/// </summary>
void AMethod(int i)
{
}
void M()
{
AMet{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var clientCompletionItem = await GetCompletionItemToResolveAsync<LSP.CompletionItem>(
testLspServer,
locations,
label: "AMethod",
new ClientCapabilities()).ConfigureAwait(false);
Assert.True(clientCompletionItem is not VSInternalCompletionItem);
var expected = @"void A.AMethod(int i)
A cref A.AMethod(int)
strong text
italic text
underline text
• Item 1.
• Item 2.
link text";
var results = await RunResolveCompletionItemAsync(
testLspServer,
clientCompletionItem,
new ClientCapabilities()).ConfigureAwait(false);
Assert.Equal(expected, results.Documentation.Value.Second.Value);
}
[Fact]
public async Task TestResolveCompletionItemWithPrefixSuffixAsync()
{
var markup =
@"class A
{
void M()
{
var a = 10;
a.{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var clientCompletionItem = await GetCompletionItemToResolveAsync<LSP.VSInternalCompletionItem>(testLspServer, locations, label: "(byte)").ConfigureAwait(false);
var results = (LSP.VSInternalCompletionItem)await RunResolveCompletionItemAsync(
testLspServer, clientCompletionItem).ConfigureAwait(false);
Assert.Equal("(byte)", results.Label);
Assert.NotNull(results.Description);
}
private static async Task<LSP.CompletionItem> RunResolveCompletionItemAsync(TestLspServer testLspServer, LSP.CompletionItem completionItem, LSP.ClientCapabilities clientCapabilities = null)
{
clientCapabilities ??= new LSP.VSInternalClientCapabilities { SupportsVisualStudioExtensions = true };
return await testLspServer.ExecuteRequestAsync<LSP.CompletionItem, LSP.CompletionItem>(LSP.Methods.TextDocumentCompletionResolveName,
completionItem, clientCapabilities, null, CancellationToken.None);
}
private static LSP.VSInternalCompletionItem CreateResolvedCompletionItem(
VSInternalCompletionItem completionItem,
ClassifiedTextElement description,
string detail,
string documentation)
{
completionItem.Detail = detail;
if (documentation != null)
{
completionItem.Documentation = new LSP.MarkupContent()
{
Kind = LSP.MarkupKind.PlainText,
Value = documentation
};
}
completionItem.Description = description;
return completionItem;
}
private static ClassifiedTextRun[] CreateClassifiedTextRunForClass(string className)
=> new ClassifiedTextRun[]
{
new ClassifiedTextRun("keyword", "class"),
new ClassifiedTextRun("whitespace", " "),
new ClassifiedTextRun("class name", className)
};
private static async Task<T> GetCompletionItemToResolveAsync<T>(
TestLspServer testLspServer,
Dictionary<string, IList<LSP.Location>> locations,
string label,
LSP.ClientCapabilities clientCapabilities = null) where T : LSP.CompletionItem
{
var completionParams = CreateCompletionParams(
locations["caret"].Single(), LSP.VSInternalCompletionInvokeKind.Explicit, "\0", LSP.CompletionTriggerKind.Invoked);
clientCapabilities ??= new LSP.VSInternalClientCapabilities { SupportsVisualStudioExtensions = true };
var completionList = await RunGetCompletionsAsync(testLspServer, completionParams, clientCapabilities);
if (clientCapabilities.HasCompletionListDataCapability())
{
var vsCompletionList = Assert.IsAssignableFrom<VSInternalCompletionList>(completionList);
Assert.NotNull(vsCompletionList.Data);
}
var serverCompletionItem = completionList.Items.FirstOrDefault(item => item.Label == label);
var clientCompletionItem = ConvertToClientCompletionItem((T)serverCompletionItem);
return clientCompletionItem;
}
private static async Task<LSP.CompletionList> RunGetCompletionsAsync(
TestLspServer testLspServer,
LSP.CompletionParams completionParams,
LSP.ClientCapabilities clientCapabilities)
{
var completionList = await testLspServer.ExecuteRequestAsync<LSP.CompletionParams, LSP.CompletionList>(LSP.Methods.TextDocumentCompletionName,
completionParams, clientCapabilities, null, CancellationToken.None);
// Emulate client behavior of promoting "Data" completion list properties onto completion items.
if (clientCapabilities.HasCompletionListDataCapability() &&
completionList is VSInternalCompletionList vsCompletionList &&
vsCompletionList.Data != null)
{
foreach (var completionItem in completionList.Items)
{
Assert.Null(completionItem.Data);
completionItem.Data = vsCompletionList.Data;
}
}
return completionList;
}
private static T ConvertToClientCompletionItem<T>(T serverCompletionItem) where T : LSP.CompletionItem
{
var serializedItem = JsonConvert.SerializeObject(serverCompletionItem);
var clientCompletionItem = JsonConvert.DeserializeObject<T>(serializedItem);
return clientCompletionItem;
}
private class TestCaretOutOfScopeCompletionService : CompletionService
{
public override string Language => LanguageNames.CSharp;
public override Task<CodeAnalysis.Completion.CompletionList> GetCompletionsAsync(
Document document,
int caretPosition,
CompletionTrigger trigger = default,
ImmutableHashSet<string> roles = null,
OptionSet options = null,
CancellationToken cancellationToken = default)
=> Task.FromResult(CodeAnalysis.Completion.CompletionList.Empty);
public override Task<CompletionChange> GetChangeAsync(
Document document,
CodeAnalysis.Completion.CompletionItem item,
char? commitCharacter = null,
CancellationToken cancellationToken = default)
{
var textChange = new TextChange(span: new TextSpan(start: 77, length: 9), newText: @"public override void M()
{
throw new System.NotImplementedException();
}");
return Task.FromResult(CompletionChange.Create(textChange, newPosition: 0));
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Microsoft.VisualStudio.Text.Adornments;
using Newtonsoft.Json;
using Roslyn.Test.Utilities;
using Xunit;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Completion
{
public class CompletionResolveTests : AbstractLanguageServerProtocolTests
{
[Fact]
public async Task TestResolveCompletionItemFromListAsync()
{
var markup =
@"class A
{
void M()
{
{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var clientCapabilities = new LSP.VSInternalClientCapabilities
{
SupportsVisualStudioExtensions = true,
TextDocument = new TextDocumentClientCapabilities()
{
Completion = new VSInternalCompletionSetting()
{
CompletionList = new VSInternalCompletionListSetting()
{
Data = true,
}
}
}
};
var clientCompletionItem = await GetCompletionItemToResolveAsync<LSP.VSInternalCompletionItem>(
testLspServer,
locations,
label: "A",
clientCapabilities).ConfigureAwait(false);
var description = new ClassifiedTextElement(CreateClassifiedTextRunForClass("A"));
var expected = CreateResolvedCompletionItem(clientCompletionItem, description, "class A", null);
var results = (LSP.VSInternalCompletionItem)await RunResolveCompletionItemAsync(
testLspServer, clientCompletionItem, clientCapabilities).ConfigureAwait(false);
AssertJsonEquals(expected, results);
}
[Fact]
public async Task TestResolveCompletionItemAsync()
{
var markup =
@"class A
{
void M()
{
{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var clientCompletionItem = await GetCompletionItemToResolveAsync<LSP.VSInternalCompletionItem>(testLspServer, locations, label: "A").ConfigureAwait(false);
var description = new ClassifiedTextElement(CreateClassifiedTextRunForClass("A"));
var expected = CreateResolvedCompletionItem(clientCompletionItem, description, "class A", null);
var results = (LSP.VSInternalCompletionItem)await RunResolveCompletionItemAsync(
testLspServer, clientCompletionItem).ConfigureAwait(false);
AssertJsonEquals(expected, results);
}
[Fact]
[WorkItem(51125, "https://github.com/dotnet/roslyn/issues/51125")]
public async Task TestResolveOverridesCompletionItemAsync()
{
var markup =
@"abstract class A
{
public abstract void M();
}
class B : A
{
override {|caret:|}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var clientCompletionItem = await GetCompletionItemToResolveAsync<LSP.VSInternalCompletionItem>(testLspServer, locations, label: "M()").ConfigureAwait(false);
var results = (LSP.VSInternalCompletionItem)await RunResolveCompletionItemAsync(
testLspServer, clientCompletionItem).ConfigureAwait(false);
Assert.NotNull(results.TextEdit);
Assert.Null(results.InsertText);
Assert.Equal(@"public override void M()
{
throw new System.NotImplementedException();
}", results.TextEdit.NewText);
}
[Fact]
[WorkItem(51125, "https://github.com/dotnet/roslyn/issues/51125")]
public async Task TestResolveOverridesCompletionItem_SnippetsEnabledAsync()
{
var markup =
@"abstract class A
{
public abstract void M();
}
class B : A
{
override {|caret:|}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
// Explicitly enable snippets. This allows us to set the cursor with $0. Currently only applies to C# in Razor docs.
var clientCapabilities = new LSP.VSInternalClientCapabilities
{
SupportsVisualStudioExtensions = true,
TextDocument = new LSP.TextDocumentClientCapabilities
{
Completion = new CompletionSetting
{
CompletionItem = new CompletionItemSetting
{
SnippetSupport = true
}
}
}
};
var clientCompletionItem = await GetCompletionItemToResolveAsync<LSP.VSInternalCompletionItem>(
testLspServer,
locations,
label: "M()",
clientCapabilities).ConfigureAwait(false);
var results = (LSP.VSInternalCompletionItem)await RunResolveCompletionItemAsync(
testLspServer, clientCompletionItem, clientCapabilities).ConfigureAwait(false);
Assert.NotNull(results.TextEdit);
Assert.Null(results.InsertText);
Assert.Equal(@"public override void M()
{
throw new System.NotImplementedException();$0
}", results.TextEdit.NewText);
}
[Fact]
[WorkItem(51125, "https://github.com/dotnet/roslyn/issues/51125")]
public async Task TestResolveOverridesCompletionItem_SnippetsEnabled_CaretOutOfSnippetScopeAsync()
{
var markup =
@"abstract class A
{
public abstract void M();
}
class B : A
{
override {|caret:|}
}";
using var testLspServer = CreateTestLspServer(markup, out _);
var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First();
var selectedItem = CodeAnalysis.Completion.CompletionItem.Create(displayText: "M");
var textEdit = await CompletionResolveHandler.GenerateTextEditAsync(
document, new TestCaretOutOfScopeCompletionService(), selectedItem, snippetsSupported: true, CancellationToken.None).ConfigureAwait(false);
Assert.Equal(@"public override void M()
{
throw new System.NotImplementedException();
}", textEdit.NewText);
}
[Fact]
public async Task TestResolveCompletionItemWithMarkupContentAsync()
{
var markup =
@"
class A
{
/// <summary>
/// A cref <see cref=""AMethod""/>
/// <br/>
/// <strong>strong text</strong>
/// <br/>
/// <em>italic text</em>
/// <br/>
/// <u>underline text</u>
/// <para>
/// <list type='bullet'>
/// <item>
/// <description>Item 1.</description>
/// </item>
/// <item>
/// <description>Item 2.</description>
/// </item>
/// </list>
/// <a href = ""https://google.com"" > link text</a>
/// </para>
/// </summary>
void AMethod(int i)
{
}
void M()
{
AMet{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var clientCompletionItem = await GetCompletionItemToResolveAsync<LSP.CompletionItem>(
testLspServer,
locations,
label: "AMethod",
new ClientCapabilities()).ConfigureAwait(false);
Assert.True(clientCompletionItem is not VSInternalCompletionItem);
var expected = @"```csharp
void A.AMethod(int i)
```
A cref A\.AMethod\(int\)
**strong text**
_italic text_
<u>underline text</u>
• Item 1\.
• Item 2\.
[link text](https://google.com)";
var results = await RunResolveCompletionItemAsync(
testLspServer,
clientCompletionItem,
new ClientCapabilities
{
TextDocument = new TextDocumentClientCapabilities
{
Completion = new CompletionSetting
{
CompletionItem = new CompletionItemSetting
{
DocumentationFormat = new MarkupKind[] { MarkupKind.Markdown }
}
}
}
}).ConfigureAwait(false);
Assert.Equal(expected, results.Documentation.Value.Second.Value);
}
[Fact]
public async Task TestResolveCompletionItemWithPlainTextAsync()
{
var markup =
@"
class A
{
/// <summary>
/// A cref <see cref=""AMethod""/>
/// <br/>
/// <strong>strong text</strong>
/// <br/>
/// <em>italic text</em>
/// <br/>
/// <u>underline text</u>
/// <para>
/// <list type='bullet'>
/// <item>
/// <description>Item 1.</description>
/// </item>
/// <item>
/// <description>Item 2.</description>
/// </item>
/// </list>
/// <a href = ""https://google.com"" > link text</a>
/// </para>
/// </summary>
void AMethod(int i)
{
}
void M()
{
AMet{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var clientCompletionItem = await GetCompletionItemToResolveAsync<LSP.CompletionItem>(
testLspServer,
locations,
label: "AMethod",
new ClientCapabilities()).ConfigureAwait(false);
Assert.True(clientCompletionItem is not VSInternalCompletionItem);
var expected = @"void A.AMethod(int i)
A cref A.AMethod(int)
strong text
italic text
underline text
• Item 1.
• Item 2.
link text";
var results = await RunResolveCompletionItemAsync(
testLspServer,
clientCompletionItem,
new ClientCapabilities()).ConfigureAwait(false);
Assert.Equal(expected, results.Documentation.Value.Second.Value);
}
[Fact]
public async Task TestResolveCompletionItemWithPrefixSuffixAsync()
{
var markup =
@"class A
{
void M()
{
var a = 10;
a.{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var clientCompletionItem = await GetCompletionItemToResolveAsync<LSP.VSInternalCompletionItem>(testLspServer, locations, label: "(byte)").ConfigureAwait(false);
var results = (LSP.VSInternalCompletionItem)await RunResolveCompletionItemAsync(
testLspServer, clientCompletionItem).ConfigureAwait(false);
Assert.Equal("(byte)", results.Label);
Assert.NotNull(results.Description);
}
private static async Task<LSP.CompletionItem> RunResolveCompletionItemAsync(TestLspServer testLspServer, LSP.CompletionItem completionItem, LSP.ClientCapabilities clientCapabilities = null)
{
clientCapabilities ??= new LSP.VSInternalClientCapabilities { SupportsVisualStudioExtensions = true };
return await testLspServer.ExecuteRequestAsync<LSP.CompletionItem, LSP.CompletionItem>(LSP.Methods.TextDocumentCompletionResolveName,
completionItem, clientCapabilities, null, CancellationToken.None);
}
private static LSP.VSInternalCompletionItem CreateResolvedCompletionItem(
VSInternalCompletionItem completionItem,
ClassifiedTextElement description,
string detail,
string documentation)
{
completionItem.Detail = detail;
if (documentation != null)
{
completionItem.Documentation = new LSP.MarkupContent()
{
Kind = LSP.MarkupKind.PlainText,
Value = documentation
};
}
completionItem.Description = description;
return completionItem;
}
private static ClassifiedTextRun[] CreateClassifiedTextRunForClass(string className)
=> new ClassifiedTextRun[]
{
new ClassifiedTextRun("keyword", "class"),
new ClassifiedTextRun("whitespace", " "),
new ClassifiedTextRun("class name", className)
};
private static async Task<T> GetCompletionItemToResolveAsync<T>(
TestLspServer testLspServer,
Dictionary<string, IList<LSP.Location>> locations,
string label,
LSP.ClientCapabilities clientCapabilities = null) where T : LSP.CompletionItem
{
var completionParams = CreateCompletionParams(
locations["caret"].Single(), LSP.VSInternalCompletionInvokeKind.Explicit, "\0", LSP.CompletionTriggerKind.Invoked);
clientCapabilities ??= new LSP.VSInternalClientCapabilities { SupportsVisualStudioExtensions = true };
var completionList = await RunGetCompletionsAsync(testLspServer, completionParams, clientCapabilities);
if (clientCapabilities.HasCompletionListDataCapability())
{
var vsCompletionList = Assert.IsAssignableFrom<VSInternalCompletionList>(completionList);
Assert.NotNull(vsCompletionList.Data);
}
var serverCompletionItem = completionList.Items.FirstOrDefault(item => item.Label == label);
var clientCompletionItem = ConvertToClientCompletionItem((T)serverCompletionItem);
return clientCompletionItem;
}
private static async Task<LSP.CompletionList> RunGetCompletionsAsync(
TestLspServer testLspServer,
LSP.CompletionParams completionParams,
LSP.ClientCapabilities clientCapabilities)
{
var completionList = await testLspServer.ExecuteRequestAsync<LSP.CompletionParams, LSP.CompletionList>(LSP.Methods.TextDocumentCompletionName,
completionParams, clientCapabilities, null, CancellationToken.None);
// Emulate client behavior of promoting "Data" completion list properties onto completion items.
if (clientCapabilities.HasCompletionListDataCapability() &&
completionList is VSInternalCompletionList vsCompletionList &&
vsCompletionList.Data != null)
{
foreach (var completionItem in completionList.Items)
{
Assert.Null(completionItem.Data);
completionItem.Data = vsCompletionList.Data;
}
}
return completionList;
}
private static T ConvertToClientCompletionItem<T>(T serverCompletionItem) where T : LSP.CompletionItem
{
var serializedItem = JsonConvert.SerializeObject(serverCompletionItem);
var clientCompletionItem = JsonConvert.DeserializeObject<T>(serializedItem);
return clientCompletionItem;
}
private class TestCaretOutOfScopeCompletionService : CompletionService
{
public override string Language => LanguageNames.CSharp;
public override Task<CodeAnalysis.Completion.CompletionList> GetCompletionsAsync(
Document document,
int caretPosition,
CompletionTrigger trigger = default,
ImmutableHashSet<string> roles = null,
OptionSet options = null,
CancellationToken cancellationToken = default)
=> Task.FromResult(CodeAnalysis.Completion.CompletionList.Empty);
public override Task<CompletionChange> GetChangeAsync(
Document document,
CodeAnalysis.Completion.CompletionItem item,
char? commitCharacter = null,
CancellationToken cancellationToken = default)
{
var textChange = new TextChange(span: new TextSpan(start: 77, length: 9), newText: @"public override void M()
{
throw new System.NotImplementedException();
}");
return Task.FromResult(CompletionChange.Create(textChange, newPosition: 0));
}
}
}
}
| -1 |
dotnet/roslyn | 55,530 | Ignore modules with bad metadata in function resolver | Fixes https://github.com/dotnet/roslyn/issues/55475 | tmat | 2021-08-10T18:56:37Z | 2021-08-11T18:37:09Z | cd0c0464c069a2b80774d70f071c29333d9fa23c | bc874ebc5111a2a33221409f895953b1536f6612 | Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475 | ./src/Compilers/Test/Core/Platform/Desktop/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
#if NET472
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.Emit;
using Roslyn.Utilities;
namespace Roslyn.Test.Utilities.Desktop
{
internal static class SerializationInfoExtensions
{
public static void AddArray<T>(this SerializationInfo info, string name, ImmutableArray<T> value) where T : class
{
// we will copy the content into an array and serialize the copy
// we could serialize element-wise, but that would require serializing
// name and type for every serialized element which seems worse than creating a copy.
info.AddValue(name, value.IsDefault ? null : value.ToArray(), typeof(T[]));
}
public static ImmutableArray<T> GetArray<T>(this SerializationInfo info, string name) where T : class
{
var arr = (T[])info.GetValue(name, typeof(T[]));
return ImmutableArray.Create<T>(arr);
}
public static void AddByteArray(this SerializationInfo info, string name, ImmutableArray<byte> value)
{
// we will copy the content into an array and serialize the copy
// we could serialize element-wise, but that would require serializing
// name and type for every serialized element which seems worse than creating a copy.
info.AddValue(name, value.IsDefault ? null : value.ToArray(), typeof(byte[]));
}
public static ImmutableArray<byte> GetByteArray(this SerializationInfo info, string name)
{
var arr = (byte[])info.GetValue(name, typeof(byte[]));
return ImmutableArray.Create<byte>(arr);
}
}
}
#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.
#nullable disable
#if NET472
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.Emit;
using Roslyn.Utilities;
namespace Roslyn.Test.Utilities.Desktop
{
internal static class SerializationInfoExtensions
{
public static void AddArray<T>(this SerializationInfo info, string name, ImmutableArray<T> value) where T : class
{
// we will copy the content into an array and serialize the copy
// we could serialize element-wise, but that would require serializing
// name and type for every serialized element which seems worse than creating a copy.
info.AddValue(name, value.IsDefault ? null : value.ToArray(), typeof(T[]));
}
public static ImmutableArray<T> GetArray<T>(this SerializationInfo info, string name) where T : class
{
var arr = (T[])info.GetValue(name, typeof(T[]));
return ImmutableArray.Create<T>(arr);
}
public static void AddByteArray(this SerializationInfo info, string name, ImmutableArray<byte> value)
{
// we will copy the content into an array and serialize the copy
// we could serialize element-wise, but that would require serializing
// name and type for every serialized element which seems worse than creating a copy.
info.AddValue(name, value.IsDefault ? null : value.ToArray(), typeof(byte[]));
}
public static ImmutableArray<byte> GetByteArray(this SerializationInfo info, string name)
{
var arr = (byte[])info.GetValue(name, typeof(byte[]));
return ImmutableArray.Create<byte>(arr);
}
}
}
#endif
| -1 |
dotnet/roslyn | 55,530 | Ignore modules with bad metadata in function resolver | Fixes https://github.com/dotnet/roslyn/issues/55475 | tmat | 2021-08-10T18:56:37Z | 2021-08-11T18:37:09Z | cd0c0464c069a2b80774d70f071c29333d9fa23c | bc874ebc5111a2a33221409f895953b1536f6612 | Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475 | ./src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker_Patterns.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class NullableWalker
{
/// <summary>
/// Learn something about the input from a test of a given expression against a given pattern. The given
/// state is updated to note that any slots that are tested against `null` may be null.
/// </summary>
private void LearnFromAnyNullPatterns(
BoundExpression expression,
BoundPattern pattern)
{
int slot = MakeSlot(expression);
LearnFromAnyNullPatterns(slot, expression.Type, pattern);
}
private void VisitPatternForRewriting(BoundPattern pattern)
{
// Don't let anything under the pattern actually affect current state,
// as we're only visiting for nullable information.
Debug.Assert(!IsConditionalState);
var currentState = State;
VisitWithoutDiagnostics(pattern);
SetState(currentState);
}
public override BoundNode VisitPositionalSubpattern(BoundPositionalSubpattern node)
{
Visit(node.Pattern);
return null;
}
public override BoundNode VisitPropertySubpattern(BoundPropertySubpattern node)
{
Visit(node.Pattern);
return null;
}
public override BoundNode VisitRecursivePattern(BoundRecursivePattern node)
{
Visit(node.DeclaredType);
VisitAndUnsplitAll(node.Deconstruction);
VisitAndUnsplitAll(node.Properties);
Visit(node.VariableAccess);
return null;
}
public override BoundNode VisitConstantPattern(BoundConstantPattern node)
{
VisitRvalue(node.Value);
return null;
}
public override BoundNode VisitDeclarationPattern(BoundDeclarationPattern node)
{
Visit(node.VariableAccess);
Visit(node.DeclaredType);
return null;
}
public override BoundNode VisitDiscardPattern(BoundDiscardPattern node)
{
return null;
}
public override BoundNode VisitTypePattern(BoundTypePattern node)
{
Visit(node.DeclaredType);
return null;
}
public override BoundNode VisitRelationalPattern(BoundRelationalPattern node)
{
Visit(node.Value);
return null;
}
public override BoundNode VisitNegatedPattern(BoundNegatedPattern node)
{
Visit(node.Negated);
return null;
}
public override BoundNode VisitBinaryPattern(BoundBinaryPattern node)
{
Visit(node.Left);
Visit(node.Right);
return null;
}
public override BoundNode VisitITuplePattern(BoundITuplePattern node)
{
VisitAndUnsplitAll(node.Subpatterns);
return null;
}
/// <summary>
/// Learn from any constant null patterns appearing in the pattern.
/// </summary>
/// <param name="inputType">Type type of the input expression (before nullable analysis).
/// Used to determine which types can contain null.</param>
private void LearnFromAnyNullPatterns(
int inputSlot,
TypeSymbol inputType,
BoundPattern pattern)
{
if (inputSlot <= 0)
return;
// https://github.com/dotnet/roslyn/issues/35041 We only need to do this when we're rewriting, so we
// can get information for any nodes in the pattern.
VisitPatternForRewriting(pattern);
switch (pattern)
{
case BoundConstantPattern cp:
bool isExplicitNullCheck = cp.Value.ConstantValue == ConstantValue.Null;
if (isExplicitNullCheck)
{
// Since we're not branching on this null test here, we just infer the top level
// nullability. We'll branch on it later.
LearnFromNullTest(inputSlot, inputType, ref this.State, markDependentSlotsNotNull: false);
}
break;
case BoundDeclarationPattern _:
case BoundDiscardPattern _:
case BoundITuplePattern _:
case BoundRelationalPattern _:
break; // nothing to learn
case BoundTypePattern tp:
if (tp.IsExplicitNotNullTest)
{
LearnFromNullTest(inputSlot, inputType, ref this.State, markDependentSlotsNotNull: false);
}
break;
case BoundRecursivePattern rp:
{
if (rp.IsExplicitNotNullTest)
{
LearnFromNullTest(inputSlot, inputType, ref this.State, markDependentSlotsNotNull: false);
}
// for positional part: we only learn from tuples (not Deconstruct)
if (rp.DeconstructMethod is null && !rp.Deconstruction.IsDefault)
{
var elements = inputType.TupleElements;
for (int i = 0, n = Math.Min(rp.Deconstruction.Length, elements.IsDefault ? 0 : elements.Length); i < n; i++)
{
BoundSubpattern item = rp.Deconstruction[i];
FieldSymbol element = elements[i];
LearnFromAnyNullPatterns(GetOrCreateSlot(element, inputSlot), element.Type, item.Pattern);
}
}
// for property part
if (!rp.Properties.IsDefault)
{
foreach (BoundPropertySubpattern subpattern in rp.Properties)
{
if (subpattern.Member is BoundPropertySubpatternMember member)
{
LearnFromAnyNullPatterns(getExtendedPropertySlot(member, inputSlot), member.Type, subpattern.Pattern);
}
}
}
}
break;
case BoundNegatedPattern p:
LearnFromAnyNullPatterns(inputSlot, inputType, p.Negated);
break;
case BoundBinaryPattern p:
LearnFromAnyNullPatterns(inputSlot, inputType, p.Left);
LearnFromAnyNullPatterns(inputSlot, inputType, p.Right);
break;
default:
throw ExceptionUtilities.UnexpectedValue(pattern);
}
int getExtendedPropertySlot(BoundPropertySubpatternMember member, int inputSlot)
{
if (member.Symbol is null)
{
return -1;
}
if (member.Receiver is not null)
{
inputSlot = getExtendedPropertySlot(member.Receiver, inputSlot);
}
if (inputSlot < 0)
{
return inputSlot;
}
return GetOrCreateSlot(member.Symbol, inputSlot);
}
}
protected override LocalState VisitSwitchStatementDispatch(BoundSwitchStatement node)
{
// first, learn from any null tests in the patterns
int slot = node.Expression.IsSuppressed ? GetOrCreatePlaceholderSlot(node.Expression) : MakeSlot(node.Expression);
if (slot > 0)
{
var originalInputType = node.Expression.Type;
foreach (var section in node.SwitchSections)
{
foreach (var label in section.SwitchLabels)
{
LearnFromAnyNullPatterns(slot, originalInputType, label.Pattern);
}
}
}
// visit switch header
Visit(node.Expression);
var expressionState = ResultType;
DeclareLocals(node.InnerLocals);
foreach (var section in node.SwitchSections)
{
// locals can be alive across jumps in the switch sections, so we declare them early.
DeclareLocals(section.Locals);
}
var labelStateMap = LearnFromDecisionDag(node.Syntax, node.DecisionDag, node.Expression, expressionState, stateWhenNotNullOpt: null);
foreach (var section in node.SwitchSections)
{
foreach (var label in section.SwitchLabels)
{
var labelResult = labelStateMap.TryGetValue(label.Label, out var s1) ? s1 : (state: UnreachableState(), believedReachable: false);
SetState(labelResult.state);
PendingBranches.Add(new PendingBranch(label, this.State, label.Label));
}
}
var afterSwitchState = labelStateMap.TryGetValue(node.BreakLabel, out var stateAndReachable) ? stateAndReachable.state : UnreachableState();
labelStateMap.Free();
return afterSwitchState;
}
protected override void VisitSwitchSection(BoundSwitchSection node, bool isLastSection)
{
TakeIncrementalSnapshot(node);
SetState(UnreachableState());
foreach (var label in node.SwitchLabels)
{
TakeIncrementalSnapshot(label);
VisitPatternForRewriting(label.Pattern);
VisitLabel(label.Label, node);
}
VisitStatementList(node);
}
private struct PossiblyConditionalState
{
public LocalState State;
public LocalState StateWhenTrue;
public LocalState StateWhenFalse;
public bool IsConditionalState;
public PossiblyConditionalState(LocalState stateWhenTrue, LocalState stateWhenFalse)
{
StateWhenTrue = stateWhenTrue.Clone();
StateWhenFalse = stateWhenFalse.Clone();
IsConditionalState = true;
State = default;
}
public PossiblyConditionalState(LocalState state)
{
StateWhenTrue = StateWhenFalse = default;
IsConditionalState = false;
State = state.Clone();
}
public static PossiblyConditionalState Create(NullableWalker nullableWalker)
{
return nullableWalker.IsConditionalState
? new PossiblyConditionalState(nullableWalker.StateWhenTrue, nullableWalker.StateWhenFalse)
: new PossiblyConditionalState(nullableWalker.State);
}
public PossiblyConditionalState Clone()
{
return IsConditionalState
? new PossiblyConditionalState(StateWhenTrue, StateWhenFalse)
: new PossiblyConditionalState(State);
}
}
private PooledDictionary<LabelSymbol, (LocalState state, bool believedReachable)> LearnFromDecisionDag(
SyntaxNode node,
BoundDecisionDag decisionDag,
BoundExpression expression,
TypeWithState expressionType,
PossiblyConditionalState? stateWhenNotNullOpt)
{
// We reuse the slot at the beginning of a switch (or is-pattern expression), pretending that we are
// not copying the input to evaluate the patterns. In this way we infer non-nullability of the original
// variable's parts based on matched pattern parts. Mutations in `when` clauses can show the inaccuracy
// of analysis based on this choice.
var rootTemp = BoundDagTemp.ForOriginalInput(expression);
int originalInputSlot = MakeSlot(expression);
if (originalInputSlot <= 0)
{
originalInputSlot = makeDagTempSlot(expressionType.ToTypeWithAnnotations(compilation), rootTemp);
}
Debug.Assert(originalInputSlot > 0);
// If the input of the switch (or is-pattern expression) is a tuple literal, we reuse the slots of
// those expressions (when possible), pretending that we are not copying them into a temporary ValueTuple instance
// to evaluate the patterns. In this way we infer non-nullability of the original element's parts.
// We do not extend such courtesy to nested tuple literals.
var originalInputElementSlots = expression is BoundTupleExpression tuple
? tuple.Arguments.SelectAsArray(static (a, w) => w.MakeSlot(a), this)
: default;
var originalInputMap = PooledDictionary<int, BoundExpression>.GetInstance();
originalInputMap.Add(originalInputSlot, expression);
var tempMap = PooledDictionary<BoundDagTemp, (int slot, TypeSymbol type)>.GetInstance();
Debug.Assert(isDerivedType(NominalSlotType(originalInputSlot), expressionType.Type));
tempMap.Add(rootTemp, (originalInputSlot, expressionType.Type));
var nodeStateMap = PooledDictionary<BoundDecisionDagNode, (PossiblyConditionalState state, bool believedReachable)>.GetInstance();
nodeStateMap.Add(decisionDag.RootNode, (state: PossiblyConditionalState.Create(this), believedReachable: true));
var labelStateMap = PooledDictionary<LabelSymbol, (LocalState state, bool believedReachable)>.GetInstance();
foreach (var dagNode in decisionDag.TopologicallySortedNodes)
{
bool found = nodeStateMap.TryGetValue(dagNode, out var nodeStateAndBelievedReachable);
Debug.Assert(found); // the topologically sorted nodes should contain only reachable nodes
(PossiblyConditionalState nodeState, bool nodeBelievedReachable) = nodeStateAndBelievedReachable;
if (nodeState.IsConditionalState)
{
SetConditionalState(nodeState.StateWhenTrue, nodeState.StateWhenFalse);
}
else
{
SetState(nodeState.State);
}
switch (dagNode)
{
case BoundEvaluationDecisionDagNode p:
{
var evaluation = p.Evaluation;
(int inputSlot, TypeSymbol inputType) = tempMap.TryGetValue(evaluation.Input, out var slotAndType) ? slotAndType : throw ExceptionUtilities.Unreachable;
Debug.Assert(inputSlot > 0);
switch (evaluation)
{
case BoundDagDeconstructEvaluation e:
{
// https://github.com/dotnet/roslyn/issues/34232
// We may need to recompute the Deconstruct method for a deconstruction if
// the receiver type has changed (e.g. its nested nullability).
var method = e.DeconstructMethod;
int extensionExtra = method.RequiresInstanceReceiver ? 0 : 1;
for (int i = 0; i < method.ParameterCount - extensionExtra; i++)
{
var parameterType = method.Parameters[i + extensionExtra].TypeWithAnnotations;
var output = new BoundDagTemp(e.Syntax, parameterType.Type, e, i);
int outputSlot = makeDagTempSlot(parameterType, output);
Debug.Assert(outputSlot > 0);
addToTempMap(output, outputSlot, parameterType.Type);
}
break;
}
case BoundDagTypeEvaluation e:
{
var output = new BoundDagTemp(e.Syntax, e.Type, e);
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
int outputSlot;
switch (_conversions.WithNullability(false).ClassifyConversionFromType(inputType, e.Type, ref discardedUseSiteInfo).Kind)
{
case ConversionKind.Identity:
case ConversionKind.ImplicitReference:
outputSlot = inputSlot;
break;
case ConversionKind.ExplicitNullable when AreNullableAndUnderlyingTypes(inputType, e.Type, out _):
outputSlot = GetNullableOfTValueSlot(inputType, inputSlot, out _, forceSlotEvenIfEmpty: true);
if (outputSlot < 0)
goto default;
break;
default:
outputSlot = makeDagTempSlot(TypeWithAnnotations.Create(e.Type, NullableAnnotation.NotAnnotated), output);
break;
}
Debug.Assert(!IsConditionalState);
Unsplit();
State[outputSlot] = NullableFlowState.NotNull;
addToTempMap(output, outputSlot, e.Type);
break;
}
case BoundDagFieldEvaluation e:
{
Debug.Assert(inputSlot > 0);
var field = (FieldSymbol)AsMemberOfType(inputType, e.Field);
var type = field.TypeWithAnnotations;
var output = new BoundDagTemp(e.Syntax, type.Type, e);
int outputSlot = -1;
var originalTupleElement = e.Input.IsOriginalInput && !originalInputElementSlots.IsDefault
? field
: null;
if (originalTupleElement is not null)
{
// Re-use the slot of the element/expression if possible
outputSlot = originalInputElementSlots[originalTupleElement.TupleElementIndex];
}
if (outputSlot <= 0)
{
outputSlot = GetOrCreateSlot(field, inputSlot, forceSlotEvenIfEmpty: true);
if (originalTupleElement is not null && outputSlot > 0)
{
// The expression in the tuple could not be assigned a slot (for example, `a?.b`),
// so we had to create a slot for the tuple element instead.
// We'll remember that so that we can apply any learnings to the expression.
if (!originalInputMap.ContainsKey(outputSlot))
{
originalInputMap.Add(outputSlot,
((BoundTupleExpression)expression).Arguments[originalTupleElement.TupleElementIndex]);
}
else
{
Debug.Assert(originalInputMap[outputSlot] == ((BoundTupleExpression)expression).Arguments[originalTupleElement.TupleElementIndex]);
}
}
}
if (outputSlot <= 0)
{
outputSlot = makeDagTempSlot(type, output);
}
Debug.Assert(outputSlot > 0);
addToTempMap(output, outputSlot, type.Type);
break;
}
case BoundDagPropertyEvaluation e:
{
Debug.Assert(inputSlot > 0);
var property = (PropertySymbol)AsMemberOfType(inputType, e.Property);
var type = property.TypeWithAnnotations;
var output = new BoundDagTemp(e.Syntax, type.Type, e);
int outputSlot = GetOrCreateSlot(property, inputSlot, forceSlotEvenIfEmpty: true);
if (outputSlot <= 0)
{
outputSlot = makeDagTempSlot(type, output);
}
Debug.Assert(outputSlot > 0);
addToTempMap(output, outputSlot, type.Type);
if (property.GetMethod is not null)
{
// A property evaluation splits the state if MemberNotNullWhen is used
ApplyMemberPostConditions(inputSlot, property.GetMethod);
}
break;
}
case BoundDagIndexEvaluation e:
{
var type = TypeWithAnnotations.Create(e.Property.Type, NullableAnnotation.Annotated);
var output = new BoundDagTemp(e.Syntax, type.Type, e);
int outputSlot = makeDagTempSlot(type, output);
Debug.Assert(outputSlot > 0);
addToTempMap(output, outputSlot, type.Type);
break;
}
default:
throw ExceptionUtilities.UnexpectedValue(p.Evaluation.Kind);
}
gotoNodeWithCurrentState(p.Next, nodeBelievedReachable);
break;
}
case BoundTestDecisionDagNode p:
{
var test = p.Test;
bool foundTemp = tempMap.TryGetValue(test.Input, out var slotAndType);
Debug.Assert(foundTemp);
(int inputSlot, TypeSymbol inputType) = slotAndType;
Debug.Assert(test is not BoundDagNonNullTest || !IsConditionalState);
Split();
switch (test)
{
case BoundDagTypeTest:
if (inputSlot > 0)
{
learnFromNonNullTest(inputSlot, ref this.StateWhenTrue);
}
gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable);
gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable);
break;
case BoundDagNonNullTest t:
var inputMaybeNull = this.StateWhenTrue[inputSlot].MayBeNull();
if (inputSlot > 0)
{
MarkDependentSlotsNotNull(inputSlot, inputType, ref this.StateWhenFalse);
if (t.IsExplicitTest)
{
LearnFromNullTest(inputSlot, inputType, ref this.StateWhenFalse, markDependentSlotsNotNull: false);
}
learnFromNonNullTest(inputSlot, ref this.StateWhenTrue);
}
gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable);
gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable & inputMaybeNull);
break;
case BoundDagExplicitNullTest _:
if (inputSlot > 0)
{
LearnFromNullTest(inputSlot, inputType, ref this.StateWhenTrue, markDependentSlotsNotNull: true);
learnFromNonNullTest(inputSlot, ref this.StateWhenFalse);
}
gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable);
gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable);
break;
case BoundDagValueTest t:
Debug.Assert(t.Value != ConstantValue.Null);
// When we compare `bool?` inputs to bool constants, we follow a graph roughly like the following:
// [0]: t0 != null ? [1] : [5]
// [1]: t1 = (bool)t0; [2]
// [2] (this node): t1 == boolConstant ? [3] : [4]
// ...(remaining states)
if (stateWhenNotNullOpt is { } stateWhenNotNull
&& t.Input.Source is BoundDagTypeEvaluation { Input: { IsOriginalInput: true } })
{
SetPossiblyConditionalState(stateWhenNotNull);
Split();
}
else if (inputSlot > 0)
{
learnFromNonNullTest(inputSlot, ref this.StateWhenTrue);
}
bool isFalseTest = t.Value == ConstantValue.False;
gotoNode(p.WhenTrue, isFalseTest ? this.StateWhenFalse : this.StateWhenTrue, nodeBelievedReachable);
gotoNode(p.WhenFalse, isFalseTest ? this.StateWhenTrue : this.StateWhenFalse, nodeBelievedReachable);
break;
case BoundDagRelationalTest _:
if (inputSlot > 0)
{
learnFromNonNullTest(inputSlot, ref this.StateWhenTrue);
}
gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable);
gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable);
break;
default:
throw ExceptionUtilities.UnexpectedValue(test.Kind);
}
break;
}
case BoundLeafDecisionDagNode d:
// We have one leaf decision dag node per reachable label
Unsplit(); // Could be split in pathological cases like `false switch { ... }`
labelStateMap.Add(d.Label, (this.State, nodeBelievedReachable));
break;
case BoundWhenDecisionDagNode w:
// bind the pattern variables, inferring their types as well
Unsplit();
foreach (var binding in w.Bindings)
{
var variableAccess = binding.VariableAccess;
var tempSource = binding.TempContainingValue;
var foundTemp = tempMap.TryGetValue(tempSource, out var tempSlotAndType);
if (foundTemp) // in erroneous programs, we might not have seen a temp defined.
{
var (tempSlot, tempType) = tempSlotAndType;
var tempState = this.State[tempSlot];
if (variableAccess is BoundLocal { LocalSymbol: SourceLocalSymbol local } boundLocal)
{
var value = TypeWithState.Create(tempType, tempState);
var inferredType = value.ToTypeWithAnnotations(compilation, asAnnotatedType: boundLocal.DeclarationKind == BoundLocalDeclarationKind.WithInferredType);
if (_variables.TryGetType(local, out var existingType))
{
// merge inferred nullable annotation from different branches of the decision tree
inferredType = TypeWithAnnotations.Create(inferredType.Type, existingType.NullableAnnotation.Join(inferredType.NullableAnnotation));
}
_variables.SetType(local, inferredType);
int localSlot = GetOrCreateSlot(local, forceSlotEvenIfEmpty: true);
if (localSlot > 0)
{
TrackNullableStateForAssignment(valueOpt: null, inferredType, localSlot, TypeWithState.Create(tempType, tempState), tempSlot);
}
}
else
{
// https://github.com/dotnet/roslyn/issues/34144 perform inference for top-level var-declared fields in scripts
}
}
}
if (w.WhenExpression != null && w.WhenExpression.ConstantValue != ConstantValue.True)
{
VisitCondition(w.WhenExpression);
Debug.Assert(this.IsConditionalState);
gotoNode(w.WhenTrue, this.StateWhenTrue, nodeBelievedReachable);
gotoNode(w.WhenFalse, this.StateWhenFalse, nodeBelievedReachable);
}
else
{
Debug.Assert(w.WhenFalse is null);
gotoNode(w.WhenTrue, this.State, nodeBelievedReachable);
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(dagNode.Kind);
}
}
SetUnreachable(); // the decision dag is always complete (no fall-through)
originalInputMap.Free();
tempMap.Free();
nodeStateMap.Free();
return labelStateMap;
void learnFromNonNullTest(int inputSlot, ref LocalState state)
{
if (stateWhenNotNullOpt is { } stateWhenNotNull && inputSlot == originalInputSlot)
{
state = CloneAndUnsplit(ref stateWhenNotNull);
}
LearnFromNonNullTest(inputSlot, ref state);
if (originalInputMap.TryGetValue(inputSlot, out var expression))
LearnFromNonNullTest(expression, ref state);
}
void addToTempMap(BoundDagTemp output, int slot, TypeSymbol type)
{
// We need to track all dag temps, so there should be a slot
Debug.Assert(slot > 0);
if (tempMap.TryGetValue(output, out var outputSlotAndType))
{
// The dag temp has already been allocated on another branch of the dag
Debug.Assert(outputSlotAndType.slot == slot);
Debug.Assert(isDerivedType(outputSlotAndType.type, type));
}
else
{
Debug.Assert(NominalSlotType(slot) is var slotType && (slotType.IsErrorType() || isDerivedType(slotType, type)));
tempMap.Add(output, (slot, type));
}
}
bool isDerivedType(TypeSymbol derivedType, TypeSymbol baseType)
{
if (derivedType.IsErrorType() || baseType.IsErrorType())
return true;
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
return _conversions.WithNullability(false).ClassifyConversionFromType(derivedType, baseType, ref discardedUseSiteInfo).Kind switch
{
ConversionKind.Identity => true,
ConversionKind.ImplicitReference => true,
ConversionKind.Boxing => true,
_ => false,
};
}
void gotoNodeWithCurrentState(BoundDecisionDagNode node, bool believedReachable)
{
if (nodeStateMap.TryGetValue(node, out var stateAndReachable))
{
switch (IsConditionalState, stateAndReachable.state.IsConditionalState)
{
case (true, true):
Debug.Assert(false);
Join(ref this.StateWhenTrue, ref stateAndReachable.state.StateWhenTrue);
Join(ref this.StateWhenFalse, ref stateAndReachable.state.StateWhenFalse);
break;
case (true, false):
Debug.Assert(false);
Join(ref this.StateWhenTrue, ref stateAndReachable.state.State);
Join(ref this.StateWhenFalse, ref stateAndReachable.state.State);
break;
case (false, true):
Debug.Assert(false);
Split();
Join(ref this.StateWhenTrue, ref stateAndReachable.state.StateWhenTrue);
Join(ref this.StateWhenFalse, ref stateAndReachable.state.StateWhenFalse);
break;
case (false, false):
Join(ref this.State, ref stateAndReachable.state.State);
break;
}
believedReachable |= stateAndReachable.believedReachable;
}
nodeStateMap[node] = (PossiblyConditionalState.Create(this), believedReachable);
}
void gotoNode(BoundDecisionDagNode node, LocalState state, bool believedReachable)
{
PossiblyConditionalState result;
if (nodeStateMap.TryGetValue(node, out var stateAndReachable))
{
result = stateAndReachable.state;
switch (result.IsConditionalState)
{
case true:
Debug.Assert(false);
Join(ref result.StateWhenTrue, ref state);
Join(ref result.StateWhenFalse, ref state);
break;
case false:
Join(ref result.State, ref state);
break;
}
believedReachable |= stateAndReachable.believedReachable;
}
else
{
result = new PossiblyConditionalState(state);
}
nodeStateMap[node] = (result, believedReachable);
}
int makeDagTempSlot(TypeWithAnnotations type, BoundDagTemp temp)
{
object slotKey = (node, temp);
return GetOrCreatePlaceholderSlot(slotKey, type);
}
}
public override BoundNode VisitConvertedSwitchExpression(BoundConvertedSwitchExpression node)
{
bool inferType = !node.WasTargetTyped;
VisitSwitchExpressionCore(node, inferType);
return null;
}
public override BoundNode VisitUnconvertedSwitchExpression(BoundUnconvertedSwitchExpression node)
{
// This method is only involved in method inference with unbound lambdas.
VisitSwitchExpressionCore(node, inferType: true);
return null;
}
private void VisitSwitchExpressionCore(BoundSwitchExpression node, bool inferType)
{
// first, learn from any null tests in the patterns
int slot = node.Expression.IsSuppressed ? GetOrCreatePlaceholderSlot(node.Expression) : MakeSlot(node.Expression);
if (slot > 0)
{
var originalInputType = node.Expression.Type;
foreach (var arm in node.SwitchArms)
{
LearnFromAnyNullPatterns(slot, originalInputType, arm.Pattern);
}
}
Visit(node.Expression);
var expressionState = ResultType;
var labelStateMap = LearnFromDecisionDag(node.Syntax, node.DecisionDag, node.Expression, expressionState, stateWhenNotNullOpt: null);
var endState = UnreachableState();
if (!node.ReportedNotExhaustive && node.DefaultLabel != null &&
labelStateMap.TryGetValue(node.DefaultLabel, out var defaultLabelState) && defaultLabelState.believedReachable)
{
SetState(defaultLabelState.state);
var nodes = node.DecisionDag.TopologicallySortedNodes;
var leaf = nodes.Where(n => n is BoundLeafDecisionDagNode leaf && leaf.Label == node.DefaultLabel).First();
var samplePattern = PatternExplainer.SamplePatternForPathToDagNode(
BoundDagTemp.ForOriginalInput(node.Expression), nodes, leaf, nullPaths: true, out bool requiresFalseWhenClause, out _);
ErrorCode warningCode = requiresFalseWhenClause ? ErrorCode.WRN_SwitchExpressionNotExhaustiveForNullWithWhen : ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull;
ReportDiagnostic(
warningCode,
((SwitchExpressionSyntax)node.Syntax).SwitchKeyword.GetLocation(),
samplePattern);
}
// collect expressions, conversions and result types
int numSwitchArms = node.SwitchArms.Length;
var conversions = ArrayBuilder<Conversion>.GetInstance(numSwitchArms);
var resultTypes = ArrayBuilder<TypeWithState>.GetInstance(numSwitchArms);
var expressions = ArrayBuilder<BoundExpression>.GetInstance(numSwitchArms);
var placeholderBuilder = ArrayBuilder<BoundExpression>.GetInstance(numSwitchArms);
foreach (var arm in node.SwitchArms)
{
SetState(getStateForArm(arm));
// https://github.com/dotnet/roslyn/issues/35836 Is this where we want to take the snapshot?
TakeIncrementalSnapshot(arm);
VisitPatternForRewriting(arm.Pattern);
(BoundExpression expression, Conversion conversion) = RemoveConversion(arm.Value, includeExplicitConversions: false);
SnapshotWalkerThroughConversionGroup(arm.Value, expression);
expressions.Add(expression);
conversions.Add(conversion);
var armType = VisitRvalueWithState(expression);
resultTypes.Add(armType);
Join(ref endState, ref this.State);
// Build placeholders for inference in order to preserve annotations.
placeholderBuilder.Add(CreatePlaceholderIfNecessary(expression, armType.ToTypeWithAnnotations(compilation)));
}
var placeholders = placeholderBuilder.ToImmutableAndFree();
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
TypeSymbol inferredType =
(inferType ? BestTypeInferrer.InferBestType(placeholders, _conversions, ref discardedUseSiteInfo) : null)
?? node.Type?.SetUnknownNullabilityForReferenceTypes();
var inferredTypeWithAnnotations = TypeWithAnnotations.Create(inferredType);
NullableFlowState inferredState;
if (inferType)
{
if (inferredType is null)
{
// This can happen when we're inferring the return type of a lambda, or when there are no arms (an error case).
// For this case, we don't need to do any work, as the unconverted switch expression can't contribute info, and
// there is nothing that is being publicly exposed to the semantic model.
Debug.Assert((node is BoundUnconvertedSwitchExpression && _returnTypesOpt is not null)
|| node is BoundSwitchExpression { SwitchArms: { Length: 0 } });
inferredState = default;
}
else
{
for (int i = 0; i < numSwitchArms; i++)
{
var nodeForSyntax = expressions[i];
var arm = node.SwitchArms[i];
var armState = getStateForArm(arm);
resultTypes[i] = ConvertConditionalOperandOrSwitchExpressionArmResult(arm.Value, nodeForSyntax, conversions[i], inferredTypeWithAnnotations, resultTypes[i], armState, armState.Reachable);
}
inferredState = BestTypeInferrer.GetNullableState(resultTypes);
}
}
else
{
var states = ArrayBuilder<(LocalState, TypeWithState, bool)>.GetInstance(numSwitchArms);
for (int i = 0; i < numSwitchArms; i++)
{
var nodeForSyntax = expressions[i];
var armState = getStateForArm(node.SwitchArms[i]);
states.Add((armState, resultTypes[i], armState.Reachable));
}
ConditionalInfoForConversion.Add(node, states.ToImmutableAndFree());
inferredState = BestTypeInferrer.GetNullableState(resultTypes);
}
var resultType = TypeWithState.Create(inferredType, inferredState);
conversions.Free();
resultTypes.Free();
expressions.Free();
labelStateMap.Free();
SetState(endState);
SetResult(node, resultType, inferredTypeWithAnnotations);
LocalState getStateForArm(BoundSwitchExpressionArm arm)
=> !arm.Pattern.HasErrors && labelStateMap.TryGetValue(arm.Label, out var labelState) ? labelState.state : UnreachableState();
}
public override BoundNode VisitIsPatternExpression(BoundIsPatternExpression node)
{
Debug.Assert(!IsConditionalState);
LearnFromAnyNullPatterns(node.Expression, node.Pattern);
VisitPatternForRewriting(node.Pattern);
var hasStateWhenNotNull = VisitPossibleConditionalAccess(node.Expression, out var conditionalStateWhenNotNull);
var expressionState = ResultType;
var labelStateMap = LearnFromDecisionDag(node.Syntax, node.DecisionDag, node.Expression, expressionState, hasStateWhenNotNull ? conditionalStateWhenNotNull : null);
var trueState = labelStateMap.TryGetValue(node.IsNegated ? node.WhenFalseLabel : node.WhenTrueLabel, out var s1) ? s1.state : UnreachableState();
var falseState = labelStateMap.TryGetValue(node.IsNegated ? node.WhenTrueLabel : node.WhenFalseLabel, out var s2) ? s2.state : UnreachableState();
labelStateMap.Free();
SetConditionalState(trueState, falseState);
SetNotNullResult(node);
return null;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class NullableWalker
{
/// <summary>
/// Learn something about the input from a test of a given expression against a given pattern. The given
/// state is updated to note that any slots that are tested against `null` may be null.
/// </summary>
private void LearnFromAnyNullPatterns(
BoundExpression expression,
BoundPattern pattern)
{
int slot = MakeSlot(expression);
LearnFromAnyNullPatterns(slot, expression.Type, pattern);
}
private void VisitPatternForRewriting(BoundPattern pattern)
{
// Don't let anything under the pattern actually affect current state,
// as we're only visiting for nullable information.
Debug.Assert(!IsConditionalState);
var currentState = State;
VisitWithoutDiagnostics(pattern);
SetState(currentState);
}
public override BoundNode VisitPositionalSubpattern(BoundPositionalSubpattern node)
{
Visit(node.Pattern);
return null;
}
public override BoundNode VisitPropertySubpattern(BoundPropertySubpattern node)
{
Visit(node.Pattern);
return null;
}
public override BoundNode VisitRecursivePattern(BoundRecursivePattern node)
{
Visit(node.DeclaredType);
VisitAndUnsplitAll(node.Deconstruction);
VisitAndUnsplitAll(node.Properties);
Visit(node.VariableAccess);
return null;
}
public override BoundNode VisitConstantPattern(BoundConstantPattern node)
{
VisitRvalue(node.Value);
return null;
}
public override BoundNode VisitDeclarationPattern(BoundDeclarationPattern node)
{
Visit(node.VariableAccess);
Visit(node.DeclaredType);
return null;
}
public override BoundNode VisitDiscardPattern(BoundDiscardPattern node)
{
return null;
}
public override BoundNode VisitTypePattern(BoundTypePattern node)
{
Visit(node.DeclaredType);
return null;
}
public override BoundNode VisitRelationalPattern(BoundRelationalPattern node)
{
Visit(node.Value);
return null;
}
public override BoundNode VisitNegatedPattern(BoundNegatedPattern node)
{
Visit(node.Negated);
return null;
}
public override BoundNode VisitBinaryPattern(BoundBinaryPattern node)
{
Visit(node.Left);
Visit(node.Right);
return null;
}
public override BoundNode VisitITuplePattern(BoundITuplePattern node)
{
VisitAndUnsplitAll(node.Subpatterns);
return null;
}
/// <summary>
/// Learn from any constant null patterns appearing in the pattern.
/// </summary>
/// <param name="inputType">Type type of the input expression (before nullable analysis).
/// Used to determine which types can contain null.</param>
private void LearnFromAnyNullPatterns(
int inputSlot,
TypeSymbol inputType,
BoundPattern pattern)
{
if (inputSlot <= 0)
return;
// https://github.com/dotnet/roslyn/issues/35041 We only need to do this when we're rewriting, so we
// can get information for any nodes in the pattern.
VisitPatternForRewriting(pattern);
switch (pattern)
{
case BoundConstantPattern cp:
bool isExplicitNullCheck = cp.Value.ConstantValue == ConstantValue.Null;
if (isExplicitNullCheck)
{
// Since we're not branching on this null test here, we just infer the top level
// nullability. We'll branch on it later.
LearnFromNullTest(inputSlot, inputType, ref this.State, markDependentSlotsNotNull: false);
}
break;
case BoundDeclarationPattern _:
case BoundDiscardPattern _:
case BoundITuplePattern _:
case BoundRelationalPattern _:
break; // nothing to learn
case BoundTypePattern tp:
if (tp.IsExplicitNotNullTest)
{
LearnFromNullTest(inputSlot, inputType, ref this.State, markDependentSlotsNotNull: false);
}
break;
case BoundRecursivePattern rp:
{
if (rp.IsExplicitNotNullTest)
{
LearnFromNullTest(inputSlot, inputType, ref this.State, markDependentSlotsNotNull: false);
}
// for positional part: we only learn from tuples (not Deconstruct)
if (rp.DeconstructMethod is null && !rp.Deconstruction.IsDefault)
{
var elements = inputType.TupleElements;
for (int i = 0, n = Math.Min(rp.Deconstruction.Length, elements.IsDefault ? 0 : elements.Length); i < n; i++)
{
BoundSubpattern item = rp.Deconstruction[i];
FieldSymbol element = elements[i];
LearnFromAnyNullPatterns(GetOrCreateSlot(element, inputSlot), element.Type, item.Pattern);
}
}
// for property part
if (!rp.Properties.IsDefault)
{
foreach (BoundPropertySubpattern subpattern in rp.Properties)
{
if (subpattern.Member is BoundPropertySubpatternMember member)
{
LearnFromAnyNullPatterns(getExtendedPropertySlot(member, inputSlot), member.Type, subpattern.Pattern);
}
}
}
}
break;
case BoundNegatedPattern p:
LearnFromAnyNullPatterns(inputSlot, inputType, p.Negated);
break;
case BoundBinaryPattern p:
LearnFromAnyNullPatterns(inputSlot, inputType, p.Left);
LearnFromAnyNullPatterns(inputSlot, inputType, p.Right);
break;
default:
throw ExceptionUtilities.UnexpectedValue(pattern);
}
int getExtendedPropertySlot(BoundPropertySubpatternMember member, int inputSlot)
{
if (member.Symbol is null)
{
return -1;
}
if (member.Receiver is not null)
{
inputSlot = getExtendedPropertySlot(member.Receiver, inputSlot);
}
if (inputSlot < 0)
{
return inputSlot;
}
return GetOrCreateSlot(member.Symbol, inputSlot);
}
}
protected override LocalState VisitSwitchStatementDispatch(BoundSwitchStatement node)
{
// first, learn from any null tests in the patterns
int slot = node.Expression.IsSuppressed ? GetOrCreatePlaceholderSlot(node.Expression) : MakeSlot(node.Expression);
if (slot > 0)
{
var originalInputType = node.Expression.Type;
foreach (var section in node.SwitchSections)
{
foreach (var label in section.SwitchLabels)
{
LearnFromAnyNullPatterns(slot, originalInputType, label.Pattern);
}
}
}
// visit switch header
Visit(node.Expression);
var expressionState = ResultType;
DeclareLocals(node.InnerLocals);
foreach (var section in node.SwitchSections)
{
// locals can be alive across jumps in the switch sections, so we declare them early.
DeclareLocals(section.Locals);
}
var labelStateMap = LearnFromDecisionDag(node.Syntax, node.DecisionDag, node.Expression, expressionState, stateWhenNotNullOpt: null);
foreach (var section in node.SwitchSections)
{
foreach (var label in section.SwitchLabels)
{
var labelResult = labelStateMap.TryGetValue(label.Label, out var s1) ? s1 : (state: UnreachableState(), believedReachable: false);
SetState(labelResult.state);
PendingBranches.Add(new PendingBranch(label, this.State, label.Label));
}
}
var afterSwitchState = labelStateMap.TryGetValue(node.BreakLabel, out var stateAndReachable) ? stateAndReachable.state : UnreachableState();
labelStateMap.Free();
return afterSwitchState;
}
protected override void VisitSwitchSection(BoundSwitchSection node, bool isLastSection)
{
TakeIncrementalSnapshot(node);
SetState(UnreachableState());
foreach (var label in node.SwitchLabels)
{
TakeIncrementalSnapshot(label);
VisitPatternForRewriting(label.Pattern);
VisitLabel(label.Label, node);
}
VisitStatementList(node);
}
private struct PossiblyConditionalState
{
public LocalState State;
public LocalState StateWhenTrue;
public LocalState StateWhenFalse;
public bool IsConditionalState;
public PossiblyConditionalState(LocalState stateWhenTrue, LocalState stateWhenFalse)
{
StateWhenTrue = stateWhenTrue.Clone();
StateWhenFalse = stateWhenFalse.Clone();
IsConditionalState = true;
State = default;
}
public PossiblyConditionalState(LocalState state)
{
StateWhenTrue = StateWhenFalse = default;
IsConditionalState = false;
State = state.Clone();
}
public static PossiblyConditionalState Create(NullableWalker nullableWalker)
{
return nullableWalker.IsConditionalState
? new PossiblyConditionalState(nullableWalker.StateWhenTrue, nullableWalker.StateWhenFalse)
: new PossiblyConditionalState(nullableWalker.State);
}
public PossiblyConditionalState Clone()
{
return IsConditionalState
? new PossiblyConditionalState(StateWhenTrue, StateWhenFalse)
: new PossiblyConditionalState(State);
}
}
private PooledDictionary<LabelSymbol, (LocalState state, bool believedReachable)> LearnFromDecisionDag(
SyntaxNode node,
BoundDecisionDag decisionDag,
BoundExpression expression,
TypeWithState expressionType,
PossiblyConditionalState? stateWhenNotNullOpt)
{
// We reuse the slot at the beginning of a switch (or is-pattern expression), pretending that we are
// not copying the input to evaluate the patterns. In this way we infer non-nullability of the original
// variable's parts based on matched pattern parts. Mutations in `when` clauses can show the inaccuracy
// of analysis based on this choice.
var rootTemp = BoundDagTemp.ForOriginalInput(expression);
int originalInputSlot = MakeSlot(expression);
if (originalInputSlot <= 0)
{
originalInputSlot = makeDagTempSlot(expressionType.ToTypeWithAnnotations(compilation), rootTemp);
}
Debug.Assert(originalInputSlot > 0);
// If the input of the switch (or is-pattern expression) is a tuple literal, we reuse the slots of
// those expressions (when possible), pretending that we are not copying them into a temporary ValueTuple instance
// to evaluate the patterns. In this way we infer non-nullability of the original element's parts.
// We do not extend such courtesy to nested tuple literals.
var originalInputElementSlots = expression is BoundTupleExpression tuple
? tuple.Arguments.SelectAsArray(static (a, w) => w.MakeSlot(a), this)
: default;
var originalInputMap = PooledDictionary<int, BoundExpression>.GetInstance();
originalInputMap.Add(originalInputSlot, expression);
var tempMap = PooledDictionary<BoundDagTemp, (int slot, TypeSymbol type)>.GetInstance();
Debug.Assert(isDerivedType(NominalSlotType(originalInputSlot), expressionType.Type));
tempMap.Add(rootTemp, (originalInputSlot, expressionType.Type));
var nodeStateMap = PooledDictionary<BoundDecisionDagNode, (PossiblyConditionalState state, bool believedReachable)>.GetInstance();
nodeStateMap.Add(decisionDag.RootNode, (state: PossiblyConditionalState.Create(this), believedReachable: true));
var labelStateMap = PooledDictionary<LabelSymbol, (LocalState state, bool believedReachable)>.GetInstance();
foreach (var dagNode in decisionDag.TopologicallySortedNodes)
{
bool found = nodeStateMap.TryGetValue(dagNode, out var nodeStateAndBelievedReachable);
Debug.Assert(found); // the topologically sorted nodes should contain only reachable nodes
(PossiblyConditionalState nodeState, bool nodeBelievedReachable) = nodeStateAndBelievedReachable;
if (nodeState.IsConditionalState)
{
SetConditionalState(nodeState.StateWhenTrue, nodeState.StateWhenFalse);
}
else
{
SetState(nodeState.State);
}
switch (dagNode)
{
case BoundEvaluationDecisionDagNode p:
{
var evaluation = p.Evaluation;
(int inputSlot, TypeSymbol inputType) = tempMap.TryGetValue(evaluation.Input, out var slotAndType) ? slotAndType : throw ExceptionUtilities.Unreachable;
Debug.Assert(inputSlot > 0);
switch (evaluation)
{
case BoundDagDeconstructEvaluation e:
{
// https://github.com/dotnet/roslyn/issues/34232
// We may need to recompute the Deconstruct method for a deconstruction if
// the receiver type has changed (e.g. its nested nullability).
var method = e.DeconstructMethod;
int extensionExtra = method.RequiresInstanceReceiver ? 0 : 1;
for (int i = 0; i < method.ParameterCount - extensionExtra; i++)
{
var parameterType = method.Parameters[i + extensionExtra].TypeWithAnnotations;
var output = new BoundDagTemp(e.Syntax, parameterType.Type, e, i);
int outputSlot = makeDagTempSlot(parameterType, output);
Debug.Assert(outputSlot > 0);
addToTempMap(output, outputSlot, parameterType.Type);
}
break;
}
case BoundDagTypeEvaluation e:
{
var output = new BoundDagTemp(e.Syntax, e.Type, e);
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
int outputSlot;
switch (_conversions.WithNullability(false).ClassifyConversionFromType(inputType, e.Type, ref discardedUseSiteInfo).Kind)
{
case ConversionKind.Identity:
case ConversionKind.ImplicitReference:
outputSlot = inputSlot;
break;
case ConversionKind.ExplicitNullable when AreNullableAndUnderlyingTypes(inputType, e.Type, out _):
outputSlot = GetNullableOfTValueSlot(inputType, inputSlot, out _, forceSlotEvenIfEmpty: true);
if (outputSlot < 0)
goto default;
break;
default:
outputSlot = makeDagTempSlot(TypeWithAnnotations.Create(e.Type, NullableAnnotation.NotAnnotated), output);
break;
}
Debug.Assert(!IsConditionalState);
Unsplit();
State[outputSlot] = NullableFlowState.NotNull;
addToTempMap(output, outputSlot, e.Type);
break;
}
case BoundDagFieldEvaluation e:
{
Debug.Assert(inputSlot > 0);
var field = (FieldSymbol)AsMemberOfType(inputType, e.Field);
var type = field.TypeWithAnnotations;
var output = new BoundDagTemp(e.Syntax, type.Type, e);
int outputSlot = -1;
var originalTupleElement = e.Input.IsOriginalInput && !originalInputElementSlots.IsDefault
? field
: null;
if (originalTupleElement is not null)
{
// Re-use the slot of the element/expression if possible
outputSlot = originalInputElementSlots[originalTupleElement.TupleElementIndex];
}
if (outputSlot <= 0)
{
outputSlot = GetOrCreateSlot(field, inputSlot, forceSlotEvenIfEmpty: true);
if (originalTupleElement is not null && outputSlot > 0)
{
// The expression in the tuple could not be assigned a slot (for example, `a?.b`),
// so we had to create a slot for the tuple element instead.
// We'll remember that so that we can apply any learnings to the expression.
if (!originalInputMap.ContainsKey(outputSlot))
{
originalInputMap.Add(outputSlot,
((BoundTupleExpression)expression).Arguments[originalTupleElement.TupleElementIndex]);
}
else
{
Debug.Assert(originalInputMap[outputSlot] == ((BoundTupleExpression)expression).Arguments[originalTupleElement.TupleElementIndex]);
}
}
}
if (outputSlot <= 0)
{
outputSlot = makeDagTempSlot(type, output);
}
Debug.Assert(outputSlot > 0);
addToTempMap(output, outputSlot, type.Type);
break;
}
case BoundDagPropertyEvaluation e:
{
Debug.Assert(inputSlot > 0);
var property = (PropertySymbol)AsMemberOfType(inputType, e.Property);
var type = property.TypeWithAnnotations;
var output = new BoundDagTemp(e.Syntax, type.Type, e);
int outputSlot = GetOrCreateSlot(property, inputSlot, forceSlotEvenIfEmpty: true);
if (outputSlot <= 0)
{
outputSlot = makeDagTempSlot(type, output);
}
Debug.Assert(outputSlot > 0);
addToTempMap(output, outputSlot, type.Type);
if (property.GetMethod is not null)
{
// A property evaluation splits the state if MemberNotNullWhen is used
ApplyMemberPostConditions(inputSlot, property.GetMethod);
}
break;
}
case BoundDagIndexEvaluation e:
{
var type = TypeWithAnnotations.Create(e.Property.Type, NullableAnnotation.Annotated);
var output = new BoundDagTemp(e.Syntax, type.Type, e);
int outputSlot = makeDagTempSlot(type, output);
Debug.Assert(outputSlot > 0);
addToTempMap(output, outputSlot, type.Type);
break;
}
default:
throw ExceptionUtilities.UnexpectedValue(p.Evaluation.Kind);
}
gotoNodeWithCurrentState(p.Next, nodeBelievedReachable);
break;
}
case BoundTestDecisionDagNode p:
{
var test = p.Test;
bool foundTemp = tempMap.TryGetValue(test.Input, out var slotAndType);
Debug.Assert(foundTemp);
(int inputSlot, TypeSymbol inputType) = slotAndType;
Debug.Assert(test is not BoundDagNonNullTest || !IsConditionalState);
Split();
switch (test)
{
case BoundDagTypeTest:
if (inputSlot > 0)
{
learnFromNonNullTest(inputSlot, ref this.StateWhenTrue);
}
gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable);
gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable);
break;
case BoundDagNonNullTest t:
var inputMaybeNull = this.StateWhenTrue[inputSlot].MayBeNull();
if (inputSlot > 0)
{
MarkDependentSlotsNotNull(inputSlot, inputType, ref this.StateWhenFalse);
if (t.IsExplicitTest)
{
LearnFromNullTest(inputSlot, inputType, ref this.StateWhenFalse, markDependentSlotsNotNull: false);
}
learnFromNonNullTest(inputSlot, ref this.StateWhenTrue);
}
gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable);
gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable & inputMaybeNull);
break;
case BoundDagExplicitNullTest _:
if (inputSlot > 0)
{
LearnFromNullTest(inputSlot, inputType, ref this.StateWhenTrue, markDependentSlotsNotNull: true);
learnFromNonNullTest(inputSlot, ref this.StateWhenFalse);
}
gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable);
gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable);
break;
case BoundDagValueTest t:
Debug.Assert(t.Value != ConstantValue.Null);
// When we compare `bool?` inputs to bool constants, we follow a graph roughly like the following:
// [0]: t0 != null ? [1] : [5]
// [1]: t1 = (bool)t0; [2]
// [2] (this node): t1 == boolConstant ? [3] : [4]
// ...(remaining states)
if (stateWhenNotNullOpt is { } stateWhenNotNull
&& t.Input.Source is BoundDagTypeEvaluation { Input: { IsOriginalInput: true } })
{
SetPossiblyConditionalState(stateWhenNotNull);
Split();
}
else if (inputSlot > 0)
{
learnFromNonNullTest(inputSlot, ref this.StateWhenTrue);
}
bool isFalseTest = t.Value == ConstantValue.False;
gotoNode(p.WhenTrue, isFalseTest ? this.StateWhenFalse : this.StateWhenTrue, nodeBelievedReachable);
gotoNode(p.WhenFalse, isFalseTest ? this.StateWhenTrue : this.StateWhenFalse, nodeBelievedReachable);
break;
case BoundDagRelationalTest _:
if (inputSlot > 0)
{
learnFromNonNullTest(inputSlot, ref this.StateWhenTrue);
}
gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable);
gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable);
break;
default:
throw ExceptionUtilities.UnexpectedValue(test.Kind);
}
break;
}
case BoundLeafDecisionDagNode d:
// We have one leaf decision dag node per reachable label
Unsplit(); // Could be split in pathological cases like `false switch { ... }`
labelStateMap.Add(d.Label, (this.State, nodeBelievedReachable));
break;
case BoundWhenDecisionDagNode w:
// bind the pattern variables, inferring their types as well
Unsplit();
foreach (var binding in w.Bindings)
{
var variableAccess = binding.VariableAccess;
var tempSource = binding.TempContainingValue;
var foundTemp = tempMap.TryGetValue(tempSource, out var tempSlotAndType);
if (foundTemp) // in erroneous programs, we might not have seen a temp defined.
{
var (tempSlot, tempType) = tempSlotAndType;
var tempState = this.State[tempSlot];
if (variableAccess is BoundLocal { LocalSymbol: SourceLocalSymbol local } boundLocal)
{
var value = TypeWithState.Create(tempType, tempState);
var inferredType = value.ToTypeWithAnnotations(compilation, asAnnotatedType: boundLocal.DeclarationKind == BoundLocalDeclarationKind.WithInferredType);
if (_variables.TryGetType(local, out var existingType))
{
// merge inferred nullable annotation from different branches of the decision tree
inferredType = TypeWithAnnotations.Create(inferredType.Type, existingType.NullableAnnotation.Join(inferredType.NullableAnnotation));
}
_variables.SetType(local, inferredType);
int localSlot = GetOrCreateSlot(local, forceSlotEvenIfEmpty: true);
if (localSlot > 0)
{
TrackNullableStateForAssignment(valueOpt: null, inferredType, localSlot, TypeWithState.Create(tempType, tempState), tempSlot);
}
}
else
{
// https://github.com/dotnet/roslyn/issues/34144 perform inference for top-level var-declared fields in scripts
}
}
}
if (w.WhenExpression != null && w.WhenExpression.ConstantValue != ConstantValue.True)
{
VisitCondition(w.WhenExpression);
Debug.Assert(this.IsConditionalState);
gotoNode(w.WhenTrue, this.StateWhenTrue, nodeBelievedReachable);
gotoNode(w.WhenFalse, this.StateWhenFalse, nodeBelievedReachable);
}
else
{
Debug.Assert(w.WhenFalse is null);
gotoNode(w.WhenTrue, this.State, nodeBelievedReachable);
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(dagNode.Kind);
}
}
SetUnreachable(); // the decision dag is always complete (no fall-through)
originalInputMap.Free();
tempMap.Free();
nodeStateMap.Free();
return labelStateMap;
void learnFromNonNullTest(int inputSlot, ref LocalState state)
{
if (stateWhenNotNullOpt is { } stateWhenNotNull && inputSlot == originalInputSlot)
{
state = CloneAndUnsplit(ref stateWhenNotNull);
}
LearnFromNonNullTest(inputSlot, ref state);
if (originalInputMap.TryGetValue(inputSlot, out var expression))
LearnFromNonNullTest(expression, ref state);
}
void addToTempMap(BoundDagTemp output, int slot, TypeSymbol type)
{
// We need to track all dag temps, so there should be a slot
Debug.Assert(slot > 0);
if (tempMap.TryGetValue(output, out var outputSlotAndType))
{
// The dag temp has already been allocated on another branch of the dag
Debug.Assert(outputSlotAndType.slot == slot);
Debug.Assert(isDerivedType(outputSlotAndType.type, type));
}
else
{
Debug.Assert(NominalSlotType(slot) is var slotType && (slotType.IsErrorType() || isDerivedType(slotType, type)));
tempMap.Add(output, (slot, type));
}
}
bool isDerivedType(TypeSymbol derivedType, TypeSymbol baseType)
{
if (derivedType.IsErrorType() || baseType.IsErrorType())
return true;
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
return _conversions.WithNullability(false).ClassifyConversionFromType(derivedType, baseType, ref discardedUseSiteInfo).Kind switch
{
ConversionKind.Identity => true,
ConversionKind.ImplicitReference => true,
ConversionKind.Boxing => true,
_ => false,
};
}
void gotoNodeWithCurrentState(BoundDecisionDagNode node, bool believedReachable)
{
if (nodeStateMap.TryGetValue(node, out var stateAndReachable))
{
switch (IsConditionalState, stateAndReachable.state.IsConditionalState)
{
case (true, true):
Debug.Assert(false);
Join(ref this.StateWhenTrue, ref stateAndReachable.state.StateWhenTrue);
Join(ref this.StateWhenFalse, ref stateAndReachable.state.StateWhenFalse);
break;
case (true, false):
Debug.Assert(false);
Join(ref this.StateWhenTrue, ref stateAndReachable.state.State);
Join(ref this.StateWhenFalse, ref stateAndReachable.state.State);
break;
case (false, true):
Debug.Assert(false);
Split();
Join(ref this.StateWhenTrue, ref stateAndReachable.state.StateWhenTrue);
Join(ref this.StateWhenFalse, ref stateAndReachable.state.StateWhenFalse);
break;
case (false, false):
Join(ref this.State, ref stateAndReachable.state.State);
break;
}
believedReachable |= stateAndReachable.believedReachable;
}
nodeStateMap[node] = (PossiblyConditionalState.Create(this), believedReachable);
}
void gotoNode(BoundDecisionDagNode node, LocalState state, bool believedReachable)
{
PossiblyConditionalState result;
if (nodeStateMap.TryGetValue(node, out var stateAndReachable))
{
result = stateAndReachable.state;
switch (result.IsConditionalState)
{
case true:
Debug.Assert(false);
Join(ref result.StateWhenTrue, ref state);
Join(ref result.StateWhenFalse, ref state);
break;
case false:
Join(ref result.State, ref state);
break;
}
believedReachable |= stateAndReachable.believedReachable;
}
else
{
result = new PossiblyConditionalState(state);
}
nodeStateMap[node] = (result, believedReachable);
}
int makeDagTempSlot(TypeWithAnnotations type, BoundDagTemp temp)
{
object slotKey = (node, temp);
return GetOrCreatePlaceholderSlot(slotKey, type);
}
}
public override BoundNode VisitConvertedSwitchExpression(BoundConvertedSwitchExpression node)
{
bool inferType = !node.WasTargetTyped;
VisitSwitchExpressionCore(node, inferType);
return null;
}
public override BoundNode VisitUnconvertedSwitchExpression(BoundUnconvertedSwitchExpression node)
{
// This method is only involved in method inference with unbound lambdas.
VisitSwitchExpressionCore(node, inferType: true);
return null;
}
private void VisitSwitchExpressionCore(BoundSwitchExpression node, bool inferType)
{
// first, learn from any null tests in the patterns
int slot = node.Expression.IsSuppressed ? GetOrCreatePlaceholderSlot(node.Expression) : MakeSlot(node.Expression);
if (slot > 0)
{
var originalInputType = node.Expression.Type;
foreach (var arm in node.SwitchArms)
{
LearnFromAnyNullPatterns(slot, originalInputType, arm.Pattern);
}
}
Visit(node.Expression);
var expressionState = ResultType;
var labelStateMap = LearnFromDecisionDag(node.Syntax, node.DecisionDag, node.Expression, expressionState, stateWhenNotNullOpt: null);
var endState = UnreachableState();
if (!node.ReportedNotExhaustive && node.DefaultLabel != null &&
labelStateMap.TryGetValue(node.DefaultLabel, out var defaultLabelState) && defaultLabelState.believedReachable)
{
SetState(defaultLabelState.state);
var nodes = node.DecisionDag.TopologicallySortedNodes;
var leaf = nodes.Where(n => n is BoundLeafDecisionDagNode leaf && leaf.Label == node.DefaultLabel).First();
var samplePattern = PatternExplainer.SamplePatternForPathToDagNode(
BoundDagTemp.ForOriginalInput(node.Expression), nodes, leaf, nullPaths: true, out bool requiresFalseWhenClause, out _);
ErrorCode warningCode = requiresFalseWhenClause ? ErrorCode.WRN_SwitchExpressionNotExhaustiveForNullWithWhen : ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull;
ReportDiagnostic(
warningCode,
((SwitchExpressionSyntax)node.Syntax).SwitchKeyword.GetLocation(),
samplePattern);
}
// collect expressions, conversions and result types
int numSwitchArms = node.SwitchArms.Length;
var conversions = ArrayBuilder<Conversion>.GetInstance(numSwitchArms);
var resultTypes = ArrayBuilder<TypeWithState>.GetInstance(numSwitchArms);
var expressions = ArrayBuilder<BoundExpression>.GetInstance(numSwitchArms);
var placeholderBuilder = ArrayBuilder<BoundExpression>.GetInstance(numSwitchArms);
foreach (var arm in node.SwitchArms)
{
SetState(getStateForArm(arm));
// https://github.com/dotnet/roslyn/issues/35836 Is this where we want to take the snapshot?
TakeIncrementalSnapshot(arm);
VisitPatternForRewriting(arm.Pattern);
(BoundExpression expression, Conversion conversion) = RemoveConversion(arm.Value, includeExplicitConversions: false);
SnapshotWalkerThroughConversionGroup(arm.Value, expression);
expressions.Add(expression);
conversions.Add(conversion);
var armType = VisitRvalueWithState(expression);
resultTypes.Add(armType);
Join(ref endState, ref this.State);
// Build placeholders for inference in order to preserve annotations.
placeholderBuilder.Add(CreatePlaceholderIfNecessary(expression, armType.ToTypeWithAnnotations(compilation)));
}
var placeholders = placeholderBuilder.ToImmutableAndFree();
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
TypeSymbol inferredType =
(inferType ? BestTypeInferrer.InferBestType(placeholders, _conversions, ref discardedUseSiteInfo) : null)
?? node.Type?.SetUnknownNullabilityForReferenceTypes();
var inferredTypeWithAnnotations = TypeWithAnnotations.Create(inferredType);
NullableFlowState inferredState;
if (inferType)
{
if (inferredType is null)
{
// This can happen when we're inferring the return type of a lambda, or when there are no arms (an error case).
// For this case, we don't need to do any work, as the unconverted switch expression can't contribute info, and
// there is nothing that is being publicly exposed to the semantic model.
Debug.Assert((node is BoundUnconvertedSwitchExpression && _returnTypesOpt is not null)
|| node is BoundSwitchExpression { SwitchArms: { Length: 0 } });
inferredState = default;
}
else
{
for (int i = 0; i < numSwitchArms; i++)
{
var nodeForSyntax = expressions[i];
var arm = node.SwitchArms[i];
var armState = getStateForArm(arm);
resultTypes[i] = ConvertConditionalOperandOrSwitchExpressionArmResult(arm.Value, nodeForSyntax, conversions[i], inferredTypeWithAnnotations, resultTypes[i], armState, armState.Reachable);
}
inferredState = BestTypeInferrer.GetNullableState(resultTypes);
}
}
else
{
var states = ArrayBuilder<(LocalState, TypeWithState, bool)>.GetInstance(numSwitchArms);
for (int i = 0; i < numSwitchArms; i++)
{
var nodeForSyntax = expressions[i];
var armState = getStateForArm(node.SwitchArms[i]);
states.Add((armState, resultTypes[i], armState.Reachable));
}
ConditionalInfoForConversion.Add(node, states.ToImmutableAndFree());
inferredState = BestTypeInferrer.GetNullableState(resultTypes);
}
var resultType = TypeWithState.Create(inferredType, inferredState);
conversions.Free();
resultTypes.Free();
expressions.Free();
labelStateMap.Free();
SetState(endState);
SetResult(node, resultType, inferredTypeWithAnnotations);
LocalState getStateForArm(BoundSwitchExpressionArm arm)
=> !arm.Pattern.HasErrors && labelStateMap.TryGetValue(arm.Label, out var labelState) ? labelState.state : UnreachableState();
}
public override BoundNode VisitIsPatternExpression(BoundIsPatternExpression node)
{
Debug.Assert(!IsConditionalState);
LearnFromAnyNullPatterns(node.Expression, node.Pattern);
VisitPatternForRewriting(node.Pattern);
var hasStateWhenNotNull = VisitPossibleConditionalAccess(node.Expression, out var conditionalStateWhenNotNull);
var expressionState = ResultType;
var labelStateMap = LearnFromDecisionDag(node.Syntax, node.DecisionDag, node.Expression, expressionState, hasStateWhenNotNull ? conditionalStateWhenNotNull : null);
var trueState = labelStateMap.TryGetValue(node.IsNegated ? node.WhenFalseLabel : node.WhenTrueLabel, out var s1) ? s1.state : UnreachableState();
var falseState = labelStateMap.TryGetValue(node.IsNegated ? node.WhenTrueLabel : node.WhenFalseLabel, out var s2) ? s2.state : UnreachableState();
labelStateMap.Free();
SetConditionalState(trueState, falseState);
SetNotNullResult(node);
return null;
}
}
}
| -1 |
dotnet/roslyn | 55,530 | Ignore modules with bad metadata in function resolver | Fixes https://github.com/dotnet/roslyn/issues/55475 | tmat | 2021-08-10T18:56:37Z | 2021-08-11T18:37:09Z | cd0c0464c069a2b80774d70f071c29333d9fa23c | bc874ebc5111a2a33221409f895953b1536f6612 | Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475 | ./src/Features/Core/Portable/UnusedReferences/UpdateAction.cs | // Licensed to the .NET Foundation under one or more 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.UnusedReferences
{
internal enum UpdateAction
{
/// <summary>
/// No action needs to be performed.
/// </summary>
None,
/// <summary>
/// Indicates the reference should be marked as used.
/// </summary>
TreatAsUsed,
/// <summary>
/// Indicates the reference should be marked as unused
/// </summary>
TreatAsUnused,
/// <summary>
/// Indicates the reference should be removed from the project.
/// </summary>
Remove,
}
}
| // Licensed to the .NET Foundation under one or more 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.UnusedReferences
{
internal enum UpdateAction
{
/// <summary>
/// No action needs to be performed.
/// </summary>
None,
/// <summary>
/// Indicates the reference should be marked as used.
/// </summary>
TreatAsUsed,
/// <summary>
/// Indicates the reference should be marked as unused
/// </summary>
TreatAsUnused,
/// <summary>
/// Indicates the reference should be removed from the project.
/// </summary>
Remove,
}
}
| -1 |
dotnet/roslyn | 55,530 | Ignore modules with bad metadata in function resolver | Fixes https://github.com/dotnet/roslyn/issues/55475 | tmat | 2021-08-10T18:56:37Z | 2021-08-11T18:37:09Z | cd0c0464c069a2b80774d70f071c29333d9fa23c | bc874ebc5111a2a33221409f895953b1536f6612 | Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475 | ./src/EditorFeatures/Test2/InlineHints/VisualBasicInlineParameterNameHintsTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.InlineHints
Public Class VisualBasicInlineParameterNameHintsTests
Inherits AbstractInlineHintsTests
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestNoParameterSimpleCase() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Main(args As String())
TestMethod()
End Sub
Sub TestMethod()
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestOneParameterSimpleCase() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Main(args As String())
TestMethod({|x:|}5)
End Sub
Sub TestMethod(x As Integer)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestTwoParametersSimpleCase() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Main(args As String())
TestMethod({|x:|}5, {|y:|}2.2)
End Sub
Sub TestMethod(x As Integer, y As Double)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestNegativeNumberParametersSimpleCase() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Main(args As String())
TestMethod({|x:|}-5, {|y:|}2.2)
End Sub
Sub TestMethod(x As Integer, y As Double)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestCIntCast() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Main(args As String())
TestMethod({|x:|}CInt(5.5), {|y:|}2.2)
End Sub
Sub TestMethod(x As Integer, y As Double)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestCTypeCast() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Main(args As String())
TestMethod({|x:|}CType(5.5, Integer), {|y:|}2.2)
End Sub
Sub TestMethod(x As Integer, y As Double)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestTryCastCase() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Test
Public Sub test(x As String)
End Sub
Public Sub Main()
test({|x:|}TryCast(New Object(), String))
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestDirectCastCase() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Test
Public Sub test(x As String)
End Sub
Public Sub Main()
test({|x:|}DirectCast(New Object(), String))
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestCastingANegativeSimpleCase() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Main(args As String())
TestMethod({|x:|}CInt(-5.5), {|y:|}2.2)
End Sub
Sub TestMethod(x As Integer, y As Double)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestObjectCreationParametersSimpleCase() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Main(args As String())
TestMethod({|x:|}CInt(-5.5), {|y:|}2.2, {|obj:|}New Object())
End Sub
Sub TestMethod(x As Integer, y As Double, obj As Object)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestMissingParameterNameSimpleCase() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Main(args As String())
TestMethod()
End Sub
Sub TestMethod(As Integer)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestDelegateParameter() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Test
Public Delegate Sub TestDelegate(ByVal str As String)
Public Sub TestTheDelegate(ByVal test As TestDelegate)
test({|str:|}"Test")
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestParamsArgument() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Test
Public Sub UseParams(ParamArray args() As Integer)
End Sub
Public Sub Main()
UseParams({|args:|}1, 2, 3, 4, 5)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestAttributesArgument() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<Obsolete({|message:|}"test")>
Public Class Foo
Sub TestMethod()
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestIncompleteFunctionCall() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Main(args As String())
TestMethod({|x:|}5,)
End Sub
Sub TestMethod(x As Integer, y As Double)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestInterpolatedString() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Main(args As String())
TestMethod({|x:|}$"")
End Sub
Sub TestMethod(x As String)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")>
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestNotOnEnableDisableBoolean1() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
class A
sub EnableLogging(value as boolean)
end sub
sub Main()
EnableLogging(true)
end sub
end class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")>
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestNotOnEnableDisableBoolean2() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
class A
sub DisableLogging(value as boolean)
end sub
sub Main()
DisableLogging(true)
end sub
end class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")>
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestOnEnableDisableNonBoolean1() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
class A
sub EnableLogging(value as string)
end sub
sub Main()
EnableLogging({|value:|}"IO")
end sub
end class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")>
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestOnEnableDisableNonBoolean2() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
class A
sub DisableLogging(value as string)
end sub
sub Main()
DisableLogging({|value:|}"IO")
end sub
end class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")>
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestOnSetMethodWithClearContext() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
class A
sub SetClassification(classification as string)
end sub
sub Main()
SetClassification("IO")
end sub
end class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")>
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestOnSetMethodWithUnclearContext() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
class A
sub SetClassification(values as string)
end sub
sub Main()
SetClassification({|values:|}"IO")
end sub
end class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")>
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestMethodWithAlphaSuffix1() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
class A
sub Goo(objA as integer, objB as integer, objC as integer)
end sub
sub Main()
Goo(1, 2, 3)
end sub
end class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")>
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestMethodWithNonAlphaSuffix1() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
class A
sub Goo(objA as integer, objB as integer, nonobjC as integer)
end sub
sub Main()
Goo({|objA:|}1, {|objB:|}2, {|nonobjC:|}3)
end sub
end class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")>
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestMethodWithNumericSuffix1() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
class A
sub Goo(obj1 as integer, obj2 as integer, obj3 as integer)
end sub
sub Main()
Goo(1, 2, 3)
end sub
end class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")>
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestMethodWithNonNumericSuffix1() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
class A
sub Goo(obj1 as integer, obj2 as integer, nonobj3 as integer)
end sub
sub Main()
Goo({|obj1:|}1, {|obj2:|}2, {|nonobj3:|}3)
end sub
end class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.InlineHints
Public Class VisualBasicInlineParameterNameHintsTests
Inherits AbstractInlineHintsTests
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestNoParameterSimpleCase() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Main(args As String())
TestMethod()
End Sub
Sub TestMethod()
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestOneParameterSimpleCase() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Main(args As String())
TestMethod({|x:|}5)
End Sub
Sub TestMethod(x As Integer)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestTwoParametersSimpleCase() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Main(args As String())
TestMethod({|x:|}5, {|y:|}2.2)
End Sub
Sub TestMethod(x As Integer, y As Double)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestNegativeNumberParametersSimpleCase() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Main(args As String())
TestMethod({|x:|}-5, {|y:|}2.2)
End Sub
Sub TestMethod(x As Integer, y As Double)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestCIntCast() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Main(args As String())
TestMethod({|x:|}CInt(5.5), {|y:|}2.2)
End Sub
Sub TestMethod(x As Integer, y As Double)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestCTypeCast() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Main(args As String())
TestMethod({|x:|}CType(5.5, Integer), {|y:|}2.2)
End Sub
Sub TestMethod(x As Integer, y As Double)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestTryCastCase() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Test
Public Sub test(x As String)
End Sub
Public Sub Main()
test({|x:|}TryCast(New Object(), String))
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestDirectCastCase() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Test
Public Sub test(x As String)
End Sub
Public Sub Main()
test({|x:|}DirectCast(New Object(), String))
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestCastingANegativeSimpleCase() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Main(args As String())
TestMethod({|x:|}CInt(-5.5), {|y:|}2.2)
End Sub
Sub TestMethod(x As Integer, y As Double)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestObjectCreationParametersSimpleCase() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Main(args As String())
TestMethod({|x:|}CInt(-5.5), {|y:|}2.2, {|obj:|}New Object())
End Sub
Sub TestMethod(x As Integer, y As Double, obj As Object)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestMissingParameterNameSimpleCase() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Main(args As String())
TestMethod()
End Sub
Sub TestMethod(As Integer)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestDelegateParameter() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Test
Public Delegate Sub TestDelegate(ByVal str As String)
Public Sub TestTheDelegate(ByVal test As TestDelegate)
test({|str:|}"Test")
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestParamsArgument() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Test
Public Sub UseParams(ParamArray args() As Integer)
End Sub
Public Sub Main()
UseParams({|args:|}1, 2, 3, 4, 5)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestAttributesArgument() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<Obsolete({|message:|}"test")>
Public Class Foo
Sub TestMethod()
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestIncompleteFunctionCall() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Main(args As String())
TestMethod({|x:|}5,)
End Sub
Sub TestMethod(x As Integer, y As Double)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestInterpolatedString() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Foo
Sub Main(args As String())
TestMethod({|x:|}$"")
End Sub
Sub TestMethod(x As String)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")>
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestNotOnEnableDisableBoolean1() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
class A
sub EnableLogging(value as boolean)
end sub
sub Main()
EnableLogging(true)
end sub
end class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")>
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestNotOnEnableDisableBoolean2() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
class A
sub DisableLogging(value as boolean)
end sub
sub Main()
DisableLogging(true)
end sub
end class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")>
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestOnEnableDisableNonBoolean1() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
class A
sub EnableLogging(value as string)
end sub
sub Main()
EnableLogging({|value:|}"IO")
end sub
end class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")>
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestOnEnableDisableNonBoolean2() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
class A
sub DisableLogging(value as string)
end sub
sub Main()
DisableLogging({|value:|}"IO")
end sub
end class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")>
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestOnSetMethodWithClearContext() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
class A
sub SetClassification(classification as string)
end sub
sub Main()
SetClassification("IO")
end sub
end class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")>
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestOnSetMethodWithUnclearContext() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
class A
sub SetClassification(values as string)
end sub
sub Main()
SetClassification({|values:|}"IO")
end sub
end class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")>
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestMethodWithAlphaSuffix1() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
class A
sub Goo(objA as integer, objB as integer, objC as integer)
end sub
sub Main()
Goo(1, 2, 3)
end sub
end class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")>
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestMethodWithNonAlphaSuffix1() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
class A
sub Goo(objA as integer, objB as integer, nonobjC as integer)
end sub
sub Main()
Goo({|objA:|}1, {|objB:|}2, {|nonobjC:|}3)
end sub
end class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")>
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestMethodWithNumericSuffix1() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
class A
sub Goo(obj1 as integer, obj2 as integer, obj3 as integer)
end sub
sub Main()
Goo(1, 2, 3)
end sub
end class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
<WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")>
<WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)>
Public Async Function TestMethodWithNonNumericSuffix1() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
class A
sub Goo(obj1 as integer, obj2 as integer, nonobj3 as integer)
end sub
sub Main()
Goo({|obj1:|}1, {|obj2:|}2, {|nonobj3:|}3)
end sub
end class
</Document>
</Project>
</Workspace>
Await VerifyParamHints(input)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,530 | Ignore modules with bad metadata in function resolver | Fixes https://github.com/dotnet/roslyn/issues/55475 | tmat | 2021-08-10T18:56:37Z | 2021-08-11T18:37:09Z | cd0c0464c069a2b80774d70f071c29333d9fa23c | bc874ebc5111a2a33221409f895953b1536f6612 | Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475 | ./src/Workspaces/Core/Portable/Formatting/Rules/IHostDependentFormattingRuleFactoryService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Formatting.Rules
{
internal interface IHostDependentFormattingRuleFactoryService : IWorkspaceService
{
bool ShouldNotFormatOrCommitOnPaste(Document document);
bool ShouldUseBaseIndentation(Document document);
AbstractFormattingRule CreateRule(Document document, int position);
IEnumerable<TextChange> FilterFormattedChanges(Document document, TextSpan span, IList<TextChange> changes);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Formatting.Rules
{
internal interface IHostDependentFormattingRuleFactoryService : IWorkspaceService
{
bool ShouldNotFormatOrCommitOnPaste(Document document);
bool ShouldUseBaseIndentation(Document document);
AbstractFormattingRule CreateRule(Document document, int position);
IEnumerable<TextChange> FilterFormattedChanges(Document document, TextSpan span, IList<TextChange> changes);
}
}
| -1 |
dotnet/roslyn | 55,530 | Ignore modules with bad metadata in function resolver | Fixes https://github.com/dotnet/roslyn/issues/55475 | tmat | 2021-08-10T18:56:37Z | 2021-08-11T18:37:09Z | cd0c0464c069a2b80774d70f071c29333d9fa23c | bc874ebc5111a2a33221409f895953b1536f6612 | Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475 | ./src/Compilers/Core/Portable/InternalUtilities/SpecializedCollections.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
namespace Roslyn.Utilities
{
internal static partial class SpecializedCollections
{
public static IEnumerator<T> EmptyEnumerator<T>()
{
return Empty.Enumerator<T>.Instance;
}
public static IEnumerable<T> EmptyEnumerable<T>()
{
return Empty.List<T>.Instance;
}
public static ICollection<T> EmptyCollection<T>()
{
return Empty.List<T>.Instance;
}
public static IList<T> EmptyList<T>()
{
return Empty.List<T>.Instance;
}
public static IReadOnlyList<T> EmptyBoxedImmutableArray<T>()
{
return Empty.BoxedImmutableArray<T>.Instance;
}
public static IReadOnlyList<T> EmptyReadOnlyList<T>()
{
return Empty.List<T>.Instance;
}
public static ISet<T> EmptySet<T>()
{
return Empty.Set<T>.Instance;
}
public static IReadOnlySet<T> EmptyReadOnlySet<T>()
{
return Empty.Set<T>.Instance;
}
public static IDictionary<TKey, TValue> EmptyDictionary<TKey, TValue>()
where TKey : notnull
{
return Empty.Dictionary<TKey, TValue>.Instance;
}
public static IReadOnlyDictionary<TKey, TValue> EmptyReadOnlyDictionary<TKey, TValue>()
where TKey : notnull
{
return Empty.Dictionary<TKey, TValue>.Instance;
}
public static IEnumerable<T> SingletonEnumerable<T>(T value)
{
return new Singleton.List<T>(value);
}
public static ICollection<T> SingletonCollection<T>(T value)
{
return new Singleton.List<T>(value);
}
public static IEnumerator<T> SingletonEnumerator<T>(T value)
{
return new Singleton.Enumerator<T>(value);
}
public static IReadOnlyList<T> SingletonReadOnlyList<T>(T value)
{
return new Singleton.List<T>(value);
}
public static IList<T> SingletonList<T>(T value)
{
return new Singleton.List<T>(value);
}
public static IEnumerable<T> ReadOnlyEnumerable<T>(IEnumerable<T> values)
{
return new ReadOnly.Enumerable<IEnumerable<T>, T>(values);
}
public static ICollection<T> ReadOnlyCollection<T>(ICollection<T>? collection)
{
return collection == null || collection.Count == 0
? EmptyCollection<T>()
: new ReadOnly.Collection<ICollection<T>, T>(collection);
}
public static ISet<T> ReadOnlySet<T>(ISet<T>? set)
{
return set == null || set.Count == 0
? EmptySet<T>()
: new ReadOnly.Set<ISet<T>, T>(set);
}
public static IReadOnlySet<T> StronglyTypedReadOnlySet<T>(ISet<T>? set)
{
return set == null || set.Count == 0
? EmptyReadOnlySet<T>()
: new ReadOnly.Set<ISet<T>, T>(set);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
namespace Roslyn.Utilities
{
internal static partial class SpecializedCollections
{
public static IEnumerator<T> EmptyEnumerator<T>()
{
return Empty.Enumerator<T>.Instance;
}
public static IEnumerable<T> EmptyEnumerable<T>()
{
return Empty.List<T>.Instance;
}
public static ICollection<T> EmptyCollection<T>()
{
return Empty.List<T>.Instance;
}
public static IList<T> EmptyList<T>()
{
return Empty.List<T>.Instance;
}
public static IReadOnlyList<T> EmptyBoxedImmutableArray<T>()
{
return Empty.BoxedImmutableArray<T>.Instance;
}
public static IReadOnlyList<T> EmptyReadOnlyList<T>()
{
return Empty.List<T>.Instance;
}
public static ISet<T> EmptySet<T>()
{
return Empty.Set<T>.Instance;
}
public static IReadOnlySet<T> EmptyReadOnlySet<T>()
{
return Empty.Set<T>.Instance;
}
public static IDictionary<TKey, TValue> EmptyDictionary<TKey, TValue>()
where TKey : notnull
{
return Empty.Dictionary<TKey, TValue>.Instance;
}
public static IReadOnlyDictionary<TKey, TValue> EmptyReadOnlyDictionary<TKey, TValue>()
where TKey : notnull
{
return Empty.Dictionary<TKey, TValue>.Instance;
}
public static IEnumerable<T> SingletonEnumerable<T>(T value)
{
return new Singleton.List<T>(value);
}
public static ICollection<T> SingletonCollection<T>(T value)
{
return new Singleton.List<T>(value);
}
public static IEnumerator<T> SingletonEnumerator<T>(T value)
{
return new Singleton.Enumerator<T>(value);
}
public static IReadOnlyList<T> SingletonReadOnlyList<T>(T value)
{
return new Singleton.List<T>(value);
}
public static IList<T> SingletonList<T>(T value)
{
return new Singleton.List<T>(value);
}
public static IEnumerable<T> ReadOnlyEnumerable<T>(IEnumerable<T> values)
{
return new ReadOnly.Enumerable<IEnumerable<T>, T>(values);
}
public static ICollection<T> ReadOnlyCollection<T>(ICollection<T>? collection)
{
return collection == null || collection.Count == 0
? EmptyCollection<T>()
: new ReadOnly.Collection<ICollection<T>, T>(collection);
}
public static ISet<T> ReadOnlySet<T>(ISet<T>? set)
{
return set == null || set.Count == 0
? EmptySet<T>()
: new ReadOnly.Set<ISet<T>, T>(set);
}
public static IReadOnlySet<T> StronglyTypedReadOnlySet<T>(ISet<T>? set)
{
return set == null || set.Count == 0
? EmptyReadOnlySet<T>()
: new ReadOnly.Set<ISet<T>, T>(set);
}
}
}
| -1 |
dotnet/roslyn | 55,530 | Ignore modules with bad metadata in function resolver | Fixes https://github.com/dotnet/roslyn/issues/55475 | tmat | 2021-08-10T18:56:37Z | 2021-08-11T18:37:09Z | cd0c0464c069a2b80774d70f071c29333d9fa23c | bc874ebc5111a2a33221409f895953b1536f6612 | Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475 | ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ThrowKeywordRecommender.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 ThrowKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public ThrowKeywordRecommender()
: base(SyntaxKind.ThrowKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
if (context.IsStatementContext || context.IsGlobalStatementContext)
{
return true;
}
// void M() => throw
if (context.TargetToken.Kind() == SyntaxKind.EqualsGreaterThanToken)
{
return true;
}
// val ?? throw
if (context.TargetToken.Kind() == SyntaxKind.QuestionQuestionToken)
{
return true;
}
// expr ? throw : ...
// expr ? ... : throw
if (context.TargetToken.Kind() == SyntaxKind.QuestionToken ||
context.TargetToken.Kind() == SyntaxKind.ColonToken)
{
return context.TargetToken.Parent.Kind() == SyntaxKind.ConditionalExpression;
}
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.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class ThrowKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public ThrowKeywordRecommender()
: base(SyntaxKind.ThrowKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
if (context.IsStatementContext || context.IsGlobalStatementContext)
{
return true;
}
// void M() => throw
if (context.TargetToken.Kind() == SyntaxKind.EqualsGreaterThanToken)
{
return true;
}
// val ?? throw
if (context.TargetToken.Kind() == SyntaxKind.QuestionQuestionToken)
{
return true;
}
// expr ? throw : ...
// expr ? ... : throw
if (context.TargetToken.Kind() == SyntaxKind.QuestionToken ||
context.TargetToken.Kind() == SyntaxKind.ColonToken)
{
return context.TargetToken.Parent.Kind() == SyntaxKind.ConditionalExpression;
}
return false;
}
}
}
| -1 |
dotnet/roslyn | 55,530 | Ignore modules with bad metadata in function resolver | Fixes https://github.com/dotnet/roslyn/issues/55475 | tmat | 2021-08-10T18:56:37Z | 2021-08-11T18:37:09Z | cd0c0464c069a2b80774d70f071c29333d9fa23c | bc874ebc5111a2a33221409f895953b1536f6612 | Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475 | ./src/Features/CSharp/Portable/ExtractMethod/CSharpSelectionValidator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.ExtractMethod;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod
{
internal partial class CSharpSelectionValidator : SelectionValidator
{
public CSharpSelectionValidator(
SemanticDocument document,
TextSpan textSpan,
OptionSet options)
: base(document, textSpan, options)
{
}
public override async Task<SelectionResult> GetValidSelectionAsync(CancellationToken cancellationToken)
{
if (!ContainsValidSelection)
{
return NullSelection;
}
var text = SemanticDocument.Text;
var root = SemanticDocument.Root;
var model = SemanticDocument.SemanticModel;
var doc = SemanticDocument;
// go through pipe line and calculate information about the user selection
var selectionInfo = GetInitialSelectionInfo(root, text);
selectionInfo = AssignInitialFinalTokens(selectionInfo, root, cancellationToken);
selectionInfo = AdjustFinalTokensBasedOnContext(selectionInfo, model, cancellationToken);
selectionInfo = AssignFinalSpan(selectionInfo, text);
selectionInfo = ApplySpecialCases(selectionInfo, text);
selectionInfo = CheckErrorCasesAndAppendDescriptions(selectionInfo, root);
// there was a fatal error that we couldn't even do negative preview, return error result
if (selectionInfo.Status.FailedWithNoBestEffortSuggestion())
{
return new ErrorSelectionResult(selectionInfo.Status);
}
var controlFlowSpan = GetControlFlowSpan(selectionInfo);
if (!selectionInfo.SelectionInExpression)
{
var statementRange = GetStatementRangeContainedInSpan<StatementSyntax>(root, controlFlowSpan, cancellationToken);
if (statementRange == null)
{
selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.Can_t_determine_valid_range_of_statements_to_extract));
return new ErrorSelectionResult(selectionInfo.Status);
}
var isFinalSpanSemanticallyValid = IsFinalSpanSemanticallyValidSpan(model, controlFlowSpan, statementRange, cancellationToken);
if (!isFinalSpanSemanticallyValid)
{
// check control flow only if we are extracting statement level, not expression
// level. you can not have goto that moves control out of scope in expression level
// (even in lambda)
selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.BestEffort, CSharpFeaturesResources.Not_all_code_paths_return));
}
}
return await CSharpSelectionResult.CreateAsync(
selectionInfo.Status,
selectionInfo.OriginalSpan,
selectionInfo.FinalSpan,
Options,
selectionInfo.SelectionInExpression,
doc,
selectionInfo.FirstTokenInFinalSpan,
selectionInfo.LastTokenInFinalSpan,
cancellationToken).ConfigureAwait(false);
}
private static SelectionInfo ApplySpecialCases(SelectionInfo selectionInfo, SourceText text)
{
if (selectionInfo.Status.FailedWithNoBestEffortSuggestion() || !selectionInfo.SelectionInExpression)
{
return selectionInfo;
}
var expressionNode = selectionInfo.FirstTokenInFinalSpan.GetCommonRoot(selectionInfo.LastTokenInFinalSpan);
if (!expressionNode.IsAnyAssignExpression())
{
return selectionInfo;
}
var assign = (AssignmentExpressionSyntax)expressionNode;
// make sure there is a visible token at right side expression
if (assign.Right.GetLastToken().Kind() == SyntaxKind.None)
{
return selectionInfo;
}
return AssignFinalSpan(selectionInfo.With(s => s.FirstTokenInFinalSpan = assign.Right.GetFirstToken(includeZeroWidth: true))
.With(s => s.LastTokenInFinalSpan = assign.Right.GetLastToken(includeZeroWidth: true)),
text);
}
private static TextSpan GetControlFlowSpan(SelectionInfo selectionInfo)
=> TextSpan.FromBounds(selectionInfo.FirstTokenInFinalSpan.SpanStart, selectionInfo.LastTokenInFinalSpan.Span.End);
private static SelectionInfo AdjustFinalTokensBasedOnContext(
SelectionInfo selectionInfo,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
if (selectionInfo.Status.FailedWithNoBestEffortSuggestion())
{
return selectionInfo;
}
// don't need to adjust anything if it is multi-statements case
if (!selectionInfo.SelectionInExpression && !selectionInfo.SelectionInSingleStatement)
{
return selectionInfo;
}
// get the node that covers the selection
var node = selectionInfo.FirstTokenInFinalSpan.GetCommonRoot(selectionInfo.LastTokenInFinalSpan);
var validNode = Check(semanticModel, node, cancellationToken);
if (validNode)
{
return selectionInfo;
}
var firstValidNode = node.GetAncestors<SyntaxNode>().FirstOrDefault(n => Check(semanticModel, n, cancellationToken));
if (firstValidNode == null)
{
// couldn't find any valid node
return selectionInfo.WithStatus(s => new OperationStatus(OperationStatusFlag.None, CSharpFeaturesResources.Selection_does_not_contain_a_valid_node))
.With(s => s.FirstTokenInFinalSpan = default)
.With(s => s.LastTokenInFinalSpan = default);
}
firstValidNode = (firstValidNode.Parent is ExpressionStatementSyntax) ? firstValidNode.Parent : firstValidNode;
return selectionInfo.With(s => s.SelectionInExpression = firstValidNode is ExpressionSyntax)
.With(s => s.SelectionInSingleStatement = firstValidNode is StatementSyntax)
.With(s => s.FirstTokenInFinalSpan = firstValidNode.GetFirstToken(includeZeroWidth: true))
.With(s => s.LastTokenInFinalSpan = firstValidNode.GetLastToken(includeZeroWidth: true));
}
private SelectionInfo GetInitialSelectionInfo(SyntaxNode root, SourceText text)
{
var adjustedSpan = GetAdjustedSpan(text, OriginalSpan);
var firstTokenInSelection = root.FindTokenOnRightOfPosition(adjustedSpan.Start, includeSkipped: false);
var lastTokenInSelection = root.FindTokenOnLeftOfPosition(adjustedSpan.End, includeSkipped: false);
if (firstTokenInSelection.Kind() == SyntaxKind.None || lastTokenInSelection.Kind() == SyntaxKind.None)
{
return new SelectionInfo { Status = new OperationStatus(OperationStatusFlag.None, FeaturesResources.Invalid_selection), OriginalSpan = adjustedSpan };
}
if (!adjustedSpan.Contains(firstTokenInSelection.Span) && !adjustedSpan.Contains(lastTokenInSelection.Span))
{
return new SelectionInfo
{
Status = new OperationStatus(OperationStatusFlag.None, FeaturesResources.Selection_does_not_contain_a_valid_token),
OriginalSpan = adjustedSpan,
FirstTokenInOriginalSpan = firstTokenInSelection,
LastTokenInOriginalSpan = lastTokenInSelection
};
}
if (!firstTokenInSelection.UnderValidContext() || !lastTokenInSelection.UnderValidContext())
{
return new SelectionInfo
{
Status = new OperationStatus(OperationStatusFlag.None, FeaturesResources.No_valid_selection_to_perform_extraction),
OriginalSpan = adjustedSpan,
FirstTokenInOriginalSpan = firstTokenInSelection,
LastTokenInOriginalSpan = lastTokenInSelection
};
}
var commonRoot = firstTokenInSelection.GetCommonRoot(lastTokenInSelection);
if (commonRoot == null)
{
return new SelectionInfo
{
Status = new OperationStatus(OperationStatusFlag.None, FeaturesResources.No_common_root_node_for_extraction),
OriginalSpan = adjustedSpan,
FirstTokenInOriginalSpan = firstTokenInSelection,
LastTokenInOriginalSpan = lastTokenInSelection
};
}
if (!commonRoot.ContainedInValidType())
{
return new SelectionInfo
{
Status = new OperationStatus(OperationStatusFlag.None, FeaturesResources.Selection_not_contained_inside_a_type),
OriginalSpan = adjustedSpan,
FirstTokenInOriginalSpan = firstTokenInSelection,
LastTokenInOriginalSpan = lastTokenInSelection
};
}
var selectionInExpression = commonRoot is ExpressionSyntax;
if (!selectionInExpression && !commonRoot.UnderValidContext())
{
return new SelectionInfo
{
Status = new OperationStatus(OperationStatusFlag.None, FeaturesResources.No_valid_selection_to_perform_extraction),
OriginalSpan = adjustedSpan,
FirstTokenInOriginalSpan = firstTokenInSelection,
LastTokenInOriginalSpan = lastTokenInSelection
};
}
return new SelectionInfo
{
Status = OperationStatus.Succeeded,
OriginalSpan = adjustedSpan,
CommonRootFromOriginalSpan = commonRoot,
SelectionInExpression = selectionInExpression,
FirstTokenInOriginalSpan = firstTokenInSelection,
LastTokenInOriginalSpan = lastTokenInSelection
};
}
private static SelectionInfo CheckErrorCasesAndAppendDescriptions(
SelectionInfo selectionInfo,
SyntaxNode root)
{
if (selectionInfo.Status.FailedWithNoBestEffortSuggestion())
{
return selectionInfo;
}
if (selectionInfo.FirstTokenInFinalSpan.IsMissing || selectionInfo.LastTokenInFinalSpan.IsMissing)
{
selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.Contains_invalid_selection));
}
// get the node that covers the selection
var commonNode = selectionInfo.FirstTokenInFinalSpan.GetCommonRoot(selectionInfo.LastTokenInFinalSpan);
if ((selectionInfo.SelectionInExpression || selectionInfo.SelectionInSingleStatement) && commonNode.HasDiagnostics())
{
selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.The_selection_contains_syntactic_errors));
}
var tokens = root.DescendantTokens(selectionInfo.FinalSpan);
if (tokens.ContainPreprocessorCrossOver(selectionInfo.FinalSpan))
{
selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.BestEffort, CSharpFeaturesResources.Selection_can_not_cross_over_preprocessor_directives));
}
// TODO : check whether this can be handled by control flow analysis engine
if (tokens.Any(t => t.Kind() == SyntaxKind.YieldKeyword))
{
selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.BestEffort, CSharpFeaturesResources.Selection_can_not_contain_a_yield_statement));
}
// TODO : check behavior of control flow analysis engine around exception and exception handling.
if (tokens.ContainArgumentlessThrowWithoutEnclosingCatch(selectionInfo.FinalSpan))
{
selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.BestEffort, CSharpFeaturesResources.Selection_can_not_contain_throw_statement));
}
if (selectionInfo.SelectionInExpression && commonNode.PartOfConstantInitializerExpression())
{
selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.Selection_can_not_be_part_of_constant_initializer_expression));
}
if (commonNode.IsUnsafeContext())
{
selectionInfo = selectionInfo.WithStatus(s => s.With(s.Flag, CSharpFeaturesResources.The_selected_code_is_inside_an_unsafe_context));
}
// For now patterns are being blanket disabled for extract method. This issue covers designing extractions for them
// and re-enabling this.
// https://github.com/dotnet/roslyn/issues/9244
if (commonNode.Kind() == SyntaxKind.IsPatternExpression)
{
selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.Selection_can_not_contain_a_pattern_expression));
}
var selectionChanged = selectionInfo.FirstTokenInOriginalSpan != selectionInfo.FirstTokenInFinalSpan || selectionInfo.LastTokenInOriginalSpan != selectionInfo.LastTokenInFinalSpan;
if (selectionChanged)
{
selectionInfo = selectionInfo.WithStatus(s => s.MarkSuggestion());
}
return selectionInfo;
}
private static SelectionInfo AssignInitialFinalTokens(SelectionInfo selectionInfo, SyntaxNode root, CancellationToken cancellationToken)
{
if (selectionInfo.Status.FailedWithNoBestEffortSuggestion())
{
return selectionInfo;
}
if (selectionInfo.SelectionInExpression)
{
// simple expression case
return selectionInfo.With(s => s.FirstTokenInFinalSpan = s.CommonRootFromOriginalSpan.GetFirstToken(includeZeroWidth: true))
.With(s => s.LastTokenInFinalSpan = s.CommonRootFromOriginalSpan.GetLastToken(includeZeroWidth: true));
}
var range = GetStatementRangeContainingSpan<StatementSyntax>(
root, TextSpan.FromBounds(selectionInfo.FirstTokenInOriginalSpan.SpanStart, selectionInfo.LastTokenInOriginalSpan.Span.End),
cancellationToken);
if (range == null)
{
return selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.No_valid_statement_range_to_extract));
}
var statement1 = (StatementSyntax)range.Item1;
var statement2 = (StatementSyntax)range.Item2;
if (statement1 == statement2)
{
// check one more time to see whether it is an expression case
var expression = selectionInfo.CommonRootFromOriginalSpan.GetAncestor<ExpressionSyntax>();
if (expression != null && statement1.Span.Contains(expression.Span))
{
return selectionInfo.With(s => s.SelectionInExpression = true)
.With(s => s.FirstTokenInFinalSpan = expression.GetFirstToken(includeZeroWidth: true))
.With(s => s.LastTokenInFinalSpan = expression.GetLastToken(includeZeroWidth: true));
}
// single statement case
return selectionInfo.With(s => s.SelectionInSingleStatement = true)
.With(s => s.FirstTokenInFinalSpan = statement1.GetFirstToken(includeZeroWidth: true))
.With(s => s.LastTokenInFinalSpan = statement1.GetLastToken(includeZeroWidth: true));
}
// move only statements inside of the block
return selectionInfo.With(s => s.FirstTokenInFinalSpan = statement1.GetFirstToken(includeZeroWidth: true))
.With(s => s.LastTokenInFinalSpan = statement2.GetLastToken(includeZeroWidth: true));
}
private static SelectionInfo AssignFinalSpan(SelectionInfo selectionInfo, SourceText text)
{
if (selectionInfo.Status.FailedWithNoBestEffortSuggestion())
{
return selectionInfo;
}
// set final span
var start = (selectionInfo.FirstTokenInOriginalSpan == selectionInfo.FirstTokenInFinalSpan) ?
Math.Min(selectionInfo.FirstTokenInOriginalSpan.SpanStart, selectionInfo.OriginalSpan.Start) :
selectionInfo.FirstTokenInFinalSpan.FullSpan.Start;
var end = (selectionInfo.LastTokenInOriginalSpan == selectionInfo.LastTokenInFinalSpan) ?
Math.Max(selectionInfo.LastTokenInOriginalSpan.Span.End, selectionInfo.OriginalSpan.End) :
selectionInfo.LastTokenInFinalSpan.FullSpan.End;
return selectionInfo.With(s => s.FinalSpan = GetAdjustedSpan(text, TextSpan.FromBounds(start, end)));
}
public override bool ContainsNonReturnExitPointsStatements(IEnumerable<SyntaxNode> jumpsOutOfRegion)
=> jumpsOutOfRegion.Where(n => !(n is ReturnStatementSyntax)).Any();
public override IEnumerable<SyntaxNode> GetOuterReturnStatements(SyntaxNode commonRoot, IEnumerable<SyntaxNode> jumpsOutOfRegion)
{
var returnStatements = jumpsOutOfRegion.Where(s => s is ReturnStatementSyntax);
var container = commonRoot.GetAncestorsOrThis<SyntaxNode>().Where(a => a.IsReturnableConstruct()).FirstOrDefault();
if (container == null)
{
return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
var returnableConstructPairs = returnStatements.Select(r => Tuple.Create(r, r.GetAncestors<SyntaxNode>().Where(a => a.IsReturnableConstruct()).FirstOrDefault()))
.Where(p => p.Item2 != null);
// now filter return statements to only include the one under outmost container
return returnableConstructPairs.Where(p => p.Item2 == container).Select(p => p.Item1);
}
public override bool IsFinalSpanSemanticallyValidSpan(
SyntaxNode root, TextSpan textSpan,
IEnumerable<SyntaxNode> returnStatements, CancellationToken cancellationToken)
{
// return statement shouldn't contain any return value
if (returnStatements.Cast<ReturnStatementSyntax>().Any(r => r.Expression != null))
{
return false;
}
var lastToken = root.FindToken(textSpan.End);
if (lastToken.Kind() == SyntaxKind.None)
{
return false;
}
var container = lastToken.GetAncestors<SyntaxNode>().FirstOrDefault(n => n.IsReturnableConstruct());
if (container == null)
{
return false;
}
var body = container.GetBlockBody();
if (body == null)
{
return false;
}
// make sure that next token of the last token in the selection is the close braces of containing block
if (body.CloseBraceToken != lastToken.GetNextToken(includeZeroWidth: true))
{
return false;
}
// alright, for these constructs, it must be okay to be extracted
switch (container.Kind())
{
case SyntaxKind.AnonymousMethodExpression:
case SyntaxKind.SimpleLambdaExpression:
case SyntaxKind.ParenthesizedLambdaExpression:
return true;
}
// now, only method is okay to be extracted out
if (!(body.Parent is MethodDeclarationSyntax method))
{
return false;
}
// make sure this method doesn't have return type.
return method.ReturnType is PredefinedTypeSyntax p &&
p.Keyword.Kind() == SyntaxKind.VoidKeyword;
}
private static TextSpan GetAdjustedSpan(SourceText text, TextSpan textSpan)
{
// beginning of a file
if (textSpan.IsEmpty || textSpan.End == 0)
{
return textSpan;
}
// if it is a start of new line, make it belong to previous line
var line = text.Lines.GetLineFromPosition(textSpan.End);
if (line.Start != textSpan.End)
{
return textSpan;
}
// get previous line
Contract.ThrowIfFalse(line.LineNumber > 0);
var previousLine = text.Lines[line.LineNumber - 1];
// if the span is past the end of the line (ie, in whitespace) then
// return to the end of the line including whitespace
if (textSpan.Start > previousLine.End)
{
return TextSpan.FromBounds(textSpan.Start, previousLine.EndIncludingLineBreak);
}
return TextSpan.FromBounds(textSpan.Start, previousLine.End);
}
private class SelectionInfo
{
public OperationStatus Status { get; set; }
public TextSpan OriginalSpan { get; set; }
public TextSpan FinalSpan { get; set; }
public SyntaxNode CommonRootFromOriginalSpan { get; set; }
public SyntaxToken FirstTokenInOriginalSpan { get; set; }
public SyntaxToken LastTokenInOriginalSpan { get; set; }
public SyntaxToken FirstTokenInFinalSpan { get; set; }
public SyntaxToken LastTokenInFinalSpan { get; set; }
public bool SelectionInExpression { get; set; }
public bool SelectionInSingleStatement { get; set; }
public SelectionInfo WithStatus(Func<OperationStatus, OperationStatus> statusGetter)
=> With(s => s.Status = statusGetter(s.Status));
public SelectionInfo With(Action<SelectionInfo> valueSetter)
{
var newInfo = Clone();
valueSetter(newInfo);
return newInfo;
}
public SelectionInfo Clone()
=> (SelectionInfo)MemberwiseClone();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.ExtractMethod;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod
{
internal partial class CSharpSelectionValidator : SelectionValidator
{
public CSharpSelectionValidator(
SemanticDocument document,
TextSpan textSpan,
OptionSet options)
: base(document, textSpan, options)
{
}
public override async Task<SelectionResult> GetValidSelectionAsync(CancellationToken cancellationToken)
{
if (!ContainsValidSelection)
{
return NullSelection;
}
var text = SemanticDocument.Text;
var root = SemanticDocument.Root;
var model = SemanticDocument.SemanticModel;
var doc = SemanticDocument;
// go through pipe line and calculate information about the user selection
var selectionInfo = GetInitialSelectionInfo(root, text);
selectionInfo = AssignInitialFinalTokens(selectionInfo, root, cancellationToken);
selectionInfo = AdjustFinalTokensBasedOnContext(selectionInfo, model, cancellationToken);
selectionInfo = AssignFinalSpan(selectionInfo, text);
selectionInfo = ApplySpecialCases(selectionInfo, text);
selectionInfo = CheckErrorCasesAndAppendDescriptions(selectionInfo, root);
// there was a fatal error that we couldn't even do negative preview, return error result
if (selectionInfo.Status.FailedWithNoBestEffortSuggestion())
{
return new ErrorSelectionResult(selectionInfo.Status);
}
var controlFlowSpan = GetControlFlowSpan(selectionInfo);
if (!selectionInfo.SelectionInExpression)
{
var statementRange = GetStatementRangeContainedInSpan<StatementSyntax>(root, controlFlowSpan, cancellationToken);
if (statementRange == null)
{
selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.Can_t_determine_valid_range_of_statements_to_extract));
return new ErrorSelectionResult(selectionInfo.Status);
}
var isFinalSpanSemanticallyValid = IsFinalSpanSemanticallyValidSpan(model, controlFlowSpan, statementRange, cancellationToken);
if (!isFinalSpanSemanticallyValid)
{
// check control flow only if we are extracting statement level, not expression
// level. you can not have goto that moves control out of scope in expression level
// (even in lambda)
selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.BestEffort, CSharpFeaturesResources.Not_all_code_paths_return));
}
}
return await CSharpSelectionResult.CreateAsync(
selectionInfo.Status,
selectionInfo.OriginalSpan,
selectionInfo.FinalSpan,
Options,
selectionInfo.SelectionInExpression,
doc,
selectionInfo.FirstTokenInFinalSpan,
selectionInfo.LastTokenInFinalSpan,
cancellationToken).ConfigureAwait(false);
}
private static SelectionInfo ApplySpecialCases(SelectionInfo selectionInfo, SourceText text)
{
if (selectionInfo.Status.FailedWithNoBestEffortSuggestion() || !selectionInfo.SelectionInExpression)
{
return selectionInfo;
}
var expressionNode = selectionInfo.FirstTokenInFinalSpan.GetCommonRoot(selectionInfo.LastTokenInFinalSpan);
if (!expressionNode.IsAnyAssignExpression())
{
return selectionInfo;
}
var assign = (AssignmentExpressionSyntax)expressionNode;
// make sure there is a visible token at right side expression
if (assign.Right.GetLastToken().Kind() == SyntaxKind.None)
{
return selectionInfo;
}
return AssignFinalSpan(selectionInfo.With(s => s.FirstTokenInFinalSpan = assign.Right.GetFirstToken(includeZeroWidth: true))
.With(s => s.LastTokenInFinalSpan = assign.Right.GetLastToken(includeZeroWidth: true)),
text);
}
private static TextSpan GetControlFlowSpan(SelectionInfo selectionInfo)
=> TextSpan.FromBounds(selectionInfo.FirstTokenInFinalSpan.SpanStart, selectionInfo.LastTokenInFinalSpan.Span.End);
private static SelectionInfo AdjustFinalTokensBasedOnContext(
SelectionInfo selectionInfo,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
if (selectionInfo.Status.FailedWithNoBestEffortSuggestion())
{
return selectionInfo;
}
// don't need to adjust anything if it is multi-statements case
if (!selectionInfo.SelectionInExpression && !selectionInfo.SelectionInSingleStatement)
{
return selectionInfo;
}
// get the node that covers the selection
var node = selectionInfo.FirstTokenInFinalSpan.GetCommonRoot(selectionInfo.LastTokenInFinalSpan);
var validNode = Check(semanticModel, node, cancellationToken);
if (validNode)
{
return selectionInfo;
}
var firstValidNode = node.GetAncestors<SyntaxNode>().FirstOrDefault(n => Check(semanticModel, n, cancellationToken));
if (firstValidNode == null)
{
// couldn't find any valid node
return selectionInfo.WithStatus(s => new OperationStatus(OperationStatusFlag.None, CSharpFeaturesResources.Selection_does_not_contain_a_valid_node))
.With(s => s.FirstTokenInFinalSpan = default)
.With(s => s.LastTokenInFinalSpan = default);
}
firstValidNode = (firstValidNode.Parent is ExpressionStatementSyntax) ? firstValidNode.Parent : firstValidNode;
return selectionInfo.With(s => s.SelectionInExpression = firstValidNode is ExpressionSyntax)
.With(s => s.SelectionInSingleStatement = firstValidNode is StatementSyntax)
.With(s => s.FirstTokenInFinalSpan = firstValidNode.GetFirstToken(includeZeroWidth: true))
.With(s => s.LastTokenInFinalSpan = firstValidNode.GetLastToken(includeZeroWidth: true));
}
private SelectionInfo GetInitialSelectionInfo(SyntaxNode root, SourceText text)
{
var adjustedSpan = GetAdjustedSpan(text, OriginalSpan);
var firstTokenInSelection = root.FindTokenOnRightOfPosition(adjustedSpan.Start, includeSkipped: false);
var lastTokenInSelection = root.FindTokenOnLeftOfPosition(adjustedSpan.End, includeSkipped: false);
if (firstTokenInSelection.Kind() == SyntaxKind.None || lastTokenInSelection.Kind() == SyntaxKind.None)
{
return new SelectionInfo { Status = new OperationStatus(OperationStatusFlag.None, FeaturesResources.Invalid_selection), OriginalSpan = adjustedSpan };
}
if (!adjustedSpan.Contains(firstTokenInSelection.Span) && !adjustedSpan.Contains(lastTokenInSelection.Span))
{
return new SelectionInfo
{
Status = new OperationStatus(OperationStatusFlag.None, FeaturesResources.Selection_does_not_contain_a_valid_token),
OriginalSpan = adjustedSpan,
FirstTokenInOriginalSpan = firstTokenInSelection,
LastTokenInOriginalSpan = lastTokenInSelection
};
}
if (!firstTokenInSelection.UnderValidContext() || !lastTokenInSelection.UnderValidContext())
{
return new SelectionInfo
{
Status = new OperationStatus(OperationStatusFlag.None, FeaturesResources.No_valid_selection_to_perform_extraction),
OriginalSpan = adjustedSpan,
FirstTokenInOriginalSpan = firstTokenInSelection,
LastTokenInOriginalSpan = lastTokenInSelection
};
}
var commonRoot = firstTokenInSelection.GetCommonRoot(lastTokenInSelection);
if (commonRoot == null)
{
return new SelectionInfo
{
Status = new OperationStatus(OperationStatusFlag.None, FeaturesResources.No_common_root_node_for_extraction),
OriginalSpan = adjustedSpan,
FirstTokenInOriginalSpan = firstTokenInSelection,
LastTokenInOriginalSpan = lastTokenInSelection
};
}
if (!commonRoot.ContainedInValidType())
{
return new SelectionInfo
{
Status = new OperationStatus(OperationStatusFlag.None, FeaturesResources.Selection_not_contained_inside_a_type),
OriginalSpan = adjustedSpan,
FirstTokenInOriginalSpan = firstTokenInSelection,
LastTokenInOriginalSpan = lastTokenInSelection
};
}
var selectionInExpression = commonRoot is ExpressionSyntax;
if (!selectionInExpression && !commonRoot.UnderValidContext())
{
return new SelectionInfo
{
Status = new OperationStatus(OperationStatusFlag.None, FeaturesResources.No_valid_selection_to_perform_extraction),
OriginalSpan = adjustedSpan,
FirstTokenInOriginalSpan = firstTokenInSelection,
LastTokenInOriginalSpan = lastTokenInSelection
};
}
return new SelectionInfo
{
Status = OperationStatus.Succeeded,
OriginalSpan = adjustedSpan,
CommonRootFromOriginalSpan = commonRoot,
SelectionInExpression = selectionInExpression,
FirstTokenInOriginalSpan = firstTokenInSelection,
LastTokenInOriginalSpan = lastTokenInSelection
};
}
private static SelectionInfo CheckErrorCasesAndAppendDescriptions(
SelectionInfo selectionInfo,
SyntaxNode root)
{
if (selectionInfo.Status.FailedWithNoBestEffortSuggestion())
{
return selectionInfo;
}
if (selectionInfo.FirstTokenInFinalSpan.IsMissing || selectionInfo.LastTokenInFinalSpan.IsMissing)
{
selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.Contains_invalid_selection));
}
// get the node that covers the selection
var commonNode = selectionInfo.FirstTokenInFinalSpan.GetCommonRoot(selectionInfo.LastTokenInFinalSpan);
if ((selectionInfo.SelectionInExpression || selectionInfo.SelectionInSingleStatement) && commonNode.HasDiagnostics())
{
selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.The_selection_contains_syntactic_errors));
}
var tokens = root.DescendantTokens(selectionInfo.FinalSpan);
if (tokens.ContainPreprocessorCrossOver(selectionInfo.FinalSpan))
{
selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.BestEffort, CSharpFeaturesResources.Selection_can_not_cross_over_preprocessor_directives));
}
// TODO : check whether this can be handled by control flow analysis engine
if (tokens.Any(t => t.Kind() == SyntaxKind.YieldKeyword))
{
selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.BestEffort, CSharpFeaturesResources.Selection_can_not_contain_a_yield_statement));
}
// TODO : check behavior of control flow analysis engine around exception and exception handling.
if (tokens.ContainArgumentlessThrowWithoutEnclosingCatch(selectionInfo.FinalSpan))
{
selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.BestEffort, CSharpFeaturesResources.Selection_can_not_contain_throw_statement));
}
if (selectionInfo.SelectionInExpression && commonNode.PartOfConstantInitializerExpression())
{
selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.Selection_can_not_be_part_of_constant_initializer_expression));
}
if (commonNode.IsUnsafeContext())
{
selectionInfo = selectionInfo.WithStatus(s => s.With(s.Flag, CSharpFeaturesResources.The_selected_code_is_inside_an_unsafe_context));
}
// For now patterns are being blanket disabled for extract method. This issue covers designing extractions for them
// and re-enabling this.
// https://github.com/dotnet/roslyn/issues/9244
if (commonNode.Kind() == SyntaxKind.IsPatternExpression)
{
selectionInfo = selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.Selection_can_not_contain_a_pattern_expression));
}
var selectionChanged = selectionInfo.FirstTokenInOriginalSpan != selectionInfo.FirstTokenInFinalSpan || selectionInfo.LastTokenInOriginalSpan != selectionInfo.LastTokenInFinalSpan;
if (selectionChanged)
{
selectionInfo = selectionInfo.WithStatus(s => s.MarkSuggestion());
}
return selectionInfo;
}
private static SelectionInfo AssignInitialFinalTokens(SelectionInfo selectionInfo, SyntaxNode root, CancellationToken cancellationToken)
{
if (selectionInfo.Status.FailedWithNoBestEffortSuggestion())
{
return selectionInfo;
}
if (selectionInfo.SelectionInExpression)
{
// simple expression case
return selectionInfo.With(s => s.FirstTokenInFinalSpan = s.CommonRootFromOriginalSpan.GetFirstToken(includeZeroWidth: true))
.With(s => s.LastTokenInFinalSpan = s.CommonRootFromOriginalSpan.GetLastToken(includeZeroWidth: true));
}
var range = GetStatementRangeContainingSpan<StatementSyntax>(
root, TextSpan.FromBounds(selectionInfo.FirstTokenInOriginalSpan.SpanStart, selectionInfo.LastTokenInOriginalSpan.Span.End),
cancellationToken);
if (range == null)
{
return selectionInfo.WithStatus(s => s.With(OperationStatusFlag.None, CSharpFeaturesResources.No_valid_statement_range_to_extract));
}
var statement1 = (StatementSyntax)range.Item1;
var statement2 = (StatementSyntax)range.Item2;
if (statement1 == statement2)
{
// check one more time to see whether it is an expression case
var expression = selectionInfo.CommonRootFromOriginalSpan.GetAncestor<ExpressionSyntax>();
if (expression != null && statement1.Span.Contains(expression.Span))
{
return selectionInfo.With(s => s.SelectionInExpression = true)
.With(s => s.FirstTokenInFinalSpan = expression.GetFirstToken(includeZeroWidth: true))
.With(s => s.LastTokenInFinalSpan = expression.GetLastToken(includeZeroWidth: true));
}
// single statement case
return selectionInfo.With(s => s.SelectionInSingleStatement = true)
.With(s => s.FirstTokenInFinalSpan = statement1.GetFirstToken(includeZeroWidth: true))
.With(s => s.LastTokenInFinalSpan = statement1.GetLastToken(includeZeroWidth: true));
}
// move only statements inside of the block
return selectionInfo.With(s => s.FirstTokenInFinalSpan = statement1.GetFirstToken(includeZeroWidth: true))
.With(s => s.LastTokenInFinalSpan = statement2.GetLastToken(includeZeroWidth: true));
}
private static SelectionInfo AssignFinalSpan(SelectionInfo selectionInfo, SourceText text)
{
if (selectionInfo.Status.FailedWithNoBestEffortSuggestion())
{
return selectionInfo;
}
// set final span
var start = (selectionInfo.FirstTokenInOriginalSpan == selectionInfo.FirstTokenInFinalSpan) ?
Math.Min(selectionInfo.FirstTokenInOriginalSpan.SpanStart, selectionInfo.OriginalSpan.Start) :
selectionInfo.FirstTokenInFinalSpan.FullSpan.Start;
var end = (selectionInfo.LastTokenInOriginalSpan == selectionInfo.LastTokenInFinalSpan) ?
Math.Max(selectionInfo.LastTokenInOriginalSpan.Span.End, selectionInfo.OriginalSpan.End) :
selectionInfo.LastTokenInFinalSpan.FullSpan.End;
return selectionInfo.With(s => s.FinalSpan = GetAdjustedSpan(text, TextSpan.FromBounds(start, end)));
}
public override bool ContainsNonReturnExitPointsStatements(IEnumerable<SyntaxNode> jumpsOutOfRegion)
=> jumpsOutOfRegion.Where(n => !(n is ReturnStatementSyntax)).Any();
public override IEnumerable<SyntaxNode> GetOuterReturnStatements(SyntaxNode commonRoot, IEnumerable<SyntaxNode> jumpsOutOfRegion)
{
var returnStatements = jumpsOutOfRegion.Where(s => s is ReturnStatementSyntax);
var container = commonRoot.GetAncestorsOrThis<SyntaxNode>().Where(a => a.IsReturnableConstruct()).FirstOrDefault();
if (container == null)
{
return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
var returnableConstructPairs = returnStatements.Select(r => Tuple.Create(r, r.GetAncestors<SyntaxNode>().Where(a => a.IsReturnableConstruct()).FirstOrDefault()))
.Where(p => p.Item2 != null);
// now filter return statements to only include the one under outmost container
return returnableConstructPairs.Where(p => p.Item2 == container).Select(p => p.Item1);
}
public override bool IsFinalSpanSemanticallyValidSpan(
SyntaxNode root, TextSpan textSpan,
IEnumerable<SyntaxNode> returnStatements, CancellationToken cancellationToken)
{
// return statement shouldn't contain any return value
if (returnStatements.Cast<ReturnStatementSyntax>().Any(r => r.Expression != null))
{
return false;
}
var lastToken = root.FindToken(textSpan.End);
if (lastToken.Kind() == SyntaxKind.None)
{
return false;
}
var container = lastToken.GetAncestors<SyntaxNode>().FirstOrDefault(n => n.IsReturnableConstruct());
if (container == null)
{
return false;
}
var body = container.GetBlockBody();
if (body == null)
{
return false;
}
// make sure that next token of the last token in the selection is the close braces of containing block
if (body.CloseBraceToken != lastToken.GetNextToken(includeZeroWidth: true))
{
return false;
}
// alright, for these constructs, it must be okay to be extracted
switch (container.Kind())
{
case SyntaxKind.AnonymousMethodExpression:
case SyntaxKind.SimpleLambdaExpression:
case SyntaxKind.ParenthesizedLambdaExpression:
return true;
}
// now, only method is okay to be extracted out
if (!(body.Parent is MethodDeclarationSyntax method))
{
return false;
}
// make sure this method doesn't have return type.
return method.ReturnType is PredefinedTypeSyntax p &&
p.Keyword.Kind() == SyntaxKind.VoidKeyword;
}
private static TextSpan GetAdjustedSpan(SourceText text, TextSpan textSpan)
{
// beginning of a file
if (textSpan.IsEmpty || textSpan.End == 0)
{
return textSpan;
}
// if it is a start of new line, make it belong to previous line
var line = text.Lines.GetLineFromPosition(textSpan.End);
if (line.Start != textSpan.End)
{
return textSpan;
}
// get previous line
Contract.ThrowIfFalse(line.LineNumber > 0);
var previousLine = text.Lines[line.LineNumber - 1];
// if the span is past the end of the line (ie, in whitespace) then
// return to the end of the line including whitespace
if (textSpan.Start > previousLine.End)
{
return TextSpan.FromBounds(textSpan.Start, previousLine.EndIncludingLineBreak);
}
return TextSpan.FromBounds(textSpan.Start, previousLine.End);
}
private class SelectionInfo
{
public OperationStatus Status { get; set; }
public TextSpan OriginalSpan { get; set; }
public TextSpan FinalSpan { get; set; }
public SyntaxNode CommonRootFromOriginalSpan { get; set; }
public SyntaxToken FirstTokenInOriginalSpan { get; set; }
public SyntaxToken LastTokenInOriginalSpan { get; set; }
public SyntaxToken FirstTokenInFinalSpan { get; set; }
public SyntaxToken LastTokenInFinalSpan { get; set; }
public bool SelectionInExpression { get; set; }
public bool SelectionInSingleStatement { get; set; }
public SelectionInfo WithStatus(Func<OperationStatus, OperationStatus> statusGetter)
=> With(s => s.Status = statusGetter(s.Status));
public SelectionInfo With(Action<SelectionInfo> valueSetter)
{
var newInfo = Clone();
valueSetter(newInfo);
return newInfo;
}
public SelectionInfo Clone()
=> (SelectionInfo)MemberwiseClone();
}
}
}
| -1 |
dotnet/roslyn | 55,530 | Ignore modules with bad metadata in function resolver | Fixes https://github.com/dotnet/roslyn/issues/55475 | tmat | 2021-08-10T18:56:37Z | 2021-08-11T18:37:09Z | cd0c0464c069a2b80774d70f071c29333d9fa23c | bc874ebc5111a2a33221409f895953b1536f6612 | Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475 | ./src/Features/Core/Portable/ValidateFormatString/ValidateFormatStringOptionProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
namespace Microsoft.CodeAnalysis.ValidateFormatString
{
[ExportOptionProvider, Shared]
internal class ValidateFormatStringOptionProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ValidateFormatStringOptionProvider()
{
}
public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(
ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
namespace Microsoft.CodeAnalysis.ValidateFormatString
{
[ExportOptionProvider, Shared]
internal class ValidateFormatStringOptionProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ValidateFormatStringOptionProvider()
{
}
public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(
ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls);
}
}
| -1 |
dotnet/roslyn | 55,530 | Ignore modules with bad metadata in function resolver | Fixes https://github.com/dotnet/roslyn/issues/55475 | tmat | 2021-08-10T18:56:37Z | 2021-08-11T18:37:09Z | cd0c0464c069a2b80774d70f071c29333d9fa23c | bc874ebc5111a2a33221409f895953b1536f6612 | Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475 | ./src/Features/Core/Portable/ImplementType/ImplementTypeOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Options;
namespace Microsoft.CodeAnalysis.ImplementType
{
internal enum ImplementTypeInsertionBehavior
{
WithOtherMembersOfTheSameKind = 0,
AtTheEnd = 1,
}
internal enum ImplementTypePropertyGenerationBehavior
{
PreferThrowingProperties = 0,
PreferAutoProperties = 1,
}
internal static class ImplementTypeOptions
{
public static readonly PerLanguageOption2<ImplementTypeInsertionBehavior> InsertionBehavior =
new(
nameof(ImplementTypeOptions),
nameof(InsertionBehavior),
defaultValue: ImplementTypeInsertionBehavior.WithOtherMembersOfTheSameKind,
storageLocations: new RoamingProfileStorageLocation(
$"TextEditor.%LANGUAGE%.{nameof(ImplementTypeOptions)}.{nameof(InsertionBehavior)}"));
public static readonly PerLanguageOption2<ImplementTypePropertyGenerationBehavior> PropertyGenerationBehavior =
new(
nameof(ImplementTypeOptions),
nameof(PropertyGenerationBehavior),
defaultValue: ImplementTypePropertyGenerationBehavior.PreferThrowingProperties,
storageLocations: new RoamingProfileStorageLocation(
$"TextEditor.%LANGUAGE%.{nameof(ImplementTypeOptions)}.{nameof(PropertyGenerationBehavior)}"));
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Options;
namespace Microsoft.CodeAnalysis.ImplementType
{
internal enum ImplementTypeInsertionBehavior
{
WithOtherMembersOfTheSameKind = 0,
AtTheEnd = 1,
}
internal enum ImplementTypePropertyGenerationBehavior
{
PreferThrowingProperties = 0,
PreferAutoProperties = 1,
}
internal static class ImplementTypeOptions
{
public static readonly PerLanguageOption2<ImplementTypeInsertionBehavior> InsertionBehavior =
new(
nameof(ImplementTypeOptions),
nameof(InsertionBehavior),
defaultValue: ImplementTypeInsertionBehavior.WithOtherMembersOfTheSameKind,
storageLocations: new RoamingProfileStorageLocation(
$"TextEditor.%LANGUAGE%.{nameof(ImplementTypeOptions)}.{nameof(InsertionBehavior)}"));
public static readonly PerLanguageOption2<ImplementTypePropertyGenerationBehavior> PropertyGenerationBehavior =
new(
nameof(ImplementTypeOptions),
nameof(PropertyGenerationBehavior),
defaultValue: ImplementTypePropertyGenerationBehavior.PreferThrowingProperties,
storageLocations: new RoamingProfileStorageLocation(
$"TextEditor.%LANGUAGE%.{nameof(ImplementTypeOptions)}.{nameof(PropertyGenerationBehavior)}"));
}
}
| -1 |
dotnet/roslyn | 55,530 | Ignore modules with bad metadata in function resolver | Fixes https://github.com/dotnet/roslyn/issues/55475 | tmat | 2021-08-10T18:56:37Z | 2021-08-11T18:37:09Z | cd0c0464c069a2b80774d70f071c29333d9fa23c | bc874ebc5111a2a33221409f895953b1536f6612 | Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475 | ./src/Dependencies/PooledObjects/ArrayBuilder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.PooledObjects
{
[DebuggerDisplay("Count = {Count,nq}")]
[DebuggerTypeProxy(typeof(ArrayBuilder<>.DebuggerProxy))]
internal sealed partial class ArrayBuilder<T> : IReadOnlyCollection<T>, IReadOnlyList<T>
{
#region DebuggerProxy
private sealed class DebuggerProxy
{
private readonly ArrayBuilder<T> _builder;
public DebuggerProxy(ArrayBuilder<T> builder)
{
_builder = builder;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public T[] A
{
get
{
var result = new T[_builder.Count];
for (var i = 0; i < result.Length; i++)
{
result[i] = _builder[i];
}
return result;
}
}
}
#endregion
private readonly ImmutableArray<T>.Builder _builder;
private readonly ObjectPool<ArrayBuilder<T>>? _pool;
public ArrayBuilder(int size)
{
_builder = ImmutableArray.CreateBuilder<T>(size);
}
public ArrayBuilder()
: this(8)
{ }
private ArrayBuilder(ObjectPool<ArrayBuilder<T>> pool)
: this()
{
_pool = pool;
}
/// <summary>
/// Realizes the array.
/// </summary>
public ImmutableArray<T> ToImmutable()
{
return _builder.ToImmutable();
}
/// <summary>
/// Realizes the array and clears the collection.
/// </summary>
public ImmutableArray<T> ToImmutableAndClear()
{
ImmutableArray<T> result;
if (Count == 0)
{
result = ImmutableArray<T>.Empty;
}
else if (_builder.Capacity == Count)
{
result = _builder.MoveToImmutable();
}
else
{
result = ToImmutable();
Clear();
}
return result;
}
public int Count
{
get
{
return _builder.Count;
}
set
{
_builder.Count = value;
}
}
public T this[int index]
{
get
{
return _builder[index];
}
set
{
_builder[index] = value;
}
}
/// <summary>
/// Write <paramref name="value"/> to slot <paramref name="index"/>.
/// Fills in unallocated slots preceding the <paramref name="index"/>, if any.
/// </summary>
public void SetItem(int index, T value)
{
while (index > _builder.Count)
{
_builder.Add(default!);
}
if (index == _builder.Count)
{
_builder.Add(value);
}
else
{
_builder[index] = value;
}
}
public void Add(T item)
{
_builder.Add(item);
}
public void Insert(int index, T item)
{
_builder.Insert(index, item);
}
public void EnsureCapacity(int capacity)
{
if (_builder.Capacity < capacity)
{
_builder.Capacity = capacity;
}
}
public void Clear()
{
_builder.Clear();
}
public bool Contains(T item)
{
return _builder.Contains(item);
}
public int IndexOf(T item)
{
return _builder.IndexOf(item);
}
public int IndexOf(T item, IEqualityComparer<T> equalityComparer)
{
return _builder.IndexOf(item, 0, _builder.Count, equalityComparer);
}
public int IndexOf(T item, int startIndex, int count)
{
return _builder.IndexOf(item, startIndex, count);
}
public int FindIndex(Predicate<T> match)
=> FindIndex(0, this.Count, match);
public int FindIndex(int startIndex, Predicate<T> match)
=> FindIndex(startIndex, this.Count - startIndex, match);
public int FindIndex(int startIndex, int count, Predicate<T> match)
{
var endIndex = startIndex + count;
for (var i = startIndex; i < endIndex; i++)
{
if (match(_builder[i]))
{
return i;
}
}
return -1;
}
public int FindIndex<TArg>(Func<T, TArg, bool> match, TArg arg)
=> FindIndex(0, Count, match, arg);
public int FindIndex<TArg>(int startIndex, Func<T, TArg, bool> match, TArg arg)
=> FindIndex(startIndex, Count - startIndex, match, arg);
public int FindIndex<TArg>(int startIndex, int count, Func<T, TArg, bool> match, TArg arg)
{
var endIndex = startIndex + count;
for (var i = startIndex; i < endIndex; i++)
{
if (match(_builder[i], arg))
{
return i;
}
}
return -1;
}
public bool Remove(T element)
{
return _builder.Remove(element);
}
public void RemoveAt(int index)
{
_builder.RemoveAt(index);
}
public void RemoveLast()
{
_builder.RemoveAt(_builder.Count - 1);
}
public void ReverseContents()
{
_builder.Reverse();
}
public void Sort()
{
_builder.Sort();
}
public void Sort(IComparer<T> comparer)
{
_builder.Sort(comparer);
}
public void Sort(Comparison<T> compare)
=> Sort(Comparer<T>.Create(compare));
public void Sort(int startIndex, IComparer<T> comparer)
{
_builder.Sort(startIndex, _builder.Count - startIndex, comparer);
}
public T[] ToArray()
{
return _builder.ToArray();
}
public void CopyTo(T[] array, int start)
{
_builder.CopyTo(array, start);
}
public T Last()
{
return _builder[_builder.Count - 1];
}
public T First()
{
return _builder[0];
}
public bool Any()
{
return _builder.Count > 0;
}
/// <summary>
/// Realizes the array.
/// </summary>
public ImmutableArray<T> ToImmutableOrNull()
{
if (Count == 0)
{
return default;
}
return this.ToImmutable();
}
/// <summary>
/// Realizes the array, downcasting each element to a derived type.
/// </summary>
public ImmutableArray<U> ToDowncastedImmutable<U>()
where U : T
{
if (Count == 0)
{
return ImmutableArray<U>.Empty;
}
var tmp = ArrayBuilder<U>.GetInstance(Count);
foreach (var i in this)
{
tmp.Add((U)i!);
}
return tmp.ToImmutableAndFree();
}
/// <summary>
/// Realizes the array and disposes the builder in one operation.
/// </summary>
public ImmutableArray<T> ToImmutableAndFree()
{
// This is mostly the same as 'MoveToImmutable', but avoids delegating to that method since 'Free' contains
// fast paths to avoid caling 'Clear' in some cases.
ImmutableArray<T> result;
if (Count == 0)
{
result = ImmutableArray<T>.Empty;
}
else if (_builder.Capacity == Count)
{
result = _builder.MoveToImmutable();
}
else
{
result = ToImmutable();
}
this.Free();
return result;
}
public T[] ToArrayAndFree()
{
var result = this.ToArray();
this.Free();
return result;
}
#region Poolable
// To implement Poolable, you need two things:
// 1) Expose Freeing primitive.
public void Free()
{
var pool = _pool;
if (pool != null)
{
// According to the statistics of a C# compiler self-build, the most commonly used builder size is 0. (808003 uses).
// The distant second is the Count == 1 (455619), then 2 (106362) ...
// After about 50 (just 67) we have a long tail of infrequently used builder sizes.
// However we have builders with size up to 50K (just one such thing)
//
// We do not want to retain (potentially indefinitely) very large builders
// while the chance that we will need their size is diminishingly small.
// It makes sense to constrain the size to some "not too small" number.
// Overall perf does not seem to be very sensitive to this number, so I picked 128 as a limit.
if (_builder.Capacity < 128)
{
if (this.Count != 0)
{
this.Clear();
}
pool.Free(this);
return;
}
else
{
pool.ForgetTrackedObject(this);
}
}
}
// 2) Expose the pool or the way to create a pool or the way to get an instance.
// for now we will expose both and figure which way works better
private static readonly ObjectPool<ArrayBuilder<T>> s_poolInstance = CreatePool();
public static ArrayBuilder<T> GetInstance()
{
var builder = s_poolInstance.Allocate();
Debug.Assert(builder.Count == 0);
return builder;
}
public static ArrayBuilder<T> GetInstance(int capacity)
{
var builder = GetInstance();
builder.EnsureCapacity(capacity);
return builder;
}
public static ArrayBuilder<T> GetInstance(int capacity, T fillWithValue)
{
var builder = GetInstance();
builder.EnsureCapacity(capacity);
for (var i = 0; i < capacity; i++)
{
builder.Add(fillWithValue);
}
return builder;
}
public static ObjectPool<ArrayBuilder<T>> CreatePool()
{
return CreatePool(128); // we rarely need more than 10
}
public static ObjectPool<ArrayBuilder<T>> CreatePool(int size)
{
ObjectPool<ArrayBuilder<T>>? pool = null;
pool = new ObjectPool<ArrayBuilder<T>>(() => new ArrayBuilder<T>(pool!), size);
return pool;
}
#endregion
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return _builder.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return _builder.GetEnumerator();
}
internal Dictionary<K, ImmutableArray<T>> ToDictionary<K>(Func<T, K> keySelector, IEqualityComparer<K>? comparer = null)
where K : notnull
{
if (this.Count == 1)
{
var dictionary1 = new Dictionary<K, ImmutableArray<T>>(1, comparer);
var value = this[0];
dictionary1.Add(keySelector(value), ImmutableArray.Create(value));
return dictionary1;
}
if (this.Count == 0)
{
return new Dictionary<K, ImmutableArray<T>>(comparer);
}
// bucketize
// prevent reallocation. it may not have 'count' entries, but it won't have more.
var accumulator = new Dictionary<K, ArrayBuilder<T>>(Count, comparer);
for (var i = 0; i < Count; i++)
{
var item = this[i];
var key = keySelector(item);
if (!accumulator.TryGetValue(key, out var bucket))
{
bucket = ArrayBuilder<T>.GetInstance();
accumulator.Add(key, bucket);
}
bucket.Add(item);
}
var dictionary = new Dictionary<K, ImmutableArray<T>>(accumulator.Count, comparer);
// freeze
foreach (var pair in accumulator)
{
dictionary.Add(pair.Key, pair.Value.ToImmutableAndFree());
}
return dictionary;
}
public void AddRange(ArrayBuilder<T> items)
{
_builder.AddRange(items._builder);
}
public void AddRange<U>(ArrayBuilder<U> items, Func<U, T> selector)
{
foreach (var item in items)
{
_builder.Add(selector(item));
}
}
public void AddRange<U>(ArrayBuilder<U> items) where U : T
{
_builder.AddRange(items._builder);
}
public void AddRange<U>(ArrayBuilder<U> items, int start, int length) where U : T
{
Debug.Assert(start >= 0 && length >= 0);
Debug.Assert(start + length <= items.Count);
for (int i = start, end = start + length; i < end; i++)
{
Add(items[i]);
}
}
public void AddRange(ImmutableArray<T> items)
{
_builder.AddRange(items);
}
public void AddRange(ImmutableArray<T> items, int length)
{
_builder.AddRange(items, length);
}
public void AddRange(ImmutableArray<T> items, int start, int length)
{
Debug.Assert(start >= 0 && length >= 0);
Debug.Assert(start + length <= items.Length);
for (int i = start, end = start + length; i < end; i++)
{
Add(items[i]);
}
}
public void AddRange<S>(ImmutableArray<S> items) where S : class, T
{
AddRange(ImmutableArray<T>.CastUp(items));
}
public void AddRange(T[] items, int start, int length)
{
Debug.Assert(start >= 0 && length >= 0);
Debug.Assert(start + length <= items.Length);
for (int i = start, end = start + length; i < end; i++)
{
Add(items[i]);
}
}
public void AddRange(IEnumerable<T> items)
{
_builder.AddRange(items);
}
public void AddRange(params T[] items)
{
_builder.AddRange(items);
}
public void AddRange(T[] items, int length)
{
_builder.AddRange(items, length);
}
public void Clip(int limit)
{
Debug.Assert(limit <= Count);
_builder.Count = limit;
}
public void ZeroInit(int count)
{
_builder.Clear();
_builder.Count = count;
}
public void AddMany(T item, int count)
{
for (var i = 0; i < count; i++)
{
Add(item);
}
}
public void RemoveDuplicates()
{
var set = PooledHashSet<T>.GetInstance();
var j = 0;
for (var i = 0; i < Count; i++)
{
if (set.Add(this[i]))
{
this[j] = this[i];
j++;
}
}
Clip(j);
set.Free();
}
public void SortAndRemoveDuplicates(IComparer<T> comparer)
{
if (Count <= 1)
{
return;
}
Sort(comparer);
int j = 0;
for (int i = 1; i < Count; i++)
{
if (comparer.Compare(this[j], this[i]) < 0)
{
j++;
this[j] = this[i];
}
}
Clip(j + 1);
}
public ImmutableArray<S> SelectDistinct<S>(Func<T, S> selector)
{
var result = ArrayBuilder<S>.GetInstance(Count);
var set = PooledHashSet<S>.GetInstance();
foreach (var item in this)
{
var selected = selector(item);
if (set.Add(selected))
{
result.Add(selected);
}
}
set.Free();
return result.ToImmutableAndFree();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.PooledObjects
{
[DebuggerDisplay("Count = {Count,nq}")]
[DebuggerTypeProxy(typeof(ArrayBuilder<>.DebuggerProxy))]
internal sealed partial class ArrayBuilder<T> : IReadOnlyCollection<T>, IReadOnlyList<T>
{
#region DebuggerProxy
private sealed class DebuggerProxy
{
private readonly ArrayBuilder<T> _builder;
public DebuggerProxy(ArrayBuilder<T> builder)
{
_builder = builder;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public T[] A
{
get
{
var result = new T[_builder.Count];
for (var i = 0; i < result.Length; i++)
{
result[i] = _builder[i];
}
return result;
}
}
}
#endregion
private readonly ImmutableArray<T>.Builder _builder;
private readonly ObjectPool<ArrayBuilder<T>>? _pool;
public ArrayBuilder(int size)
{
_builder = ImmutableArray.CreateBuilder<T>(size);
}
public ArrayBuilder()
: this(8)
{ }
private ArrayBuilder(ObjectPool<ArrayBuilder<T>> pool)
: this()
{
_pool = pool;
}
/// <summary>
/// Realizes the array.
/// </summary>
public ImmutableArray<T> ToImmutable()
{
return _builder.ToImmutable();
}
/// <summary>
/// Realizes the array and clears the collection.
/// </summary>
public ImmutableArray<T> ToImmutableAndClear()
{
ImmutableArray<T> result;
if (Count == 0)
{
result = ImmutableArray<T>.Empty;
}
else if (_builder.Capacity == Count)
{
result = _builder.MoveToImmutable();
}
else
{
result = ToImmutable();
Clear();
}
return result;
}
public int Count
{
get
{
return _builder.Count;
}
set
{
_builder.Count = value;
}
}
public T this[int index]
{
get
{
return _builder[index];
}
set
{
_builder[index] = value;
}
}
/// <summary>
/// Write <paramref name="value"/> to slot <paramref name="index"/>.
/// Fills in unallocated slots preceding the <paramref name="index"/>, if any.
/// </summary>
public void SetItem(int index, T value)
{
while (index > _builder.Count)
{
_builder.Add(default!);
}
if (index == _builder.Count)
{
_builder.Add(value);
}
else
{
_builder[index] = value;
}
}
public void Add(T item)
{
_builder.Add(item);
}
public void Insert(int index, T item)
{
_builder.Insert(index, item);
}
public void EnsureCapacity(int capacity)
{
if (_builder.Capacity < capacity)
{
_builder.Capacity = capacity;
}
}
public void Clear()
{
_builder.Clear();
}
public bool Contains(T item)
{
return _builder.Contains(item);
}
public int IndexOf(T item)
{
return _builder.IndexOf(item);
}
public int IndexOf(T item, IEqualityComparer<T> equalityComparer)
{
return _builder.IndexOf(item, 0, _builder.Count, equalityComparer);
}
public int IndexOf(T item, int startIndex, int count)
{
return _builder.IndexOf(item, startIndex, count);
}
public int FindIndex(Predicate<T> match)
=> FindIndex(0, this.Count, match);
public int FindIndex(int startIndex, Predicate<T> match)
=> FindIndex(startIndex, this.Count - startIndex, match);
public int FindIndex(int startIndex, int count, Predicate<T> match)
{
var endIndex = startIndex + count;
for (var i = startIndex; i < endIndex; i++)
{
if (match(_builder[i]))
{
return i;
}
}
return -1;
}
public int FindIndex<TArg>(Func<T, TArg, bool> match, TArg arg)
=> FindIndex(0, Count, match, arg);
public int FindIndex<TArg>(int startIndex, Func<T, TArg, bool> match, TArg arg)
=> FindIndex(startIndex, Count - startIndex, match, arg);
public int FindIndex<TArg>(int startIndex, int count, Func<T, TArg, bool> match, TArg arg)
{
var endIndex = startIndex + count;
for (var i = startIndex; i < endIndex; i++)
{
if (match(_builder[i], arg))
{
return i;
}
}
return -1;
}
public bool Remove(T element)
{
return _builder.Remove(element);
}
public void RemoveAt(int index)
{
_builder.RemoveAt(index);
}
public void RemoveLast()
{
_builder.RemoveAt(_builder.Count - 1);
}
public void ReverseContents()
{
_builder.Reverse();
}
public void Sort()
{
_builder.Sort();
}
public void Sort(IComparer<T> comparer)
{
_builder.Sort(comparer);
}
public void Sort(Comparison<T> compare)
=> Sort(Comparer<T>.Create(compare));
public void Sort(int startIndex, IComparer<T> comparer)
{
_builder.Sort(startIndex, _builder.Count - startIndex, comparer);
}
public T[] ToArray()
{
return _builder.ToArray();
}
public void CopyTo(T[] array, int start)
{
_builder.CopyTo(array, start);
}
public T Last()
{
return _builder[_builder.Count - 1];
}
public T First()
{
return _builder[0];
}
public bool Any()
{
return _builder.Count > 0;
}
/// <summary>
/// Realizes the array.
/// </summary>
public ImmutableArray<T> ToImmutableOrNull()
{
if (Count == 0)
{
return default;
}
return this.ToImmutable();
}
/// <summary>
/// Realizes the array, downcasting each element to a derived type.
/// </summary>
public ImmutableArray<U> ToDowncastedImmutable<U>()
where U : T
{
if (Count == 0)
{
return ImmutableArray<U>.Empty;
}
var tmp = ArrayBuilder<U>.GetInstance(Count);
foreach (var i in this)
{
tmp.Add((U)i!);
}
return tmp.ToImmutableAndFree();
}
/// <summary>
/// Realizes the array and disposes the builder in one operation.
/// </summary>
public ImmutableArray<T> ToImmutableAndFree()
{
// This is mostly the same as 'MoveToImmutable', but avoids delegating to that method since 'Free' contains
// fast paths to avoid caling 'Clear' in some cases.
ImmutableArray<T> result;
if (Count == 0)
{
result = ImmutableArray<T>.Empty;
}
else if (_builder.Capacity == Count)
{
result = _builder.MoveToImmutable();
}
else
{
result = ToImmutable();
}
this.Free();
return result;
}
public T[] ToArrayAndFree()
{
var result = this.ToArray();
this.Free();
return result;
}
#region Poolable
// To implement Poolable, you need two things:
// 1) Expose Freeing primitive.
public void Free()
{
var pool = _pool;
if (pool != null)
{
// According to the statistics of a C# compiler self-build, the most commonly used builder size is 0. (808003 uses).
// The distant second is the Count == 1 (455619), then 2 (106362) ...
// After about 50 (just 67) we have a long tail of infrequently used builder sizes.
// However we have builders with size up to 50K (just one such thing)
//
// We do not want to retain (potentially indefinitely) very large builders
// while the chance that we will need their size is diminishingly small.
// It makes sense to constrain the size to some "not too small" number.
// Overall perf does not seem to be very sensitive to this number, so I picked 128 as a limit.
if (_builder.Capacity < 128)
{
if (this.Count != 0)
{
this.Clear();
}
pool.Free(this);
return;
}
else
{
pool.ForgetTrackedObject(this);
}
}
}
// 2) Expose the pool or the way to create a pool or the way to get an instance.
// for now we will expose both and figure which way works better
private static readonly ObjectPool<ArrayBuilder<T>> s_poolInstance = CreatePool();
public static ArrayBuilder<T> GetInstance()
{
var builder = s_poolInstance.Allocate();
Debug.Assert(builder.Count == 0);
return builder;
}
public static ArrayBuilder<T> GetInstance(int capacity)
{
var builder = GetInstance();
builder.EnsureCapacity(capacity);
return builder;
}
public static ArrayBuilder<T> GetInstance(int capacity, T fillWithValue)
{
var builder = GetInstance();
builder.EnsureCapacity(capacity);
for (var i = 0; i < capacity; i++)
{
builder.Add(fillWithValue);
}
return builder;
}
public static ObjectPool<ArrayBuilder<T>> CreatePool()
{
return CreatePool(128); // we rarely need more than 10
}
public static ObjectPool<ArrayBuilder<T>> CreatePool(int size)
{
ObjectPool<ArrayBuilder<T>>? pool = null;
pool = new ObjectPool<ArrayBuilder<T>>(() => new ArrayBuilder<T>(pool!), size);
return pool;
}
#endregion
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return _builder.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return _builder.GetEnumerator();
}
internal Dictionary<K, ImmutableArray<T>> ToDictionary<K>(Func<T, K> keySelector, IEqualityComparer<K>? comparer = null)
where K : notnull
{
if (this.Count == 1)
{
var dictionary1 = new Dictionary<K, ImmutableArray<T>>(1, comparer);
var value = this[0];
dictionary1.Add(keySelector(value), ImmutableArray.Create(value));
return dictionary1;
}
if (this.Count == 0)
{
return new Dictionary<K, ImmutableArray<T>>(comparer);
}
// bucketize
// prevent reallocation. it may not have 'count' entries, but it won't have more.
var accumulator = new Dictionary<K, ArrayBuilder<T>>(Count, comparer);
for (var i = 0; i < Count; i++)
{
var item = this[i];
var key = keySelector(item);
if (!accumulator.TryGetValue(key, out var bucket))
{
bucket = ArrayBuilder<T>.GetInstance();
accumulator.Add(key, bucket);
}
bucket.Add(item);
}
var dictionary = new Dictionary<K, ImmutableArray<T>>(accumulator.Count, comparer);
// freeze
foreach (var pair in accumulator)
{
dictionary.Add(pair.Key, pair.Value.ToImmutableAndFree());
}
return dictionary;
}
public void AddRange(ArrayBuilder<T> items)
{
_builder.AddRange(items._builder);
}
public void AddRange<U>(ArrayBuilder<U> items, Func<U, T> selector)
{
foreach (var item in items)
{
_builder.Add(selector(item));
}
}
public void AddRange<U>(ArrayBuilder<U> items) where U : T
{
_builder.AddRange(items._builder);
}
public void AddRange<U>(ArrayBuilder<U> items, int start, int length) where U : T
{
Debug.Assert(start >= 0 && length >= 0);
Debug.Assert(start + length <= items.Count);
for (int i = start, end = start + length; i < end; i++)
{
Add(items[i]);
}
}
public void AddRange(ImmutableArray<T> items)
{
_builder.AddRange(items);
}
public void AddRange(ImmutableArray<T> items, int length)
{
_builder.AddRange(items, length);
}
public void AddRange(ImmutableArray<T> items, int start, int length)
{
Debug.Assert(start >= 0 && length >= 0);
Debug.Assert(start + length <= items.Length);
for (int i = start, end = start + length; i < end; i++)
{
Add(items[i]);
}
}
public void AddRange<S>(ImmutableArray<S> items) where S : class, T
{
AddRange(ImmutableArray<T>.CastUp(items));
}
public void AddRange(T[] items, int start, int length)
{
Debug.Assert(start >= 0 && length >= 0);
Debug.Assert(start + length <= items.Length);
for (int i = start, end = start + length; i < end; i++)
{
Add(items[i]);
}
}
public void AddRange(IEnumerable<T> items)
{
_builder.AddRange(items);
}
public void AddRange(params T[] items)
{
_builder.AddRange(items);
}
public void AddRange(T[] items, int length)
{
_builder.AddRange(items, length);
}
public void Clip(int limit)
{
Debug.Assert(limit <= Count);
_builder.Count = limit;
}
public void ZeroInit(int count)
{
_builder.Clear();
_builder.Count = count;
}
public void AddMany(T item, int count)
{
for (var i = 0; i < count; i++)
{
Add(item);
}
}
public void RemoveDuplicates()
{
var set = PooledHashSet<T>.GetInstance();
var j = 0;
for (var i = 0; i < Count; i++)
{
if (set.Add(this[i]))
{
this[j] = this[i];
j++;
}
}
Clip(j);
set.Free();
}
public void SortAndRemoveDuplicates(IComparer<T> comparer)
{
if (Count <= 1)
{
return;
}
Sort(comparer);
int j = 0;
for (int i = 1; i < Count; i++)
{
if (comparer.Compare(this[j], this[i]) < 0)
{
j++;
this[j] = this[i];
}
}
Clip(j + 1);
}
public ImmutableArray<S> SelectDistinct<S>(Func<T, S> selector)
{
var result = ArrayBuilder<S>.GetInstance(Count);
var set = PooledHashSet<S>.GetInstance();
foreach (var item in this)
{
var selected = selector(item);
if (set.Add(selected))
{
result.Add(selected);
}
}
set.Free();
return result.ToImmutableAndFree();
}
}
}
| -1 |
dotnet/roslyn | 55,530 | Ignore modules with bad metadata in function resolver | Fixes https://github.com/dotnet/roslyn/issues/55475 | tmat | 2021-08-10T18:56:37Z | 2021-08-11T18:37:09Z | cd0c0464c069a2b80774d70f071c29333d9fa23c | bc874ebc5111a2a33221409f895953b1536f6612 | Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475 | ./src/Compilers/CSharp/Portable/Symbols/Attributes/WellKnownAttributeData/ReturnTypeWellKnownAttributeData.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.CSharp.Symbols
{
internal sealed class ReturnTypeWellKnownAttributeData : CommonReturnTypeWellKnownAttributeData
{
private bool _hasMaybeNullAttribute;
public bool HasMaybeNullAttribute
{
get
{
VerifySealed(expected: true);
return _hasMaybeNullAttribute;
}
set
{
VerifySealed(expected: false);
_hasMaybeNullAttribute = value;
SetDataStored();
}
}
private bool _hasNotNullAttribute;
public bool HasNotNullAttribute
{
get
{
VerifySealed(expected: true);
return _hasNotNullAttribute;
}
set
{
VerifySealed(expected: false);
_hasNotNullAttribute = value;
SetDataStored();
}
}
private ImmutableHashSet<string> _notNullIfParameterNotNull = ImmutableHashSet<string>.Empty;
public ImmutableHashSet<string> NotNullIfParameterNotNull
{
get
{
VerifySealed(expected: true);
return _notNullIfParameterNotNull;
}
}
public void AddNotNullIfParameterNotNull(string parameterName)
{
VerifySealed(expected: false);
// The common case is zero or one attribute
_notNullIfParameterNotNull = _notNullIfParameterNotNull.Add(parameterName);
SetDataStored();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.CSharp.Symbols
{
internal sealed class ReturnTypeWellKnownAttributeData : CommonReturnTypeWellKnownAttributeData
{
private bool _hasMaybeNullAttribute;
public bool HasMaybeNullAttribute
{
get
{
VerifySealed(expected: true);
return _hasMaybeNullAttribute;
}
set
{
VerifySealed(expected: false);
_hasMaybeNullAttribute = value;
SetDataStored();
}
}
private bool _hasNotNullAttribute;
public bool HasNotNullAttribute
{
get
{
VerifySealed(expected: true);
return _hasNotNullAttribute;
}
set
{
VerifySealed(expected: false);
_hasNotNullAttribute = value;
SetDataStored();
}
}
private ImmutableHashSet<string> _notNullIfParameterNotNull = ImmutableHashSet<string>.Empty;
public ImmutableHashSet<string> NotNullIfParameterNotNull
{
get
{
VerifySealed(expected: true);
return _notNullIfParameterNotNull;
}
}
public void AddNotNullIfParameterNotNull(string parameterName)
{
VerifySealed(expected: false);
// The common case is zero or one attribute
_notNullIfParameterNotNull = _notNullIfParameterNotNull.Add(parameterName);
SetDataStored();
}
}
}
| -1 |
dotnet/roslyn | 55,530 | Ignore modules with bad metadata in function resolver | Fixes https://github.com/dotnet/roslyn/issues/55475 | tmat | 2021-08-10T18:56:37Z | 2021-08-11T18:37:09Z | cd0c0464c069a2b80774d70f071c29333d9fa23c | bc874ebc5111a2a33221409f895953b1536f6612 | Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475 | ./src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/RegexKind.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions
{
internal enum RegexKind
{
None = 0,
EndOfFile,
Sequence,
CompilationUnit,
Text,
StartAnchor,
EndAnchor,
Alternation,
Wildcard,
CharacterClass,
NegatedCharacterClass,
CharacterClassRange,
CharacterClassSubtraction,
PosixProperty,
ZeroOrMoreQuantifier,
OneOrMoreQuantifier,
ZeroOrOneQuantifier,
ExactNumericQuantifier,
OpenRangeNumericQuantifier,
ClosedRangeNumericQuantifier,
LazyQuantifier,
SimpleGrouping,
SimpleOptionsGrouping,
NestedOptionsGrouping,
NonCapturingGrouping,
PositiveLookaheadGrouping,
NegativeLookaheadGrouping,
PositiveLookbehindGrouping,
NegativeLookbehindGrouping,
AtomicGrouping,
CaptureGrouping,
BalancingGrouping,
ConditionalCaptureGrouping,
ConditionalExpressionGrouping,
SimpleEscape,
AnchorEscape,
CharacterClassEscape,
CategoryEscape,
ControlEscape,
HexEscape,
UnicodeEscape,
OctalEscape,
CaptureEscape,
KCaptureEscape,
BackreferenceEscape,
// Tokens
DollarToken,
OpenBraceToken,
CloseBraceToken,
OpenBracketToken,
CloseBracketToken,
OpenParenToken,
CloseParenToken,
BarToken,
DotToken,
CaretToken,
TextToken,
QuestionToken,
AsteriskToken,
PlusToken,
CommaToken,
BackslashToken,
ColonToken,
EqualsToken,
ExclamationToken,
GreaterThanToken,
LessThanToken,
MinusToken,
SingleQuoteToken,
// Special multi-character tokens that have to be explicitly requested.
OptionsToken,
NumberToken,
CaptureNameToken,
EscapeCategoryToken,
// Trivia
CommentTrivia,
WhitespaceTrivia,
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions
{
internal enum RegexKind
{
None = 0,
EndOfFile,
Sequence,
CompilationUnit,
Text,
StartAnchor,
EndAnchor,
Alternation,
Wildcard,
CharacterClass,
NegatedCharacterClass,
CharacterClassRange,
CharacterClassSubtraction,
PosixProperty,
ZeroOrMoreQuantifier,
OneOrMoreQuantifier,
ZeroOrOneQuantifier,
ExactNumericQuantifier,
OpenRangeNumericQuantifier,
ClosedRangeNumericQuantifier,
LazyQuantifier,
SimpleGrouping,
SimpleOptionsGrouping,
NestedOptionsGrouping,
NonCapturingGrouping,
PositiveLookaheadGrouping,
NegativeLookaheadGrouping,
PositiveLookbehindGrouping,
NegativeLookbehindGrouping,
AtomicGrouping,
CaptureGrouping,
BalancingGrouping,
ConditionalCaptureGrouping,
ConditionalExpressionGrouping,
SimpleEscape,
AnchorEscape,
CharacterClassEscape,
CategoryEscape,
ControlEscape,
HexEscape,
UnicodeEscape,
OctalEscape,
CaptureEscape,
KCaptureEscape,
BackreferenceEscape,
// Tokens
DollarToken,
OpenBraceToken,
CloseBraceToken,
OpenBracketToken,
CloseBracketToken,
OpenParenToken,
CloseParenToken,
BarToken,
DotToken,
CaretToken,
TextToken,
QuestionToken,
AsteriskToken,
PlusToken,
CommaToken,
BackslashToken,
ColonToken,
EqualsToken,
ExclamationToken,
GreaterThanToken,
LessThanToken,
MinusToken,
SingleQuoteToken,
// Special multi-character tokens that have to be explicitly requested.
OptionsToken,
NumberToken,
CaptureNameToken,
EscapeCategoryToken,
// Trivia
CommentTrivia,
WhitespaceTrivia,
}
}
| -1 |
dotnet/roslyn | 55,530 | Ignore modules with bad metadata in function resolver | Fixes https://github.com/dotnet/roslyn/issues/55475 | tmat | 2021-08-10T18:56:37Z | 2021-08-11T18:37:09Z | cd0c0464c069a2b80774d70f071c29333d9fa23c | bc874ebc5111a2a33221409f895953b1536f6612 | Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475 | ./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenTryFinally.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class CodeGenTryFinallyTests : CSharpTestBase
{
[Fact]
public void EmptyTryFinally()
{
var source =
@"class C
{
static void EmptyTryFinally()
{
try { }
finally { }
}
static void EmptyTryFinallyInTry()
{
try
{
try { }
finally { }
}
finally { }
}
static void EmptyTryFinallyInFinally()
{
try { }
finally
{
try { }
finally { }
}
}
}";
var compilation = CompileAndVerify(source);
compilation.VerifyIL("C.EmptyTryFinally",
@"{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}");
compilation.VerifyIL("C.EmptyTryFinallyInTry",
@"{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}");
compilation.VerifyIL("C.EmptyTryFinallyInFinally",
@"{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}");
}
[Theory, WorkItem(4729, "https://github.com/dotnet/roslyn/issues/4729")]
[InlineData("")]
[InlineData(";")]
public void NopInTryCatchFinally(string doNothingStatements)
{
var source =
$@"class C
{{
static void M1()
{{
try {{ {doNothingStatements} }}
catch (System.Exception) {{ {doNothingStatements} }}
finally {{ {doNothingStatements} }}
}}
static void M2()
{{
try {{
try {{ {doNothingStatements} }}
catch (System.Exception) {{ {doNothingStatements} }}
finally {{ {doNothingStatements} }}
}}
catch (System.Exception) {{
try {{ {doNothingStatements} }}
catch (System.Exception) {{ {doNothingStatements} }}
finally {{ {doNothingStatements} }}
}}
finally {{
try {{ {doNothingStatements} }}
catch (System.Exception) {{ {doNothingStatements} }}
finally {{ {doNothingStatements} }}
}}
}}
static void M3()
{{
try {{ System.Console.WriteLine(1); }}
catch (System.Exception) {{ {doNothingStatements} }}
finally {{ {doNothingStatements} }}
}}
static void M4()
{{
try {{ {doNothingStatements} }}
catch (System.Exception) {{ System.Console.WriteLine(1); }}
finally {{ {doNothingStatements} }}
}}
static void M5()
{{
try {{ {doNothingStatements} }}
catch (System.Exception) {{ {doNothingStatements} }}
finally {{ System.Console.WriteLine(1); }}
}}
}}";
var compilation = CompileAndVerify(source);
compilation.VerifyIL("C.M1",
@"{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}");
compilation.VerifyIL("C.M2",
@"{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}");
compilation.VerifyIL("C.M3",
@"{
// Code size 12 (0xc)
.maxstack 1
.try
{
IL_0000: ldc.i4.1
IL_0001: call ""void System.Console.WriteLine(int)""
IL_0006: leave.s IL_000b
}
catch System.Exception
{
IL_0008: pop
IL_0009: leave.s IL_000b
}
IL_000b: ret
}");
compilation.VerifyIL("C.M4",
@"{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}");
compilation.VerifyIL("C.M5",
@"{
// Code size 10 (0xa)
.maxstack 1
.try
{
IL_0000: leave.s IL_0009
}
finally
{
IL_0002: ldc.i4.1
IL_0003: call ""void System.Console.WriteLine(int)""
IL_0008: endfinally
}
IL_0009: ret
}");
}
[Fact]
public void TryFinally()
{
var source =
@"class C
{
static void Main()
{
M(1);
M(0);
}
static void M(int f)
{
try
{
System.Console.Write(""1, "");
if (f > 0)
goto End;
System.Console.Write(""2, "");
return;
}
finally
{
System.Console.Write(""3, "");
}
End:
System.Console.Write(""4, "");
}
}";
var compilation = CompileAndVerify(source, expectedOutput: "1, 3, 4, 1, 2, 3, ");
compilation.VerifyIL("C.M",
@"{
// Code size 50 (0x32)
.maxstack 2
.try
{
IL_0000: ldstr ""1, ""
IL_0005: call ""void System.Console.Write(string)""
IL_000a: ldarg.0
IL_000b: ldc.i4.0
IL_000c: ble.s IL_0010
IL_000e: leave.s IL_0027
IL_0010: ldstr ""2, ""
IL_0015: call ""void System.Console.Write(string)""
IL_001a: leave.s IL_0031
}
finally
{
IL_001c: ldstr ""3, ""
IL_0021: call ""void System.Console.Write(string)""
IL_0026: endfinally
}
IL_0027: ldstr ""4, ""
IL_002c: call ""void System.Console.Write(string)""
IL_0031: ret
}");
}
[Fact]
public void TryCatch()
{
var source =
@"using System;
class C
{
static void Main()
{
M(1);
M(0);
}
static void M(int f)
{
try
{
Console.Write(""before, "");
N(f);
Console.Write(""after, "");
}
catch (Exception)
{
Console.Write(""catch, "");
}
}
static void N(int f)
{
if (f > 0)
throw new Exception();
}
}";
var compilation = CompileAndVerify(source, expectedOutput: "before, catch, before, after,");
compilation.VerifyIL("C.M",
@"{
// Code size 42 (0x2a)
.maxstack 1
.try
{
IL_0000: ldstr ""before, ""
IL_0005: call ""void System.Console.Write(string)""
IL_000a: ldarg.0
IL_000b: call ""void C.N(int)""
IL_0010: ldstr ""after, ""
IL_0015: call ""void System.Console.Write(string)""
IL_001a: leave.s IL_0029
}
catch System.Exception
{
IL_001c: pop
IL_001d: ldstr ""catch, ""
IL_0022: call ""void System.Console.Write(string)""
IL_0027: leave.s IL_0029
}
IL_0029: ret
}");
}
[Fact]
public void TryCatch001()
{
var source =
@"using System;
class C
{
static void Main()
{
}
static void M()
{
try
{
System.Object o = null;
o.ToString();//null Exception throw
}
catch (System.NullReferenceException NullException)//null Exception caught
{
try
{
throw new System.ApplicationException();//app Exception throw
}
catch (System.ApplicationException AppException)//app Exception caught
{
throw new System.DivideByZeroException();//Zero Exception throw
}
}
}
}";
var compilation = CompileAndVerify(source, expectedOutput: "");
compilation.VerifyIL("C.M",
@"{
// Code size 24 (0x18)
.maxstack 1
.try
{
IL_0000: ldnull
IL_0001: callvirt ""string object.ToString()""
IL_0006: pop
IL_0007: leave.s IL_0017
}
catch System.NullReferenceException
{
IL_0009: pop
.try
{
IL_000a: newobj ""System.ApplicationException..ctor()""
IL_000f: throw
}
catch System.ApplicationException
{
IL_0010: pop
IL_0011: newobj ""System.DivideByZeroException..ctor()""
IL_0016: throw
}
}
IL_0017: ret
}");
}
[Fact]
public void TryCatch002()
{
var source =
@"using System;
class C
{
static void Main()
{
}
static void M()
{
try
{
System.Object o = null;
o.ToString();//null Exception throw
goto l1;
}
catch (System.NullReferenceException NullException)//null Exception caught
{
try
{
throw new System.ApplicationException();//app Exception throw
}
catch (System.ApplicationException AppException)//app Exception caught
{
throw new System.DivideByZeroException();//Zero Exception throw
}
}
l1:
;
;
;
}
}";
var compilation = CompileAndVerify(source, expectedOutput: "");
compilation.VerifyIL("C.M", @"
{
// Code size 24 (0x18)
.maxstack 1
.try
{
IL_0000: ldnull
IL_0001: callvirt ""string object.ToString()""
IL_0006: pop
IL_0007: leave.s IL_0017
}
catch System.NullReferenceException
{
IL_0009: pop
.try
{
IL_000a: newobj ""System.ApplicationException..ctor()""
IL_000f: throw
}
catch System.ApplicationException
{
IL_0010: pop
IL_0011: newobj ""System.DivideByZeroException..ctor()""
IL_0016: throw
}
}
IL_0017: ret
}");
}
[WorkItem(813428, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/813428")]
[Fact]
public void TryCatchOptimized001()
{
var source =
@"
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
try
{
throw new Exception(""debug only"");
}
catch (Exception ex)
{
Debug.Write(ex.Message);
}
try
{
throw new Exception(""hello"");
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
try
{
throw new Exception(""bye"");
}
catch (Exception ex)
{
Console.Write(ex.Message);
Console.Write(ex.Message);
}
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "hellobyebye");
compilation.VerifyIL("Program.Main",
@"
{
// Code size 74 (0x4a)
.maxstack 2
.try
{
IL_0000: ldstr ""debug only""
IL_0005: newobj ""System.Exception..ctor(string)""
IL_000a: throw
}
catch System.Exception
{
IL_000b: pop
IL_000c: leave.s IL_000e
}
IL_000e: nop
.try
{
IL_000f: ldstr ""hello""
IL_0014: newobj ""System.Exception..ctor(string)""
IL_0019: throw
}
catch System.Exception
{
IL_001a: callvirt ""string System.Exception.Message.get""
IL_001f: call ""void System.Console.Write(string)""
IL_0024: leave.s IL_0026
}
IL_0026: nop
.try
{
IL_0027: ldstr ""bye""
IL_002c: newobj ""System.Exception..ctor(string)""
IL_0031: throw
}
catch System.Exception
{
IL_0032: dup
IL_0033: callvirt ""string System.Exception.Message.get""
IL_0038: call ""void System.Console.Write(string)""
IL_003d: callvirt ""string System.Exception.Message.get""
IL_0042: call ""void System.Console.Write(string)""
IL_0047: leave.s IL_0049
}
IL_0049: ret
}
");
}
[Fact]
public void TryFilterOptimized001()
{
var source =
@"
using System;
class Program
{
static void Main()
{
try
{
throw new Exception(""hello"");
}
catch (Exception ex1) when (ex1.Message == null)
{
}
try
{
throw new Exception(""bye"");
}
catch (Exception ex2) when (F(ex2, ex2))
{
}
}
private static bool F(Exception e1, Exception e2)
{
return false;
}
}
";
var compilation = CompileAndVerify(source);
compilation.VerifyIL("Program.Main", @"
{
// Code size 78 (0x4e)
.maxstack 2
.try
{
IL_0000: ldstr ""hello""
IL_0005: newobj ""System.Exception..ctor(string)""
IL_000a: throw
}
filter
{
IL_000b: isinst ""System.Exception""
IL_0010: dup
IL_0011: brtrue.s IL_0017
IL_0013: pop
IL_0014: ldc.i4.0
IL_0015: br.s IL_0022
IL_0017: callvirt ""string System.Exception.Message.get""
IL_001c: ldnull
IL_001d: ceq
IL_001f: ldc.i4.0
IL_0020: cgt.un
IL_0022: endfilter
} // end filter
{ // handler
IL_0024: pop
IL_0025: leave.s IL_0027
}
IL_0027: nop
.try
{
IL_0028: ldstr ""bye""
IL_002d: newobj ""System.Exception..ctor(string)""
IL_0032: throw
}
filter
{
IL_0033: isinst ""System.Exception""
IL_0038: dup
IL_0039: brtrue.s IL_003f
IL_003b: pop
IL_003c: ldc.i4.0
IL_003d: br.s IL_0048
IL_003f: dup
IL_0040: call ""bool Program.F(System.Exception, System.Exception)""
IL_0045: ldc.i4.0
IL_0046: cgt.un
IL_0048: endfilter
} // end filter
{ // handler
IL_004a: pop
IL_004b: leave.s IL_004d
}
IL_004d: ret
}
");
}
[Fact]
public void TryFilterOptimized002()
{
var source =
@"
using System;
class Program
{
static void Main()
{
try
{
throw new Exception(""bye"");
}
catch (Exception ex) when (F(ex, ex))
{
Console.WriteLine(ex);
}
}
private static bool F(Exception e1, Exception e2)
{
return false;
}
}
";
var compilation = CompileAndVerify(source);
compilation.VerifyIL("Program.Main", @"
{
// Code size 46 (0x2e)
.maxstack 2
.locals init (System.Exception V_0) //ex
.try
{
IL_0000: ldstr ""bye""
IL_0005: newobj ""System.Exception..ctor(string)""
IL_000a: throw
}
filter
{
IL_000b: isinst ""System.Exception""
IL_0010: dup
IL_0011: brtrue.s IL_0017
IL_0013: pop
IL_0014: ldc.i4.0
IL_0015: br.s IL_0022
IL_0017: stloc.0
IL_0018: ldloc.0
IL_0019: ldloc.0
IL_001a: call ""bool Program.F(System.Exception, System.Exception)""
IL_001f: ldc.i4.0
IL_0020: cgt.un
IL_0022: endfilter
} // end filter
{ // handler
IL_0024: pop
IL_0025: ldloc.0
IL_0026: call ""void System.Console.WriteLine(object)""
IL_002b: leave.s IL_002d
}
IL_002d: ret
}
");
}
[Fact]
public void TryFilterOptimized003()
{
var source =
@"
using System;
class Program
{
static void Main()
{
try
{
throw new Exception(""bye"");
}
catch (Exception ex) when (F(ref ex))
{
Console.WriteLine(ex);
}
}
private static bool F(ref Exception e)
{
e = null;
return true;
}
}
";
var compilation = CompileAndVerify(source);
compilation.VerifyIL("Program.Main", @"
{
// Code size 46 (0x2e)
.maxstack 2
.locals init (System.Exception V_0) //ex
.try
{
IL_0000: ldstr ""bye""
IL_0005: newobj ""System.Exception..ctor(string)""
IL_000a: throw
}
filter
{
IL_000b: isinst ""System.Exception""
IL_0010: dup
IL_0011: brtrue.s IL_0017
IL_0013: pop
IL_0014: ldc.i4.0
IL_0015: br.s IL_0022
IL_0017: stloc.0
IL_0018: ldloca.s V_0
IL_001a: call ""bool Program.F(ref System.Exception)""
IL_001f: ldc.i4.0
IL_0020: cgt.un
IL_0022: endfilter
} // end filter
{ // handler
IL_0024: pop
IL_0025: ldloc.0
IL_0026: call ""void System.Console.WriteLine(object)""
IL_002b: leave.s IL_002d
}
IL_002d: ret
}");
}
[Fact]
public void TryFilterOptimized004()
{
var source =
@"
using System;
class Program
{
static void F<T>() where T : Exception
{
try
{
throw new Exception(""bye"");
}
catch (T ex) when (F(ex, ex))
{
Console.WriteLine(ex);
}
}
private static bool F<S>(S e1, S e2)
{
return false;
}
}
";
var compilation = CompileAndVerify(source);
compilation.VerifyIL("Program.F<T>", @"
{
// Code size 56 (0x38)
.maxstack 2
.locals init (T V_0) //ex
.try
{
IL_0000: ldstr ""bye""
IL_0005: newobj ""System.Exception..ctor(string)""
IL_000a: throw
}
filter
{
IL_000b: isinst ""T""
IL_0010: dup
IL_0011: brtrue.s IL_0017
IL_0013: pop
IL_0014: ldc.i4.0
IL_0015: br.s IL_0027
IL_0017: unbox.any ""T""
IL_001c: stloc.0
IL_001d: ldloc.0
IL_001e: ldloc.0
IL_001f: call ""bool Program.F<T>(T, T)""
IL_0024: ldc.i4.0
IL_0025: cgt.un
IL_0027: endfilter
} // end filter
{ // handler
IL_0029: pop
IL_002a: ldloc.0
IL_002b: box ""T""
IL_0030: call ""void System.Console.WriteLine(object)""
IL_0035: leave.s IL_0037
}
IL_0037: ret
}
");
}
[Fact, WorkItem(854935, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854935")]
public void LiftedExceptionVariableInGenericIterator()
{
var source = @"
using System;
using System.IO;
using System.Collections.Generic;
class C
{
public IEnumerable<int> Iter2<T>()
{
try
{
throw new IOException(""Hi"");
}
catch (Exception e)
{
( (Action) delegate { Console.WriteLine(e.Message); })();
}
yield return 1;
}
static void Main()
{
foreach (var x in new C().Iter2<object>()) { }
}
}";
CompileAndVerify(source, expectedOutput: "Hi");
}
[Fact, WorkItem(854935, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854935")]
public void GenericLiftedExceptionVariableInGenericIterator()
{
var source = @"
using System;
using System.IO;
using System.Collections.Generic;
class C
{
public IEnumerable<int> Iter2<T, E>() where E : Exception
{
try
{
throw new IOException(""Hi"");
}
catch (E e) when (new Func<bool>(() => e.Message != null)())
{
( (Action) delegate { Console.WriteLine(e.Message); })();
}
yield return 1;
}
static void Main()
{
foreach (var x in new C().Iter2<object, IOException>()) { }
}
}";
CompileAndVerify(source, expectedOutput: "Hi");
}
[WorkItem(579778, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579778")]
[Fact]
public void Regression579778()
{
var source =
@"
using System;
using System.Security;
[assembly: SecurityTransparent()]
class C
{
static void nop() {}
static void Main()
{
try
{
throw null;
}
catch (Exception)
{
}
finally
{
try { nop(); }
catch { }
}
}
}";
var compilation = CompileAndVerify(source, expectedOutput: "");
compilation.VerifyIL("C.Main",
@"
{
// Code size 18 (0x12)
.maxstack 1
.try
{
.try
{
IL_0000: ldnull
IL_0001: throw
}
catch System.Exception
{
IL_0002: pop
IL_0003: leave.s IL_0011
}
}
finally
{
IL_0005: nop
.try
{
IL_0006: call ""void C.nop()""
IL_000b: leave.s IL_0010
}
catch object
{
IL_000d: pop
IL_000e: leave.s IL_0010
}
IL_0010: endfinally
}
IL_0011: ret
}
");
}
[Fact]
public void NestedExceptionHandlers()
{
var source =
@"using System;
class C
{
static void F(int i)
{
if (i == 0)
{
throw new Exception(""i == 0"");
}
throw new InvalidOperationException(""i != 0"");
}
static void M(int i)
{
try
{
try
{
F(i);
}
catch (InvalidOperationException e)
{
Console.WriteLine(""InvalidOperationException: {0}"", e.Message);
F(i + 1);
}
}
catch (Exception e)
{
Console.WriteLine(""Exception: {0}"", e.Message);
}
}
static void Main()
{
M(0);
M(1);
}
}";
var compilation = CompileAndVerify(source, expectedOutput:
@"Exception: i == 0
InvalidOperationException: i != 0
Exception: i != 0");
compilation.VerifyIL("C.M",
@"
{
// Code size 57 (0x39)
.maxstack 2
.locals init (System.InvalidOperationException V_0, //e
System.Exception V_1) //e
.try
{
.try
{
IL_0000: ldarg.0
IL_0001: call ""void C.F(int)""
IL_0006: leave.s IL_0023
}
catch System.InvalidOperationException
{
IL_0008: stloc.0
IL_0009: ldstr ""InvalidOperationException: {0}""
IL_000e: ldloc.0
IL_000f: callvirt ""string System.Exception.Message.get""
IL_0014: call ""void System.Console.WriteLine(string, object)""
IL_0019: ldarg.0
IL_001a: ldc.i4.1
IL_001b: add
IL_001c: call ""void C.F(int)""
IL_0021: leave.s IL_0023
}
IL_0023: leave.s IL_0038
}
catch System.Exception
{
IL_0025: stloc.1
IL_0026: ldstr ""Exception: {0}""
IL_002b: ldloc.1
IL_002c: callvirt ""string System.Exception.Message.get""
IL_0031: call ""void System.Console.WriteLine(string, object)""
IL_0036: leave.s IL_0038
}
IL_0038: ret
}
");
}
[ConditionalFact(typeof(WindowsDesktopOnly))]
public void NestedExceptionHandlersThreadAbort01()
{
var source =
@"
using System;
using System.Threading;
class Program
{
static ManualResetEventSlim s = new ManualResetEventSlim(false);
static void Main(string[] args)
{
var ts = new ThreadStart(Test);
var t = new Thread(ts);
t.Start();
s.Wait();
t.Abort();
t.Join();
}
public static void Test()
{
try
{
try
{
s.Set();
for (; ;) ;
}
catch (Exception ex)
{
Console.WriteLine(""catch1"");
}
}
catch (Exception ex)
{
Console.WriteLine(""catch2"");
}
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"
catch1
catch2
");
compilation.VerifyIL("Program.Test",
@"
{
// Code size 41 (0x29)
.maxstack 1
.try
{
.try
{
IL_0000: ldsfld ""System.Threading.ManualResetEventSlim Program.s""
IL_0005: callvirt ""void System.Threading.ManualResetEventSlim.Set()""
IL_000a: br.s IL_000a
}
catch System.Exception
{
IL_000c: pop
IL_000d: ldstr ""catch1""
IL_0012: call ""void System.Console.WriteLine(string)""
IL_0017: leave.s IL_0019
}
IL_0019: leave.s IL_0028
}
catch System.Exception
{
IL_001b: pop
IL_001c: ldstr ""catch2""
IL_0021: call ""void System.Console.WriteLine(string)""
IL_0026: leave.s IL_0028
}
IL_0028: ret
}
");
}
[ConditionalFact(typeof(WindowsDesktopOnly))]
public void NestedExceptionHandlersThreadAbort02()
{
var source =
@"
using System;
using System.Threading;
class Program
{
static ManualResetEventSlim s = new ManualResetEventSlim(false);
static void Main(string[] args)
{
var ts = new ThreadStart(Test);
var t = new Thread(ts);
t.Start();
s.Wait();
t.Abort();
t.Join();
}
public static void Test()
{
try
{
try
{
try
{
s.Set();
for (; ;) ;
}
catch (Exception ex)
{
Console.WriteLine(""catch1"");
}
}
finally
{
Console.WriteLine(""finally"");
}
}
catch (Exception ex)
{
Console.WriteLine(""catch2"");
}
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"
catch1
finally
catch2
");
compilation.VerifyIL("Program.Test",
@"
{
// Code size 54 (0x36)
.maxstack 1
.try
{
.try
{
.try
{
IL_0000: ldsfld ""System.Threading.ManualResetEventSlim Program.s""
IL_0005: callvirt ""void System.Threading.ManualResetEventSlim.Set()""
IL_000a: br.s IL_000a
}
catch System.Exception
{
IL_000c: pop
IL_000d: ldstr ""catch1""
IL_0012: call ""void System.Console.WriteLine(string)""
IL_0017: leave.s IL_0019
}
IL_0019: leave.s IL_0026
}
finally
{
IL_001b: ldstr ""finally""
IL_0020: call ""void System.Console.WriteLine(string)""
IL_0025: endfinally
}
IL_0026: leave.s IL_0035
}
catch System.Exception
{
IL_0028: pop
IL_0029: ldstr ""catch2""
IL_002e: call ""void System.Console.WriteLine(string)""
IL_0033: leave.s IL_0035
}
IL_0035: ret
}
");
}
[ConditionalFact(typeof(WindowsDesktopOnly))]
public void NestedExceptionHandlersThreadAbort03()
{
var source =
@"
using System;
using System.Threading;
class Program
{
static ManualResetEventSlim s = new ManualResetEventSlim(false);
static void Main(string[] args)
{
var ts = new ThreadStart(Test);
var t = new Thread(ts);
t.Start();
s.Wait();
t.Abort();
t.Join();
}
public static void Test()
{
try
{
try
{
try
{
try
{
s.Set();
while (s != null) {};
}
catch (Exception ex)
{
Console.WriteLine(""catch1"");
}
}
finally
{
Console.WriteLine(""finally1"");
}
}
catch (Exception ex)
{
Console.WriteLine(""catch2"");
}
}
finally
{
Console.WriteLine(""finally2"");
}
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"
catch1
finally1
catch2
finally2
");
compilation.VerifyIL("Program.Test",
@"
{
// Code size 72 (0x48)
.maxstack 1
.try
{
.try
{
.try
{
.try
{
IL_0000: ldsfld ""System.Threading.ManualResetEventSlim Program.s""
IL_0005: callvirt ""void System.Threading.ManualResetEventSlim.Set()""
IL_000a: ldsfld ""System.Threading.ManualResetEventSlim Program.s""
IL_000f: brtrue.s IL_000a
IL_0011: leave.s IL_0020
}
catch System.Exception
{
IL_0013: pop
IL_0014: ldstr ""catch1""
IL_0019: call ""void System.Console.WriteLine(string)""
IL_001e: leave.s IL_0020
}
IL_0020: leave.s IL_002d
}
finally
{
IL_0022: ldstr ""finally1""
IL_0027: call ""void System.Console.WriteLine(string)""
IL_002c: endfinally
}
IL_002d: leave.s IL_0047
}
catch System.Exception
{
IL_002f: pop
IL_0030: ldstr ""catch2""
IL_0035: call ""void System.Console.WriteLine(string)""
IL_003a: leave.s IL_0047
}
}
finally
{
IL_003c: ldstr ""finally2""
IL_0041: call ""void System.Console.WriteLine(string)""
IL_0046: endfinally
}
IL_0047: ret
}
");
}
[ConditionalFact(typeof(WindowsDesktopOnly))]
public void NestedExceptionHandlersThreadAbort04()
{
var source =
@"
using System;
using System.Threading;
class Program
{
static ManualResetEventSlim s = new ManualResetEventSlim(false);
static void Main(string[] args)
{
var ts = new ThreadStart(Test);
var t = new Thread(ts);
t.Start();
s.Wait();
t.Abort();
t.Join();
}
public static void Test()
{
try
{
try
{
try
{
try
{
s.Set();
while (s != null) {};
}
catch (Exception ex)
{
Console.WriteLine(""catch1"");
}
}
finally
{
Console.WriteLine(""finally1"");
}
}
catch (Exception ex) when (ex != null)
{
Console.WriteLine(""catch2"");
}
}
finally
{
Console.WriteLine(""finally2"");
}
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"
catch1
finally1
catch2
finally2
");
compilation.VerifyIL("Program.Test",
@"
{
// Code size 92 (0x5c)
.maxstack 2
.try
{
.try
{
.try
{
.try
{
IL_0000: ldsfld ""System.Threading.ManualResetEventSlim Program.s""
IL_0005: callvirt ""void System.Threading.ManualResetEventSlim.Set()""
IL_000a: ldsfld ""System.Threading.ManualResetEventSlim Program.s""
IL_000f: brtrue.s IL_000a
IL_0011: leave.s IL_0020
}
catch System.Exception
{
IL_0013: pop
IL_0014: ldstr ""catch1""
IL_0019: call ""void System.Console.WriteLine(string)""
IL_001e: leave.s IL_0020
}
IL_0020: leave.s IL_002d
}
finally
{
IL_0022: ldstr ""finally1""
IL_0027: call ""void System.Console.WriteLine(string)""
IL_002c: endfinally
}
IL_002d: leave.s IL_005b
}
filter
{
IL_002f: isinst ""System.Exception""
IL_0034: dup
IL_0035: brtrue.s IL_003b
IL_0037: pop
IL_0038: ldc.i4.0
IL_0039: br.s IL_0041
IL_003b: ldnull
IL_003c: cgt.un
IL_003e: ldc.i4.0
IL_003f: cgt.un
IL_0041: endfilter
} // end filter
{ // handler
IL_0043: pop
IL_0044: ldstr ""catch2""
IL_0049: call ""void System.Console.WriteLine(string)""
IL_004e: leave.s IL_005b
}
}
finally
{
IL_0050: ldstr ""finally2""
IL_0055: call ""void System.Console.WriteLine(string)""
IL_005a: endfinally
}
IL_005b: ret
}
");
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)]
public void NestedExceptionHandlersThreadAbort05()
{
var source =
@"
using System;
using System.Threading;
class Program
{
static void nop() { }
static ManualResetEventSlim s = new ManualResetEventSlim(false);
static void Main(string[] args)
{
var ts = new ThreadStart(Test);
var t = new Thread(ts);
t.Start();
s.Wait();
t.Abort();
t.Join();
}
public static void Test()
{
try
{
try
{
s.Set();
while (s != null) {};
}
catch
{
try
{
nop();
}
catch
{
Console.WriteLine(""catch1"");
}
}
finally
{
try
{
Console.WriteLine(""try2"");
}
catch
{
Console.WriteLine(""catch2"");
}
}
}
catch
{
Console.WriteLine(""catch3"");
}
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"
try2
catch3
");
compilation.VerifyIL("Program.Test",
@"{
// Code size 87 (0x57)
.maxstack 1
.try
{
.try
{
.try
{
IL_0000: ldsfld ""System.Threading.ManualResetEventSlim Program.s""
IL_0005: callvirt ""void System.Threading.ManualResetEventSlim.Set()""
IL_000a: ldsfld ""System.Threading.ManualResetEventSlim Program.s""
IL_000f: brtrue.s IL_000a
IL_0011: leave.s IL_002a
}
catch object
{
IL_0013: pop
.try
{
IL_0014: call ""void Program.nop()""
IL_0019: leave.s IL_0028
}
catch object
{
IL_001b: pop
IL_001c: ldstr ""catch1""
IL_0021: call ""void System.Console.WriteLine(string)""
IL_0026: leave.s IL_0028
}
IL_0028: leave.s IL_002a
}
IL_002a: leave.s IL_0047
}
finally
{
IL_002c: nop
.try
{
IL_002d: ldstr ""try2""
IL_0032: call ""void System.Console.WriteLine(string)""
IL_0037: leave.s IL_0046
}
catch object
{
IL_0039: pop
IL_003a: ldstr ""catch2""
IL_003f: call ""void System.Console.WriteLine(string)""
IL_0044: leave.s IL_0046
}
IL_0046: endfinally
}
IL_0047: leave.s IL_0056
}
catch object
{
IL_0049: pop
IL_004a: ldstr ""catch3""
IL_004f: call ""void System.Console.WriteLine(string)""
IL_0054: leave.s IL_0056
}
IL_0056: ret
}");
}
[ConditionalFact(typeof(WindowsDesktopOnly))]
public void NestedExceptionHandlersThreadAbort06()
{
var source =
@"
using System;
using System.Threading;
class Program
{
static ManualResetEventSlim s = new ManualResetEventSlim(false);
static void Main(string[] args)
{
var ts = new ThreadStart(Test);
var t = new Thread(ts);
t.Start();
s.Wait();
t.Abort();
t.Join();
}
public static void Test()
{
try
{
try
{
s.Set();
while (s != null) {};
}
catch
{
try
{
int i = 0;
i = i / i;
}
catch
{
Console.WriteLine(""catch1"");
}
}
finally
{
try
{
Console.WriteLine(""try2"");
}
catch
{
Console.WriteLine(""catch2"");
}
}
}
catch
{
Console.WriteLine(""catch3"");
}
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"
catch1
try2
catch3
");
compilation.VerifyIL("Program.Test",
@"
{
// Code size 86 (0x56)
.maxstack 2
.try
{
.try
{
.try
{
IL_0000: ldsfld ""System.Threading.ManualResetEventSlim Program.s""
IL_0005: callvirt ""void System.Threading.ManualResetEventSlim.Set()""
IL_000a: ldsfld ""System.Threading.ManualResetEventSlim Program.s""
IL_000f: brtrue.s IL_000a
IL_0011: leave.s IL_0029
}
catch object
{
IL_0013: pop
.try
{
IL_0014: ldc.i4.0
IL_0015: dup
IL_0016: div
IL_0017: pop
IL_0018: leave.s IL_0027
}
catch object
{
IL_001a: pop
IL_001b: ldstr ""catch1""
IL_0020: call ""void System.Console.WriteLine(string)""
IL_0025: leave.s IL_0027
}
IL_0027: leave.s IL_0029
}
IL_0029: leave.s IL_0046
}
finally
{
IL_002b: nop
.try
{
IL_002c: ldstr ""try2""
IL_0031: call ""void System.Console.WriteLine(string)""
IL_0036: leave.s IL_0045
}
catch object
{
IL_0038: pop
IL_0039: ldstr ""catch2""
IL_003e: call ""void System.Console.WriteLine(string)""
IL_0043: leave.s IL_0045
}
IL_0045: endfinally
}
IL_0046: leave.s IL_0055
}
catch object
{
IL_0048: pop
IL_0049: ldstr ""catch3""
IL_004e: call ""void System.Console.WriteLine(string)""
IL_0053: leave.s IL_0055
}
IL_0055: ret
}
");
}
[ConditionalFact(typeof(WindowsDesktopOnly))]
public void NestedExceptionHandlersThreadAbort07()
{
var source =
@"
using System;
using System.Threading;
class Program
{
static ManualResetEventSlim s = new ManualResetEventSlim(false);
static void Main(string[] args)
{
var ts = new ThreadStart(Test);
var t = new Thread(ts);
t.Start();
s.Wait();
t.Abort();
t.Join();
}
public static void Test()
{
try
{
try
{
try
{
try
{
s.Set();
while (s != null) {};
}
catch (Exception ex)
{
Console.WriteLine(""catch1"");
}
}
finally
{
Console.WriteLine(""finally1"");
}
}
finally
{
Console.WriteLine(""finally2"");
}
}
catch (Exception ex)
{
Console.WriteLine(""catch2"");
}
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"
catch1
finally1
finally2
catch2
");
compilation.VerifyIL("Program.Test",
@"
{
// Code size 74 (0x4a)
.maxstack 1
.try
{
.try
{
.try
{
.try
{
IL_0000: ldsfld ""System.Threading.ManualResetEventSlim Program.s""
IL_0005: callvirt ""void System.Threading.ManualResetEventSlim.Set()""
IL_000a: ldsfld ""System.Threading.ManualResetEventSlim Program.s""
IL_000f: brtrue.s IL_000a
IL_0011: leave.s IL_0020
}
catch System.Exception
{
IL_0013: pop
IL_0014: ldstr ""catch1""
IL_0019: call ""void System.Console.WriteLine(string)""
IL_001e: leave.s IL_0020
}
IL_0020: leave.s IL_002d
}
finally
{
IL_0022: ldstr ""finally1""
IL_0027: call ""void System.Console.WriteLine(string)""
IL_002c: endfinally
}
IL_002d: leave.s IL_003a
}
finally
{
IL_002f: ldstr ""finally2""
IL_0034: call ""void System.Console.WriteLine(string)""
IL_0039: endfinally
}
IL_003a: leave.s IL_0049
}
catch System.Exception
{
IL_003c: pop
IL_003d: ldstr ""catch2""
IL_0042: call ""void System.Console.WriteLine(string)""
IL_0047: leave.s IL_0049
}
IL_0049: ret
}
");
}
[Fact]
public void ThrowInTry()
{
var source =
@"using System;
class C
{
static void nop() { }
static void ThrowInTry()
{
try { throw new Exception(); }
finally { }
}
static void ThrowInTryInTry()
{
try
{
try { throw new Exception(); }
finally { }
}
finally { }
}
static void ThrowInTryInFinally()
{
try { }
finally
{
try { throw new Exception(); }
finally { }
}
}
}
class D
{
static void nop() { }
static void ThrowInTry()
{
try { throw new Exception(); }
catch { }
finally { }
}
static void ThrowInTryInTry()
{
try
{
try { throw new Exception(); }
catch { }
finally { }
}
finally { }
}
static void ThrowInTryInFinally()
{
try { nop(); }
catch { }
finally
{
try { throw new Exception(); }
catch { }
finally { }
}
}
}";
var compilation = CompileAndVerify(source);
compilation.VerifyIL("C.ThrowInTry",
@"{
// Code size 6 (0x6)
.maxstack 1
IL_0000: newobj ""System.Exception..ctor()""
IL_0005: throw
}");
compilation.VerifyIL("C.ThrowInTryInTry",
@"{
// Code size 6 (0x6)
.maxstack 1
IL_0000: newobj ""System.Exception..ctor()""
IL_0005: throw
}");
compilation.VerifyIL("C.ThrowInTryInFinally",
@"{
// Code size 10 (0xa)
.maxstack 1
.try
{
IL_0000: leave.s IL_0008
}
finally
{
IL_0002: newobj ""System.Exception..ctor()""
IL_0007: throw
}
IL_0008: br.s IL_0008
}");
compilation.VerifyIL("D.ThrowInTry",
@"{
// Code size 10 (0xa)
.maxstack 1
.try
{
IL_0000: newobj ""System.Exception..ctor()""
IL_0005: throw
}
catch object
{
IL_0006: pop
IL_0007: leave.s IL_0009
}
IL_0009: ret
}");
compilation.VerifyIL("D.ThrowInTryInTry",
@"{
// Code size 10 (0xa)
.maxstack 1
.try
{
IL_0000: newobj ""System.Exception..ctor()""
IL_0005: throw
}
catch object
{
IL_0006: pop
IL_0007: leave.s IL_0009
}
IL_0009: ret
}");
compilation.VerifyIL("D.ThrowInTryInFinally",
@"{
// Code size 22 (0x16)
.maxstack 1
.try
{
.try
{
IL_0000: call ""void D.nop()""
IL_0005: leave.s IL_0015
}
catch object
{
IL_0007: pop
IL_0008: leave.s IL_0015
}
}
finally
{
IL_000a: nop
.try
{
IL_000b: newobj ""System.Exception..ctor()""
IL_0010: throw
}
catch object
{
IL_0011: pop
IL_0012: leave.s IL_0014
}
IL_0014: endfinally
}
IL_0015: ret
}");
}
[WorkItem(540716, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540716")]
[Fact]
public void ThrowInFinally()
{
var source =
@"using System;
class C
{
static void nop() { }
static void ThrowInFinally()
{
try { }
finally { throw new Exception(); }
}
static void ThrowInFinallyInTry()
{
try
{
try { }
finally { throw new Exception(); }
}
finally { nop(); }
}
static int ThrowInFinallyInFinally()
{
try { }
finally
{
try { }
finally { throw new Exception(); }
}
// unreachable and has no return
System.Console.WriteLine();
}
}
class D
{
static void nop() { }
static void ThrowInFinally()
{
try { nop(); }
catch { }
finally { throw new Exception(); }
}
static void ThrowInFinallyInTry()
{
try
{
try { nop(); }
catch { }
finally { throw new Exception(); }
}
catch { }
finally { nop(); }
}
static void ThrowInFinallyInFinally()
{
try { nop(); }
catch { }
finally
{
try { nop(); }
catch { }
finally { throw new Exception(); }
}
}
}";
var compilation = CompileAndVerify(source);
compilation.VerifyIL("C.ThrowInFinally",
@"{
// Code size 10 (0xa)
.maxstack 1
.try
{
IL_0000: leave.s IL_0008
}
finally
{
IL_0002: newobj ""System.Exception..ctor()""
IL_0007: throw
}
IL_0008: br.s IL_0008
}");
compilation.VerifyIL("C.ThrowInFinallyInTry",
@"{
// Code size 16 (0x10)
.maxstack 1
.try
{
.try
{
IL_0000: leave.s IL_0008
}
finally
{
IL_0002: newobj ""System.Exception..ctor()""
IL_0007: throw
}
IL_0008: br.s IL_0008
}
finally
{
IL_000a: call ""void C.nop()""
IL_000f: endfinally
}
}");
// The nop below is to work around a verifier bug.
// See DevDiv 563799.
compilation.VerifyIL("C.ThrowInFinallyInFinally",
@"{
// Code size 15 (0xf)
.maxstack 1
.try
{
IL_0000: leave.s IL_000d
}
finally
{
IL_0002: nop
.try
{
IL_0003: leave.s IL_000b
}
finally
{
IL_0005: newobj ""System.Exception..ctor()""
IL_000a: throw
}
IL_000b: br.s IL_000b
}
IL_000d: br.s IL_000d
}");
compilation.VerifyIL("D.ThrowInFinally",
@"{
// Code size 18 (0x12)
.maxstack 1
.try
{
.try
{
IL_0000: call ""void D.nop()""
IL_0005: leave.s IL_0010
}
catch object
{
IL_0007: pop
IL_0008: leave.s IL_0010
}
}
finally
{
IL_000a: newobj ""System.Exception..ctor()""
IL_000f: throw
}
IL_0010: br.s IL_0010
}");
compilation.VerifyIL("D.ThrowInFinallyInTry",
@"{
// Code size 30 (0x1e)
.maxstack 1
.try
{
.try
{
.try
{
.try
{
IL_0000: call ""void D.nop()""
IL_0005: leave.s IL_000a
}
catch object
{
IL_0007: pop
IL_0008: leave.s IL_000a
}
IL_000a: leave.s IL_0012
}
finally
{
IL_000c: newobj ""System.Exception..ctor()""
IL_0011: throw
}
IL_0012: br.s IL_0012
}
catch object
{
IL_0014: pop
IL_0015: leave.s IL_001d
}
}
finally
{
IL_0017: call ""void D.nop()""
IL_001c: endfinally
}
IL_001d: ret
}");
compilation.VerifyIL("D.ThrowInFinallyInFinally",
@"{
// Code size 31 (0x1f)
.maxstack 1
.try
{
.try
{
IL_0000: call ""void D.nop()""
IL_0005: leave.s IL_001d
}
catch object
{
IL_0007: pop
IL_0008: leave.s IL_001d
}
}
finally
{
IL_000a: nop
.try
{
.try
{
IL_000b: call ""void D.nop()""
IL_0010: leave.s IL_001b
}
catch object
{
IL_0012: pop
IL_0013: leave.s IL_001b
}
}
finally
{
IL_0015: newobj ""System.Exception..ctor()""
IL_001a: throw
}
IL_001b: br.s IL_001b
}
IL_001d: br.s IL_001d
}");
}
[Fact]
public void TryFilterSimple()
{
var src = @"
using System;
class C
{
static bool Filter()
{
Console.Write(""Filter"");
return true;
}
static void Main()
{
int x = 0;
try
{
Console.Write(""Try"");
x = x / x;
}
catch when (Filter())
{
Console.Write(""Catch"");
}
finally
{
Console.Write(""Finally"");
}
}
}";
var comp = CompileAndVerify(src,
expectedOutput: "TryFilterCatchFinally");
comp.VerifyIL("C.Main", @"
{
// Code size 54 (0x36)
.maxstack 2
.locals init (int V_0) //x
IL_0000: ldc.i4.0
IL_0001: stloc.0
.try
{
.try
{
IL_0002: ldstr ""Try""
IL_0007: call ""void System.Console.Write(string)""
IL_000c: ldloc.0
IL_000d: ldloc.0
IL_000e: div
IL_000f: stloc.0
IL_0010: leave.s IL_0035
}
filter
{
IL_0012: pop
IL_0013: call ""bool C.Filter()""
IL_0018: ldc.i4.0
IL_0019: cgt.un
IL_001b: endfilter
} // end filter
{ // handler
IL_001d: pop
IL_001e: ldstr ""Catch""
IL_0023: call ""void System.Console.Write(string)""
IL_0028: leave.s IL_0035
}
}
finally
{
IL_002a: ldstr ""Finally""
IL_002f: call ""void System.Console.Write(string)""
IL_0034: endfinally
}
IL_0035: ret
}
");
}
[Fact]
public void TryFilterUseException()
{
var src = @"
using System;
class C
{
static void Main()
{
System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture;
try
{
Test();
}
finally
{
System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture;
}
}
static void Test()
{
int x = 0;
try
{
Console.Write(""Try"");
x = x / x;
}
catch (DivideByZeroException e)
when (e.Message == null)
{
Console.Write(""Catch1"");
}
catch (DivideByZeroException e)
when (e.Message != null)
{
Console.Write(""Catch2"" + e.Message.Length);
}
finally
{
Console.Write(""Finally"");
}
}
}";
CompileAndVerify(src, expectedOutput: "TryCatch228Finally").
VerifyIL("C.Test", @"
{
// Code size 132 (0x84)
.maxstack 2
.locals init (int V_0, //x
System.DivideByZeroException V_1, //e
int V_2)
IL_0000: ldc.i4.0
IL_0001: stloc.0
.try
{
.try
{
IL_0002: ldstr ""Try""
IL_0007: call ""void System.Console.Write(string)""
IL_000c: ldloc.0
IL_000d: ldloc.0
IL_000e: div
IL_000f: stloc.0
IL_0010: leave.s IL_0083
}
filter
{
IL_0012: isinst ""System.DivideByZeroException""
IL_0017: dup
IL_0018: brtrue.s IL_001e
IL_001a: pop
IL_001b: ldc.i4.0
IL_001c: br.s IL_0029
IL_001e: callvirt ""string System.Exception.Message.get""
IL_0023: ldnull
IL_0024: ceq
IL_0026: ldc.i4.0
IL_0027: cgt.un
IL_0029: endfilter
} // end filter
{ // handler
IL_002b: pop
IL_002c: ldstr ""Catch1""
IL_0031: call ""void System.Console.Write(string)""
IL_0036: leave.s IL_0083
}
filter
{
IL_0038: isinst ""System.DivideByZeroException""
IL_003d: dup
IL_003e: brtrue.s IL_0044
IL_0040: pop
IL_0041: ldc.i4.0
IL_0042: br.s IL_0051
IL_0044: stloc.1
IL_0045: ldloc.1
IL_0046: callvirt ""string System.Exception.Message.get""
IL_004b: ldnull
IL_004c: cgt.un
IL_004e: ldc.i4.0
IL_004f: cgt.un
IL_0051: endfilter
} // end filter
{ // handler
IL_0053: pop
IL_0054: ldstr ""Catch2""
IL_0059: ldloc.1
IL_005a: callvirt ""string System.Exception.Message.get""
IL_005f: callvirt ""int string.Length.get""
IL_0064: stloc.2
IL_0065: ldloca.s V_2
IL_0067: call ""string int.ToString()""
IL_006c: call ""string string.Concat(string, string)""
IL_0071: call ""void System.Console.Write(string)""
IL_0076: leave.s IL_0083
}
}
finally
{
IL_0078: ldstr ""Finally""
IL_007d: call ""void System.Console.Write(string)""
IL_0082: endfinally
}
IL_0083: ret
}");
}
[Fact]
public void TryFilterScoping()
{
var src = @"
using System;
class C
{
private static string str = ""S1"";
static void Main()
{
int x = 0;
try
{
Console.Write(""Try"");
x = x / x;
}
catch when (new Func<bool>(() => str.Length == 2)())
{
Console.Write(""Catch"" + str);
}
finally
{
Console.Write(""Finally"");
}
}
}";
var comp = CompileAndVerify(src, expectedOutput: "TryCatchS1Finally");
comp.VerifyIL("C.Main", @"
{
// Code size 95 (0x5f)
.maxstack 2
.locals init (int V_0) //x
IL_0000: ldc.i4.0
IL_0001: stloc.0
.try
{
.try
{
IL_0002: ldstr ""Try""
IL_0007: call ""void System.Console.Write(string)""
IL_000c: ldloc.0
IL_000d: ldloc.0
IL_000e: div
IL_000f: stloc.0
IL_0010: leave.s IL_005e
}
filter
{
IL_0012: pop
IL_0013: ldsfld ""System.Func<bool> C.<>c.<>9__1_0""
IL_0018: dup
IL_0019: brtrue.s IL_0032
IL_001b: pop
IL_001c: ldsfld ""C.<>c C.<>c.<>9""
IL_0021: ldftn ""bool C.<>c.<Main>b__1_0()""
IL_0027: newobj ""System.Func<bool>..ctor(object, System.IntPtr)""
IL_002c: dup
IL_002d: stsfld ""System.Func<bool> C.<>c.<>9__1_0""
IL_0032: callvirt ""bool System.Func<bool>.Invoke()""
IL_0037: ldc.i4.0
IL_0038: cgt.un
IL_003a: endfilter
} // end filter
{ // handler
IL_003c: pop
IL_003d: ldstr ""Catch""
IL_0042: ldsfld ""string C.str""
IL_0047: call ""string string.Concat(string, string)""
IL_004c: call ""void System.Console.Write(string)""
IL_0051: leave.s IL_005e
}
}
finally
{
IL_0053: ldstr ""Finally""
IL_0058: call ""void System.Console.Write(string)""
IL_005d: endfinally
}
IL_005e: ret
}
");
}
[WorkItem(18678, "https://github.com/dotnet/roslyn/issues/18678")]
[Fact]
public void TryCatchConstantFalseFilter1()
{
var src = @"
using System;
class C
{
static void Main()
{
try
{
throw new Exception();
}
catch (Exception) when (false)
{
Console.Write(""Catch"");
}
}
}";
var comp = CompileAndVerify(src);
comp.VerifyIL("C.Main", @"
{
// Code size 6 (0x6)
.maxstack 1
IL_0000: newobj ""System.Exception..ctor()""
IL_0005: throw
}");
}
[WorkItem(18678, "https://github.com/dotnet/roslyn/issues/18678")]
[Fact]
public void TryCatchConstantFalseFilter2()
{
var src = @"
using System;
class C
{
static void Main()
{
try
{
throw new Exception();
}
catch (NullReferenceException) when (false)
{
Console.Write(""Catch1"");
}
catch (Exception) when (false)
{
Console.Write(""Catch2"");
}
catch when (false)
{
Console.Write(""Catch"");
}
}
}";
var comp = CompileAndVerify(src);
comp.VerifyIL("C.Main", @"
{
// Code size 6 (0x6)
.maxstack 1
IL_0000: newobj ""System.Exception..ctor()""
IL_0005: throw
}");
}
[WorkItem(18678, "https://github.com/dotnet/roslyn/issues/18678")]
[Fact]
public void TryCatchConstantFalseFilter3()
{
var src = @"
using System;
class C
{
static void Main()
{
try
{
throw new Exception();
}
catch (NullReferenceException) when ((1+1) == 2)
{
Console.Write(""Catch1"");
}
catch (Exception) when (true == false)
{
Console.Write(""Catch2"");
}
catch when ((1+1) != 2)
{
Console.Write(""Catch"");
}
}
}";
var comp = CompileAndVerify(src);
comp.VerifyIL("C.Main", @"
{
// Code size 39 (0x27)
.maxstack 2
.try
{
IL_0000: newobj ""System.Exception..ctor()""
IL_0005: throw
}
filter
{
IL_0006: isinst ""System.NullReferenceException""
IL_000b: dup
IL_000c: brtrue.s IL_0012
IL_000e: pop
IL_000f: ldc.i4.0
IL_0010: br.s IL_0017
IL_0012: pop
IL_0013: ldc.i4.1
IL_0014: ldc.i4.0
IL_0015: cgt.un
IL_0017: endfilter
} // end filter
{ // handler
IL_0019: pop
IL_001a: ldstr ""Catch1""
IL_001f: call ""void System.Console.Write(string)""
IL_0024: leave.s IL_0026
}
IL_0026: ret
}");
}
[WorkItem(18678, "https://github.com/dotnet/roslyn/issues/18678")]
[Fact]
public void TryCatchConstantFalseFilterCombined()
{
var src = @"
using System;
class C
{
static void Main()
{
var message = ""ExceptionMessage"";
try
{
throw new Exception(message);
}
catch (NullReferenceException) when (false)
{
Console.Write(""NullReferenceCatch"");
}
catch (Exception e) when (e.Message == message)
{
Console.Write(""ExceptionFilter"");
}
catch (Exception)
{
Console.Write(""ExceptionCatch"");
}
catch when (false)
{
Console.Write(""Catch"");
}
}
}";
var comp = CompileAndVerify(src, expectedOutput: "ExceptionFilter");
comp.VerifyIL("C.Main", @"
{
// Code size 68 (0x44)
.maxstack 2
.locals init (string V_0) //message
IL_0000: ldstr ""ExceptionMessage""
IL_0005: stloc.0
.try
{
IL_0006: ldloc.0
IL_0007: newobj ""System.Exception..ctor(string)""
IL_000c: throw
}
filter
{
IL_000d: isinst ""System.Exception""
IL_0012: dup
IL_0013: brtrue.s IL_0019
IL_0015: pop
IL_0016: ldc.i4.0
IL_0017: br.s IL_0027
IL_0019: callvirt ""string System.Exception.Message.get""
IL_001e: ldloc.0
IL_001f: call ""bool string.op_Equality(string, string)""
IL_0024: ldc.i4.0
IL_0025: cgt.un
IL_0027: endfilter
} // end filter
{ // handler
IL_0029: pop
IL_002a: ldstr ""ExceptionFilter""
IL_002f: call ""void System.Console.Write(string)""
IL_0034: leave.s IL_0043
}
catch System.Exception
{
IL_0036: pop
IL_0037: ldstr ""ExceptionCatch""
IL_003c: call ""void System.Console.Write(string)""
IL_0041: leave.s IL_0043
}
IL_0043: ret
}");
}
[WorkItem(18678, "https://github.com/dotnet/roslyn/issues/18678")]
[Fact]
public void TryCatchFinallyConstantFalseFilter()
{
var src = @"
using System;
class C
{
static void Main()
{
try
{
try
{
throw new Exception();
}
catch (NullReferenceException) when (false)
{
Console.Write(""Catch1"");
}
catch (Exception) when (false)
{
Console.Write(""Catch2"");
}
finally
{
Console.Write(""Finally"");
}
}
catch
{
Console.Write(""OuterCatch"");
}
}
}";
var comp = CompileAndVerify(src, expectedOutput: "FinallyOuterCatch");
comp.VerifyIL("C.Main", @"
{
// Code size 31 (0x1f)
.maxstack 1
.try
{
.try
{
IL_0000: newobj ""System.Exception..ctor()""
IL_0005: throw
}
finally
{
IL_0006: ldstr ""Finally""
IL_000b: call ""void System.Console.Write(string)""
IL_0010: endfinally
}
}
catch object
{
IL_0011: pop
IL_0012: ldstr ""OuterCatch""
IL_0017: call ""void System.Console.Write(string)""
IL_001c: leave.s IL_001e
}
IL_001e: ret
}");
}
[Fact]
public void TryCatchWithReturnValue()
{
var source =
@"using System;
class C
{
static int F(int i)
{
if (i == 0)
{
throw new InvalidOperationException();
}
else if (i == 1)
{
throw new InvalidCastException();
}
return i;
}
static int M(int i)
{
try
{
return F(i) * 3;
}
catch (InvalidOperationException)
{
return (i - 1) * 4;
}
catch
{
}
finally
{
i = i + 10;
}
return i;
}
static void Main()
{
Console.WriteLine(""M(0)={0}, M(1)={1}, M(2)={2}"", M(0), M(1), M(2));
}
}";
var compilation = CompileAndVerify(source, expectedOutput: "M(0)=-4, M(1)=11, M(2)=6");
compilation.VerifyIL("C.M",
@"{
// Code size 34 (0x22)
.maxstack 2
.locals init (int V_0)
.try
{
.try
{
IL_0000: ldarg.0
IL_0001: call ""int C.F(int)""
IL_0006: ldc.i4.3
IL_0007: mul
IL_0008: stloc.0
IL_0009: leave.s IL_0020
}
catch System.InvalidOperationException
{
IL_000b: pop
IL_000c: ldarg.0
IL_000d: ldc.i4.1
IL_000e: sub
IL_000f: ldc.i4.4
IL_0010: mul
IL_0011: stloc.0
IL_0012: leave.s IL_0020
}
catch object
{
IL_0014: pop
IL_0015: leave.s IL_001e
}
}
finally
{
IL_0017: ldarg.0
IL_0018: ldc.i4.s 10
IL_001a: add
IL_001b: starg.s V_0
IL_001d: endfinally
}
IL_001e: ldarg.0
IL_001f: ret
IL_0020: ldloc.0
IL_0021: ret
}");
}
[Fact]
public void Rethrow()
{
var source =
@"using System.IO;
class C
{
static void nop() { }
static int F = 0;
static void M()
{
try
{
nop();
}
catch (FileNotFoundException e)
{
if (F > 0)
{
throw;
}
else
{
throw e;
}
}
catch (IOException)
{
throw;
}
catch
{
throw;
}
}
}";
var compilation = CompileAndVerify(source);
compilation.VerifyIL("C.M",
@"{
// Code size 27 (0x1b)
.maxstack 2
.locals init (System.IO.FileNotFoundException V_0) //e
.try
{
IL_0000: call ""void C.nop()""
IL_0005: leave.s IL_001a
}
catch System.IO.FileNotFoundException
{
IL_0007: stloc.0
IL_0008: ldsfld ""int C.F""
IL_000d: ldc.i4.0
IL_000e: ble.s IL_0012
IL_0010: rethrow
IL_0012: ldloc.0
IL_0013: throw
}
catch System.IO.IOException
{
IL_0014: pop
IL_0015: rethrow
}
catch object
{
IL_0017: pop
IL_0018: rethrow
}
IL_001a: ret
}");
}
[WorkItem(541494, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541494")]
[Fact]
public void CatchT()
{
var source =
@"using System;
class C
{
internal static void TryCatch<T>() where T : Exception
{
try
{
Throw();
}
catch (T t)
{
Catch(t);
}
}
static void Throw() { throw new NotImplementedException(); }
static void Catch(Exception e)
{
Console.WriteLine(""Handled"");
}
static void Main()
{
try
{
TryCatch<NotImplementedException>();
TryCatch<InvalidOperationException>();
}
catch (Exception)
{
Console.WriteLine(""Unhandled"");
}
}
}";
var compilation = CompileAndVerify(source, expectedOutput:
@"Handled
Unhandled");
compilation.VerifyIL("C.TryCatch<T>()",
@"
{
// Code size 25 (0x19)
.maxstack 1
.try
{
IL_0000: call ""void C.Throw()""
IL_0005: leave.s IL_0018
}
catch T
{
IL_0007: unbox.any ""T""
IL_000c: box ""T""
IL_0011: call ""void C.Catch(System.Exception)""
IL_0016: leave.s IL_0018
}
IL_0018: ret
}
");
}
[WorkItem(540664, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540664")]
[Fact]
public void ExceptionAlreadyCaught1()
{
var source =
@"class C
{
static void M()
{
try { }
catch (System.Exception) { }
catch { }
}
}";
CompileAndVerify(source).VerifyDiagnostics(
Diagnostic(ErrorCode.WRN_UnreachableGeneralCatch, "catch").WithLocation(7, 9));
}
[Fact]
public void ExceptionAlreadyCaught2()
{
var text = @"
class Program
{
static void M()
{
int a = 1;
try { }
catch (System.Exception) { }
catch when (a == 1) { }
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (9,9): warning CS1058: A previous catch clause already catches all exceptions. All non-exceptions thrown will be wrapped in a System.Runtime.CompilerServices.RuntimeWrappedException.
// catch when (a == 1) { }
Diagnostic(ErrorCode.WRN_UnreachableGeneralCatch, "catch").WithLocation(9, 9));
}
[Fact]
public void ExceptionAlreadyCaught3()
{
var text = @"
class Program
{
static void M()
{
int a = 1;
try { }
catch when (a == 2) { }
catch (System.Exception) when (a == 3) { }
catch { }
}
}
";
CreateCompilation(text).VerifyDiagnostics();
}
[WorkItem(540666, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540666")]
[Fact]
public void EmptyTryFinally_Simple()
{
var source =
@"class C
{
static void M()
{
try { }
finally { }
}
}";
CompileAndVerify(source);
}
[WorkItem(542002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542002")]
[Fact]
public void ConditionInTry()
{
var source =
@"using System;
class Program
{
static void Main()
{
int a = 10;
try
{
if (a == 3)
{
}
}
catch (System.Exception)
{
}
}
}";
var compilation = CompileAndVerify(source, expectedOutput: "");
compilation.VerifyIL("Program.Main",
@"
{
// Code size 13 (0xd)
.maxstack 2
.locals init (int V_0) //a
IL_0000: ldc.i4.s 10
IL_0002: stloc.0
.try
{
IL_0003: ldloc.0
IL_0004: ldc.i4.3
IL_0005: pop
IL_0006: pop
IL_0007: leave.s IL_000c
}
catch System.Exception
{
IL_0009: pop
IL_000a: leave.s IL_000c
}
IL_000c: ret
}
");
}
[Fact(), WorkItem(544911, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544911")]
public void UnreachableAfterTryFinally()
{
var source = @"
using System;
class Program
{
static int Result = 0;
static void F()
{
Result = 1;
}
static void T1()
{
try
{
goto L;
}
finally
{
for (; ; ) { }
}
L:
F(); //unreachable
}
static void Main()
{
Console.Write(Result);
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "0");
compilation.VerifyIL("Program.T1",
@"
{
// Code size 6 (0x6)
.maxstack 0
.try
{
IL_0000: leave.s IL_0004
}
finally
{
IL_0002: br.s IL_0002
}
IL_0004: br.s IL_0004
}
");
}
[Fact(), WorkItem(544911, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544911")]
public void ReachableAfterBlockingCatch()
{
var source =
@"using System;
class Program
{
static void nop() { }
static void F()
{
Console.WriteLine(""hello"");
}
static void T1()
{
try
{
nop();
}
catch
{
for (; ; ) { }
}
F(); //reachable
}
static void Main()
{
T1();
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "hello");
compilation.VerifyIL("Program.T1",
@"{
// Code size 16 (0x10)
.maxstack 1
.try
{
IL_0000: call ""void Program.nop()""
IL_0005: leave.s IL_000a
}
catch object
{
IL_0007: pop
IL_0008: br.s IL_0008
}
IL_000a: call ""void Program.F()""
IL_000f: ret
}");
}
[Fact(), WorkItem(544911, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544911")]
public void UnreachableAfterTryFinallyConditional()
{
var source = @"
using System;
class Program
{
static int Result = 0;
static void F()
{
Result = 1;
}
static void T1()
{
try
{
if (Result == 0)
goto L;
}
finally
{
for (; ; ) { }
}
L:
F(); //unreachable
}
static void Main()
{
Console.Write(Result);
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "0");
compilation.VerifyIL("Program.T1",
@"
{
// Code size 12 (0xc)
.maxstack 1
.try
{
IL_0000: ldsfld ""int Program.Result""
IL_0005: pop
IL_0006: leave.s IL_000a
}
finally
{
IL_0008: br.s IL_0008
}
IL_000a: br.s IL_000a
}
");
}
[Fact()]
public void ReachableAfterFinallyButNotFromTryConditional01()
{
var source = @"
using System;
class Program
{
static int Result = 0;
static void F()
{
Result = 1;
}
static void T1()
{
if (Result == 1)
goto L;
try
{
try
{
if (Result == 0)
goto L;
goto L;
}
finally
{
for (; ; ) { }
}
if (Result == 0)
goto L;
}
finally
{
for (; ; ) { }
}
L:
F(); //reachable but not from the try
}
static void Main()
{
Console.Write(Result);
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "0");
compilation.VerifyIL("Program.T1",
@"
{
// Code size 29 (0x1d)
.maxstack 2
IL_0000: ldsfld ""int Program.Result""
IL_0005: ldc.i4.1
IL_0006: beq.s IL_0017
IL_0008: nop
.try
{
.try
{
IL_0009: ldsfld ""int Program.Result""
IL_000e: pop
IL_000f: leave.s IL_0013
}
finally
{
IL_0011: br.s IL_0011
}
IL_0013: br.s IL_0013
}
finally
{
IL_0015: br.s IL_0015
}
IL_0017: call ""void Program.F()""
IL_001c: ret
}
");
}
[Fact(), WorkItem(544911, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544911")]
public void ReachableAfterFinallyButNotFromTryConditional()
{
var source = @"
using System;
class Program
{
static int Result = 0;
static void F()
{
Result = 1;
}
static void T1()
{
if (Result == 1)
goto L;
try
{
try
{
if (Result == 0)
goto L;
}
finally
{
for (; ; ) { }
}
if (Result == 0)
goto L;
}
finally
{
for (; ; ) { }
}
L:
F(); //reachable but not from the try
}
static void Main()
{
Console.Write(Result);
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "0");
compilation.VerifyIL("Program.T1",
@"
{
// Code size 29 (0x1d)
.maxstack 2
IL_0000: ldsfld ""int Program.Result""
IL_0005: ldc.i4.1
IL_0006: beq.s IL_0017
IL_0008: nop
.try
{
.try
{
IL_0009: ldsfld ""int Program.Result""
IL_000e: pop
IL_000f: leave.s IL_0013
}
finally
{
IL_0011: br.s IL_0011
}
IL_0013: br.s IL_0013
}
finally
{
IL_0015: br.s IL_0015
}
IL_0017: call ""void Program.F()""
IL_001c: ret
}
");
}
[Fact(), WorkItem(713418, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/713418")]
public void ConditionalUnconditionalBranches()
{
var source = @"
using System;
class Program
{
private static int x = 123;
static void Main(string[] args)
{
try
{
if (x == 10)
{
goto l2;;
}
if (x != 0)
{
Console.WriteLine(""2"");
}
goto l1;
l2:
Console.WriteLine(""l2"");
l1:
goto lOut;
}
finally
{
Console.WriteLine(""Finally"");
}
lOut:
Console.WriteLine(""Out"");
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"2
Finally
Out");
compilation.VerifyIL("Program.Main",
@"
{
// Code size 62 (0x3e)
.maxstack 2
.try
{
IL_0000: ldsfld ""int Program.x""
IL_0005: ldc.i4.s 10
IL_0007: beq.s IL_001c
IL_0009: ldsfld ""int Program.x""
IL_000e: brfalse.s IL_0026
IL_0010: ldstr ""2""
IL_0015: call ""void System.Console.WriteLine(string)""
IL_001a: leave.s IL_0033
IL_001c: ldstr ""l2""
IL_0021: call ""void System.Console.WriteLine(string)""
IL_0026: leave.s IL_0033
}
finally
{
IL_0028: ldstr ""Finally""
IL_002d: call ""void System.Console.WriteLine(string)""
IL_0032: endfinally
}
IL_0033: ldstr ""Out""
IL_0038: call ""void System.Console.WriteLine(string)""
IL_003d: ret
}
");
}
[Fact(), WorkItem(713418, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/713418")]
public void ConditionalUnconditionalBranches001()
{
var source = @"
using System;
class Program
{
private static int x = 123;
static void Main(string[] args)
{
try
{
if (x == 10)
{
goto l2;;
}
if (x != 0)
{
Console.WriteLine(""2"");
}
goto l1;
l2:
// Console.WriteLine(""l2"");
l1:
goto lOut;
}
finally
{
Console.WriteLine(""Finally"");
}
lOut:
Console.WriteLine(""Out"");
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"2
Finally
Out");
compilation.VerifyIL("Program.Main",
@"
{
// Code size 52 (0x34)
.maxstack 2
.try
{
IL_0000: ldsfld ""int Program.x""
IL_0005: ldc.i4.s 10
IL_0007: bne.un.s IL_000b
IL_0009: leave.s IL_0029
IL_000b: ldsfld ""int Program.x""
IL_0010: brfalse.s IL_001c
IL_0012: ldstr ""2""
IL_0017: call ""void System.Console.WriteLine(string)""
IL_001c: leave.s IL_0029
}
finally
{
IL_001e: ldstr ""Finally""
IL_0023: call ""void System.Console.WriteLine(string)""
IL_0028: endfinally
}
IL_0029: ldstr ""Out""
IL_002e: call ""void System.Console.WriteLine(string)""
IL_0033: ret
}
");
}
[Fact(), WorkItem(2443, "https://github.com/dotnet/roslyn/issues/2443")]
public void OptimizeEmptyTryBlock()
{
var source = @"
using System;
class Program
{
public static void Main(string[] args)
{
try
{
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"");
compilation.VerifyIL("Program.Main",
@"
{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}
");
}
[Fact]
[WorkItem(29481, "https://github.com/dotnet/roslyn/issues/29481")]
public void Issue29481()
{
var source = @"
using System;
public class Program
{
public static void Main()
{
try
{
bool b = false;
if (b)
{
try
{
return;
}
finally
{
Console.WriteLine(""Prints"");
}
}
else
{
return;
}
}
finally
{
GC.KeepAlive(null);
}
}
}";
CompileAndVerify(source, expectedOutput: "", options: TestOptions.DebugExe);
CompileAndVerify(source, expectedOutput: "", options: TestOptions.ReleaseExe).VerifyIL("Program.Main",
@"
{
// Code size 26 (0x1a)
.maxstack 1
.try
{
IL_0000: ldc.i4.0
IL_0001: brfalse.s IL_0010
.try
{
IL_0003: leave.s IL_0019
}
finally
{
IL_0005: ldstr ""Prints""
IL_000a: call ""void System.Console.WriteLine(string)""
IL_000f: endfinally
}
IL_0010: leave.s IL_0019
}
finally
{
IL_0012: ldnull
IL_0013: call ""void System.GC.KeepAlive(object)""
IL_0018: endfinally
}
IL_0019: ret
}
");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class CodeGenTryFinallyTests : CSharpTestBase
{
[Fact]
public void EmptyTryFinally()
{
var source =
@"class C
{
static void EmptyTryFinally()
{
try { }
finally { }
}
static void EmptyTryFinallyInTry()
{
try
{
try { }
finally { }
}
finally { }
}
static void EmptyTryFinallyInFinally()
{
try { }
finally
{
try { }
finally { }
}
}
}";
var compilation = CompileAndVerify(source);
compilation.VerifyIL("C.EmptyTryFinally",
@"{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}");
compilation.VerifyIL("C.EmptyTryFinallyInTry",
@"{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}");
compilation.VerifyIL("C.EmptyTryFinallyInFinally",
@"{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}");
}
[Theory, WorkItem(4729, "https://github.com/dotnet/roslyn/issues/4729")]
[InlineData("")]
[InlineData(";")]
public void NopInTryCatchFinally(string doNothingStatements)
{
var source =
$@"class C
{{
static void M1()
{{
try {{ {doNothingStatements} }}
catch (System.Exception) {{ {doNothingStatements} }}
finally {{ {doNothingStatements} }}
}}
static void M2()
{{
try {{
try {{ {doNothingStatements} }}
catch (System.Exception) {{ {doNothingStatements} }}
finally {{ {doNothingStatements} }}
}}
catch (System.Exception) {{
try {{ {doNothingStatements} }}
catch (System.Exception) {{ {doNothingStatements} }}
finally {{ {doNothingStatements} }}
}}
finally {{
try {{ {doNothingStatements} }}
catch (System.Exception) {{ {doNothingStatements} }}
finally {{ {doNothingStatements} }}
}}
}}
static void M3()
{{
try {{ System.Console.WriteLine(1); }}
catch (System.Exception) {{ {doNothingStatements} }}
finally {{ {doNothingStatements} }}
}}
static void M4()
{{
try {{ {doNothingStatements} }}
catch (System.Exception) {{ System.Console.WriteLine(1); }}
finally {{ {doNothingStatements} }}
}}
static void M5()
{{
try {{ {doNothingStatements} }}
catch (System.Exception) {{ {doNothingStatements} }}
finally {{ System.Console.WriteLine(1); }}
}}
}}";
var compilation = CompileAndVerify(source);
compilation.VerifyIL("C.M1",
@"{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}");
compilation.VerifyIL("C.M2",
@"{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}");
compilation.VerifyIL("C.M3",
@"{
// Code size 12 (0xc)
.maxstack 1
.try
{
IL_0000: ldc.i4.1
IL_0001: call ""void System.Console.WriteLine(int)""
IL_0006: leave.s IL_000b
}
catch System.Exception
{
IL_0008: pop
IL_0009: leave.s IL_000b
}
IL_000b: ret
}");
compilation.VerifyIL("C.M4",
@"{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}");
compilation.VerifyIL("C.M5",
@"{
// Code size 10 (0xa)
.maxstack 1
.try
{
IL_0000: leave.s IL_0009
}
finally
{
IL_0002: ldc.i4.1
IL_0003: call ""void System.Console.WriteLine(int)""
IL_0008: endfinally
}
IL_0009: ret
}");
}
[Fact]
public void TryFinally()
{
var source =
@"class C
{
static void Main()
{
M(1);
M(0);
}
static void M(int f)
{
try
{
System.Console.Write(""1, "");
if (f > 0)
goto End;
System.Console.Write(""2, "");
return;
}
finally
{
System.Console.Write(""3, "");
}
End:
System.Console.Write(""4, "");
}
}";
var compilation = CompileAndVerify(source, expectedOutput: "1, 3, 4, 1, 2, 3, ");
compilation.VerifyIL("C.M",
@"{
// Code size 50 (0x32)
.maxstack 2
.try
{
IL_0000: ldstr ""1, ""
IL_0005: call ""void System.Console.Write(string)""
IL_000a: ldarg.0
IL_000b: ldc.i4.0
IL_000c: ble.s IL_0010
IL_000e: leave.s IL_0027
IL_0010: ldstr ""2, ""
IL_0015: call ""void System.Console.Write(string)""
IL_001a: leave.s IL_0031
}
finally
{
IL_001c: ldstr ""3, ""
IL_0021: call ""void System.Console.Write(string)""
IL_0026: endfinally
}
IL_0027: ldstr ""4, ""
IL_002c: call ""void System.Console.Write(string)""
IL_0031: ret
}");
}
[Fact]
public void TryCatch()
{
var source =
@"using System;
class C
{
static void Main()
{
M(1);
M(0);
}
static void M(int f)
{
try
{
Console.Write(""before, "");
N(f);
Console.Write(""after, "");
}
catch (Exception)
{
Console.Write(""catch, "");
}
}
static void N(int f)
{
if (f > 0)
throw new Exception();
}
}";
var compilation = CompileAndVerify(source, expectedOutput: "before, catch, before, after,");
compilation.VerifyIL("C.M",
@"{
// Code size 42 (0x2a)
.maxstack 1
.try
{
IL_0000: ldstr ""before, ""
IL_0005: call ""void System.Console.Write(string)""
IL_000a: ldarg.0
IL_000b: call ""void C.N(int)""
IL_0010: ldstr ""after, ""
IL_0015: call ""void System.Console.Write(string)""
IL_001a: leave.s IL_0029
}
catch System.Exception
{
IL_001c: pop
IL_001d: ldstr ""catch, ""
IL_0022: call ""void System.Console.Write(string)""
IL_0027: leave.s IL_0029
}
IL_0029: ret
}");
}
[Fact]
public void TryCatch001()
{
var source =
@"using System;
class C
{
static void Main()
{
}
static void M()
{
try
{
System.Object o = null;
o.ToString();//null Exception throw
}
catch (System.NullReferenceException NullException)//null Exception caught
{
try
{
throw new System.ApplicationException();//app Exception throw
}
catch (System.ApplicationException AppException)//app Exception caught
{
throw new System.DivideByZeroException();//Zero Exception throw
}
}
}
}";
var compilation = CompileAndVerify(source, expectedOutput: "");
compilation.VerifyIL("C.M",
@"{
// Code size 24 (0x18)
.maxstack 1
.try
{
IL_0000: ldnull
IL_0001: callvirt ""string object.ToString()""
IL_0006: pop
IL_0007: leave.s IL_0017
}
catch System.NullReferenceException
{
IL_0009: pop
.try
{
IL_000a: newobj ""System.ApplicationException..ctor()""
IL_000f: throw
}
catch System.ApplicationException
{
IL_0010: pop
IL_0011: newobj ""System.DivideByZeroException..ctor()""
IL_0016: throw
}
}
IL_0017: ret
}");
}
[Fact]
public void TryCatch002()
{
var source =
@"using System;
class C
{
static void Main()
{
}
static void M()
{
try
{
System.Object o = null;
o.ToString();//null Exception throw
goto l1;
}
catch (System.NullReferenceException NullException)//null Exception caught
{
try
{
throw new System.ApplicationException();//app Exception throw
}
catch (System.ApplicationException AppException)//app Exception caught
{
throw new System.DivideByZeroException();//Zero Exception throw
}
}
l1:
;
;
;
}
}";
var compilation = CompileAndVerify(source, expectedOutput: "");
compilation.VerifyIL("C.M", @"
{
// Code size 24 (0x18)
.maxstack 1
.try
{
IL_0000: ldnull
IL_0001: callvirt ""string object.ToString()""
IL_0006: pop
IL_0007: leave.s IL_0017
}
catch System.NullReferenceException
{
IL_0009: pop
.try
{
IL_000a: newobj ""System.ApplicationException..ctor()""
IL_000f: throw
}
catch System.ApplicationException
{
IL_0010: pop
IL_0011: newobj ""System.DivideByZeroException..ctor()""
IL_0016: throw
}
}
IL_0017: ret
}");
}
[WorkItem(813428, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/813428")]
[Fact]
public void TryCatchOptimized001()
{
var source =
@"
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
try
{
throw new Exception(""debug only"");
}
catch (Exception ex)
{
Debug.Write(ex.Message);
}
try
{
throw new Exception(""hello"");
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
try
{
throw new Exception(""bye"");
}
catch (Exception ex)
{
Console.Write(ex.Message);
Console.Write(ex.Message);
}
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "hellobyebye");
compilation.VerifyIL("Program.Main",
@"
{
// Code size 74 (0x4a)
.maxstack 2
.try
{
IL_0000: ldstr ""debug only""
IL_0005: newobj ""System.Exception..ctor(string)""
IL_000a: throw
}
catch System.Exception
{
IL_000b: pop
IL_000c: leave.s IL_000e
}
IL_000e: nop
.try
{
IL_000f: ldstr ""hello""
IL_0014: newobj ""System.Exception..ctor(string)""
IL_0019: throw
}
catch System.Exception
{
IL_001a: callvirt ""string System.Exception.Message.get""
IL_001f: call ""void System.Console.Write(string)""
IL_0024: leave.s IL_0026
}
IL_0026: nop
.try
{
IL_0027: ldstr ""bye""
IL_002c: newobj ""System.Exception..ctor(string)""
IL_0031: throw
}
catch System.Exception
{
IL_0032: dup
IL_0033: callvirt ""string System.Exception.Message.get""
IL_0038: call ""void System.Console.Write(string)""
IL_003d: callvirt ""string System.Exception.Message.get""
IL_0042: call ""void System.Console.Write(string)""
IL_0047: leave.s IL_0049
}
IL_0049: ret
}
");
}
[Fact]
public void TryFilterOptimized001()
{
var source =
@"
using System;
class Program
{
static void Main()
{
try
{
throw new Exception(""hello"");
}
catch (Exception ex1) when (ex1.Message == null)
{
}
try
{
throw new Exception(""bye"");
}
catch (Exception ex2) when (F(ex2, ex2))
{
}
}
private static bool F(Exception e1, Exception e2)
{
return false;
}
}
";
var compilation = CompileAndVerify(source);
compilation.VerifyIL("Program.Main", @"
{
// Code size 78 (0x4e)
.maxstack 2
.try
{
IL_0000: ldstr ""hello""
IL_0005: newobj ""System.Exception..ctor(string)""
IL_000a: throw
}
filter
{
IL_000b: isinst ""System.Exception""
IL_0010: dup
IL_0011: brtrue.s IL_0017
IL_0013: pop
IL_0014: ldc.i4.0
IL_0015: br.s IL_0022
IL_0017: callvirt ""string System.Exception.Message.get""
IL_001c: ldnull
IL_001d: ceq
IL_001f: ldc.i4.0
IL_0020: cgt.un
IL_0022: endfilter
} // end filter
{ // handler
IL_0024: pop
IL_0025: leave.s IL_0027
}
IL_0027: nop
.try
{
IL_0028: ldstr ""bye""
IL_002d: newobj ""System.Exception..ctor(string)""
IL_0032: throw
}
filter
{
IL_0033: isinst ""System.Exception""
IL_0038: dup
IL_0039: brtrue.s IL_003f
IL_003b: pop
IL_003c: ldc.i4.0
IL_003d: br.s IL_0048
IL_003f: dup
IL_0040: call ""bool Program.F(System.Exception, System.Exception)""
IL_0045: ldc.i4.0
IL_0046: cgt.un
IL_0048: endfilter
} // end filter
{ // handler
IL_004a: pop
IL_004b: leave.s IL_004d
}
IL_004d: ret
}
");
}
[Fact]
public void TryFilterOptimized002()
{
var source =
@"
using System;
class Program
{
static void Main()
{
try
{
throw new Exception(""bye"");
}
catch (Exception ex) when (F(ex, ex))
{
Console.WriteLine(ex);
}
}
private static bool F(Exception e1, Exception e2)
{
return false;
}
}
";
var compilation = CompileAndVerify(source);
compilation.VerifyIL("Program.Main", @"
{
// Code size 46 (0x2e)
.maxstack 2
.locals init (System.Exception V_0) //ex
.try
{
IL_0000: ldstr ""bye""
IL_0005: newobj ""System.Exception..ctor(string)""
IL_000a: throw
}
filter
{
IL_000b: isinst ""System.Exception""
IL_0010: dup
IL_0011: brtrue.s IL_0017
IL_0013: pop
IL_0014: ldc.i4.0
IL_0015: br.s IL_0022
IL_0017: stloc.0
IL_0018: ldloc.0
IL_0019: ldloc.0
IL_001a: call ""bool Program.F(System.Exception, System.Exception)""
IL_001f: ldc.i4.0
IL_0020: cgt.un
IL_0022: endfilter
} // end filter
{ // handler
IL_0024: pop
IL_0025: ldloc.0
IL_0026: call ""void System.Console.WriteLine(object)""
IL_002b: leave.s IL_002d
}
IL_002d: ret
}
");
}
[Fact]
public void TryFilterOptimized003()
{
var source =
@"
using System;
class Program
{
static void Main()
{
try
{
throw new Exception(""bye"");
}
catch (Exception ex) when (F(ref ex))
{
Console.WriteLine(ex);
}
}
private static bool F(ref Exception e)
{
e = null;
return true;
}
}
";
var compilation = CompileAndVerify(source);
compilation.VerifyIL("Program.Main", @"
{
// Code size 46 (0x2e)
.maxstack 2
.locals init (System.Exception V_0) //ex
.try
{
IL_0000: ldstr ""bye""
IL_0005: newobj ""System.Exception..ctor(string)""
IL_000a: throw
}
filter
{
IL_000b: isinst ""System.Exception""
IL_0010: dup
IL_0011: brtrue.s IL_0017
IL_0013: pop
IL_0014: ldc.i4.0
IL_0015: br.s IL_0022
IL_0017: stloc.0
IL_0018: ldloca.s V_0
IL_001a: call ""bool Program.F(ref System.Exception)""
IL_001f: ldc.i4.0
IL_0020: cgt.un
IL_0022: endfilter
} // end filter
{ // handler
IL_0024: pop
IL_0025: ldloc.0
IL_0026: call ""void System.Console.WriteLine(object)""
IL_002b: leave.s IL_002d
}
IL_002d: ret
}");
}
[Fact]
public void TryFilterOptimized004()
{
var source =
@"
using System;
class Program
{
static void F<T>() where T : Exception
{
try
{
throw new Exception(""bye"");
}
catch (T ex) when (F(ex, ex))
{
Console.WriteLine(ex);
}
}
private static bool F<S>(S e1, S e2)
{
return false;
}
}
";
var compilation = CompileAndVerify(source);
compilation.VerifyIL("Program.F<T>", @"
{
// Code size 56 (0x38)
.maxstack 2
.locals init (T V_0) //ex
.try
{
IL_0000: ldstr ""bye""
IL_0005: newobj ""System.Exception..ctor(string)""
IL_000a: throw
}
filter
{
IL_000b: isinst ""T""
IL_0010: dup
IL_0011: brtrue.s IL_0017
IL_0013: pop
IL_0014: ldc.i4.0
IL_0015: br.s IL_0027
IL_0017: unbox.any ""T""
IL_001c: stloc.0
IL_001d: ldloc.0
IL_001e: ldloc.0
IL_001f: call ""bool Program.F<T>(T, T)""
IL_0024: ldc.i4.0
IL_0025: cgt.un
IL_0027: endfilter
} // end filter
{ // handler
IL_0029: pop
IL_002a: ldloc.0
IL_002b: box ""T""
IL_0030: call ""void System.Console.WriteLine(object)""
IL_0035: leave.s IL_0037
}
IL_0037: ret
}
");
}
[Fact, WorkItem(854935, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854935")]
public void LiftedExceptionVariableInGenericIterator()
{
var source = @"
using System;
using System.IO;
using System.Collections.Generic;
class C
{
public IEnumerable<int> Iter2<T>()
{
try
{
throw new IOException(""Hi"");
}
catch (Exception e)
{
( (Action) delegate { Console.WriteLine(e.Message); })();
}
yield return 1;
}
static void Main()
{
foreach (var x in new C().Iter2<object>()) { }
}
}";
CompileAndVerify(source, expectedOutput: "Hi");
}
[Fact, WorkItem(854935, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854935")]
public void GenericLiftedExceptionVariableInGenericIterator()
{
var source = @"
using System;
using System.IO;
using System.Collections.Generic;
class C
{
public IEnumerable<int> Iter2<T, E>() where E : Exception
{
try
{
throw new IOException(""Hi"");
}
catch (E e) when (new Func<bool>(() => e.Message != null)())
{
( (Action) delegate { Console.WriteLine(e.Message); })();
}
yield return 1;
}
static void Main()
{
foreach (var x in new C().Iter2<object, IOException>()) { }
}
}";
CompileAndVerify(source, expectedOutput: "Hi");
}
[WorkItem(579778, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579778")]
[Fact]
public void Regression579778()
{
var source =
@"
using System;
using System.Security;
[assembly: SecurityTransparent()]
class C
{
static void nop() {}
static void Main()
{
try
{
throw null;
}
catch (Exception)
{
}
finally
{
try { nop(); }
catch { }
}
}
}";
var compilation = CompileAndVerify(source, expectedOutput: "");
compilation.VerifyIL("C.Main",
@"
{
// Code size 18 (0x12)
.maxstack 1
.try
{
.try
{
IL_0000: ldnull
IL_0001: throw
}
catch System.Exception
{
IL_0002: pop
IL_0003: leave.s IL_0011
}
}
finally
{
IL_0005: nop
.try
{
IL_0006: call ""void C.nop()""
IL_000b: leave.s IL_0010
}
catch object
{
IL_000d: pop
IL_000e: leave.s IL_0010
}
IL_0010: endfinally
}
IL_0011: ret
}
");
}
[Fact]
public void NestedExceptionHandlers()
{
var source =
@"using System;
class C
{
static void F(int i)
{
if (i == 0)
{
throw new Exception(""i == 0"");
}
throw new InvalidOperationException(""i != 0"");
}
static void M(int i)
{
try
{
try
{
F(i);
}
catch (InvalidOperationException e)
{
Console.WriteLine(""InvalidOperationException: {0}"", e.Message);
F(i + 1);
}
}
catch (Exception e)
{
Console.WriteLine(""Exception: {0}"", e.Message);
}
}
static void Main()
{
M(0);
M(1);
}
}";
var compilation = CompileAndVerify(source, expectedOutput:
@"Exception: i == 0
InvalidOperationException: i != 0
Exception: i != 0");
compilation.VerifyIL("C.M",
@"
{
// Code size 57 (0x39)
.maxstack 2
.locals init (System.InvalidOperationException V_0, //e
System.Exception V_1) //e
.try
{
.try
{
IL_0000: ldarg.0
IL_0001: call ""void C.F(int)""
IL_0006: leave.s IL_0023
}
catch System.InvalidOperationException
{
IL_0008: stloc.0
IL_0009: ldstr ""InvalidOperationException: {0}""
IL_000e: ldloc.0
IL_000f: callvirt ""string System.Exception.Message.get""
IL_0014: call ""void System.Console.WriteLine(string, object)""
IL_0019: ldarg.0
IL_001a: ldc.i4.1
IL_001b: add
IL_001c: call ""void C.F(int)""
IL_0021: leave.s IL_0023
}
IL_0023: leave.s IL_0038
}
catch System.Exception
{
IL_0025: stloc.1
IL_0026: ldstr ""Exception: {0}""
IL_002b: ldloc.1
IL_002c: callvirt ""string System.Exception.Message.get""
IL_0031: call ""void System.Console.WriteLine(string, object)""
IL_0036: leave.s IL_0038
}
IL_0038: ret
}
");
}
[ConditionalFact(typeof(WindowsDesktopOnly))]
public void NestedExceptionHandlersThreadAbort01()
{
var source =
@"
using System;
using System.Threading;
class Program
{
static ManualResetEventSlim s = new ManualResetEventSlim(false);
static void Main(string[] args)
{
var ts = new ThreadStart(Test);
var t = new Thread(ts);
t.Start();
s.Wait();
t.Abort();
t.Join();
}
public static void Test()
{
try
{
try
{
s.Set();
for (; ;) ;
}
catch (Exception ex)
{
Console.WriteLine(""catch1"");
}
}
catch (Exception ex)
{
Console.WriteLine(""catch2"");
}
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"
catch1
catch2
");
compilation.VerifyIL("Program.Test",
@"
{
// Code size 41 (0x29)
.maxstack 1
.try
{
.try
{
IL_0000: ldsfld ""System.Threading.ManualResetEventSlim Program.s""
IL_0005: callvirt ""void System.Threading.ManualResetEventSlim.Set()""
IL_000a: br.s IL_000a
}
catch System.Exception
{
IL_000c: pop
IL_000d: ldstr ""catch1""
IL_0012: call ""void System.Console.WriteLine(string)""
IL_0017: leave.s IL_0019
}
IL_0019: leave.s IL_0028
}
catch System.Exception
{
IL_001b: pop
IL_001c: ldstr ""catch2""
IL_0021: call ""void System.Console.WriteLine(string)""
IL_0026: leave.s IL_0028
}
IL_0028: ret
}
");
}
[ConditionalFact(typeof(WindowsDesktopOnly))]
public void NestedExceptionHandlersThreadAbort02()
{
var source =
@"
using System;
using System.Threading;
class Program
{
static ManualResetEventSlim s = new ManualResetEventSlim(false);
static void Main(string[] args)
{
var ts = new ThreadStart(Test);
var t = new Thread(ts);
t.Start();
s.Wait();
t.Abort();
t.Join();
}
public static void Test()
{
try
{
try
{
try
{
s.Set();
for (; ;) ;
}
catch (Exception ex)
{
Console.WriteLine(""catch1"");
}
}
finally
{
Console.WriteLine(""finally"");
}
}
catch (Exception ex)
{
Console.WriteLine(""catch2"");
}
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"
catch1
finally
catch2
");
compilation.VerifyIL("Program.Test",
@"
{
// Code size 54 (0x36)
.maxstack 1
.try
{
.try
{
.try
{
IL_0000: ldsfld ""System.Threading.ManualResetEventSlim Program.s""
IL_0005: callvirt ""void System.Threading.ManualResetEventSlim.Set()""
IL_000a: br.s IL_000a
}
catch System.Exception
{
IL_000c: pop
IL_000d: ldstr ""catch1""
IL_0012: call ""void System.Console.WriteLine(string)""
IL_0017: leave.s IL_0019
}
IL_0019: leave.s IL_0026
}
finally
{
IL_001b: ldstr ""finally""
IL_0020: call ""void System.Console.WriteLine(string)""
IL_0025: endfinally
}
IL_0026: leave.s IL_0035
}
catch System.Exception
{
IL_0028: pop
IL_0029: ldstr ""catch2""
IL_002e: call ""void System.Console.WriteLine(string)""
IL_0033: leave.s IL_0035
}
IL_0035: ret
}
");
}
[ConditionalFact(typeof(WindowsDesktopOnly))]
public void NestedExceptionHandlersThreadAbort03()
{
var source =
@"
using System;
using System.Threading;
class Program
{
static ManualResetEventSlim s = new ManualResetEventSlim(false);
static void Main(string[] args)
{
var ts = new ThreadStart(Test);
var t = new Thread(ts);
t.Start();
s.Wait();
t.Abort();
t.Join();
}
public static void Test()
{
try
{
try
{
try
{
try
{
s.Set();
while (s != null) {};
}
catch (Exception ex)
{
Console.WriteLine(""catch1"");
}
}
finally
{
Console.WriteLine(""finally1"");
}
}
catch (Exception ex)
{
Console.WriteLine(""catch2"");
}
}
finally
{
Console.WriteLine(""finally2"");
}
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"
catch1
finally1
catch2
finally2
");
compilation.VerifyIL("Program.Test",
@"
{
// Code size 72 (0x48)
.maxstack 1
.try
{
.try
{
.try
{
.try
{
IL_0000: ldsfld ""System.Threading.ManualResetEventSlim Program.s""
IL_0005: callvirt ""void System.Threading.ManualResetEventSlim.Set()""
IL_000a: ldsfld ""System.Threading.ManualResetEventSlim Program.s""
IL_000f: brtrue.s IL_000a
IL_0011: leave.s IL_0020
}
catch System.Exception
{
IL_0013: pop
IL_0014: ldstr ""catch1""
IL_0019: call ""void System.Console.WriteLine(string)""
IL_001e: leave.s IL_0020
}
IL_0020: leave.s IL_002d
}
finally
{
IL_0022: ldstr ""finally1""
IL_0027: call ""void System.Console.WriteLine(string)""
IL_002c: endfinally
}
IL_002d: leave.s IL_0047
}
catch System.Exception
{
IL_002f: pop
IL_0030: ldstr ""catch2""
IL_0035: call ""void System.Console.WriteLine(string)""
IL_003a: leave.s IL_0047
}
}
finally
{
IL_003c: ldstr ""finally2""
IL_0041: call ""void System.Console.WriteLine(string)""
IL_0046: endfinally
}
IL_0047: ret
}
");
}
[ConditionalFact(typeof(WindowsDesktopOnly))]
public void NestedExceptionHandlersThreadAbort04()
{
var source =
@"
using System;
using System.Threading;
class Program
{
static ManualResetEventSlim s = new ManualResetEventSlim(false);
static void Main(string[] args)
{
var ts = new ThreadStart(Test);
var t = new Thread(ts);
t.Start();
s.Wait();
t.Abort();
t.Join();
}
public static void Test()
{
try
{
try
{
try
{
try
{
s.Set();
while (s != null) {};
}
catch (Exception ex)
{
Console.WriteLine(""catch1"");
}
}
finally
{
Console.WriteLine(""finally1"");
}
}
catch (Exception ex) when (ex != null)
{
Console.WriteLine(""catch2"");
}
}
finally
{
Console.WriteLine(""finally2"");
}
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"
catch1
finally1
catch2
finally2
");
compilation.VerifyIL("Program.Test",
@"
{
// Code size 92 (0x5c)
.maxstack 2
.try
{
.try
{
.try
{
.try
{
IL_0000: ldsfld ""System.Threading.ManualResetEventSlim Program.s""
IL_0005: callvirt ""void System.Threading.ManualResetEventSlim.Set()""
IL_000a: ldsfld ""System.Threading.ManualResetEventSlim Program.s""
IL_000f: brtrue.s IL_000a
IL_0011: leave.s IL_0020
}
catch System.Exception
{
IL_0013: pop
IL_0014: ldstr ""catch1""
IL_0019: call ""void System.Console.WriteLine(string)""
IL_001e: leave.s IL_0020
}
IL_0020: leave.s IL_002d
}
finally
{
IL_0022: ldstr ""finally1""
IL_0027: call ""void System.Console.WriteLine(string)""
IL_002c: endfinally
}
IL_002d: leave.s IL_005b
}
filter
{
IL_002f: isinst ""System.Exception""
IL_0034: dup
IL_0035: brtrue.s IL_003b
IL_0037: pop
IL_0038: ldc.i4.0
IL_0039: br.s IL_0041
IL_003b: ldnull
IL_003c: cgt.un
IL_003e: ldc.i4.0
IL_003f: cgt.un
IL_0041: endfilter
} // end filter
{ // handler
IL_0043: pop
IL_0044: ldstr ""catch2""
IL_0049: call ""void System.Console.WriteLine(string)""
IL_004e: leave.s IL_005b
}
}
finally
{
IL_0050: ldstr ""finally2""
IL_0055: call ""void System.Console.WriteLine(string)""
IL_005a: endfinally
}
IL_005b: ret
}
");
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)]
public void NestedExceptionHandlersThreadAbort05()
{
var source =
@"
using System;
using System.Threading;
class Program
{
static void nop() { }
static ManualResetEventSlim s = new ManualResetEventSlim(false);
static void Main(string[] args)
{
var ts = new ThreadStart(Test);
var t = new Thread(ts);
t.Start();
s.Wait();
t.Abort();
t.Join();
}
public static void Test()
{
try
{
try
{
s.Set();
while (s != null) {};
}
catch
{
try
{
nop();
}
catch
{
Console.WriteLine(""catch1"");
}
}
finally
{
try
{
Console.WriteLine(""try2"");
}
catch
{
Console.WriteLine(""catch2"");
}
}
}
catch
{
Console.WriteLine(""catch3"");
}
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"
try2
catch3
");
compilation.VerifyIL("Program.Test",
@"{
// Code size 87 (0x57)
.maxstack 1
.try
{
.try
{
.try
{
IL_0000: ldsfld ""System.Threading.ManualResetEventSlim Program.s""
IL_0005: callvirt ""void System.Threading.ManualResetEventSlim.Set()""
IL_000a: ldsfld ""System.Threading.ManualResetEventSlim Program.s""
IL_000f: brtrue.s IL_000a
IL_0011: leave.s IL_002a
}
catch object
{
IL_0013: pop
.try
{
IL_0014: call ""void Program.nop()""
IL_0019: leave.s IL_0028
}
catch object
{
IL_001b: pop
IL_001c: ldstr ""catch1""
IL_0021: call ""void System.Console.WriteLine(string)""
IL_0026: leave.s IL_0028
}
IL_0028: leave.s IL_002a
}
IL_002a: leave.s IL_0047
}
finally
{
IL_002c: nop
.try
{
IL_002d: ldstr ""try2""
IL_0032: call ""void System.Console.WriteLine(string)""
IL_0037: leave.s IL_0046
}
catch object
{
IL_0039: pop
IL_003a: ldstr ""catch2""
IL_003f: call ""void System.Console.WriteLine(string)""
IL_0044: leave.s IL_0046
}
IL_0046: endfinally
}
IL_0047: leave.s IL_0056
}
catch object
{
IL_0049: pop
IL_004a: ldstr ""catch3""
IL_004f: call ""void System.Console.WriteLine(string)""
IL_0054: leave.s IL_0056
}
IL_0056: ret
}");
}
[ConditionalFact(typeof(WindowsDesktopOnly))]
public void NestedExceptionHandlersThreadAbort06()
{
var source =
@"
using System;
using System.Threading;
class Program
{
static ManualResetEventSlim s = new ManualResetEventSlim(false);
static void Main(string[] args)
{
var ts = new ThreadStart(Test);
var t = new Thread(ts);
t.Start();
s.Wait();
t.Abort();
t.Join();
}
public static void Test()
{
try
{
try
{
s.Set();
while (s != null) {};
}
catch
{
try
{
int i = 0;
i = i / i;
}
catch
{
Console.WriteLine(""catch1"");
}
}
finally
{
try
{
Console.WriteLine(""try2"");
}
catch
{
Console.WriteLine(""catch2"");
}
}
}
catch
{
Console.WriteLine(""catch3"");
}
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"
catch1
try2
catch3
");
compilation.VerifyIL("Program.Test",
@"
{
// Code size 86 (0x56)
.maxstack 2
.try
{
.try
{
.try
{
IL_0000: ldsfld ""System.Threading.ManualResetEventSlim Program.s""
IL_0005: callvirt ""void System.Threading.ManualResetEventSlim.Set()""
IL_000a: ldsfld ""System.Threading.ManualResetEventSlim Program.s""
IL_000f: brtrue.s IL_000a
IL_0011: leave.s IL_0029
}
catch object
{
IL_0013: pop
.try
{
IL_0014: ldc.i4.0
IL_0015: dup
IL_0016: div
IL_0017: pop
IL_0018: leave.s IL_0027
}
catch object
{
IL_001a: pop
IL_001b: ldstr ""catch1""
IL_0020: call ""void System.Console.WriteLine(string)""
IL_0025: leave.s IL_0027
}
IL_0027: leave.s IL_0029
}
IL_0029: leave.s IL_0046
}
finally
{
IL_002b: nop
.try
{
IL_002c: ldstr ""try2""
IL_0031: call ""void System.Console.WriteLine(string)""
IL_0036: leave.s IL_0045
}
catch object
{
IL_0038: pop
IL_0039: ldstr ""catch2""
IL_003e: call ""void System.Console.WriteLine(string)""
IL_0043: leave.s IL_0045
}
IL_0045: endfinally
}
IL_0046: leave.s IL_0055
}
catch object
{
IL_0048: pop
IL_0049: ldstr ""catch3""
IL_004e: call ""void System.Console.WriteLine(string)""
IL_0053: leave.s IL_0055
}
IL_0055: ret
}
");
}
[ConditionalFact(typeof(WindowsDesktopOnly))]
public void NestedExceptionHandlersThreadAbort07()
{
var source =
@"
using System;
using System.Threading;
class Program
{
static ManualResetEventSlim s = new ManualResetEventSlim(false);
static void Main(string[] args)
{
var ts = new ThreadStart(Test);
var t = new Thread(ts);
t.Start();
s.Wait();
t.Abort();
t.Join();
}
public static void Test()
{
try
{
try
{
try
{
try
{
s.Set();
while (s != null) {};
}
catch (Exception ex)
{
Console.WriteLine(""catch1"");
}
}
finally
{
Console.WriteLine(""finally1"");
}
}
finally
{
Console.WriteLine(""finally2"");
}
}
catch (Exception ex)
{
Console.WriteLine(""catch2"");
}
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"
catch1
finally1
finally2
catch2
");
compilation.VerifyIL("Program.Test",
@"
{
// Code size 74 (0x4a)
.maxstack 1
.try
{
.try
{
.try
{
.try
{
IL_0000: ldsfld ""System.Threading.ManualResetEventSlim Program.s""
IL_0005: callvirt ""void System.Threading.ManualResetEventSlim.Set()""
IL_000a: ldsfld ""System.Threading.ManualResetEventSlim Program.s""
IL_000f: brtrue.s IL_000a
IL_0011: leave.s IL_0020
}
catch System.Exception
{
IL_0013: pop
IL_0014: ldstr ""catch1""
IL_0019: call ""void System.Console.WriteLine(string)""
IL_001e: leave.s IL_0020
}
IL_0020: leave.s IL_002d
}
finally
{
IL_0022: ldstr ""finally1""
IL_0027: call ""void System.Console.WriteLine(string)""
IL_002c: endfinally
}
IL_002d: leave.s IL_003a
}
finally
{
IL_002f: ldstr ""finally2""
IL_0034: call ""void System.Console.WriteLine(string)""
IL_0039: endfinally
}
IL_003a: leave.s IL_0049
}
catch System.Exception
{
IL_003c: pop
IL_003d: ldstr ""catch2""
IL_0042: call ""void System.Console.WriteLine(string)""
IL_0047: leave.s IL_0049
}
IL_0049: ret
}
");
}
[Fact]
public void ThrowInTry()
{
var source =
@"using System;
class C
{
static void nop() { }
static void ThrowInTry()
{
try { throw new Exception(); }
finally { }
}
static void ThrowInTryInTry()
{
try
{
try { throw new Exception(); }
finally { }
}
finally { }
}
static void ThrowInTryInFinally()
{
try { }
finally
{
try { throw new Exception(); }
finally { }
}
}
}
class D
{
static void nop() { }
static void ThrowInTry()
{
try { throw new Exception(); }
catch { }
finally { }
}
static void ThrowInTryInTry()
{
try
{
try { throw new Exception(); }
catch { }
finally { }
}
finally { }
}
static void ThrowInTryInFinally()
{
try { nop(); }
catch { }
finally
{
try { throw new Exception(); }
catch { }
finally { }
}
}
}";
var compilation = CompileAndVerify(source);
compilation.VerifyIL("C.ThrowInTry",
@"{
// Code size 6 (0x6)
.maxstack 1
IL_0000: newobj ""System.Exception..ctor()""
IL_0005: throw
}");
compilation.VerifyIL("C.ThrowInTryInTry",
@"{
// Code size 6 (0x6)
.maxstack 1
IL_0000: newobj ""System.Exception..ctor()""
IL_0005: throw
}");
compilation.VerifyIL("C.ThrowInTryInFinally",
@"{
// Code size 10 (0xa)
.maxstack 1
.try
{
IL_0000: leave.s IL_0008
}
finally
{
IL_0002: newobj ""System.Exception..ctor()""
IL_0007: throw
}
IL_0008: br.s IL_0008
}");
compilation.VerifyIL("D.ThrowInTry",
@"{
// Code size 10 (0xa)
.maxstack 1
.try
{
IL_0000: newobj ""System.Exception..ctor()""
IL_0005: throw
}
catch object
{
IL_0006: pop
IL_0007: leave.s IL_0009
}
IL_0009: ret
}");
compilation.VerifyIL("D.ThrowInTryInTry",
@"{
// Code size 10 (0xa)
.maxstack 1
.try
{
IL_0000: newobj ""System.Exception..ctor()""
IL_0005: throw
}
catch object
{
IL_0006: pop
IL_0007: leave.s IL_0009
}
IL_0009: ret
}");
compilation.VerifyIL("D.ThrowInTryInFinally",
@"{
// Code size 22 (0x16)
.maxstack 1
.try
{
.try
{
IL_0000: call ""void D.nop()""
IL_0005: leave.s IL_0015
}
catch object
{
IL_0007: pop
IL_0008: leave.s IL_0015
}
}
finally
{
IL_000a: nop
.try
{
IL_000b: newobj ""System.Exception..ctor()""
IL_0010: throw
}
catch object
{
IL_0011: pop
IL_0012: leave.s IL_0014
}
IL_0014: endfinally
}
IL_0015: ret
}");
}
[WorkItem(540716, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540716")]
[Fact]
public void ThrowInFinally()
{
var source =
@"using System;
class C
{
static void nop() { }
static void ThrowInFinally()
{
try { }
finally { throw new Exception(); }
}
static void ThrowInFinallyInTry()
{
try
{
try { }
finally { throw new Exception(); }
}
finally { nop(); }
}
static int ThrowInFinallyInFinally()
{
try { }
finally
{
try { }
finally { throw new Exception(); }
}
// unreachable and has no return
System.Console.WriteLine();
}
}
class D
{
static void nop() { }
static void ThrowInFinally()
{
try { nop(); }
catch { }
finally { throw new Exception(); }
}
static void ThrowInFinallyInTry()
{
try
{
try { nop(); }
catch { }
finally { throw new Exception(); }
}
catch { }
finally { nop(); }
}
static void ThrowInFinallyInFinally()
{
try { nop(); }
catch { }
finally
{
try { nop(); }
catch { }
finally { throw new Exception(); }
}
}
}";
var compilation = CompileAndVerify(source);
compilation.VerifyIL("C.ThrowInFinally",
@"{
// Code size 10 (0xa)
.maxstack 1
.try
{
IL_0000: leave.s IL_0008
}
finally
{
IL_0002: newobj ""System.Exception..ctor()""
IL_0007: throw
}
IL_0008: br.s IL_0008
}");
compilation.VerifyIL("C.ThrowInFinallyInTry",
@"{
// Code size 16 (0x10)
.maxstack 1
.try
{
.try
{
IL_0000: leave.s IL_0008
}
finally
{
IL_0002: newobj ""System.Exception..ctor()""
IL_0007: throw
}
IL_0008: br.s IL_0008
}
finally
{
IL_000a: call ""void C.nop()""
IL_000f: endfinally
}
}");
// The nop below is to work around a verifier bug.
// See DevDiv 563799.
compilation.VerifyIL("C.ThrowInFinallyInFinally",
@"{
// Code size 15 (0xf)
.maxstack 1
.try
{
IL_0000: leave.s IL_000d
}
finally
{
IL_0002: nop
.try
{
IL_0003: leave.s IL_000b
}
finally
{
IL_0005: newobj ""System.Exception..ctor()""
IL_000a: throw
}
IL_000b: br.s IL_000b
}
IL_000d: br.s IL_000d
}");
compilation.VerifyIL("D.ThrowInFinally",
@"{
// Code size 18 (0x12)
.maxstack 1
.try
{
.try
{
IL_0000: call ""void D.nop()""
IL_0005: leave.s IL_0010
}
catch object
{
IL_0007: pop
IL_0008: leave.s IL_0010
}
}
finally
{
IL_000a: newobj ""System.Exception..ctor()""
IL_000f: throw
}
IL_0010: br.s IL_0010
}");
compilation.VerifyIL("D.ThrowInFinallyInTry",
@"{
// Code size 30 (0x1e)
.maxstack 1
.try
{
.try
{
.try
{
.try
{
IL_0000: call ""void D.nop()""
IL_0005: leave.s IL_000a
}
catch object
{
IL_0007: pop
IL_0008: leave.s IL_000a
}
IL_000a: leave.s IL_0012
}
finally
{
IL_000c: newobj ""System.Exception..ctor()""
IL_0011: throw
}
IL_0012: br.s IL_0012
}
catch object
{
IL_0014: pop
IL_0015: leave.s IL_001d
}
}
finally
{
IL_0017: call ""void D.nop()""
IL_001c: endfinally
}
IL_001d: ret
}");
compilation.VerifyIL("D.ThrowInFinallyInFinally",
@"{
// Code size 31 (0x1f)
.maxstack 1
.try
{
.try
{
IL_0000: call ""void D.nop()""
IL_0005: leave.s IL_001d
}
catch object
{
IL_0007: pop
IL_0008: leave.s IL_001d
}
}
finally
{
IL_000a: nop
.try
{
.try
{
IL_000b: call ""void D.nop()""
IL_0010: leave.s IL_001b
}
catch object
{
IL_0012: pop
IL_0013: leave.s IL_001b
}
}
finally
{
IL_0015: newobj ""System.Exception..ctor()""
IL_001a: throw
}
IL_001b: br.s IL_001b
}
IL_001d: br.s IL_001d
}");
}
[Fact]
public void TryFilterSimple()
{
var src = @"
using System;
class C
{
static bool Filter()
{
Console.Write(""Filter"");
return true;
}
static void Main()
{
int x = 0;
try
{
Console.Write(""Try"");
x = x / x;
}
catch when (Filter())
{
Console.Write(""Catch"");
}
finally
{
Console.Write(""Finally"");
}
}
}";
var comp = CompileAndVerify(src,
expectedOutput: "TryFilterCatchFinally");
comp.VerifyIL("C.Main", @"
{
// Code size 54 (0x36)
.maxstack 2
.locals init (int V_0) //x
IL_0000: ldc.i4.0
IL_0001: stloc.0
.try
{
.try
{
IL_0002: ldstr ""Try""
IL_0007: call ""void System.Console.Write(string)""
IL_000c: ldloc.0
IL_000d: ldloc.0
IL_000e: div
IL_000f: stloc.0
IL_0010: leave.s IL_0035
}
filter
{
IL_0012: pop
IL_0013: call ""bool C.Filter()""
IL_0018: ldc.i4.0
IL_0019: cgt.un
IL_001b: endfilter
} // end filter
{ // handler
IL_001d: pop
IL_001e: ldstr ""Catch""
IL_0023: call ""void System.Console.Write(string)""
IL_0028: leave.s IL_0035
}
}
finally
{
IL_002a: ldstr ""Finally""
IL_002f: call ""void System.Console.Write(string)""
IL_0034: endfinally
}
IL_0035: ret
}
");
}
[Fact]
public void TryFilterUseException()
{
var src = @"
using System;
class C
{
static void Main()
{
System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture;
try
{
Test();
}
finally
{
System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture;
}
}
static void Test()
{
int x = 0;
try
{
Console.Write(""Try"");
x = x / x;
}
catch (DivideByZeroException e)
when (e.Message == null)
{
Console.Write(""Catch1"");
}
catch (DivideByZeroException e)
when (e.Message != null)
{
Console.Write(""Catch2"" + e.Message.Length);
}
finally
{
Console.Write(""Finally"");
}
}
}";
CompileAndVerify(src, expectedOutput: "TryCatch228Finally").
VerifyIL("C.Test", @"
{
// Code size 132 (0x84)
.maxstack 2
.locals init (int V_0, //x
System.DivideByZeroException V_1, //e
int V_2)
IL_0000: ldc.i4.0
IL_0001: stloc.0
.try
{
.try
{
IL_0002: ldstr ""Try""
IL_0007: call ""void System.Console.Write(string)""
IL_000c: ldloc.0
IL_000d: ldloc.0
IL_000e: div
IL_000f: stloc.0
IL_0010: leave.s IL_0083
}
filter
{
IL_0012: isinst ""System.DivideByZeroException""
IL_0017: dup
IL_0018: brtrue.s IL_001e
IL_001a: pop
IL_001b: ldc.i4.0
IL_001c: br.s IL_0029
IL_001e: callvirt ""string System.Exception.Message.get""
IL_0023: ldnull
IL_0024: ceq
IL_0026: ldc.i4.0
IL_0027: cgt.un
IL_0029: endfilter
} // end filter
{ // handler
IL_002b: pop
IL_002c: ldstr ""Catch1""
IL_0031: call ""void System.Console.Write(string)""
IL_0036: leave.s IL_0083
}
filter
{
IL_0038: isinst ""System.DivideByZeroException""
IL_003d: dup
IL_003e: brtrue.s IL_0044
IL_0040: pop
IL_0041: ldc.i4.0
IL_0042: br.s IL_0051
IL_0044: stloc.1
IL_0045: ldloc.1
IL_0046: callvirt ""string System.Exception.Message.get""
IL_004b: ldnull
IL_004c: cgt.un
IL_004e: ldc.i4.0
IL_004f: cgt.un
IL_0051: endfilter
} // end filter
{ // handler
IL_0053: pop
IL_0054: ldstr ""Catch2""
IL_0059: ldloc.1
IL_005a: callvirt ""string System.Exception.Message.get""
IL_005f: callvirt ""int string.Length.get""
IL_0064: stloc.2
IL_0065: ldloca.s V_2
IL_0067: call ""string int.ToString()""
IL_006c: call ""string string.Concat(string, string)""
IL_0071: call ""void System.Console.Write(string)""
IL_0076: leave.s IL_0083
}
}
finally
{
IL_0078: ldstr ""Finally""
IL_007d: call ""void System.Console.Write(string)""
IL_0082: endfinally
}
IL_0083: ret
}");
}
[Fact]
public void TryFilterScoping()
{
var src = @"
using System;
class C
{
private static string str = ""S1"";
static void Main()
{
int x = 0;
try
{
Console.Write(""Try"");
x = x / x;
}
catch when (new Func<bool>(() => str.Length == 2)())
{
Console.Write(""Catch"" + str);
}
finally
{
Console.Write(""Finally"");
}
}
}";
var comp = CompileAndVerify(src, expectedOutput: "TryCatchS1Finally");
comp.VerifyIL("C.Main", @"
{
// Code size 95 (0x5f)
.maxstack 2
.locals init (int V_0) //x
IL_0000: ldc.i4.0
IL_0001: stloc.0
.try
{
.try
{
IL_0002: ldstr ""Try""
IL_0007: call ""void System.Console.Write(string)""
IL_000c: ldloc.0
IL_000d: ldloc.0
IL_000e: div
IL_000f: stloc.0
IL_0010: leave.s IL_005e
}
filter
{
IL_0012: pop
IL_0013: ldsfld ""System.Func<bool> C.<>c.<>9__1_0""
IL_0018: dup
IL_0019: brtrue.s IL_0032
IL_001b: pop
IL_001c: ldsfld ""C.<>c C.<>c.<>9""
IL_0021: ldftn ""bool C.<>c.<Main>b__1_0()""
IL_0027: newobj ""System.Func<bool>..ctor(object, System.IntPtr)""
IL_002c: dup
IL_002d: stsfld ""System.Func<bool> C.<>c.<>9__1_0""
IL_0032: callvirt ""bool System.Func<bool>.Invoke()""
IL_0037: ldc.i4.0
IL_0038: cgt.un
IL_003a: endfilter
} // end filter
{ // handler
IL_003c: pop
IL_003d: ldstr ""Catch""
IL_0042: ldsfld ""string C.str""
IL_0047: call ""string string.Concat(string, string)""
IL_004c: call ""void System.Console.Write(string)""
IL_0051: leave.s IL_005e
}
}
finally
{
IL_0053: ldstr ""Finally""
IL_0058: call ""void System.Console.Write(string)""
IL_005d: endfinally
}
IL_005e: ret
}
");
}
[WorkItem(18678, "https://github.com/dotnet/roslyn/issues/18678")]
[Fact]
public void TryCatchConstantFalseFilter1()
{
var src = @"
using System;
class C
{
static void Main()
{
try
{
throw new Exception();
}
catch (Exception) when (false)
{
Console.Write(""Catch"");
}
}
}";
var comp = CompileAndVerify(src);
comp.VerifyIL("C.Main", @"
{
// Code size 6 (0x6)
.maxstack 1
IL_0000: newobj ""System.Exception..ctor()""
IL_0005: throw
}");
}
[WorkItem(18678, "https://github.com/dotnet/roslyn/issues/18678")]
[Fact]
public void TryCatchConstantFalseFilter2()
{
var src = @"
using System;
class C
{
static void Main()
{
try
{
throw new Exception();
}
catch (NullReferenceException) when (false)
{
Console.Write(""Catch1"");
}
catch (Exception) when (false)
{
Console.Write(""Catch2"");
}
catch when (false)
{
Console.Write(""Catch"");
}
}
}";
var comp = CompileAndVerify(src);
comp.VerifyIL("C.Main", @"
{
// Code size 6 (0x6)
.maxstack 1
IL_0000: newobj ""System.Exception..ctor()""
IL_0005: throw
}");
}
[WorkItem(18678, "https://github.com/dotnet/roslyn/issues/18678")]
[Fact]
public void TryCatchConstantFalseFilter3()
{
var src = @"
using System;
class C
{
static void Main()
{
try
{
throw new Exception();
}
catch (NullReferenceException) when ((1+1) == 2)
{
Console.Write(""Catch1"");
}
catch (Exception) when (true == false)
{
Console.Write(""Catch2"");
}
catch when ((1+1) != 2)
{
Console.Write(""Catch"");
}
}
}";
var comp = CompileAndVerify(src);
comp.VerifyIL("C.Main", @"
{
// Code size 39 (0x27)
.maxstack 2
.try
{
IL_0000: newobj ""System.Exception..ctor()""
IL_0005: throw
}
filter
{
IL_0006: isinst ""System.NullReferenceException""
IL_000b: dup
IL_000c: brtrue.s IL_0012
IL_000e: pop
IL_000f: ldc.i4.0
IL_0010: br.s IL_0017
IL_0012: pop
IL_0013: ldc.i4.1
IL_0014: ldc.i4.0
IL_0015: cgt.un
IL_0017: endfilter
} // end filter
{ // handler
IL_0019: pop
IL_001a: ldstr ""Catch1""
IL_001f: call ""void System.Console.Write(string)""
IL_0024: leave.s IL_0026
}
IL_0026: ret
}");
}
[WorkItem(18678, "https://github.com/dotnet/roslyn/issues/18678")]
[Fact]
public void TryCatchConstantFalseFilterCombined()
{
var src = @"
using System;
class C
{
static void Main()
{
var message = ""ExceptionMessage"";
try
{
throw new Exception(message);
}
catch (NullReferenceException) when (false)
{
Console.Write(""NullReferenceCatch"");
}
catch (Exception e) when (e.Message == message)
{
Console.Write(""ExceptionFilter"");
}
catch (Exception)
{
Console.Write(""ExceptionCatch"");
}
catch when (false)
{
Console.Write(""Catch"");
}
}
}";
var comp = CompileAndVerify(src, expectedOutput: "ExceptionFilter");
comp.VerifyIL("C.Main", @"
{
// Code size 68 (0x44)
.maxstack 2
.locals init (string V_0) //message
IL_0000: ldstr ""ExceptionMessage""
IL_0005: stloc.0
.try
{
IL_0006: ldloc.0
IL_0007: newobj ""System.Exception..ctor(string)""
IL_000c: throw
}
filter
{
IL_000d: isinst ""System.Exception""
IL_0012: dup
IL_0013: brtrue.s IL_0019
IL_0015: pop
IL_0016: ldc.i4.0
IL_0017: br.s IL_0027
IL_0019: callvirt ""string System.Exception.Message.get""
IL_001e: ldloc.0
IL_001f: call ""bool string.op_Equality(string, string)""
IL_0024: ldc.i4.0
IL_0025: cgt.un
IL_0027: endfilter
} // end filter
{ // handler
IL_0029: pop
IL_002a: ldstr ""ExceptionFilter""
IL_002f: call ""void System.Console.Write(string)""
IL_0034: leave.s IL_0043
}
catch System.Exception
{
IL_0036: pop
IL_0037: ldstr ""ExceptionCatch""
IL_003c: call ""void System.Console.Write(string)""
IL_0041: leave.s IL_0043
}
IL_0043: ret
}");
}
[WorkItem(18678, "https://github.com/dotnet/roslyn/issues/18678")]
[Fact]
public void TryCatchFinallyConstantFalseFilter()
{
var src = @"
using System;
class C
{
static void Main()
{
try
{
try
{
throw new Exception();
}
catch (NullReferenceException) when (false)
{
Console.Write(""Catch1"");
}
catch (Exception) when (false)
{
Console.Write(""Catch2"");
}
finally
{
Console.Write(""Finally"");
}
}
catch
{
Console.Write(""OuterCatch"");
}
}
}";
var comp = CompileAndVerify(src, expectedOutput: "FinallyOuterCatch");
comp.VerifyIL("C.Main", @"
{
// Code size 31 (0x1f)
.maxstack 1
.try
{
.try
{
IL_0000: newobj ""System.Exception..ctor()""
IL_0005: throw
}
finally
{
IL_0006: ldstr ""Finally""
IL_000b: call ""void System.Console.Write(string)""
IL_0010: endfinally
}
}
catch object
{
IL_0011: pop
IL_0012: ldstr ""OuterCatch""
IL_0017: call ""void System.Console.Write(string)""
IL_001c: leave.s IL_001e
}
IL_001e: ret
}");
}
[Fact]
public void TryCatchWithReturnValue()
{
var source =
@"using System;
class C
{
static int F(int i)
{
if (i == 0)
{
throw new InvalidOperationException();
}
else if (i == 1)
{
throw new InvalidCastException();
}
return i;
}
static int M(int i)
{
try
{
return F(i) * 3;
}
catch (InvalidOperationException)
{
return (i - 1) * 4;
}
catch
{
}
finally
{
i = i + 10;
}
return i;
}
static void Main()
{
Console.WriteLine(""M(0)={0}, M(1)={1}, M(2)={2}"", M(0), M(1), M(2));
}
}";
var compilation = CompileAndVerify(source, expectedOutput: "M(0)=-4, M(1)=11, M(2)=6");
compilation.VerifyIL("C.M",
@"{
// Code size 34 (0x22)
.maxstack 2
.locals init (int V_0)
.try
{
.try
{
IL_0000: ldarg.0
IL_0001: call ""int C.F(int)""
IL_0006: ldc.i4.3
IL_0007: mul
IL_0008: stloc.0
IL_0009: leave.s IL_0020
}
catch System.InvalidOperationException
{
IL_000b: pop
IL_000c: ldarg.0
IL_000d: ldc.i4.1
IL_000e: sub
IL_000f: ldc.i4.4
IL_0010: mul
IL_0011: stloc.0
IL_0012: leave.s IL_0020
}
catch object
{
IL_0014: pop
IL_0015: leave.s IL_001e
}
}
finally
{
IL_0017: ldarg.0
IL_0018: ldc.i4.s 10
IL_001a: add
IL_001b: starg.s V_0
IL_001d: endfinally
}
IL_001e: ldarg.0
IL_001f: ret
IL_0020: ldloc.0
IL_0021: ret
}");
}
[Fact]
public void Rethrow()
{
var source =
@"using System.IO;
class C
{
static void nop() { }
static int F = 0;
static void M()
{
try
{
nop();
}
catch (FileNotFoundException e)
{
if (F > 0)
{
throw;
}
else
{
throw e;
}
}
catch (IOException)
{
throw;
}
catch
{
throw;
}
}
}";
var compilation = CompileAndVerify(source);
compilation.VerifyIL("C.M",
@"{
// Code size 27 (0x1b)
.maxstack 2
.locals init (System.IO.FileNotFoundException V_0) //e
.try
{
IL_0000: call ""void C.nop()""
IL_0005: leave.s IL_001a
}
catch System.IO.FileNotFoundException
{
IL_0007: stloc.0
IL_0008: ldsfld ""int C.F""
IL_000d: ldc.i4.0
IL_000e: ble.s IL_0012
IL_0010: rethrow
IL_0012: ldloc.0
IL_0013: throw
}
catch System.IO.IOException
{
IL_0014: pop
IL_0015: rethrow
}
catch object
{
IL_0017: pop
IL_0018: rethrow
}
IL_001a: ret
}");
}
[WorkItem(541494, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541494")]
[Fact]
public void CatchT()
{
var source =
@"using System;
class C
{
internal static void TryCatch<T>() where T : Exception
{
try
{
Throw();
}
catch (T t)
{
Catch(t);
}
}
static void Throw() { throw new NotImplementedException(); }
static void Catch(Exception e)
{
Console.WriteLine(""Handled"");
}
static void Main()
{
try
{
TryCatch<NotImplementedException>();
TryCatch<InvalidOperationException>();
}
catch (Exception)
{
Console.WriteLine(""Unhandled"");
}
}
}";
var compilation = CompileAndVerify(source, expectedOutput:
@"Handled
Unhandled");
compilation.VerifyIL("C.TryCatch<T>()",
@"
{
// Code size 25 (0x19)
.maxstack 1
.try
{
IL_0000: call ""void C.Throw()""
IL_0005: leave.s IL_0018
}
catch T
{
IL_0007: unbox.any ""T""
IL_000c: box ""T""
IL_0011: call ""void C.Catch(System.Exception)""
IL_0016: leave.s IL_0018
}
IL_0018: ret
}
");
}
[WorkItem(540664, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540664")]
[Fact]
public void ExceptionAlreadyCaught1()
{
var source =
@"class C
{
static void M()
{
try { }
catch (System.Exception) { }
catch { }
}
}";
CompileAndVerify(source).VerifyDiagnostics(
Diagnostic(ErrorCode.WRN_UnreachableGeneralCatch, "catch").WithLocation(7, 9));
}
[Fact]
public void ExceptionAlreadyCaught2()
{
var text = @"
class Program
{
static void M()
{
int a = 1;
try { }
catch (System.Exception) { }
catch when (a == 1) { }
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (9,9): warning CS1058: A previous catch clause already catches all exceptions. All non-exceptions thrown will be wrapped in a System.Runtime.CompilerServices.RuntimeWrappedException.
// catch when (a == 1) { }
Diagnostic(ErrorCode.WRN_UnreachableGeneralCatch, "catch").WithLocation(9, 9));
}
[Fact]
public void ExceptionAlreadyCaught3()
{
var text = @"
class Program
{
static void M()
{
int a = 1;
try { }
catch when (a == 2) { }
catch (System.Exception) when (a == 3) { }
catch { }
}
}
";
CreateCompilation(text).VerifyDiagnostics();
}
[WorkItem(540666, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540666")]
[Fact]
public void EmptyTryFinally_Simple()
{
var source =
@"class C
{
static void M()
{
try { }
finally { }
}
}";
CompileAndVerify(source);
}
[WorkItem(542002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542002")]
[Fact]
public void ConditionInTry()
{
var source =
@"using System;
class Program
{
static void Main()
{
int a = 10;
try
{
if (a == 3)
{
}
}
catch (System.Exception)
{
}
}
}";
var compilation = CompileAndVerify(source, expectedOutput: "");
compilation.VerifyIL("Program.Main",
@"
{
// Code size 13 (0xd)
.maxstack 2
.locals init (int V_0) //a
IL_0000: ldc.i4.s 10
IL_0002: stloc.0
.try
{
IL_0003: ldloc.0
IL_0004: ldc.i4.3
IL_0005: pop
IL_0006: pop
IL_0007: leave.s IL_000c
}
catch System.Exception
{
IL_0009: pop
IL_000a: leave.s IL_000c
}
IL_000c: ret
}
");
}
[Fact(), WorkItem(544911, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544911")]
public void UnreachableAfterTryFinally()
{
var source = @"
using System;
class Program
{
static int Result = 0;
static void F()
{
Result = 1;
}
static void T1()
{
try
{
goto L;
}
finally
{
for (; ; ) { }
}
L:
F(); //unreachable
}
static void Main()
{
Console.Write(Result);
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "0");
compilation.VerifyIL("Program.T1",
@"
{
// Code size 6 (0x6)
.maxstack 0
.try
{
IL_0000: leave.s IL_0004
}
finally
{
IL_0002: br.s IL_0002
}
IL_0004: br.s IL_0004
}
");
}
[Fact(), WorkItem(544911, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544911")]
public void ReachableAfterBlockingCatch()
{
var source =
@"using System;
class Program
{
static void nop() { }
static void F()
{
Console.WriteLine(""hello"");
}
static void T1()
{
try
{
nop();
}
catch
{
for (; ; ) { }
}
F(); //reachable
}
static void Main()
{
T1();
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "hello");
compilation.VerifyIL("Program.T1",
@"{
// Code size 16 (0x10)
.maxstack 1
.try
{
IL_0000: call ""void Program.nop()""
IL_0005: leave.s IL_000a
}
catch object
{
IL_0007: pop
IL_0008: br.s IL_0008
}
IL_000a: call ""void Program.F()""
IL_000f: ret
}");
}
[Fact(), WorkItem(544911, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544911")]
public void UnreachableAfterTryFinallyConditional()
{
var source = @"
using System;
class Program
{
static int Result = 0;
static void F()
{
Result = 1;
}
static void T1()
{
try
{
if (Result == 0)
goto L;
}
finally
{
for (; ; ) { }
}
L:
F(); //unreachable
}
static void Main()
{
Console.Write(Result);
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "0");
compilation.VerifyIL("Program.T1",
@"
{
// Code size 12 (0xc)
.maxstack 1
.try
{
IL_0000: ldsfld ""int Program.Result""
IL_0005: pop
IL_0006: leave.s IL_000a
}
finally
{
IL_0008: br.s IL_0008
}
IL_000a: br.s IL_000a
}
");
}
[Fact()]
public void ReachableAfterFinallyButNotFromTryConditional01()
{
var source = @"
using System;
class Program
{
static int Result = 0;
static void F()
{
Result = 1;
}
static void T1()
{
if (Result == 1)
goto L;
try
{
try
{
if (Result == 0)
goto L;
goto L;
}
finally
{
for (; ; ) { }
}
if (Result == 0)
goto L;
}
finally
{
for (; ; ) { }
}
L:
F(); //reachable but not from the try
}
static void Main()
{
Console.Write(Result);
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "0");
compilation.VerifyIL("Program.T1",
@"
{
// Code size 29 (0x1d)
.maxstack 2
IL_0000: ldsfld ""int Program.Result""
IL_0005: ldc.i4.1
IL_0006: beq.s IL_0017
IL_0008: nop
.try
{
.try
{
IL_0009: ldsfld ""int Program.Result""
IL_000e: pop
IL_000f: leave.s IL_0013
}
finally
{
IL_0011: br.s IL_0011
}
IL_0013: br.s IL_0013
}
finally
{
IL_0015: br.s IL_0015
}
IL_0017: call ""void Program.F()""
IL_001c: ret
}
");
}
[Fact(), WorkItem(544911, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544911")]
public void ReachableAfterFinallyButNotFromTryConditional()
{
var source = @"
using System;
class Program
{
static int Result = 0;
static void F()
{
Result = 1;
}
static void T1()
{
if (Result == 1)
goto L;
try
{
try
{
if (Result == 0)
goto L;
}
finally
{
for (; ; ) { }
}
if (Result == 0)
goto L;
}
finally
{
for (; ; ) { }
}
L:
F(); //reachable but not from the try
}
static void Main()
{
Console.Write(Result);
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "0");
compilation.VerifyIL("Program.T1",
@"
{
// Code size 29 (0x1d)
.maxstack 2
IL_0000: ldsfld ""int Program.Result""
IL_0005: ldc.i4.1
IL_0006: beq.s IL_0017
IL_0008: nop
.try
{
.try
{
IL_0009: ldsfld ""int Program.Result""
IL_000e: pop
IL_000f: leave.s IL_0013
}
finally
{
IL_0011: br.s IL_0011
}
IL_0013: br.s IL_0013
}
finally
{
IL_0015: br.s IL_0015
}
IL_0017: call ""void Program.F()""
IL_001c: ret
}
");
}
[Fact(), WorkItem(713418, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/713418")]
public void ConditionalUnconditionalBranches()
{
var source = @"
using System;
class Program
{
private static int x = 123;
static void Main(string[] args)
{
try
{
if (x == 10)
{
goto l2;;
}
if (x != 0)
{
Console.WriteLine(""2"");
}
goto l1;
l2:
Console.WriteLine(""l2"");
l1:
goto lOut;
}
finally
{
Console.WriteLine(""Finally"");
}
lOut:
Console.WriteLine(""Out"");
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"2
Finally
Out");
compilation.VerifyIL("Program.Main",
@"
{
// Code size 62 (0x3e)
.maxstack 2
.try
{
IL_0000: ldsfld ""int Program.x""
IL_0005: ldc.i4.s 10
IL_0007: beq.s IL_001c
IL_0009: ldsfld ""int Program.x""
IL_000e: brfalse.s IL_0026
IL_0010: ldstr ""2""
IL_0015: call ""void System.Console.WriteLine(string)""
IL_001a: leave.s IL_0033
IL_001c: ldstr ""l2""
IL_0021: call ""void System.Console.WriteLine(string)""
IL_0026: leave.s IL_0033
}
finally
{
IL_0028: ldstr ""Finally""
IL_002d: call ""void System.Console.WriteLine(string)""
IL_0032: endfinally
}
IL_0033: ldstr ""Out""
IL_0038: call ""void System.Console.WriteLine(string)""
IL_003d: ret
}
");
}
[Fact(), WorkItem(713418, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/713418")]
public void ConditionalUnconditionalBranches001()
{
var source = @"
using System;
class Program
{
private static int x = 123;
static void Main(string[] args)
{
try
{
if (x == 10)
{
goto l2;;
}
if (x != 0)
{
Console.WriteLine(""2"");
}
goto l1;
l2:
// Console.WriteLine(""l2"");
l1:
goto lOut;
}
finally
{
Console.WriteLine(""Finally"");
}
lOut:
Console.WriteLine(""Out"");
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"2
Finally
Out");
compilation.VerifyIL("Program.Main",
@"
{
// Code size 52 (0x34)
.maxstack 2
.try
{
IL_0000: ldsfld ""int Program.x""
IL_0005: ldc.i4.s 10
IL_0007: bne.un.s IL_000b
IL_0009: leave.s IL_0029
IL_000b: ldsfld ""int Program.x""
IL_0010: brfalse.s IL_001c
IL_0012: ldstr ""2""
IL_0017: call ""void System.Console.WriteLine(string)""
IL_001c: leave.s IL_0029
}
finally
{
IL_001e: ldstr ""Finally""
IL_0023: call ""void System.Console.WriteLine(string)""
IL_0028: endfinally
}
IL_0029: ldstr ""Out""
IL_002e: call ""void System.Console.WriteLine(string)""
IL_0033: ret
}
");
}
[Fact(), WorkItem(2443, "https://github.com/dotnet/roslyn/issues/2443")]
public void OptimizeEmptyTryBlock()
{
var source = @"
using System;
class Program
{
public static void Main(string[] args)
{
try
{
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"");
compilation.VerifyIL("Program.Main",
@"
{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}
");
}
[Fact]
[WorkItem(29481, "https://github.com/dotnet/roslyn/issues/29481")]
public void Issue29481()
{
var source = @"
using System;
public class Program
{
public static void Main()
{
try
{
bool b = false;
if (b)
{
try
{
return;
}
finally
{
Console.WriteLine(""Prints"");
}
}
else
{
return;
}
}
finally
{
GC.KeepAlive(null);
}
}
}";
CompileAndVerify(source, expectedOutput: "", options: TestOptions.DebugExe);
CompileAndVerify(source, expectedOutput: "", options: TestOptions.ReleaseExe).VerifyIL("Program.Main",
@"
{
// Code size 26 (0x1a)
.maxstack 1
.try
{
IL_0000: ldc.i4.0
IL_0001: brfalse.s IL_0010
.try
{
IL_0003: leave.s IL_0019
}
finally
{
IL_0005: ldstr ""Prints""
IL_000a: call ""void System.Console.WriteLine(string)""
IL_000f: endfinally
}
IL_0010: leave.s IL_0019
}
finally
{
IL_0012: ldnull
IL_0013: call ""void System.GC.KeepAlive(object)""
IL_0018: endfinally
}
IL_0019: ret
}
");
}
}
}
| -1 |
dotnet/roslyn | 55,530 | Ignore modules with bad metadata in function resolver | Fixes https://github.com/dotnet/roslyn/issues/55475 | tmat | 2021-08-10T18:56:37Z | 2021-08-11T18:37:09Z | cd0c0464c069a2b80774d70f071c29333d9fa23c | bc874ebc5111a2a33221409f895953b1536f6612 | Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475 | ./src/Compilers/Core/Portable/InternalUtilities/ReferenceEqualityComparer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace Roslyn.Utilities
{
/// <summary>
/// Compares objects based upon their reference identity.
/// </summary>
internal class ReferenceEqualityComparer : IEqualityComparer<object?>
{
public static readonly ReferenceEqualityComparer Instance = new();
private ReferenceEqualityComparer()
{
}
bool IEqualityComparer<object?>.Equals(object? a, object? b)
{
return a == b;
}
int IEqualityComparer<object?>.GetHashCode(object? a)
{
return ReferenceEqualityComparer.GetHashCode(a);
}
public static int GetHashCode(object? a)
{
// https://github.com/dotnet/roslyn/issues/41539
return RuntimeHelpers.GetHashCode(a!);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace Roslyn.Utilities
{
/// <summary>
/// Compares objects based upon their reference identity.
/// </summary>
internal class ReferenceEqualityComparer : IEqualityComparer<object?>
{
public static readonly ReferenceEqualityComparer Instance = new();
private ReferenceEqualityComparer()
{
}
bool IEqualityComparer<object?>.Equals(object? a, object? b)
{
return a == b;
}
int IEqualityComparer<object?>.GetHashCode(object? a)
{
return ReferenceEqualityComparer.GetHashCode(a);
}
public static int GetHashCode(object? a)
{
// https://github.com/dotnet/roslyn/issues/41539
return RuntimeHelpers.GetHashCode(a!);
}
}
}
| -1 |
dotnet/roslyn | 55,530 | Ignore modules with bad metadata in function resolver | Fixes https://github.com/dotnet/roslyn/issues/55475 | tmat | 2021-08-10T18:56:37Z | 2021-08-11T18:37:09Z | cd0c0464c069a2b80774d70f071c29333d9fa23c | bc874ebc5111a2a33221409f895953b1536f6612 | Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475 | ./src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/RegexParser.CaptureInfoAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis.EmbeddedLanguages.Common;
using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions
{
using static EmbeddedSyntaxHelpers;
using static RegexHelpers;
using RegexToken = EmbeddedSyntaxToken<RegexKind>;
internal partial struct RegexParser
{
/// <summary>
/// Analyzes the first parsed tree to determine the set of capture numbers and names. These are
/// then used to do the second parsing pass as they can change how the regex engine interprets
/// some parts of the pattern (though not the groups themselves).
/// </summary>
private struct CaptureInfoAnalyzer
{
private readonly VirtualCharSequence _text;
private readonly ImmutableDictionary<int, TextSpan>.Builder _captureNumberToSpan;
private readonly ImmutableDictionary<string, TextSpan>.Builder _captureNameToSpan;
private readonly ArrayBuilder<string> _captureNames;
private int _autoNumber;
private CaptureInfoAnalyzer(VirtualCharSequence text)
{
_text = text;
_captureNumberToSpan = ImmutableDictionary.CreateBuilder<int, TextSpan>();
_captureNameToSpan = ImmutableDictionary.CreateBuilder<string, TextSpan>();
_captureNames = ArrayBuilder<string>.GetInstance();
_autoNumber = 1;
_captureNumberToSpan.Add(0, text.IsEmpty ? default : GetSpan(text));
}
public static (ImmutableDictionary<string, TextSpan>, ImmutableDictionary<int, TextSpan>) Analyze(
VirtualCharSequence text, RegexCompilationUnit root, RegexOptions options)
{
var analyzer = new CaptureInfoAnalyzer(text);
return analyzer.Analyze(root, options);
}
private (ImmutableDictionary<string, TextSpan>, ImmutableDictionary<int, TextSpan>) Analyze(
RegexCompilationUnit root, RegexOptions options)
{
CollectCaptures(root, options);
AssignNumbersToCaptureNames();
_captureNames.Free();
return (_captureNameToSpan.ToImmutable(), _captureNumberToSpan.ToImmutable());
}
private void CollectCaptures(RegexNode node, RegexOptions options)
{
switch (node.Kind)
{
case RegexKind.CaptureGrouping:
var captureGrouping = (RegexCaptureGroupingNode)node;
RecordCapture(captureGrouping.CaptureToken, GetGroupingSpan(captureGrouping));
break;
case RegexKind.BalancingGrouping:
var balancingGroup = (RegexBalancingGroupingNode)node;
RecordCapture(balancingGroup.FirstCaptureToken, GetGroupingSpan(balancingGroup));
break;
case RegexKind.ConditionalExpressionGrouping:
// Explicitly recurse into conditionalGrouping.Grouping. That grouping
// itself does not create a capture group, but nested groupings inside of it
// will.
var conditionalGrouping = (RegexConditionalExpressionGroupingNode)node;
RecurseIntoChildren(conditionalGrouping.Grouping, options);
CollectCaptures(conditionalGrouping.Result, options);
return;
case RegexKind.SimpleGrouping:
RecordSimpleGroupingCapture((RegexSimpleGroupingNode)node, options);
break;
case RegexKind.NestedOptionsGrouping:
// When we see (?opts:...)
// Recurse explicitly, setting the new options as we process the inner expression.
// When this pops out we'll be back to these options we're currently at now.
var nestedOptions = (RegexNestedOptionsGroupingNode)node;
CollectCaptures(nestedOptions.Expression, GetNewOptionsFromToken(options, nestedOptions.OptionsToken));
return;
}
RecurseIntoChildren(node, options);
}
private void RecurseIntoChildren(RegexNode node, RegexOptions options)
{
foreach (var child in node)
{
if (child.IsNode)
{
// When we see a SimpleOptionsGroup ```(?opts)``` then determine what the options will
// be for successive nodes in the sequence.
var childNode = child.Node;
if (childNode is RegexSimpleOptionsGroupingNode simpleOptions)
{
options = GetNewOptionsFromToken(options, simpleOptions.OptionsToken);
}
CollectCaptures(child.Node, options);
}
}
}
private TextSpan GetGroupingSpan(RegexGroupingNode grouping)
{
Debug.Assert(!grouping.OpenParenToken.IsMissing);
var lastChar = grouping.CloseParenToken.IsMissing
? _text.Last()
: grouping.CloseParenToken.VirtualChars.Last();
return GetSpan(grouping.OpenParenToken.VirtualChars[0], lastChar);
}
private void RecordSimpleGroupingCapture(RegexSimpleGroupingNode node, RegexOptions options)
{
if (HasOption(options, RegexOptions.ExplicitCapture))
{
// Don't automatically add simple groups if the explicit capture option is on.
// Only add captures for 'CaptureGrouping' and 'BalancingGrouping' nodes.
return;
}
// Don't count a bogus (? node as a capture node. We only have this to keep our error
// messages in line with the native parser. i.e. even though the bogus (? code would
// cause an exception, we might get an earlier exception if there's a reference to
// this grouping. So if we note this grouping we'll end up not causing that error
// to happen, bringing out behavior out of sync with the native system.
var expr = node.Expression;
while (expr is RegexAlternationNode alternation)
{
expr = alternation.Left;
}
if (expr is RegexSequenceNode sequence &&
sequence.ChildCount > 0)
{
var leftMost = sequence.ChildAt(0);
if (leftMost.Node is RegexTextNode textNode &&
IsTextChar(textNode.TextToken, '?'))
{
return;
}
}
AddIfMissing(_captureNumberToSpan, list: null, _autoNumber++, GetGroupingSpan(node));
}
private void RecordCapture(RegexToken token, TextSpan span)
{
if (!token.IsMissing)
{
if (token.Kind == RegexKind.NumberToken)
{
AddIfMissing(_captureNumberToSpan, list: null, (int)token.Value, span);
}
else
{
AddIfMissing(_captureNameToSpan, list: _captureNames, (string)token.Value, span);
}
}
}
private static void AddIfMissing<T>(
ImmutableDictionary<T, TextSpan>.Builder mapping,
ArrayBuilder<T> list,
T val, TextSpan span)
{
if (!mapping.ContainsKey(val))
{
mapping.Add(val, span);
list?.Add(val);
}
}
/// <summary>
/// Give numbers to all named captures. They will get successive <see
/// cref="_autoNumber"/> values that have not already been handed out to existing
/// numbered capture groups.
/// </summary>
private void AssignNumbersToCaptureNames()
{
foreach (var name in _captureNames)
{
while (_captureNumberToSpan.ContainsKey(_autoNumber))
{
_autoNumber++;
}
_captureNumberToSpan.Add(_autoNumber, _captureNameToSpan[name]);
_autoNumber++;
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis.EmbeddedLanguages.Common;
using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions
{
using static EmbeddedSyntaxHelpers;
using static RegexHelpers;
using RegexToken = EmbeddedSyntaxToken<RegexKind>;
internal partial struct RegexParser
{
/// <summary>
/// Analyzes the first parsed tree to determine the set of capture numbers and names. These are
/// then used to do the second parsing pass as they can change how the regex engine interprets
/// some parts of the pattern (though not the groups themselves).
/// </summary>
private struct CaptureInfoAnalyzer
{
private readonly VirtualCharSequence _text;
private readonly ImmutableDictionary<int, TextSpan>.Builder _captureNumberToSpan;
private readonly ImmutableDictionary<string, TextSpan>.Builder _captureNameToSpan;
private readonly ArrayBuilder<string> _captureNames;
private int _autoNumber;
private CaptureInfoAnalyzer(VirtualCharSequence text)
{
_text = text;
_captureNumberToSpan = ImmutableDictionary.CreateBuilder<int, TextSpan>();
_captureNameToSpan = ImmutableDictionary.CreateBuilder<string, TextSpan>();
_captureNames = ArrayBuilder<string>.GetInstance();
_autoNumber = 1;
_captureNumberToSpan.Add(0, text.IsEmpty ? default : GetSpan(text));
}
public static (ImmutableDictionary<string, TextSpan>, ImmutableDictionary<int, TextSpan>) Analyze(
VirtualCharSequence text, RegexCompilationUnit root, RegexOptions options)
{
var analyzer = new CaptureInfoAnalyzer(text);
return analyzer.Analyze(root, options);
}
private (ImmutableDictionary<string, TextSpan>, ImmutableDictionary<int, TextSpan>) Analyze(
RegexCompilationUnit root, RegexOptions options)
{
CollectCaptures(root, options);
AssignNumbersToCaptureNames();
_captureNames.Free();
return (_captureNameToSpan.ToImmutable(), _captureNumberToSpan.ToImmutable());
}
private void CollectCaptures(RegexNode node, RegexOptions options)
{
switch (node.Kind)
{
case RegexKind.CaptureGrouping:
var captureGrouping = (RegexCaptureGroupingNode)node;
RecordCapture(captureGrouping.CaptureToken, GetGroupingSpan(captureGrouping));
break;
case RegexKind.BalancingGrouping:
var balancingGroup = (RegexBalancingGroupingNode)node;
RecordCapture(balancingGroup.FirstCaptureToken, GetGroupingSpan(balancingGroup));
break;
case RegexKind.ConditionalExpressionGrouping:
// Explicitly recurse into conditionalGrouping.Grouping. That grouping
// itself does not create a capture group, but nested groupings inside of it
// will.
var conditionalGrouping = (RegexConditionalExpressionGroupingNode)node;
RecurseIntoChildren(conditionalGrouping.Grouping, options);
CollectCaptures(conditionalGrouping.Result, options);
return;
case RegexKind.SimpleGrouping:
RecordSimpleGroupingCapture((RegexSimpleGroupingNode)node, options);
break;
case RegexKind.NestedOptionsGrouping:
// When we see (?opts:...)
// Recurse explicitly, setting the new options as we process the inner expression.
// When this pops out we'll be back to these options we're currently at now.
var nestedOptions = (RegexNestedOptionsGroupingNode)node;
CollectCaptures(nestedOptions.Expression, GetNewOptionsFromToken(options, nestedOptions.OptionsToken));
return;
}
RecurseIntoChildren(node, options);
}
private void RecurseIntoChildren(RegexNode node, RegexOptions options)
{
foreach (var child in node)
{
if (child.IsNode)
{
// When we see a SimpleOptionsGroup ```(?opts)``` then determine what the options will
// be for successive nodes in the sequence.
var childNode = child.Node;
if (childNode is RegexSimpleOptionsGroupingNode simpleOptions)
{
options = GetNewOptionsFromToken(options, simpleOptions.OptionsToken);
}
CollectCaptures(child.Node, options);
}
}
}
private TextSpan GetGroupingSpan(RegexGroupingNode grouping)
{
Debug.Assert(!grouping.OpenParenToken.IsMissing);
var lastChar = grouping.CloseParenToken.IsMissing
? _text.Last()
: grouping.CloseParenToken.VirtualChars.Last();
return GetSpan(grouping.OpenParenToken.VirtualChars[0], lastChar);
}
private void RecordSimpleGroupingCapture(RegexSimpleGroupingNode node, RegexOptions options)
{
if (HasOption(options, RegexOptions.ExplicitCapture))
{
// Don't automatically add simple groups if the explicit capture option is on.
// Only add captures for 'CaptureGrouping' and 'BalancingGrouping' nodes.
return;
}
// Don't count a bogus (? node as a capture node. We only have this to keep our error
// messages in line with the native parser. i.e. even though the bogus (? code would
// cause an exception, we might get an earlier exception if there's a reference to
// this grouping. So if we note this grouping we'll end up not causing that error
// to happen, bringing out behavior out of sync with the native system.
var expr = node.Expression;
while (expr is RegexAlternationNode alternation)
{
expr = alternation.Left;
}
if (expr is RegexSequenceNode sequence &&
sequence.ChildCount > 0)
{
var leftMost = sequence.ChildAt(0);
if (leftMost.Node is RegexTextNode textNode &&
IsTextChar(textNode.TextToken, '?'))
{
return;
}
}
AddIfMissing(_captureNumberToSpan, list: null, _autoNumber++, GetGroupingSpan(node));
}
private void RecordCapture(RegexToken token, TextSpan span)
{
if (!token.IsMissing)
{
if (token.Kind == RegexKind.NumberToken)
{
AddIfMissing(_captureNumberToSpan, list: null, (int)token.Value, span);
}
else
{
AddIfMissing(_captureNameToSpan, list: _captureNames, (string)token.Value, span);
}
}
}
private static void AddIfMissing<T>(
ImmutableDictionary<T, TextSpan>.Builder mapping,
ArrayBuilder<T> list,
T val, TextSpan span)
{
if (!mapping.ContainsKey(val))
{
mapping.Add(val, span);
list?.Add(val);
}
}
/// <summary>
/// Give numbers to all named captures. They will get successive <see
/// cref="_autoNumber"/> values that have not already been handed out to existing
/// numbered capture groups.
/// </summary>
private void AssignNumbersToCaptureNames()
{
foreach (var name in _captureNames)
{
while (_captureNumberToSpan.ContainsKey(_autoNumber))
{
_autoNumber++;
}
_captureNumberToSpan.Add(_autoNumber, _captureNameToSpan[name]);
_autoNumber++;
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,530 | Ignore modules with bad metadata in function resolver | Fixes https://github.com/dotnet/roslyn/issues/55475 | tmat | 2021-08-10T18:56:37Z | 2021-08-11T18:37:09Z | cd0c0464c069a2b80774d70f071c29333d9fa23c | bc874ebc5111a2a33221409f895953b1536f6612 | Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475 | ./src/Compilers/Core/CodeAnalysisTest/InternalUtilities/StreamExtensionsTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis;
using Roslyn.Test.Utilities;
using System;
using System.IO;
using Xunit;
namespace Roslyn.Utilities.UnitTests.InternalUtilities
{
public class StreamExtensionsTests
{
[Fact]
public void TryReadAll_CallsReadMultipleTimes()
{
var firstRead = true;
var sourceArray = new byte[] { 1, 2, 3, 4 };
int sourceOffset = 0;
var stream = new TestStream(readFunc: (buf, offset, count) =>
{
if (firstRead)
{
count = count / 2;
firstRead = false;
}
Array.Copy(sourceArray, sourceOffset, buf, offset, count);
sourceOffset += count;
return count;
});
var destArray = new byte[4];
var destCopy = destArray.AsImmutable();
// Note: Buffer is in undefined state after receiving an exception
Assert.Equal(sourceArray.Length, stream.TryReadAll(destArray, 0, sourceArray.Length));
Assert.Equal(sourceArray, destArray);
}
[Fact]
public void TryReadAll_ExceptionsPropagate()
{
var buffer = new byte[10];
var stream = new TestStream(readFunc: (_1, _2, _3) => { throw new IOException(); });
Assert.Throws<IOException>(() => stream.TryReadAll(null, 0, 1));
stream = new TestStream(readFunc: (buf, offset, count) =>
{
if (offset + count > buf.Length)
{
throw new ArgumentException();
}
return 0;
});
Assert.Equal(0, stream.TryReadAll(buffer, 0, 1));
Assert.Throws<ArgumentException>(() => stream.TryReadAll(buffer, 0, 100));
}
[Fact]
public void TryReadAll_ExceptionMayChangeOutput()
{
var firstRead = true;
var sourceArray = new byte[] { 1, 2, 3, 4 };
var stream = new TestStream(readFunc: (buf, offset, count) =>
{
if (firstRead)
{
count = count / 2;
Array.Copy(sourceArray, 0, buf, offset, count);
firstRead = false;
return count;
}
throw new IOException();
});
var destArray = new byte[4];
var destCopy = destArray.AsImmutable();
// Note: Buffer is in undefined state after receiving an exception
Assert.Throws<IOException>(() => stream.TryReadAll(destArray, 0, sourceArray.Length));
Assert.NotEqual(destArray, destCopy);
}
[Fact]
public void TryReadAll_ExceptionMayChangePosition()
{
var firstRead = true;
var sourceArray = new byte[] { 1, 2, 3, 4 };
var backingStream = new MemoryStream(sourceArray);
var stream = new TestStream(readFunc: (buf, offset, count) =>
{
if (firstRead)
{
count = count / 2;
backingStream.Read(buf, offset, count);
firstRead = false;
return count;
}
throw new IOException();
});
var destArray = new byte[4];
Assert.Equal(0, backingStream.Position);
Assert.Throws<IOException>(() => stream.TryReadAll(destArray, 0, sourceArray.Length));
Assert.Equal(2, backingStream.Position);
}
[Fact]
public void TryReadAll_PrematureEndOfStream()
{
var sourceArray = new byte[] { 1, 2, 3, 4 };
var stream = new MemoryStream(sourceArray);
var destArray = new byte[6];
// Try to read more bytes than exist in the stream
Assert.Equal(4, stream.TryReadAll(destArray, 0, 6));
var expected = new byte[] { 1, 2, 3, 4, 0, 0 };
Assert.Equal(expected, destArray);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void ReadAllBytes(bool canSeek)
{
var sourceArray = new byte[] { 1, 2, 3, 4 };
var stream = new TestStream(canSeek: canSeek, backingStream: new MemoryStream(sourceArray));
stream.ReadByte();
Assert.Equal(new byte[] { 2, 3, 4 }, stream.ReadAllBytes());
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void ReadAllBytes_End(bool canSeek)
{
var sourceArray = new byte[] { 1, 2 };
var stream = new TestStream(canSeek: canSeek, backingStream: new MemoryStream(sourceArray));
stream.ReadByte();
stream.ReadByte();
Assert.Equal(new byte[0], stream.ReadAllBytes());
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void ReadAllBytes_Resize(bool canSeek)
{
var sourceArray = new byte[] { 1, 2 };
var stream = new TestStream(canSeek: canSeek, backingStream: new MemoryStream(sourceArray), length: 3);
Assert.Equal(new byte[] { 1, 2 }, stream.ReadAllBytes());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis;
using Roslyn.Test.Utilities;
using System;
using System.IO;
using Xunit;
namespace Roslyn.Utilities.UnitTests.InternalUtilities
{
public class StreamExtensionsTests
{
[Fact]
public void TryReadAll_CallsReadMultipleTimes()
{
var firstRead = true;
var sourceArray = new byte[] { 1, 2, 3, 4 };
int sourceOffset = 0;
var stream = new TestStream(readFunc: (buf, offset, count) =>
{
if (firstRead)
{
count = count / 2;
firstRead = false;
}
Array.Copy(sourceArray, sourceOffset, buf, offset, count);
sourceOffset += count;
return count;
});
var destArray = new byte[4];
var destCopy = destArray.AsImmutable();
// Note: Buffer is in undefined state after receiving an exception
Assert.Equal(sourceArray.Length, stream.TryReadAll(destArray, 0, sourceArray.Length));
Assert.Equal(sourceArray, destArray);
}
[Fact]
public void TryReadAll_ExceptionsPropagate()
{
var buffer = new byte[10];
var stream = new TestStream(readFunc: (_1, _2, _3) => { throw new IOException(); });
Assert.Throws<IOException>(() => stream.TryReadAll(null, 0, 1));
stream = new TestStream(readFunc: (buf, offset, count) =>
{
if (offset + count > buf.Length)
{
throw new ArgumentException();
}
return 0;
});
Assert.Equal(0, stream.TryReadAll(buffer, 0, 1));
Assert.Throws<ArgumentException>(() => stream.TryReadAll(buffer, 0, 100));
}
[Fact]
public void TryReadAll_ExceptionMayChangeOutput()
{
var firstRead = true;
var sourceArray = new byte[] { 1, 2, 3, 4 };
var stream = new TestStream(readFunc: (buf, offset, count) =>
{
if (firstRead)
{
count = count / 2;
Array.Copy(sourceArray, 0, buf, offset, count);
firstRead = false;
return count;
}
throw new IOException();
});
var destArray = new byte[4];
var destCopy = destArray.AsImmutable();
// Note: Buffer is in undefined state after receiving an exception
Assert.Throws<IOException>(() => stream.TryReadAll(destArray, 0, sourceArray.Length));
Assert.NotEqual(destArray, destCopy);
}
[Fact]
public void TryReadAll_ExceptionMayChangePosition()
{
var firstRead = true;
var sourceArray = new byte[] { 1, 2, 3, 4 };
var backingStream = new MemoryStream(sourceArray);
var stream = new TestStream(readFunc: (buf, offset, count) =>
{
if (firstRead)
{
count = count / 2;
backingStream.Read(buf, offset, count);
firstRead = false;
return count;
}
throw new IOException();
});
var destArray = new byte[4];
Assert.Equal(0, backingStream.Position);
Assert.Throws<IOException>(() => stream.TryReadAll(destArray, 0, sourceArray.Length));
Assert.Equal(2, backingStream.Position);
}
[Fact]
public void TryReadAll_PrematureEndOfStream()
{
var sourceArray = new byte[] { 1, 2, 3, 4 };
var stream = new MemoryStream(sourceArray);
var destArray = new byte[6];
// Try to read more bytes than exist in the stream
Assert.Equal(4, stream.TryReadAll(destArray, 0, 6));
var expected = new byte[] { 1, 2, 3, 4, 0, 0 };
Assert.Equal(expected, destArray);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void ReadAllBytes(bool canSeek)
{
var sourceArray = new byte[] { 1, 2, 3, 4 };
var stream = new TestStream(canSeek: canSeek, backingStream: new MemoryStream(sourceArray));
stream.ReadByte();
Assert.Equal(new byte[] { 2, 3, 4 }, stream.ReadAllBytes());
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void ReadAllBytes_End(bool canSeek)
{
var sourceArray = new byte[] { 1, 2 };
var stream = new TestStream(canSeek: canSeek, backingStream: new MemoryStream(sourceArray));
stream.ReadByte();
stream.ReadByte();
Assert.Equal(new byte[0], stream.ReadAllBytes());
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void ReadAllBytes_Resize(bool canSeek)
{
var sourceArray = new byte[] { 1, 2 };
var stream = new TestStream(canSeek: canSeek, backingStream: new MemoryStream(sourceArray), length: 3);
Assert.Equal(new byte[] { 1, 2 }, stream.ReadAllBytes());
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/EditorFeatures/CSharpTest/ExtractClass/ExtractClassTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.ExtractClass;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Microsoft.CodeAnalysis.ExtractClass;
using Microsoft.CodeAnalysis.PullMemberUp;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ExtractClass
{
public class ExtractClassTests : AbstractCSharpCodeActionTest
{
private Task TestExtractClassAsync(
string input,
string? expected = null,
IEnumerable<(string name, bool makeAbstract)>? dialogSelection = null,
bool sameFile = false,
bool isClassDeclarationSelection = false,
TestParameters testParameters = default)
{
var service = new TestExtractClassOptionsService(dialogSelection, sameFile, isClassDeclarationSelection);
var parametersWithOptionsService = testParameters.WithFixProviderData(service);
if (expected is null)
{
return TestMissingAsync(input, parametersWithOptionsService);
}
return TestInRegularAndScript1Async(
input,
expected,
parameters: parametersWithOptionsService);
}
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new CSharpExtractClassCodeRefactoringProvider((IExtractClassOptionsService)parameters.fixProviderData);
[Fact]
public async Task TestSingleMethod()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test
{
int [||]Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[Fact]
public async Task TestErrorBaseMethod()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : ErrorBase
{
int [||]Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input);
}
[Fact]
public async Task TestMiscellaneousFiles()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test
{
int [||]Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
TestParameters parameters = default;
await TestExtractClassAsync(input, testParameters: parameters.WithWorkspaceKind(WorkspaceKind.MiscellaneousFiles));
}
[Fact]
public async Task TestPartialClass()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
partial class Test
{
int [||]Method()
{
return 1 + 1;
}
}
</Document>
<Document FilePath=""Test.Other.cs"">
partial class Test
{
int Method2()
{
return 5;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
partial class Test : MyBase
{
}
</Document>
<Document FilePath=""Test.Other.cs"">
partial class Test
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int Method()
{
return 1 + 1;
}
int Method2()
{
return 5;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(
input,
expected,
dialogSelection: MakeSelection("Method", "Method2"));
}
[Fact]
public async Task TestInNamespace()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
namespace MyNamespace
{
class Test
{
int [||]Method()
{
return 1 + 1;
}
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
namespace MyNamespace
{
class Test : MyBase
{
}
}
</Document>
<Document FilePath=""MyBase.cs"">namespace MyNamespace
{
internal class MyBase
{
int Method()
{
return 1 + 1;
}
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[Fact]
public async Task TestInNamespace_FileScopedNamespace1()
{
var input = @"
<Workspace>
<Project Language=""C#"" LanguageVersion=""10"">
<Document FilePath=""Test.cs"">
namespace MyNamespace
{
class Test
{
int [||]Method()
{
return 1 + 1;
}
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" LanguageVersion=""10"">
<Document FilePath=""Test.cs"">
namespace MyNamespace
{
class Test : MyBase
{
}
}
</Document>
<Document FilePath=""MyBase.cs"">namespace MyNamespace;
internal class MyBase
{
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestAsync(
input, expected,
CSharpParseOptions.Default,
options: Option(CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped, NotificationOption2.Silent),
fixProviderData: new TestExtractClassOptionsService());
}
[Fact]
public async Task TestInNamespace_FileScopedNamespace2()
{
var input = @"
<Workspace>
<Project Language=""C#"" LanguageVersion=""9"">
<Document FilePath=""Test.cs"">
namespace MyNamespace
{
class Test
{
int [||]Method()
{
return 1 + 1;
}
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" LanguageVersion=""9"">
<Document FilePath=""Test.cs"">
namespace MyNamespace
{
class Test : MyBase
{
}
}
</Document>
<Document FilePath=""MyBase.cs"">namespace MyNamespace
{
internal class MyBase
{
int Method()
{
return 1 + 1;
}
}
}</Document>
</Project>
</Workspace>";
await TestAsync(
input, expected,
CSharpParseOptions.Default,
options: Option(CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped, NotificationOption2.Silent),
fixProviderData: new TestExtractClassOptionsService());
}
[Fact]
public async Task TestInNamespace_FileScopedNamespace3()
{
var input = @"
<Workspace>
<Project Language=""C#"" LanguageVersion=""10"">
<Document FilePath=""Test.cs"">
namespace MyNamespace
{
class Test
{
int [||]Method()
{
return 1 + 1;
}
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" LanguageVersion=""10"">
<Document FilePath=""Test.cs"">
namespace MyNamespace
{
class Test : MyBase
{
}
}
</Document>
<Document FilePath=""MyBase.cs"">namespace MyNamespace
{
internal class MyBase
{
int Method()
{
return 1 + 1;
}
}
}</Document>
</Project>
</Workspace>";
await TestAsync(
input, expected,
CSharpParseOptions.Default,
options: Option(CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped, NotificationOption2.Silent),
fixProviderData: new TestExtractClassOptionsService());
}
[Fact]
public async Task TestAccessibility()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
public class Test
{
int [||]Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
public class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">public class MyBase
{
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[Fact]
public async Task TestEvent()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
class Test
{
private event EventHandler [||]Event1;
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
private event EventHandler Event1;
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[Fact]
public async Task TestProperty()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test
{
int [||]MyProperty { get; set; }
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int MyProperty { get; set; }
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[Fact]
public async Task TestField()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test
{
int [||]MyField;
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int MyField;
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[Fact]
public async Task TestFileHeader()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">// this is my document header
// that should be copied over
class Test
{
int [||]Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">// this is my document header
// that should be copied over
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">// this is my document header
// that should be copied over
internal class MyBase
{
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[Fact]
public async Task TestWithInterface()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
interface ITest
{
int Method();
}
class Test : ITest
{
int [||]Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
interface ITest
{
int Method();
}
class Test : MyBase, ITest
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[ConditionalFact(AlwaysSkip = "https://github.com/dotnet/roslyn/issues/45977")]
public async Task TestRegion()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test
{
#region MyRegion
int [||]Method()
{
return 1 + 1;
}
void OtherMethiod() { }
#endregion
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
#region MyRegion
void OtherMethiod() { }
#endregion
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
#region MyRegion
int Method()
{
return 1 + 1;
}
#endregion
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(
input,
expected,
dialogSelection: MakeSelection("Method"));
}
[Fact]
public async Task TestMakeAbstract_SingleMethod()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test
{
int [||]Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
override int Method()
{
return 1 + 1;
}
}
</Document>
<Document FilePath=""MyBase.cs"">internal abstract class MyBase
{
private abstract global::System.Int32 Method();
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(
input,
expected,
dialogSelection: MakeAbstractSelection("Method"));
}
[Fact]
public async Task TestMakeAbstract_MultipleMethods()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test
{
int [||]Method()
{
return 1 + 1;
}
int Method2() => 2;
int Method3() => 3;
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
override int Method()
{
return 1 + 1;
}
override int Method2() => 2;
override int Method3() => 3;
}
</Document>
<Document FilePath=""MyBase.cs"">internal abstract class MyBase
{
private abstract global::System.Int32 Method();
private abstract global::System.Int32 Method2();
private abstract global::System.Int32 Method3();
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(
input,
expected,
dialogSelection: MakeAbstractSelection("Method", "Method2", "Method3"));
}
[Fact]
public async Task TestMultipleMethods()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test
{
int [||]Method()
{
return Method2() + 1;
}
int Method2() => 1;
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int Method()
{
return Method2() + 1;
}
int Method2() => 1;
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(
input,
expected,
dialogSelection: MakeSelection("Method", "Method2"));
}
[Fact]
public async Task TestMultipleMethods_SomeSelected()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test
{
int [||]Method()
{
return Method2() + 1;
}
int Method2() => 1;
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
int Method()
{
return Method2() + 1;
}
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int Method2() => 1;
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(
input,
expected,
dialogSelection: MakeSelection("Method2"));
}
[Fact]
public async Task TestSelection_CompleteMethodAndComments()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test
{
[|/// <summary>
/// this is a test method
/// </summary>
int Method()
{
return 1 + 1;
}|]
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
/// <summary>
/// this is a test method
/// </summary>
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[Fact]
public async Task TestSelection_PartialMethodAndComments()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test
{
[|/// <summary>
/// this is a test method
/// </summary>
int Method()
{|]
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
/// <summary>
/// this is a test method
/// </summary>
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[Fact]
public async Task TestSelection_PartialMethodAndComments2()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test
{
/// <summary>
/// [|this is a test method
/// </summary>
int Method()
{|]
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
/// <summary>
/// this is a test method
/// </summary>
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[Fact]
public async Task TestSelection_PartialMethodAndComments3()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test
{
/// <summary>
/// [|this is a test method
/// </summary>
int Method()|]
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
/// <summary>
/// this is a test method
/// </summary>
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[Fact]
public async Task TestAttributes()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
class TestAttribute : Attribute { }
class Test
{
/// <summary>
/// this is a test method
/// </summary>
[||][TestAttribute]
int Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
class TestAttribute : Attribute { }
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
/// <summary>
/// this is a test method
/// </summary>
[TestAttribute]
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[Fact]
public async Task TestAttributes2()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
class TestAttribute : Attribute { }
class TestAttribute2 : Attribute { }
class Test
{
/// <summary>
/// this is a test method
/// </summary>
[||][TestAttribute]
[TestAttribute2]
int Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
class TestAttribute : Attribute { }
class TestAttribute2 : Attribute { }
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
/// <summary>
/// this is a test method
/// </summary>
[TestAttribute]
[TestAttribute2]
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[ConditionalFact(AlwaysSkip = "https://github.com/dotnet/roslyn/issues/45987")]
public async Task TestAttributes3()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
class TestAttribute : Attribute { }
class TestAttribute2 : Attribute { }
class Test
{
/// <summary>
/// this is a test method
/// </summary>
[TestAttribute]
[||][TestAttribute2]
int Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
class TestAttribute : Attribute { }
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
/// <summary>
/// this is a test method
/// </summary>
[TestAttribute]
[TestAttribute2]
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[ConditionalFact(AlwaysSkip = "https://github.com/dotnet/roslyn/issues/45987")]
public async Task TestAttributes4()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
class TestAttribute : Attribute { }
class TestAttribute2 : Attribute { }
class Test
{
/// <summary>
/// this is a test method
/// </summary>
[TestAttribute]
[TestAttribute2][||]
int Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
class TestAttribute : Attribute { }
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
/// <summary>
/// this is a test method
/// </summary>
[TestAttribute]
[TestAttribute2]
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[Fact]
public async Task TestSameFile()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test
{
void Method[||]()
{
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
internal class MyBase
{
void Method()
{
}
}
class Test : MyBase
{
}
</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected, sameFile: true);
}
[Fact]
public async Task TestClassDeclaration()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test[||]
{
int Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true);
}
[Fact]
public async Task TestClassDeclaration2()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class [||]Test
{
int Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true);
}
[Fact]
public async Task TestClassDeclaration3()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
[||]class Test
{
int Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true);
}
[Fact]
public async Task TestClassDeclaration4()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class[||] Test
{
int Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true);
}
[Fact]
public async Task TestClassDeclaration_Comment()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
/// <summary>
/// [|This is a test class
/// </summary>
class Test|]
{
int Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
/// <summary>
/// This is a test class
/// </summary>
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true);
}
[Fact]
public async Task TestClassDeclaration_Comment2()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
/// <summary>
/// This is a test class
/// [|</summary>
class Test|]
{
int Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
/// <summary>
/// This is a test class
/// </summary>
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true);
}
[Fact]
public async Task TestClassDeclaration_Comment3()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
/// <summary>
/// This is a [|test class
/// </summary>
class|] Test
{
int Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
/// <summary>
/// This is a test class
/// </summary>
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true);
}
[Fact]
public async Task TestClassDeclaration_Attribute()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
public class MyAttribute : Attribute { }
[||][MyAttribute]
class Test
{
int Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
public class MyAttribute : Attribute { }
[MyAttribute]
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">[MyAttribute]
internal class MyBase
{
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true);
}
[Fact]
public async Task TestClassDeclaration_SelectWithMembers()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
[|class Test
{
int Method()
{
return 1 + 1;
}
}|]
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true);
}
[Fact]
public async Task TestClassDeclaration_SelectWithMembers2()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
[|class Test
{
int Method()
{
return 1 + 1;
}|]
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true);
}
private static IEnumerable<(string name, bool makeAbstract)> MakeAbstractSelection(params string[] memberNames)
=> memberNames.Select(m => (m, true));
private static IEnumerable<(string name, bool makeAbstract)> MakeSelection(params string[] memberNames)
=> memberNames.Select(m => (m, false));
private class TestExtractClassOptionsService : IExtractClassOptionsService
{
private readonly IEnumerable<(string name, bool makeAbstract)>? _dialogSelection;
private readonly bool _sameFile;
private readonly bool isClassDeclarationSelection;
public TestExtractClassOptionsService(IEnumerable<(string name, bool makeAbstract)>? dialogSelection = null, bool sameFile = false, bool isClassDeclarationSelection = false)
{
_dialogSelection = dialogSelection;
_sameFile = sameFile;
this.isClassDeclarationSelection = isClassDeclarationSelection;
}
public string FileName { get; set; } = "MyBase.cs";
public string BaseName { get; set; } = "MyBase";
public Task<ExtractClassOptions?> GetExtractClassOptionsAsync(Document document, INamedTypeSymbol originalSymbol, ISymbol? selectedMember)
{
var availableMembers = originalSymbol.GetMembers().Where(member => MemberAndDestinationValidator.IsMemberValid(member));
IEnumerable<(ISymbol member, bool makeAbstract)> selections;
if (_dialogSelection == null)
{
if (selectedMember is null)
{
Assert.True(isClassDeclarationSelection);
selections = availableMembers.Select(member => (member, makeAbstract: false));
}
else
{
Assert.False(isClassDeclarationSelection);
selections = new[] { (selectedMember, false) };
}
}
else
{
selections = _dialogSelection.Select(selection => (member: availableMembers.Single(symbol => symbol.Name == selection.name), selection.makeAbstract));
}
var memberAnalysis = selections.Select(s =>
new ExtractClassMemberAnalysisResult(
s.member,
s.makeAbstract))
.ToImmutableArray();
return Task.FromResult<ExtractClassOptions?>(new ExtractClassOptions(FileName, BaseName, _sameFile, memberAnalysis));
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.ExtractClass;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Microsoft.CodeAnalysis.ExtractClass;
using Microsoft.CodeAnalysis.PullMemberUp;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ExtractClass
{
public class ExtractClassTests : AbstractCSharpCodeActionTest
{
private Task TestExtractClassAsync(
string input,
string? expected = null,
IEnumerable<(string name, bool makeAbstract)>? dialogSelection = null,
bool sameFile = false,
bool isClassDeclarationSelection = false,
TestParameters testParameters = default)
{
var service = new TestExtractClassOptionsService(dialogSelection, sameFile, isClassDeclarationSelection);
var parametersWithOptionsService = testParameters.WithFixProviderData(service);
if (expected is null)
{
return TestMissingAsync(input, parametersWithOptionsService);
}
return TestInRegularAndScript1Async(
input,
expected,
parameters: parametersWithOptionsService);
}
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new CSharpExtractClassCodeRefactoringProvider((IExtractClassOptionsService)parameters.fixProviderData);
[Fact]
public async Task TestSingleMethod()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test
{
int [||]Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[Fact]
public async Task TestErrorBaseMethod()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : ErrorBase
{
int [||]Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input);
}
[Fact]
public async Task TestMiscellaneousFiles()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test
{
int [||]Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
TestParameters parameters = default;
await TestExtractClassAsync(input, testParameters: parameters.WithWorkspaceKind(WorkspaceKind.MiscellaneousFiles));
}
[Fact]
public async Task TestPartialClass()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
partial class Test
{
int [||]Method()
{
return 1 + 1;
}
}
</Document>
<Document FilePath=""Test.Other.cs"">
partial class Test
{
int Method2()
{
return 5;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
partial class Test : MyBase
{
}
</Document>
<Document FilePath=""Test.Other.cs"">
partial class Test
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int Method()
{
return 1 + 1;
}
int Method2()
{
return 5;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(
input,
expected,
dialogSelection: MakeSelection("Method", "Method2"));
}
[Fact]
public async Task TestInNamespace()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
namespace MyNamespace
{
class Test
{
int [||]Method()
{
return 1 + 1;
}
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
namespace MyNamespace
{
class Test : MyBase
{
}
}
</Document>
<Document FilePath=""MyBase.cs"">namespace MyNamespace
{
internal class MyBase
{
int Method()
{
return 1 + 1;
}
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[Fact]
public async Task TestInNamespace_FileScopedNamespace1()
{
var input = @"
<Workspace>
<Project Language=""C#"" LanguageVersion=""10"">
<Document FilePath=""Test.cs"">
namespace MyNamespace
{
class Test
{
int [||]Method()
{
return 1 + 1;
}
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" LanguageVersion=""10"">
<Document FilePath=""Test.cs"">
namespace MyNamespace
{
class Test : MyBase
{
}
}
</Document>
<Document FilePath=""MyBase.cs"">namespace MyNamespace;
internal class MyBase
{
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestAsync(
input, expected,
CSharpParseOptions.Default,
options: Option(CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped, NotificationOption2.Silent),
fixProviderData: new TestExtractClassOptionsService());
}
[Fact]
public async Task TestInNamespace_FileScopedNamespace2()
{
var input = @"
<Workspace>
<Project Language=""C#"" LanguageVersion=""9"">
<Document FilePath=""Test.cs"">
namespace MyNamespace
{
class Test
{
int [||]Method()
{
return 1 + 1;
}
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" LanguageVersion=""9"">
<Document FilePath=""Test.cs"">
namespace MyNamespace
{
class Test : MyBase
{
}
}
</Document>
<Document FilePath=""MyBase.cs"">namespace MyNamespace
{
internal class MyBase
{
int Method()
{
return 1 + 1;
}
}
}</Document>
</Project>
</Workspace>";
await TestAsync(
input, expected,
CSharpParseOptions.Default,
options: Option(CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped, NotificationOption2.Silent),
fixProviderData: new TestExtractClassOptionsService());
}
[Fact]
public async Task TestInNamespace_FileScopedNamespace3()
{
var input = @"
<Workspace>
<Project Language=""C#"" LanguageVersion=""10"">
<Document FilePath=""Test.cs"">
namespace MyNamespace
{
class Test
{
int [||]Method()
{
return 1 + 1;
}
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" LanguageVersion=""10"">
<Document FilePath=""Test.cs"">
namespace MyNamespace
{
class Test : MyBase
{
}
}
</Document>
<Document FilePath=""MyBase.cs"">namespace MyNamespace
{
internal class MyBase
{
int Method()
{
return 1 + 1;
}
}
}</Document>
</Project>
</Workspace>";
await TestAsync(
input, expected,
CSharpParseOptions.Default,
options: Option(CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped, NotificationOption2.Silent),
fixProviderData: new TestExtractClassOptionsService());
}
[Fact]
public async Task TestAccessibility()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
public class Test
{
int [||]Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
public class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">public class MyBase
{
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[Fact]
public async Task TestEvent()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
class Test
{
private event EventHandler [||]Event1;
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
private event EventHandler Event1;
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[Fact]
public async Task TestProperty()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test
{
int [||]MyProperty { get; set; }
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int MyProperty { get; set; }
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[Fact]
public async Task TestField()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test
{
int [||]MyField;
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int MyField;
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[Fact]
public async Task TestFileHeader_FromExistingFile()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">// this is my document header
// that should be copied over
class Test
{
int [||]Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">// this is my document header
// that should be copied over
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">// this is my document header
// that should be copied over
internal class MyBase
{
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[Fact]
public async Task TestFileHeader_FromOption()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">// this is my document header
// that should be ignored
class Test
{
int [||]Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">// this is my document header
// that should be ignored
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">// this is my real document header
internal class MyBase
{
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected, testParameters: new TestParameters(options: Option(CodeStyleOptions2.FileHeaderTemplate, "this is my real document header")));
}
[Fact]
public async Task TestWithInterface()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
interface ITest
{
int Method();
}
class Test : ITest
{
int [||]Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
interface ITest
{
int Method();
}
class Test : MyBase, ITest
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[ConditionalFact(AlwaysSkip = "https://github.com/dotnet/roslyn/issues/45977")]
public async Task TestRegion()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test
{
#region MyRegion
int [||]Method()
{
return 1 + 1;
}
void OtherMethiod() { }
#endregion
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
#region MyRegion
void OtherMethiod() { }
#endregion
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
#region MyRegion
int Method()
{
return 1 + 1;
}
#endregion
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(
input,
expected,
dialogSelection: MakeSelection("Method"));
}
[Fact]
public async Task TestMakeAbstract_SingleMethod()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test
{
int [||]Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
override int Method()
{
return 1 + 1;
}
}
</Document>
<Document FilePath=""MyBase.cs"">internal abstract class MyBase
{
private abstract global::System.Int32 Method();
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(
input,
expected,
dialogSelection: MakeAbstractSelection("Method"));
}
[Fact]
public async Task TestMakeAbstract_MultipleMethods()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test
{
int [||]Method()
{
return 1 + 1;
}
int Method2() => 2;
int Method3() => 3;
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
override int Method()
{
return 1 + 1;
}
override int Method2() => 2;
override int Method3() => 3;
}
</Document>
<Document FilePath=""MyBase.cs"">internal abstract class MyBase
{
private abstract global::System.Int32 Method();
private abstract global::System.Int32 Method2();
private abstract global::System.Int32 Method3();
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(
input,
expected,
dialogSelection: MakeAbstractSelection("Method", "Method2", "Method3"));
}
[Fact]
public async Task TestMultipleMethods()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test
{
int [||]Method()
{
return Method2() + 1;
}
int Method2() => 1;
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int Method()
{
return Method2() + 1;
}
int Method2() => 1;
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(
input,
expected,
dialogSelection: MakeSelection("Method", "Method2"));
}
[Fact]
public async Task TestMultipleMethods_SomeSelected()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test
{
int [||]Method()
{
return Method2() + 1;
}
int Method2() => 1;
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
int Method()
{
return Method2() + 1;
}
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int Method2() => 1;
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(
input,
expected,
dialogSelection: MakeSelection("Method2"));
}
[Fact]
public async Task TestSelection_CompleteMethodAndComments()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test
{
[|/// <summary>
/// this is a test method
/// </summary>
int Method()
{
return 1 + 1;
}|]
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
/// <summary>
/// this is a test method
/// </summary>
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[Fact]
public async Task TestSelection_PartialMethodAndComments()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test
{
[|/// <summary>
/// this is a test method
/// </summary>
int Method()
{|]
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
/// <summary>
/// this is a test method
/// </summary>
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[Fact]
public async Task TestSelection_PartialMethodAndComments2()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test
{
/// <summary>
/// [|this is a test method
/// </summary>
int Method()
{|]
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
/// <summary>
/// this is a test method
/// </summary>
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[Fact]
public async Task TestSelection_PartialMethodAndComments3()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test
{
/// <summary>
/// [|this is a test method
/// </summary>
int Method()|]
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
/// <summary>
/// this is a test method
/// </summary>
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[Fact]
public async Task TestAttributes()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
class TestAttribute : Attribute { }
class Test
{
/// <summary>
/// this is a test method
/// </summary>
[||][TestAttribute]
int Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
class TestAttribute : Attribute { }
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
/// <summary>
/// this is a test method
/// </summary>
[TestAttribute]
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[Fact]
public async Task TestAttributes2()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
class TestAttribute : Attribute { }
class TestAttribute2 : Attribute { }
class Test
{
/// <summary>
/// this is a test method
/// </summary>
[||][TestAttribute]
[TestAttribute2]
int Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
class TestAttribute : Attribute { }
class TestAttribute2 : Attribute { }
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
/// <summary>
/// this is a test method
/// </summary>
[TestAttribute]
[TestAttribute2]
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[ConditionalFact(AlwaysSkip = "https://github.com/dotnet/roslyn/issues/45987")]
public async Task TestAttributes3()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
class TestAttribute : Attribute { }
class TestAttribute2 : Attribute { }
class Test
{
/// <summary>
/// this is a test method
/// </summary>
[TestAttribute]
[||][TestAttribute2]
int Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
class TestAttribute : Attribute { }
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
/// <summary>
/// this is a test method
/// </summary>
[TestAttribute]
[TestAttribute2]
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[ConditionalFact(AlwaysSkip = "https://github.com/dotnet/roslyn/issues/45987")]
public async Task TestAttributes4()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
class TestAttribute : Attribute { }
class TestAttribute2 : Attribute { }
class Test
{
/// <summary>
/// this is a test method
/// </summary>
[TestAttribute]
[TestAttribute2][||]
int Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
class TestAttribute : Attribute { }
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
/// <summary>
/// this is a test method
/// </summary>
[TestAttribute]
[TestAttribute2]
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected);
}
[Fact]
public async Task TestSameFile()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test
{
void Method[||]()
{
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
internal class MyBase
{
void Method()
{
}
}
class Test : MyBase
{
}
</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected, sameFile: true);
}
[Fact]
public async Task TestClassDeclaration()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test[||]
{
int Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true);
}
[Fact]
public async Task TestClassDeclaration2()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class [||]Test
{
int Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true);
}
[Fact]
public async Task TestClassDeclaration3()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
[||]class Test
{
int Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true);
}
[Fact]
public async Task TestClassDeclaration4()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class[||] Test
{
int Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true);
}
[Fact]
public async Task TestClassDeclaration_Comment()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
/// <summary>
/// [|This is a test class
/// </summary>
class Test|]
{
int Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
/// <summary>
/// This is a test class
/// </summary>
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true);
}
[Fact]
public async Task TestClassDeclaration_Comment2()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
/// <summary>
/// This is a test class
/// [|</summary>
class Test|]
{
int Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
/// <summary>
/// This is a test class
/// </summary>
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true);
}
[Fact]
public async Task TestClassDeclaration_Comment3()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
/// <summary>
/// This is a [|test class
/// </summary>
class|] Test
{
int Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
/// <summary>
/// This is a test class
/// </summary>
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true);
}
[Fact]
public async Task TestClassDeclaration_Attribute()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
public class MyAttribute : Attribute { }
[||][MyAttribute]
class Test
{
int Method()
{
return 1 + 1;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
using System;
public class MyAttribute : Attribute { }
[MyAttribute]
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">[MyAttribute]
internal class MyBase
{
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true);
}
[Fact]
public async Task TestClassDeclaration_SelectWithMembers()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
[|class Test
{
int Method()
{
return 1 + 1;
}
}|]
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true);
}
[Fact]
public async Task TestClassDeclaration_SelectWithMembers2()
{
var input = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
[|class Test
{
int Method()
{
return 1 + 1;
}|]
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"">
<Document FilePath=""Test.cs"">
class Test : MyBase
{
}
</Document>
<Document FilePath=""MyBase.cs"">internal class MyBase
{
int Method()
{
return 1 + 1;
}
}</Document>
</Project>
</Workspace>";
await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true);
}
private static IEnumerable<(string name, bool makeAbstract)> MakeAbstractSelection(params string[] memberNames)
=> memberNames.Select(m => (m, true));
private static IEnumerable<(string name, bool makeAbstract)> MakeSelection(params string[] memberNames)
=> memberNames.Select(m => (m, false));
private class TestExtractClassOptionsService : IExtractClassOptionsService
{
private readonly IEnumerable<(string name, bool makeAbstract)>? _dialogSelection;
private readonly bool _sameFile;
private readonly bool isClassDeclarationSelection;
public TestExtractClassOptionsService(IEnumerable<(string name, bool makeAbstract)>? dialogSelection = null, bool sameFile = false, bool isClassDeclarationSelection = false)
{
_dialogSelection = dialogSelection;
_sameFile = sameFile;
this.isClassDeclarationSelection = isClassDeclarationSelection;
}
public string FileName { get; set; } = "MyBase.cs";
public string BaseName { get; set; } = "MyBase";
public Task<ExtractClassOptions?> GetExtractClassOptionsAsync(Document document, INamedTypeSymbol originalSymbol, ISymbol? selectedMember)
{
var availableMembers = originalSymbol.GetMembers().Where(member => MemberAndDestinationValidator.IsMemberValid(member));
IEnumerable<(ISymbol member, bool makeAbstract)> selections;
if (_dialogSelection == null)
{
if (selectedMember is null)
{
Assert.True(isClassDeclarationSelection);
selections = availableMembers.Select(member => (member, makeAbstract: false));
}
else
{
Assert.False(isClassDeclarationSelection);
selections = new[] { (selectedMember, false) };
}
}
else
{
selections = _dialogSelection.Select(selection => (member: availableMembers.Single(symbol => symbol.Name == selection.name), selection.makeAbstract));
}
var memberAnalysis = selections.Select(s =>
new ExtractClassMemberAnalysisResult(
s.member,
s.makeAbstract))
.ToImmutableArray();
return Task.FromResult<ExtractClassOptions?>(new ExtractClassOptions(FileName, BaseName, _sameFile, memberAnalysis));
}
}
}
}
| 1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/EditorFeatures/CSharpTest/ExtractInterface/ExtractInterfaceTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.Editor.CSharp.ExtractInterface;
using Microsoft.CodeAnalysis.Editor.UnitTests;
using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions;
using Microsoft.CodeAnalysis.Editor.UnitTests.ExtractInterface;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.ExtractInterface;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Roslyn.Test.Utilities;
using Xunit;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ExtractInterface
{
public class ExtractInterfaceTests : AbstractExtractInterfaceTests
{
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_Invocation_CaretInMethod()
{
var markup = @"
using System;
class MyClass
{
public void Goo()
{
$$
}
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_Invocation_CaretAfterClassClosingBrace()
{
var markup = @"
using System;
class MyClass
{
public void Goo()
{
}
}$$";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_Invocation_CaretBeforeClassKeyword()
{
var markup = @"
using System;
$$class MyClass
{
public void Goo()
{
}
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_Invocation_FromInnerClass1()
{
var markup = @"
using System;
class MyClass
{
public void Goo()
{
}
class AnotherClass
{
$$public void Bar()
{
}
}
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "Bar");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_Invocation_FromInnerClass2()
{
var markup = @"
using System;
class MyClass
{
public void Goo()
{
}
$$class AnotherClass
{
public async Task Bar()
{
}
}
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "Bar");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_Invocation_FromOuterClass()
{
var markup = @"
using System;
class MyClass
{
public void Goo()
{
}$$
class AnotherClass
{
public async Task Bar()
{
}
}
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "Goo");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_Invocation_FromInterface()
{
var markup = @"
using System;
interface IMyInterface
{
$$void Goo();
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "Goo", expectedInterfaceName: "IMyInterface1");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_Invocation_FromStruct()
{
var markup = @"
using System;
struct SomeStruct
{
$$public void Goo() { }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "Goo", expectedInterfaceName: "ISomeStruct");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_Invocation_FromNamespace()
{
var markup = @"
using System;
namespace Ns$$
{
class MyClass
{
public async Task Goo() { }
}
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_ExtractableMembers_DoesNotIncludeFields()
{
var markup = @"
using System;
class MyClass
{
$$public int x;
public void Goo()
{
}
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "Goo");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_ExtractableMembers_IncludesPublicProperty_WithGetAndSet()
{
var markup = @"
using System;
class MyClass
{
$$public int Prop { get; set; }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "Prop");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterfaceAction_ExtractableMembers_IncludesPublicProperty_WithGetAndSet()
{
var markup = @"
class MyClass$$
{
public int Prop { get; set; }
}";
var expectedMarkup = @"
interface IMyClass
{
int Prop { get; set; }
}
class MyClass : IMyClass
{
public int Prop { get; set; }
}";
await TestExtractInterfaceCodeActionCSharpAsync(markup, expectedMarkup);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_ExtractableMembers_IncludesPublicProperty_WithGetAndPrivateSet()
{
var markup = @"
using System;
class MyClass
{
$$public int Prop { get; private set; }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "Prop");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_ExtractableMembers_IncludesPublicProperty_WithGet()
{
var markup = @"
using System;
class MyClass
{
$$public int Prop { get; }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "Prop");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_ExtractableMembers_ExcludesPublicProperty_WithPrivateGetAndPrivateSet()
{
var markup = @"
using System;
class MyClass
{
$$public int Prop { private get; private set; }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_ExtractableMembers_IncludesPublicIndexer()
{
var markup = @"
using System;
class MyClass
{
$$public int this[int x] { get { return 5; } set { } }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "this[]");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_ExtractableMembers_ExcludesInternalIndexer()
{
var markup = @"
using System;
class MyClass
{
$$internal int this[int x] { get { return 5; } set { } }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_ExtractableMembers_IncludesPublicMethod()
{
var markup = @"
using System;
class MyClass
{
$$public void M()
{
}
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "M");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_ExtractableMembers_ExcludesInternalMethod()
{
var markup = @"
using System;
class MyClass
{
$$internal void M()
{
}
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_ExtractableMembers_IncludesAbstractMethod()
{
var markup = @"
using System;
abstract class MyClass
{
$$public abstract void M();
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "M");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_ExtractableMembers_IncludesPublicEvent()
{
var markup = @"
using System;
class MyClass
{
$$public event Action MyEvent;
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "MyEvent");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_ExtractableMembers_ExcludesPrivateEvent()
{
var markup = @"
using System;
class MyClass
{
$$private event Action MyEvent;
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_DefaultInterfaceName_DoesNotConflictWithOtherTypeNames()
{
var markup = @"
using System;
class MyClass
{
$$public void Goo() { }
}
interface IMyClass { }
struct IMyClass1 { }
class IMyClass2 { }";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceName: "IMyClass3");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_NamespaceName_NoNamespace()
{
var markup = @"
using System;
class MyClass
{
$$public void Goo() { }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedNamespaceName: "");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_NamespaceName_SingleNamespace()
{
var markup = @"
using System;
namespace MyNamespace
{
class MyClass
{
$$public void Goo() { }
}
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedNamespaceName: "MyNamespace");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_NamespaceName_NestedNamespaces()
{
var markup = @"
using System;
namespace OuterNamespace
{
namespace InnerNamespace
{
class MyClass
{
$$public void Goo() { }
}
}
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedNamespaceName: "OuterNamespace.InnerNamespace");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_NamespaceName_NestedNamespaces_FileScopedNamespace1()
{
var markup = @"
using System;
namespace OuterNamespace
{
namespace InnerNamespace
{
class MyClass
{
$$public void Goo() { }
}
}
}";
using var testState = ExtractInterfaceTestState.Create(
markup, LanguageNames.CSharp,
parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp10),
options: new OptionsCollection(LanguageNames.CSharp)
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped, NotificationOption2.Silent }
});
var result = await testState.ExtractViaCommandAsync();
var interfaceDocument = result.UpdatedSolution.GetRequiredDocument(result.NavigationDocumentId);
var interfaceCode = (await interfaceDocument.GetTextAsync()).ToString();
Assert.Equal(@"namespace OuterNamespace.InnerNamespace;
interface IMyClass
{
void Goo();
}", interfaceCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_NamespaceName_NestedNamespaces_FileScopedNamespace2()
{
var markup = @"
using System;
namespace OuterNamespace
{
namespace InnerNamespace
{
class MyClass
{
$$public void Goo() { }
}
}
}";
using var testState = ExtractInterfaceTestState.Create(
markup, LanguageNames.CSharp,
parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9),
options: new OptionsCollection(LanguageNames.CSharp)
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped, NotificationOption2.Silent }
});
var result = await testState.ExtractViaCommandAsync();
var interfaceDocument = result.UpdatedSolution.GetRequiredDocument(result.NavigationDocumentId);
var interfaceCode = (await interfaceDocument.GetTextAsync()).ToString();
Assert.Equal(@"namespace OuterNamespace.InnerNamespace
{
interface IMyClass
{
void Goo();
}
}", interfaceCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_NamespaceName_NestedNamespaces_FileScopedNamespace3()
{
var markup = @"
using System;
namespace OuterNamespace
{
namespace InnerNamespace
{
class MyClass
{
$$public void Goo() { }
}
}
}";
using var testState = ExtractInterfaceTestState.Create(
markup, LanguageNames.CSharp,
parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp10),
options: new OptionsCollection(LanguageNames.CSharp)
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped, NotificationOption2.Silent }
});
var result = await testState.ExtractViaCommandAsync();
var interfaceDocument = result.UpdatedSolution.GetRequiredDocument(result.NavigationDocumentId);
var interfaceCode = (await interfaceDocument.GetTextAsync()).ToString();
Assert.Equal(@"namespace OuterNamespace.InnerNamespace
{
interface IMyClass
{
void Goo();
}
}", interfaceCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_ClassesImplementExtractedInterface()
{
var markup = @"using System;
class MyClass
{
$$public void Goo() { }
}";
var expectedCode = @"using System;
class MyClass : IMyClass
{
public void Goo() { }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: expectedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_StructsImplementExtractedInterface()
{
var markup = @"
using System;
struct MyStruct
{
$$public void Goo() { }
}";
var expectedCode = @"
using System;
struct MyStruct : IMyStruct
{
public void Goo() { }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: expectedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_InterfacesDoNotImplementExtractedInterface()
{
var markup = @"
using System;
interface MyInterface
{
$$void Goo();
}";
var expectedCode = @"
using System;
interface MyInterface
{
void Goo();
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: expectedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_Methods()
{
var markup = @"
using System;
abstract class MyClass$$
{
public void ExtractableMethod_Normal() { }
public void ExtractableMethod_ParameterTypes(System.Diagnostics.CorrelationManager x, Nullable<Int32> y = 7, string z = ""42"") { }
public abstract void ExtractableMethod_Abstract();
unsafe public void NotActuallyUnsafeMethod(int p) { }
unsafe public void UnsafeMethod(int *p) { }
}";
var expectedInterfaceCode = @"using System.Diagnostics;
interface IMyClass
{
void ExtractableMethod_Abstract();
void ExtractableMethod_Normal();
void ExtractableMethod_ParameterTypes(CorrelationManager x, int? y = 7, string z = ""42"");
void NotActuallyUnsafeMethod(int p);
unsafe void UnsafeMethod(int* p);
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_MethodsInRecord()
{
var markup = @"
abstract record R$$
{
public void M() { }
}";
var expectedInterfaceCode = @"interface IR
{
bool Equals(object obj);
bool Equals(R other);
int GetHashCode();
void M();
string ToString();
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_Events()
{
var markup = @"
using System;
abstract internal class MyClass$$
{
public event Action ExtractableEvent1;
public event Action<Nullable<Int32>> ExtractableEvent2;
}";
var expectedInterfaceCode = @"using System;
internal interface IMyClass
{
event Action ExtractableEvent1;
event Action<int?> ExtractableEvent2;
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_Properties()
{
var markup = @"
using System;
abstract class MyClass$$
{
public int ExtractableProp { get; set; }
public int ExtractableProp_GetOnly { get { return 1; } }
public int ExtractableProp_SetOnly { set { } }
public int ExtractableProp_SetPrivate { get; private set; }
public int ExtractableProp_GetPrivate { private get; set; }
public int ExtractableProp_SetInternal { get; internal set; }
public int ExtractableProp_GetInternal { internal get; set; }
unsafe public int NotActuallyUnsafeProp { get; set; }
unsafe public int* UnsafeProp { get; set; }
}";
var expectedInterfaceCode = @"interface IMyClass
{
int ExtractableProp { get; set; }
int ExtractableProp_GetOnly { get; }
int ExtractableProp_SetOnly { set; }
int ExtractableProp_SetPrivate { get; }
int ExtractableProp_GetPrivate { set; }
int ExtractableProp_SetInternal { get; }
int ExtractableProp_GetInternal { set; }
int NotActuallyUnsafeProp { get; set; }
unsafe int* UnsafeProp { get; set; }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_Indexers()
{
var markup = @"
using System;
abstract class MyClass$$
{
public int this[int x] { set { } }
public int this[string x] { get { return 1; } }
public int this[double x] { get { return 1; } set { } }
public int this[Nullable<Int32> x, string y = ""42""] { get { return 1; } set { } }
}";
var expectedInterfaceCode = @"interface IMyClass
{
int this[int x] { set; }
int this[string x] { get; }
int this[double x] { get; set; }
int this[int? x, string y = ""42""] { get; set; }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_Imports()
{
var markup = @"
public class Class
{
$$public System.Diagnostics.BooleanSwitch M1(System.Globalization.Calendar x) { return null; }
public void M2(System.Collections.Generic.List<System.IO.BinaryWriter> x) { }
public void M3<T>() where T : System.Net.WebProxy { }
}";
var expectedInterfaceCode = @"using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
public interface IClass
{
BooleanSwitch M1(Calendar x);
void M2(List<BinaryWriter> x);
void M3<T>() where T : WebProxy;
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_TypeParameters1()
{
var markup = @"
public class Class<A, B, C, D, E, F, G, H, NO1> where E : F
{
$$public void Goo1(A a) { }
public B Goo2() { return default(B); }
public void Goo3(List<C> list) { }
public event Func<D> Goo4;
public List<E> Prop { set { } }
public List<G> this[List<List<H>> list] { set { } }
public void Bar1() { var x = default(NO1); }
}";
var expectedInterfaceCode = @"public interface IClass<A, B, C, D, E, F, G, H> where E : F
{
List<G> this[List<List<H>> list] { set; }
List<E> Prop { set; }
event Func<D> Goo4;
void Bar1();
void Goo1(A a);
B Goo2();
void Goo3(List<C> list);
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode);
}
[WorkItem(706894, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/706894")]
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_TypeParameters2()
{
var markup = @"using System.Collections.Generic;
class Program<A, B, C, D, E> where A : List<B> where B : Dictionary<List<D>, List<E>>
{
$$public void Goo<T>(T t) where T : List<A> { }
}";
var expectedInterfaceCode = @"using System.Collections.Generic;
interface IProgram<A, B, D, E>
where A : List<B>
where B : Dictionary<List<D>, List<E>>
{
void Goo<T>(T t) where T : List<A>;
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_TypeParameters3()
{
var markup = @"
class $$Class1<A, B>
{
public void method(A P1, Class2 P2)
{
}
public class Class2
{
}
}";
var expectedInterfaceCode = @"interface IClass1<A, B>
{
void method(A P1, Class1<A, B>.Class2 P2);
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode);
}
[WorkItem(706894, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/706894")]
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_TypeParameters4()
{
var markup = @"
class C1<A>
{
public class C2<B> where B : new()
{
public class C3<C> where C : System.Collections.ICollection
{
public class C4
{$$
public A method() { return default(A); }
public B property { set { } }
public C this[int i] { get { return default(C); } }
}
}
}
}";
var expectedInterfaceCode = @"using System.Collections;
public interface IC4<A, B, C>
where B : new()
where C : ICollection
{
C this[int i] { get; }
B property { set; }
A method();
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_BaseList_NewBaseListNonGeneric()
{
var markup = @"
class Program
{
$$public void Goo() { }
}";
var expectedCode = @"
class Program : IProgram
{
public void Goo() { }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: expectedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_BaseList_NewBaseListGeneric()
{
var markup = @"
class Program<T>
{
$$public void Goo(T t) { }
}";
var expectedCode = @"
class Program<T> : IProgram<T>
{
public void Goo(T t) { }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: expectedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_BaseList_NewBaseListWithWhereClause()
{
var markup = @"
class Program<T, U> where T : U
{
$$public void Goo(T t, U u) { }
}";
var expectedCode = @"
class Program<T, U> : IProgram<T, U> where T : U
{
public void Goo(T t, U u) { }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: expectedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_BaseList_LargerBaseList1()
{
var markup = @"
class Program : ISomeInterface
{
$$public void Goo() { }
}
interface ISomeInterface {}";
var expectedCode = @"
class Program : ISomeInterface, IProgram
{
public void Goo() { }
}
interface ISomeInterface {}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: expectedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_BaseList_LargerBaseList2()
{
var markup = @"
class Program<T, U> : ISomeInterface<T>
{
$$public void Goo(T t, U u) { }
}
interface ISomeInterface<T> {}";
var expectedCode = @"
class Program<T, U> : ISomeInterface<T>, IProgram<T, U>
{
public void Goo(T t, U u) { }
}
interface ISomeInterface<T> {}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: expectedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_BaseList_LargerBaseList3()
{
var markup = @"
class Program<T, U> : ISomeInterface<T>, ISomeInterface2<T, U>
{
$$public void Goo(T t, U u) { }
}
interface ISomeInterface<T> {}
interface ISomeInterface2<T, U> {}";
var expectedCode = @"
class Program<T, U> : ISomeInterface<T>, ISomeInterface2<T, U>, IProgram<T, U>
{
public void Goo(T t, U u) { }
}
interface ISomeInterface<T> {}
interface ISomeInterface2<T, U> {}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: expectedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_BaseList_LargerBaseList4()
{
var markup = @"
class Program<T, U> : ISomeInterface<T>, ISomeInterface2<T, U> where T : U
{
$$public void Goo(T t, U u) { }
}
interface ISomeInterface<T> {}
interface ISomeInterface2<T, U> {}";
var expectedCode = @"
class Program<T, U> : ISomeInterface<T>, ISomeInterface2<T, U>, IProgram<T, U> where T : U
{
public void Goo(T t, U u) { }
}
interface ISomeInterface<T> {}
interface ISomeInterface2<T, U> {}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: expectedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_TypeDiscovery_NameOnly1()
{
var markup = @"
interface ISomeInterface<T> {}
class Program<T, U> : ISomeInterface<T> where T : U
{
$$public void Goo(T t, U u) { }
}";
await TestTypeDiscoveryAsync(markup, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_TypeDiscovery_NameOnly2()
{
var markup = @"
interface ISomeInterface<T> {}
class Program<T, U> $$: ISomeInterface<T> where T : U
{
public void Goo(T t, U u) { }
}";
await TestTypeDiscoveryAsync(markup, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_TypeDiscovery_NameOnly3()
{
var markup = @"
interface ISomeInterface<T> {}
class$$ Program<T, U> : ISomeInterface<T> where T : U
{
public void Goo(T t, U u) { }
}";
await TestTypeDiscoveryAsync(markup, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_TypeDiscovery_NameOnly4()
{
var markup = @"
interface ISomeInterface<T> {}
class Program<T, U>$$ : ISomeInterface<T> where T : U
{
public void Goo(T t, U u) { }
}";
await TestTypeDiscoveryAsync(markup, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_TypeDiscovery_NameOnly5()
{
var markup = @"
interface ISomeInterface<T> {}
class Program $$ <T, U> : ISomeInterface<T> where T : U
{
public void Goo(T t, U u) { }
}";
await TestTypeDiscoveryAsync(markup, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_TypeDiscovery_NameOnly6()
{
var markup = @"
interface ISomeInterface<T> {}
class $$Program <T, U> : ISomeInterface<T> where T : U
{
public void Goo(T t, U u) { }
}";
await TestTypeDiscoveryAsync(markup, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_TypeDiscovery_NameOnly7()
{
var markup = @"
interface ISomeInterface<T> {}
class $$Program : ISomeInterface<object>
{
public void Goo() { }
}";
await TestTypeDiscoveryAsync(markup, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_TypeDiscovery_NameOnly8()
{
var markup = @"
interface ISomeInterface<T> {}
class Program$$ : ISomeInterface<object>
{
public void Goo() { }
}";
await TestTypeDiscoveryAsync(markup, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_TypeDiscovery_NameOnly9()
{
var markup = @"
interface ISomeInterface<T> {}
class$$ Program : ISomeInterface<object>
{
public void Goo() { }
}";
await TestTypeDiscoveryAsync(markup, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_TypeDiscovery_NameOnly10()
{
var markup = @"
interface ISomeInterface<T> {}
class Program $$: ISomeInterface<object>
{
public void Goo() { }
}";
await TestTypeDiscoveryAsync(markup, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: false);
}
private static async Task TestTypeDiscoveryAsync(
string markup,
TypeDiscoveryRule typeDiscoveryRule,
bool expectedExtractable)
{
using var testState = ExtractInterfaceTestState.Create(markup, LanguageNames.CSharp, compilationOptions: null);
var result = await testState.GetTypeAnalysisResultAsync(typeDiscoveryRule);
Assert.Equal(expectedExtractable, result.CanExtractInterface);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_GeneratedNameTypeParameterSuffix1()
{
var markup = @"
class $$Test<T>
{
public void M(T a) { }
}";
var expectedTypeParameterSuffix = @"<T>";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedTypeParameterSuffix: expectedTypeParameterSuffix);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_GeneratedNameTypeParameterSuffix2()
{
var markup = @"
class $$Test<T, U>
{
public void M(T a) { }
}";
var expectedTypeParameterSuffix = @"<T>";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedTypeParameterSuffix: expectedTypeParameterSuffix);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_GeneratedNameTypeParameterSuffix3()
{
var markup = @"
class $$Test<T, U>
{
public void M(T a, U b) { }
}";
var expectedTypeParameterSuffix = @"<T, U>";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedTypeParameterSuffix: expectedTypeParameterSuffix);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.ExtractInterface)]
[Trait(Traits.Feature, Traits.Features.Interactive)]
public void ExtractInterfaceCommandDisabledInSubmission()
{
using var workspace = TestWorkspace.Create(XElement.Parse(@"
<Workspace>
<Submission Language=""C#"" CommonReferences=""true"">
public class $$C
{
public void M() { }
}
</Submission>
</Workspace> "),
workspaceKind: WorkspaceKind.Interactive,
composition: EditorTestCompositions.EditorFeaturesWpf);
// Force initialization.
workspace.GetOpenDocumentIds().Select(id => workspace.GetTestDocument(id).GetTextView()).ToList();
var textView = workspace.Documents.Single().GetTextView();
var handler = workspace.ExportProvider.GetCommandHandler<ExtractInterfaceCommandHandler>(PredefinedCommandHandlerNames.ExtractInterface, ContentTypeNames.CSharpContentType);
var state = handler.GetCommandState(new ExtractInterfaceCommandArgs(textView, textView.TextBuffer));
Assert.True(state.IsUnspecified);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task TestInWithMethod_Parameters()
{
var markup = @"
using System;
class $$TestClass
{
public void Method(in int p1)
{
}
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode:
@"interface ITestClass
{
void Method(in int p1);
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task TestRefReadOnlyWithMethod_ReturnType()
{
var markup = @"
using System;
class $$TestClass
{
public ref readonly int Method() => throw null;
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode:
@"interface ITestClass
{
ref readonly int Method();
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task TestRefReadOnlyWithProperty()
{
var markup = @"
using System;
class $$TestClass
{
public ref readonly int Property => throw null;
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode:
@"interface ITestClass
{
ref readonly int Property { get; }
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task TestInWithIndexer_Parameters()
{
var markup = @"
using System;
class $$TestClass
{
public int this[in int p1] { set { } }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode:
@"interface ITestClass
{
int this[in int p1] { set; }
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task TestRefReadOnlyWithIndexer_ReturnType()
{
var markup = @"
using System;
class $$TestClass
{
public ref readonly int this[int p1] => throw null;
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode:
@"interface ITestClass
{
ref readonly int this[int p1] { get; }
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task TestUnmanagedConstraint_Type()
{
var markup = @"
class $$TestClass<T> where T : unmanaged
{
public void M(T arg) => throw null;
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode:
@"interface ITestClass<T> where T : unmanaged
{
void M(T arg);
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task TestUnmanagedConstraint_Method()
{
var markup = @"
class $$TestClass
{
public void M<T>() where T : unmanaged => throw null;
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode:
@"interface ITestClass
{
void M<T>() where T : unmanaged;
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task TestNotNullConstraint_Type()
{
var markup = @"
class $$TestClass<T> where T : notnull
{
public void M(T arg) => throw null;
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode:
@"interface ITestClass<T> where T : notnull
{
void M(T arg);
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task TestNotNullConstraint_Method()
{
var markup = @"
class $$TestClass
{
public void M<T>() where T : notnull => throw null;
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode:
@"interface ITestClass
{
void M<T>() where T : notnull;
}");
}
[WorkItem(23855, "https://github.com/dotnet/roslyn/issues/23855")]
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task TestExtractInterface_WithCopyright1()
{
var markup =
@"// Copyright
public class $$Goo
{
public void Test()
{
}
}";
var updatedMarkup =
@"// Copyright
public class Goo : IGoo
{
public void Test()
{
}
}";
var expectedInterfaceCode =
@"// Copyright
public interface IGoo
{
void Test();
}";
await TestExtractInterfaceCommandCSharpAsync(
markup,
expectedSuccess: true,
expectedUpdatedOriginalDocumentCode: updatedMarkup,
expectedInterfaceCode: expectedInterfaceCode);
}
[WorkItem(23855, "https://github.com/dotnet/roslyn/issues/23855")]
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task TestExtractInterface_WithCopyright2()
{
var markup =
@"// Copyright
public class Goo
{
public class $$A
{
public void Test()
{
}
}
}";
var updatedMarkup =
@"// Copyright
public class Goo
{
public class A : IA
{
public void Test()
{
}
}
}";
var expectedInterfaceCode =
@"// Copyright
public interface IA
{
void Test();
}";
await TestExtractInterfaceCommandCSharpAsync(
markup,
expectedSuccess: true,
expectedUpdatedOriginalDocumentCode: updatedMarkup,
expectedInterfaceCode: expectedInterfaceCode);
}
[WorkItem(49739, "https://github.com/dotnet/roslyn/issues/49739")]
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task TestRecord1()
{
var markup =
@"namespace Test
{
record $$Whatever(int X, string Y);
}";
var updatedMarkup =
@"namespace Test
{
record Whatever(int X, string Y) : IWhatever;
}";
var expectedInterfaceCode =
@"namespace Test
{
interface IWhatever
{
int X { get; init; }
string Y { get; init; }
void Deconstruct(out int X, out string Y);
bool Equals(object obj);
bool Equals(Whatever other);
int GetHashCode();
string ToString();
}
}";
await TestExtractInterfaceCommandCSharpAsync(
markup,
expectedSuccess: true,
expectedUpdatedOriginalDocumentCode: updatedMarkup,
expectedInterfaceCode: expectedInterfaceCode);
}
[WorkItem(49739, "https://github.com/dotnet/roslyn/issues/49739")]
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task TestRecord2()
{
var markup =
@"namespace Test
{
record $$Whatever(int X, string Y) { }
}";
var updatedMarkup =
@"namespace Test
{
record Whatever(int X, string Y) : IWhatever { }
}";
var expectedInterfaceCode =
@"namespace Test
{
interface IWhatever
{
int X { get; init; }
string Y { get; init; }
void Deconstruct(out int X, out string Y);
bool Equals(object obj);
bool Equals(Whatever other);
int GetHashCode();
string ToString();
}
}";
await TestExtractInterfaceCommandCSharpAsync(
markup,
expectedSuccess: true,
expectedUpdatedOriginalDocumentCode: updatedMarkup,
expectedInterfaceCode: expectedInterfaceCode);
}
[WorkItem(49739, "https://github.com/dotnet/roslyn/issues/49739")]
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task TestRecord3()
{
var markup =
@"namespace Test
{
/// <summary></summary>
record $$Whatever(int X, string Y);
}";
var updatedMarkup =
@"namespace Test
{
/// <summary></summary>
record Whatever(int X, string Y) : IWhatever;
}";
var expectedInterfaceCode =
@"namespace Test
{
interface IWhatever
{
int X { get; init; }
string Y { get; init; }
void Deconstruct(out int X, out string Y);
bool Equals(object obj);
bool Equals(Whatever other);
int GetHashCode();
string ToString();
}
}";
await TestExtractInterfaceCommandCSharpAsync(
markup,
expectedSuccess: true,
expectedUpdatedOriginalDocumentCode: updatedMarkup,
expectedInterfaceCode: expectedInterfaceCode);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.Editor.CSharp.ExtractInterface;
using Microsoft.CodeAnalysis.Editor.UnitTests;
using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions;
using Microsoft.CodeAnalysis.Editor.UnitTests.ExtractInterface;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.ExtractInterface;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Roslyn.Test.Utilities;
using Xunit;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ExtractInterface
{
public class ExtractInterfaceTests : AbstractExtractInterfaceTests
{
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_Invocation_CaretInMethod()
{
var markup = @"
using System;
class MyClass
{
public void Goo()
{
$$
}
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_Invocation_CaretAfterClassClosingBrace()
{
var markup = @"
using System;
class MyClass
{
public void Goo()
{
}
}$$";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_Invocation_CaretBeforeClassKeyword()
{
var markup = @"
using System;
$$class MyClass
{
public void Goo()
{
}
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_Invocation_FromInnerClass1()
{
var markup = @"
using System;
class MyClass
{
public void Goo()
{
}
class AnotherClass
{
$$public void Bar()
{
}
}
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "Bar");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_Invocation_FromInnerClass2()
{
var markup = @"
using System;
class MyClass
{
public void Goo()
{
}
$$class AnotherClass
{
public async Task Bar()
{
}
}
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "Bar");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_Invocation_FromOuterClass()
{
var markup = @"
using System;
class MyClass
{
public void Goo()
{
}$$
class AnotherClass
{
public async Task Bar()
{
}
}
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "Goo");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_Invocation_FromInterface()
{
var markup = @"
using System;
interface IMyInterface
{
$$void Goo();
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "Goo", expectedInterfaceName: "IMyInterface1");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_Invocation_FromStruct()
{
var markup = @"
using System;
struct SomeStruct
{
$$public void Goo() { }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "Goo", expectedInterfaceName: "ISomeStruct");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_Invocation_FromNamespace()
{
var markup = @"
using System;
namespace Ns$$
{
class MyClass
{
public async Task Goo() { }
}
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_ExtractableMembers_DoesNotIncludeFields()
{
var markup = @"
using System;
class MyClass
{
$$public int x;
public void Goo()
{
}
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "Goo");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_ExtractableMembers_IncludesPublicProperty_WithGetAndSet()
{
var markup = @"
using System;
class MyClass
{
$$public int Prop { get; set; }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "Prop");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterfaceAction_ExtractableMembers_IncludesPublicProperty_WithGetAndSet()
{
var markup = @"
class MyClass$$
{
public int Prop { get; set; }
}";
var expectedMarkup = @"
interface IMyClass
{
int Prop { get; set; }
}
class MyClass : IMyClass
{
public int Prop { get; set; }
}";
await TestExtractInterfaceCodeActionCSharpAsync(markup, expectedMarkup);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_ExtractableMembers_IncludesPublicProperty_WithGetAndPrivateSet()
{
var markup = @"
using System;
class MyClass
{
$$public int Prop { get; private set; }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "Prop");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_ExtractableMembers_IncludesPublicProperty_WithGet()
{
var markup = @"
using System;
class MyClass
{
$$public int Prop { get; }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "Prop");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_ExtractableMembers_ExcludesPublicProperty_WithPrivateGetAndPrivateSet()
{
var markup = @"
using System;
class MyClass
{
$$public int Prop { private get; private set; }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_ExtractableMembers_IncludesPublicIndexer()
{
var markup = @"
using System;
class MyClass
{
$$public int this[int x] { get { return 5; } set { } }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "this[]");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_ExtractableMembers_ExcludesInternalIndexer()
{
var markup = @"
using System;
class MyClass
{
$$internal int this[int x] { get { return 5; } set { } }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_ExtractableMembers_IncludesPublicMethod()
{
var markup = @"
using System;
class MyClass
{
$$public void M()
{
}
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "M");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_ExtractableMembers_ExcludesInternalMethod()
{
var markup = @"
using System;
class MyClass
{
$$internal void M()
{
}
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_ExtractableMembers_IncludesAbstractMethod()
{
var markup = @"
using System;
abstract class MyClass
{
$$public abstract void M();
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "M");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_ExtractableMembers_IncludesPublicEvent()
{
var markup = @"
using System;
class MyClass
{
$$public event Action MyEvent;
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedMemberName: "MyEvent");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_ExtractableMembers_ExcludesPrivateEvent()
{
var markup = @"
using System;
class MyClass
{
$$private event Action MyEvent;
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_DefaultInterfaceName_DoesNotConflictWithOtherTypeNames()
{
var markup = @"
using System;
class MyClass
{
$$public void Goo() { }
}
interface IMyClass { }
struct IMyClass1 { }
class IMyClass2 { }";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceName: "IMyClass3");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_NamespaceName_NoNamespace()
{
var markup = @"
using System;
class MyClass
{
$$public void Goo() { }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedNamespaceName: "");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_NamespaceName_SingleNamespace()
{
var markup = @"
using System;
namespace MyNamespace
{
class MyClass
{
$$public void Goo() { }
}
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedNamespaceName: "MyNamespace");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_NamespaceName_NestedNamespaces()
{
var markup = @"
using System;
namespace OuterNamespace
{
namespace InnerNamespace
{
class MyClass
{
$$public void Goo() { }
}
}
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedNamespaceName: "OuterNamespace.InnerNamespace");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_NamespaceName_NestedNamespaces_FileScopedNamespace1()
{
var markup = @"
using System;
namespace OuterNamespace
{
namespace InnerNamespace
{
class MyClass
{
$$public void Goo() { }
}
}
}";
using var testState = ExtractInterfaceTestState.Create(
markup, LanguageNames.CSharp,
parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp10),
options: new OptionsCollection(LanguageNames.CSharp)
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped, NotificationOption2.Silent }
});
var result = await testState.ExtractViaCommandAsync();
var interfaceDocument = result.UpdatedSolution.GetRequiredDocument(result.NavigationDocumentId);
var interfaceCode = (await interfaceDocument.GetTextAsync()).ToString();
Assert.Equal(@"namespace OuterNamespace.InnerNamespace;
internal interface IMyClass
{
void Goo();
}", interfaceCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_NamespaceName_NestedNamespaces_FileScopedNamespace2()
{
var markup = @"
using System;
namespace OuterNamespace
{
namespace InnerNamespace
{
class MyClass
{
$$public void Goo() { }
}
}
}";
using var testState = ExtractInterfaceTestState.Create(
markup, LanguageNames.CSharp,
parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9),
options: new OptionsCollection(LanguageNames.CSharp)
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped, NotificationOption2.Silent }
});
var result = await testState.ExtractViaCommandAsync();
var interfaceDocument = result.UpdatedSolution.GetRequiredDocument(result.NavigationDocumentId);
var interfaceCode = (await interfaceDocument.GetTextAsync()).ToString();
Assert.Equal(@"namespace OuterNamespace.InnerNamespace
{
internal interface IMyClass
{
void Goo();
}
}", interfaceCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_NamespaceName_NestedNamespaces_FileScopedNamespace3()
{
var markup = @"
using System;
namespace OuterNamespace
{
namespace InnerNamespace
{
class MyClass
{
$$public void Goo() { }
}
}
}";
using var testState = ExtractInterfaceTestState.Create(
markup, LanguageNames.CSharp,
parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp10),
options: new OptionsCollection(LanguageNames.CSharp)
{
{ CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped, NotificationOption2.Silent }
});
var result = await testState.ExtractViaCommandAsync();
var interfaceDocument = result.UpdatedSolution.GetRequiredDocument(result.NavigationDocumentId);
var interfaceCode = (await interfaceDocument.GetTextAsync()).ToString();
Assert.Equal(@"namespace OuterNamespace.InnerNamespace
{
internal interface IMyClass
{
void Goo();
}
}", interfaceCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_ClassesImplementExtractedInterface()
{
var markup = @"using System;
class MyClass
{
$$public void Goo() { }
}";
var expectedCode = @"using System;
class MyClass : IMyClass
{
public void Goo() { }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: expectedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_StructsImplementExtractedInterface()
{
var markup = @"
using System;
struct MyStruct
{
$$public void Goo() { }
}";
var expectedCode = @"
using System;
struct MyStruct : IMyStruct
{
public void Goo() { }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: expectedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_InterfacesDoNotImplementExtractedInterface()
{
var markup = @"
using System;
interface MyInterface
{
$$void Goo();
}";
var expectedCode = @"
using System;
interface MyInterface
{
void Goo();
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: expectedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_Methods()
{
var markup = @"
using System;
abstract class MyClass$$
{
public void ExtractableMethod_Normal() { }
public void ExtractableMethod_ParameterTypes(System.Diagnostics.CorrelationManager x, Nullable<Int32> y = 7, string z = ""42"") { }
public abstract void ExtractableMethod_Abstract();
unsafe public void NotActuallyUnsafeMethod(int p) { }
unsafe public void UnsafeMethod(int *p) { }
}";
var expectedInterfaceCode = @"using System.Diagnostics;
interface IMyClass
{
void ExtractableMethod_Abstract();
void ExtractableMethod_Normal();
void ExtractableMethod_ParameterTypes(CorrelationManager x, int? y = 7, string z = ""42"");
void NotActuallyUnsafeMethod(int p);
unsafe void UnsafeMethod(int* p);
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_MethodsInRecord()
{
var markup = @"
abstract record R$$
{
public void M() { }
}";
var expectedInterfaceCode = @"interface IR
{
bool Equals(object obj);
bool Equals(R other);
int GetHashCode();
void M();
string ToString();
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_Events()
{
var markup = @"
using System;
abstract internal class MyClass$$
{
public event Action ExtractableEvent1;
public event Action<Nullable<Int32>> ExtractableEvent2;
}";
var expectedInterfaceCode = @"using System;
internal interface IMyClass
{
event Action ExtractableEvent1;
event Action<int?> ExtractableEvent2;
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_Properties()
{
var markup = @"
using System;
abstract class MyClass$$
{
public int ExtractableProp { get; set; }
public int ExtractableProp_GetOnly { get { return 1; } }
public int ExtractableProp_SetOnly { set { } }
public int ExtractableProp_SetPrivate { get; private set; }
public int ExtractableProp_GetPrivate { private get; set; }
public int ExtractableProp_SetInternal { get; internal set; }
public int ExtractableProp_GetInternal { internal get; set; }
unsafe public int NotActuallyUnsafeProp { get; set; }
unsafe public int* UnsafeProp { get; set; }
}";
var expectedInterfaceCode = @"interface IMyClass
{
int ExtractableProp { get; set; }
int ExtractableProp_GetOnly { get; }
int ExtractableProp_SetOnly { set; }
int ExtractableProp_SetPrivate { get; }
int ExtractableProp_GetPrivate { set; }
int ExtractableProp_SetInternal { get; }
int ExtractableProp_GetInternal { set; }
int NotActuallyUnsafeProp { get; set; }
unsafe int* UnsafeProp { get; set; }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_Indexers()
{
var markup = @"
using System;
abstract class MyClass$$
{
public int this[int x] { set { } }
public int this[string x] { get { return 1; } }
public int this[double x] { get { return 1; } set { } }
public int this[Nullable<Int32> x, string y = ""42""] { get { return 1; } set { } }
}";
var expectedInterfaceCode = @"interface IMyClass
{
int this[int x] { set; }
int this[string x] { get; }
int this[double x] { get; set; }
int this[int? x, string y = ""42""] { get; set; }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_Imports()
{
var markup = @"
public class Class
{
$$public System.Diagnostics.BooleanSwitch M1(System.Globalization.Calendar x) { return null; }
public void M2(System.Collections.Generic.List<System.IO.BinaryWriter> x) { }
public void M3<T>() where T : System.Net.WebProxy { }
}";
var expectedInterfaceCode = @"using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
public interface IClass
{
BooleanSwitch M1(Calendar x);
void M2(List<BinaryWriter> x);
void M3<T>() where T : WebProxy;
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_TypeParameters1()
{
var markup = @"
public class Class<A, B, C, D, E, F, G, H, NO1> where E : F
{
$$public void Goo1(A a) { }
public B Goo2() { return default(B); }
public void Goo3(List<C> list) { }
public event Func<D> Goo4;
public List<E> Prop { set { } }
public List<G> this[List<List<H>> list] { set { } }
public void Bar1() { var x = default(NO1); }
}";
var expectedInterfaceCode = @"public interface IClass<A, B, C, D, E, F, G, H> where E : F
{
List<G> this[List<List<H>> list] { set; }
List<E> Prop { set; }
event Func<D> Goo4;
void Bar1();
void Goo1(A a);
B Goo2();
void Goo3(List<C> list);
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode);
}
[WorkItem(706894, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/706894")]
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_TypeParameters2()
{
var markup = @"using System.Collections.Generic;
class Program<A, B, C, D, E> where A : List<B> where B : Dictionary<List<D>, List<E>>
{
$$public void Goo<T>(T t) where T : List<A> { }
}";
var expectedInterfaceCode = @"using System.Collections.Generic;
interface IProgram<A, B, D, E>
where A : List<B>
where B : Dictionary<List<D>, List<E>>
{
void Goo<T>(T t) where T : List<A>;
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_TypeParameters3()
{
var markup = @"
class $$Class1<A, B>
{
public void method(A P1, Class2 P2)
{
}
public class Class2
{
}
}";
var expectedInterfaceCode = @"interface IClass1<A, B>
{
void method(A P1, Class1<A, B>.Class2 P2);
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode);
}
[WorkItem(706894, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/706894")]
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_TypeParameters4()
{
var markup = @"
class C1<A>
{
public class C2<B> where B : new()
{
public class C3<C> where C : System.Collections.ICollection
{
public class C4
{$$
public A method() { return default(A); }
public B property { set { } }
public C this[int i] { get { return default(C); } }
}
}
}
}";
var expectedInterfaceCode = @"using System.Collections;
public interface IC4<A, B, C>
where B : new()
where C : ICollection
{
C this[int i] { get; }
B property { set; }
A method();
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode: expectedInterfaceCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_AccessibilityModifiers()
{
var markup = @"
using System;
abstract class MyClass$$
{
public void Goo() { }
}";
using var testState = ExtractInterfaceTestState.Create(
markup, LanguageNames.CSharp,
options: new OptionsCollection(LanguageNames.CSharp)
{
{ CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.Always, NotificationOption2.Silent }
});
var result = await testState.ExtractViaCommandAsync();
var interfaceDocument = result.UpdatedSolution.GetRequiredDocument(result.NavigationDocumentId);
var interfaceCode = (await interfaceDocument.GetTextAsync()).ToString();
Assert.Equal(@"internal interface IMyClass
{
void Goo();
}", interfaceCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_BaseList_NewBaseListNonGeneric()
{
var markup = @"
class Program
{
$$public void Goo() { }
}";
var expectedCode = @"
class Program : IProgram
{
public void Goo() { }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: expectedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_BaseList_NewBaseListGeneric()
{
var markup = @"
class Program<T>
{
$$public void Goo(T t) { }
}";
var expectedCode = @"
class Program<T> : IProgram<T>
{
public void Goo(T t) { }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: expectedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_BaseList_NewBaseListWithWhereClause()
{
var markup = @"
class Program<T, U> where T : U
{
$$public void Goo(T t, U u) { }
}";
var expectedCode = @"
class Program<T, U> : IProgram<T, U> where T : U
{
public void Goo(T t, U u) { }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: expectedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_BaseList_LargerBaseList1()
{
var markup = @"
class Program : ISomeInterface
{
$$public void Goo() { }
}
interface ISomeInterface {}";
var expectedCode = @"
class Program : ISomeInterface, IProgram
{
public void Goo() { }
}
interface ISomeInterface {}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: expectedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_BaseList_LargerBaseList2()
{
var markup = @"
class Program<T, U> : ISomeInterface<T>
{
$$public void Goo(T t, U u) { }
}
interface ISomeInterface<T> {}";
var expectedCode = @"
class Program<T, U> : ISomeInterface<T>, IProgram<T, U>
{
public void Goo(T t, U u) { }
}
interface ISomeInterface<T> {}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: expectedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_BaseList_LargerBaseList3()
{
var markup = @"
class Program<T, U> : ISomeInterface<T>, ISomeInterface2<T, U>
{
$$public void Goo(T t, U u) { }
}
interface ISomeInterface<T> {}
interface ISomeInterface2<T, U> {}";
var expectedCode = @"
class Program<T, U> : ISomeInterface<T>, ISomeInterface2<T, U>, IProgram<T, U>
{
public void Goo(T t, U u) { }
}
interface ISomeInterface<T> {}
interface ISomeInterface2<T, U> {}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: expectedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_CodeGen_BaseList_LargerBaseList4()
{
var markup = @"
class Program<T, U> : ISomeInterface<T>, ISomeInterface2<T, U> where T : U
{
$$public void Goo(T t, U u) { }
}
interface ISomeInterface<T> {}
interface ISomeInterface2<T, U> {}";
var expectedCode = @"
class Program<T, U> : ISomeInterface<T>, ISomeInterface2<T, U>, IProgram<T, U> where T : U
{
public void Goo(T t, U u) { }
}
interface ISomeInterface<T> {}
interface ISomeInterface2<T, U> {}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedUpdatedOriginalDocumentCode: expectedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_TypeDiscovery_NameOnly1()
{
var markup = @"
interface ISomeInterface<T> {}
class Program<T, U> : ISomeInterface<T> where T : U
{
$$public void Goo(T t, U u) { }
}";
await TestTypeDiscoveryAsync(markup, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_TypeDiscovery_NameOnly2()
{
var markup = @"
interface ISomeInterface<T> {}
class Program<T, U> $$: ISomeInterface<T> where T : U
{
public void Goo(T t, U u) { }
}";
await TestTypeDiscoveryAsync(markup, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_TypeDiscovery_NameOnly3()
{
var markup = @"
interface ISomeInterface<T> {}
class$$ Program<T, U> : ISomeInterface<T> where T : U
{
public void Goo(T t, U u) { }
}";
await TestTypeDiscoveryAsync(markup, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_TypeDiscovery_NameOnly4()
{
var markup = @"
interface ISomeInterface<T> {}
class Program<T, U>$$ : ISomeInterface<T> where T : U
{
public void Goo(T t, U u) { }
}";
await TestTypeDiscoveryAsync(markup, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_TypeDiscovery_NameOnly5()
{
var markup = @"
interface ISomeInterface<T> {}
class Program $$ <T, U> : ISomeInterface<T> where T : U
{
public void Goo(T t, U u) { }
}";
await TestTypeDiscoveryAsync(markup, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_TypeDiscovery_NameOnly6()
{
var markup = @"
interface ISomeInterface<T> {}
class $$Program <T, U> : ISomeInterface<T> where T : U
{
public void Goo(T t, U u) { }
}";
await TestTypeDiscoveryAsync(markup, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_TypeDiscovery_NameOnly7()
{
var markup = @"
interface ISomeInterface<T> {}
class $$Program : ISomeInterface<object>
{
public void Goo() { }
}";
await TestTypeDiscoveryAsync(markup, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_TypeDiscovery_NameOnly8()
{
var markup = @"
interface ISomeInterface<T> {}
class Program$$ : ISomeInterface<object>
{
public void Goo() { }
}";
await TestTypeDiscoveryAsync(markup, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_TypeDiscovery_NameOnly9()
{
var markup = @"
interface ISomeInterface<T> {}
class$$ Program : ISomeInterface<object>
{
public void Goo() { }
}";
await TestTypeDiscoveryAsync(markup, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_TypeDiscovery_NameOnly10()
{
var markup = @"
interface ISomeInterface<T> {}
class Program $$: ISomeInterface<object>
{
public void Goo() { }
}";
await TestTypeDiscoveryAsync(markup, TypeDiscoveryRule.TypeNameOnly, expectedExtractable: false);
}
private static async Task TestTypeDiscoveryAsync(
string markup,
TypeDiscoveryRule typeDiscoveryRule,
bool expectedExtractable)
{
using var testState = ExtractInterfaceTestState.Create(markup, LanguageNames.CSharp, compilationOptions: null);
var result = await testState.GetTypeAnalysisResultAsync(typeDiscoveryRule);
Assert.Equal(expectedExtractable, result.CanExtractInterface);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_GeneratedNameTypeParameterSuffix1()
{
var markup = @"
class $$Test<T>
{
public void M(T a) { }
}";
var expectedTypeParameterSuffix = @"<T>";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedTypeParameterSuffix: expectedTypeParameterSuffix);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_GeneratedNameTypeParameterSuffix2()
{
var markup = @"
class $$Test<T, U>
{
public void M(T a) { }
}";
var expectedTypeParameterSuffix = @"<T>";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedTypeParameterSuffix: expectedTypeParameterSuffix);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task ExtractInterface_GeneratedNameTypeParameterSuffix3()
{
var markup = @"
class $$Test<T, U>
{
public void M(T a, U b) { }
}";
var expectedTypeParameterSuffix = @"<T, U>";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedTypeParameterSuffix: expectedTypeParameterSuffix);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.ExtractInterface)]
[Trait(Traits.Feature, Traits.Features.Interactive)]
public void ExtractInterfaceCommandDisabledInSubmission()
{
using var workspace = TestWorkspace.Create(XElement.Parse(@"
<Workspace>
<Submission Language=""C#"" CommonReferences=""true"">
public class $$C
{
public void M() { }
}
</Submission>
</Workspace> "),
workspaceKind: WorkspaceKind.Interactive,
composition: EditorTestCompositions.EditorFeaturesWpf);
// Force initialization.
workspace.GetOpenDocumentIds().Select(id => workspace.GetTestDocument(id).GetTextView()).ToList();
var textView = workspace.Documents.Single().GetTextView();
var handler = workspace.ExportProvider.GetCommandHandler<ExtractInterfaceCommandHandler>(PredefinedCommandHandlerNames.ExtractInterface, ContentTypeNames.CSharpContentType);
var state = handler.GetCommandState(new ExtractInterfaceCommandArgs(textView, textView.TextBuffer));
Assert.True(state.IsUnspecified);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task TestInWithMethod_Parameters()
{
var markup = @"
using System;
class $$TestClass
{
public void Method(in int p1)
{
}
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode:
@"interface ITestClass
{
void Method(in int p1);
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task TestRefReadOnlyWithMethod_ReturnType()
{
var markup = @"
using System;
class $$TestClass
{
public ref readonly int Method() => throw null;
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode:
@"interface ITestClass
{
ref readonly int Method();
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task TestRefReadOnlyWithProperty()
{
var markup = @"
using System;
class $$TestClass
{
public ref readonly int Property => throw null;
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode:
@"interface ITestClass
{
ref readonly int Property { get; }
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task TestInWithIndexer_Parameters()
{
var markup = @"
using System;
class $$TestClass
{
public int this[in int p1] { set { } }
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode:
@"interface ITestClass
{
int this[in int p1] { set; }
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task TestRefReadOnlyWithIndexer_ReturnType()
{
var markup = @"
using System;
class $$TestClass
{
public ref readonly int this[int p1] => throw null;
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode:
@"interface ITestClass
{
ref readonly int this[int p1] { get; }
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task TestUnmanagedConstraint_Type()
{
var markup = @"
class $$TestClass<T> where T : unmanaged
{
public void M(T arg) => throw null;
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode:
@"interface ITestClass<T> where T : unmanaged
{
void M(T arg);
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task TestUnmanagedConstraint_Method()
{
var markup = @"
class $$TestClass
{
public void M<T>() where T : unmanaged => throw null;
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode:
@"interface ITestClass
{
void M<T>() where T : unmanaged;
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task TestNotNullConstraint_Type()
{
var markup = @"
class $$TestClass<T> where T : notnull
{
public void M(T arg) => throw null;
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode:
@"interface ITestClass<T> where T : notnull
{
void M(T arg);
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task TestNotNullConstraint_Method()
{
var markup = @"
class $$TestClass
{
public void M<T>() where T : notnull => throw null;
}";
await TestExtractInterfaceCommandCSharpAsync(markup, expectedSuccess: true, expectedInterfaceCode:
@"interface ITestClass
{
void M<T>() where T : notnull;
}");
}
[WorkItem(23855, "https://github.com/dotnet/roslyn/issues/23855")]
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task TestExtractInterface_WithCopyright1()
{
var markup =
@"// Copyright
public class $$Goo
{
public void Test()
{
}
}";
var updatedMarkup =
@"// Copyright
public class Goo : IGoo
{
public void Test()
{
}
}";
var expectedInterfaceCode =
@"// Copyright
public interface IGoo
{
void Test();
}";
await TestExtractInterfaceCommandCSharpAsync(
markup,
expectedSuccess: true,
expectedUpdatedOriginalDocumentCode: updatedMarkup,
expectedInterfaceCode: expectedInterfaceCode);
}
[WorkItem(23855, "https://github.com/dotnet/roslyn/issues/23855")]
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task TestExtractInterface_WithCopyright2()
{
var markup =
@"// Copyright
public class Goo
{
public class $$A
{
public void Test()
{
}
}
}";
var updatedMarkup =
@"// Copyright
public class Goo
{
public class A : IA
{
public void Test()
{
}
}
}";
var expectedInterfaceCode =
@"// Copyright
public interface IA
{
void Test();
}";
await TestExtractInterfaceCommandCSharpAsync(
markup,
expectedSuccess: true,
expectedUpdatedOriginalDocumentCode: updatedMarkup,
expectedInterfaceCode: expectedInterfaceCode);
}
[WorkItem(49739, "https://github.com/dotnet/roslyn/issues/49739")]
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task TestRecord1()
{
var markup =
@"namespace Test
{
record $$Whatever(int X, string Y);
}";
var updatedMarkup =
@"namespace Test
{
record Whatever(int X, string Y) : IWhatever;
}";
var expectedInterfaceCode =
@"namespace Test
{
interface IWhatever
{
int X { get; init; }
string Y { get; init; }
void Deconstruct(out int X, out string Y);
bool Equals(object obj);
bool Equals(Whatever other);
int GetHashCode();
string ToString();
}
}";
await TestExtractInterfaceCommandCSharpAsync(
markup,
expectedSuccess: true,
expectedUpdatedOriginalDocumentCode: updatedMarkup,
expectedInterfaceCode: expectedInterfaceCode);
}
[WorkItem(49739, "https://github.com/dotnet/roslyn/issues/49739")]
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task TestRecord2()
{
var markup =
@"namespace Test
{
record $$Whatever(int X, string Y) { }
}";
var updatedMarkup =
@"namespace Test
{
record Whatever(int X, string Y) : IWhatever { }
}";
var expectedInterfaceCode =
@"namespace Test
{
interface IWhatever
{
int X { get; init; }
string Y { get; init; }
void Deconstruct(out int X, out string Y);
bool Equals(object obj);
bool Equals(Whatever other);
int GetHashCode();
string ToString();
}
}";
await TestExtractInterfaceCommandCSharpAsync(
markup,
expectedSuccess: true,
expectedUpdatedOriginalDocumentCode: updatedMarkup,
expectedInterfaceCode: expectedInterfaceCode);
}
[WorkItem(49739, "https://github.com/dotnet/roslyn/issues/49739")]
[WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)]
public async Task TestRecord3()
{
var markup =
@"namespace Test
{
/// <summary></summary>
record $$Whatever(int X, string Y);
}";
var updatedMarkup =
@"namespace Test
{
/// <summary></summary>
record Whatever(int X, string Y) : IWhatever;
}";
var expectedInterfaceCode =
@"namespace Test
{
interface IWhatever
{
int X { get; init; }
string Y { get; init; }
void Deconstruct(out int X, out string Y);
bool Equals(object obj);
bool Equals(Whatever other);
int GetHashCode();
string ToString();
}
}";
await TestExtractInterfaceCommandCSharpAsync(
markup,
expectedSuccess: true,
expectedUpdatedOriginalDocumentCode: updatedMarkup,
expectedInterfaceCode: expectedInterfaceCode);
}
}
}
| 1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/EditorFeatures/TestUtilities/ExtractInterface/AbstractExtractInterfaceTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.VisualBasic;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.ExtractInterface
{
[UseExportProvider]
public abstract class AbstractExtractInterfaceTests
{
public static async Task TestExtractInterfaceCommandCSharpAsync(
string markup,
bool expectedSuccess,
string expectedMemberName = null,
string expectedInterfaceName = null,
string expectedNamespaceName = null,
string expectedTypeParameterSuffix = null,
string expectedUpdatedOriginalDocumentCode = null,
string expectedInterfaceCode = null)
{
await TestExtractInterfaceCommandAsync(
markup,
LanguageNames.CSharp,
expectedSuccess,
expectedMemberName,
expectedInterfaceName,
expectedNamespaceName,
expectedTypeParameterSuffix,
expectedUpdatedOriginalDocumentCode,
expectedInterfaceCode);
}
public static async Task TestExtractInterfaceCodeActionCSharpAsync(
string markup,
string expectedMarkup)
{
await TestExtractInterfaceCodeActionAsync(
markup,
LanguageNames.CSharp,
expectedMarkup);
}
public static async Task TestExtractInterfaceCommandVisualBasicAsync(
string markup,
bool expectedSuccess,
string expectedMemberName = null,
string expectedInterfaceName = null,
string expectedNamespaceName = null,
string expectedTypeParameterSuffix = null,
string expectedUpdatedOriginalDocumentCode = null,
string expectedInterfaceCode = null,
string rootNamespace = null)
{
await TestExtractInterfaceCommandAsync(
markup,
LanguageNames.VisualBasic,
expectedSuccess,
expectedMemberName,
expectedInterfaceName,
expectedNamespaceName,
expectedTypeParameterSuffix,
expectedUpdatedOriginalDocumentCode,
expectedInterfaceCode,
new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, rootNamespace: rootNamespace));
}
public static async Task TestExtractInterfaceCodeActionVisualBasicAsync(
string markup,
string expectedMarkup)
{
await TestExtractInterfaceCodeActionAsync(
markup,
LanguageNames.VisualBasic,
expectedMarkup);
}
private static async Task TestExtractInterfaceCommandAsync(
string markup,
string languageName,
bool expectedSuccess,
string expectedMemberName = null,
string expectedInterfaceName = null,
string expectedNamespaceName = null,
string expectedTypeParameterSuffix = null,
string expectedUpdatedOriginalDocumentCode = null,
string expectedInterfaceCode = null,
CompilationOptions compilationOptions = null)
{
using var testState = ExtractInterfaceTestState.Create(markup, languageName, compilationOptions);
var result = await testState.ExtractViaCommandAsync();
if (expectedSuccess)
{
Assert.True(result.Succeeded);
Assert.False(testState.Workspace.Documents.Select(d => d.Id).Contains(result.NavigationDocumentId));
Assert.NotNull(result.UpdatedSolution.GetDocument(result.NavigationDocumentId));
if (expectedMemberName != null)
{
Assert.Equal(1, testState.TestExtractInterfaceOptionsService.AllExtractableMembers.Count());
Assert.Equal(expectedMemberName, testState.TestExtractInterfaceOptionsService.AllExtractableMembers.Single().Name);
}
if (expectedInterfaceName != null)
{
Assert.Equal(expectedInterfaceName, testState.TestExtractInterfaceOptionsService.DefaultInterfaceName);
}
if (expectedNamespaceName != null)
{
Assert.Equal(expectedNamespaceName, testState.TestExtractInterfaceOptionsService.DefaultNamespace);
}
if (expectedTypeParameterSuffix != null)
{
Assert.Equal(expectedTypeParameterSuffix, testState.TestExtractInterfaceOptionsService.GeneratedNameTypeParameterSuffix);
}
if (expectedUpdatedOriginalDocumentCode != null)
{
var updatedOriginalDocument = result.UpdatedSolution.GetDocument(testState.ExtractFromDocument.Id);
var updatedCode = (await updatedOriginalDocument.GetTextAsync()).ToString();
Assert.Equal(expectedUpdatedOriginalDocumentCode, updatedCode);
}
if (expectedInterfaceCode != null)
{
var interfaceDocument = result.UpdatedSolution.GetDocument(result.NavigationDocumentId);
var interfaceCode = (await interfaceDocument.GetTextAsync()).ToString();
Assert.Equal(expectedInterfaceCode, interfaceCode);
}
}
else
{
Assert.False(result.Succeeded);
}
}
private static async Task TestExtractInterfaceCodeActionAsync(
string markup,
string languageName,
string expectedMarkup,
CompilationOptions compilationOptions = null)
{
using var testState = ExtractInterfaceTestState.Create(markup, languageName, compilationOptions);
var updatedSolution = await testState.ExtractViaCodeAction();
var updatedDocument = updatedSolution.GetDocument(testState.ExtractFromDocument.Id);
var updatedCode = (await updatedDocument.GetTextAsync()).ToString();
Assert.Equal(expectedMarkup, updatedCode);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.VisualBasic;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.ExtractInterface
{
[UseExportProvider]
public abstract class AbstractExtractInterfaceTests
{
public static async Task TestExtractInterfaceCommandCSharpAsync(
string markup,
bool expectedSuccess,
string expectedMemberName = null,
string expectedInterfaceName = null,
string expectedNamespaceName = null,
string expectedTypeParameterSuffix = null,
string expectedUpdatedOriginalDocumentCode = null,
string expectedInterfaceCode = null)
{
await TestExtractInterfaceCommandAsync(
markup,
LanguageNames.CSharp,
expectedSuccess,
expectedMemberName,
expectedInterfaceName,
expectedNamespaceName,
expectedTypeParameterSuffix,
expectedUpdatedOriginalDocumentCode,
expectedInterfaceCode);
}
public static async Task TestExtractInterfaceCodeActionCSharpAsync(
string markup,
string expectedMarkup)
{
await TestExtractInterfaceCodeActionAsync(
markup,
LanguageNames.CSharp,
expectedMarkup);
}
public static async Task TestExtractInterfaceCommandVisualBasicAsync(
string markup,
bool expectedSuccess,
string expectedMemberName = null,
string expectedInterfaceName = null,
string expectedNamespaceName = null,
string expectedTypeParameterSuffix = null,
string expectedUpdatedOriginalDocumentCode = null,
string expectedInterfaceCode = null,
string rootNamespace = null)
{
await TestExtractInterfaceCommandAsync(
markup,
LanguageNames.VisualBasic,
expectedSuccess,
expectedMemberName,
expectedInterfaceName,
expectedNamespaceName,
expectedTypeParameterSuffix,
expectedUpdatedOriginalDocumentCode,
expectedInterfaceCode,
new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, rootNamespace: rootNamespace));
}
public static async Task TestExtractInterfaceCodeActionVisualBasicAsync(
string markup,
string expectedMarkup)
{
await TestExtractInterfaceCodeActionAsync(
markup,
LanguageNames.VisualBasic,
expectedMarkup);
}
private static async Task TestExtractInterfaceCommandAsync(
string markup,
string languageName,
bool expectedSuccess,
string expectedMemberName = null,
string expectedInterfaceName = null,
string expectedNamespaceName = null,
string expectedTypeParameterSuffix = null,
string expectedUpdatedOriginalDocumentCode = null,
string expectedInterfaceCode = null,
CompilationOptions compilationOptions = null)
{
using var testState = ExtractInterfaceTestState.Create(markup, languageName, compilationOptions,
options: new OptionsCollection(languageName)
{
{ CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.Never, NotificationOption2.Silent }
});
var result = await testState.ExtractViaCommandAsync();
if (expectedSuccess)
{
Assert.True(result.Succeeded);
Assert.False(testState.Workspace.Documents.Select(d => d.Id).Contains(result.NavigationDocumentId));
Assert.NotNull(result.UpdatedSolution.GetDocument(result.NavigationDocumentId));
if (expectedMemberName != null)
{
Assert.Equal(1, testState.TestExtractInterfaceOptionsService.AllExtractableMembers.Count());
Assert.Equal(expectedMemberName, testState.TestExtractInterfaceOptionsService.AllExtractableMembers.Single().Name);
}
if (expectedInterfaceName != null)
{
Assert.Equal(expectedInterfaceName, testState.TestExtractInterfaceOptionsService.DefaultInterfaceName);
}
if (expectedNamespaceName != null)
{
Assert.Equal(expectedNamespaceName, testState.TestExtractInterfaceOptionsService.DefaultNamespace);
}
if (expectedTypeParameterSuffix != null)
{
Assert.Equal(expectedTypeParameterSuffix, testState.TestExtractInterfaceOptionsService.GeneratedNameTypeParameterSuffix);
}
if (expectedUpdatedOriginalDocumentCode != null)
{
var updatedOriginalDocument = result.UpdatedSolution.GetDocument(testState.ExtractFromDocument.Id);
var updatedCode = (await updatedOriginalDocument.GetTextAsync()).ToString();
Assert.Equal(expectedUpdatedOriginalDocumentCode, updatedCode);
}
if (expectedInterfaceCode != null)
{
var interfaceDocument = result.UpdatedSolution.GetDocument(result.NavigationDocumentId);
var interfaceCode = (await interfaceDocument.GetTextAsync()).ToString();
Assert.Equal(expectedInterfaceCode, interfaceCode);
}
}
else
{
Assert.False(result.Succeeded);
}
}
private static async Task TestExtractInterfaceCodeActionAsync(
string markup,
string languageName,
string expectedMarkup,
CompilationOptions compilationOptions = null)
{
using var testState = ExtractInterfaceTestState.Create(markup, languageName, compilationOptions);
var updatedSolution = await testState.ExtractViaCodeAction();
var updatedDocument = updatedSolution.GetDocument(testState.ExtractFromDocument.Id);
var updatedCode = (await updatedDocument.GetTextAsync()).ToString();
Assert.Equal(expectedMarkup, updatedCode);
}
}
}
| 1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Features/Core/Portable/ExtractClass/ExtractClassWithDialogCodeAction.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.ExtractInterface;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExtractClass
{
internal class ExtractClassWithDialogCodeAction : CodeActionWithOptions
{
private readonly Document _document;
private readonly ISymbol? _selectedMember;
private readonly INamedTypeSymbol _selectedType;
private readonly SyntaxNode _selectedTypeDeclarationNode;
private readonly IExtractClassOptionsService _service;
public TextSpan Span { get; }
public override string Title => FeaturesResources.Extract_base_class;
public ExtractClassWithDialogCodeAction(
Document document,
TextSpan span,
IExtractClassOptionsService service,
INamedTypeSymbol selectedType,
SyntaxNode selectedTypeDeclarationNode,
ISymbol? selectedMember = null)
{
_document = document;
_service = service;
_selectedType = selectedType;
_selectedTypeDeclarationNode = selectedTypeDeclarationNode;
_selectedMember = selectedMember;
Span = span;
}
public override object? GetOptions(CancellationToken cancellationToken)
{
var extractClassService = _service ?? _document.Project.Solution.Workspace.Services.GetRequiredService<IExtractClassOptionsService>();
return extractClassService.GetExtractClassOptionsAsync(_document, _selectedType, _selectedMember)
.WaitAndGetResult_CanCallOnBackground(cancellationToken);
}
protected override async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(object options, CancellationToken cancellationToken)
{
if (options is ExtractClassOptions extractClassOptions)
{
// Find the original type
var syntaxFacts = _document.GetRequiredLanguageService<ISyntaxFactsService>();
var root = await _document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
// Map the symbols we're removing to annotations
// so we can find them easily
var codeGenerator = _document.GetRequiredLanguageService<ICodeGenerationService>();
var symbolMapping = await AnnotatedSymbolMapping.CreateAsync(
extractClassOptions.MemberAnalysisResults.Select(m => m.Member),
_document.Project.Solution,
_selectedTypeDeclarationNode,
cancellationToken).ConfigureAwait(false);
var fileBanner = syntaxFacts.GetFileBanner(root);
var namespaceService = _document.GetRequiredLanguageService<AbstractExtractInterfaceService>();
// Create the symbol for the new type
var newType = CodeGenerationSymbolFactory.CreateNamedTypeSymbol(
_selectedType.GetAttributes(),
_selectedType.DeclaredAccessibility,
_selectedType.GetSymbolModifiers(),
TypeKind.Class,
extractClassOptions.TypeName);
var containingNamespaceDisplay = namespaceService.GetContainingNamespaceDisplay(
_selectedType,
_document.Project.CompilationOptions);
// Add the new type to the solution. It can go in a new file or
// be added to an existing. The returned document is always the document
// containing the new type
var (updatedDocument, typeAnnotation) = extractClassOptions.SameFile
? await ExtractTypeHelpers.AddTypeToExistingFileAsync(
symbolMapping.AnnotatedSolution.GetRequiredDocument(_document.Id),
newType,
symbolMapping,
cancellationToken).ConfigureAwait(false)
: await ExtractTypeHelpers.AddTypeToNewFileAsync(
symbolMapping.AnnotatedSolution,
containingNamespaceDisplay,
extractClassOptions.FileName,
_document.Project.Id,
_document.Folders,
newType,
fileBanner,
cancellationToken).ConfigureAwait(false);
// Update the original type to have the new base
var solutionWithUpdatedOriginalType = await GetSolutionWithBaseAddedAsync(
updatedDocument.Project.Solution,
symbolMapping,
newType,
extractClassOptions.MemberAnalysisResults,
cancellationToken).ConfigureAwait(false);
// After all the changes, make sure we're using the most up to date symbol
// as the destination for pulling members into
var documentWithTypeDeclaration = solutionWithUpdatedOriginalType.GetRequiredDocument(updatedDocument.Id);
var newTypeAfterEdits = await GetNewTypeSymbolAsync(documentWithTypeDeclaration, typeAnnotation, cancellationToken).ConfigureAwait(false);
// Use Members Puller to move the members to the new symbol
var finalSolution = await PullMembersUpAsync(
solutionWithUpdatedOriginalType,
newTypeAfterEdits,
symbolMapping,
extractClassOptions.MemberAnalysisResults,
cancellationToken).ConfigureAwait(false);
return new[] { new ApplyChangesOperation(finalSolution) };
}
else
{
// If user click cancel button, options will be null and hit this branch
return SpecializedCollections.EmptyEnumerable<CodeActionOperation>();
}
}
private async Task<Solution> PullMembersUpAsync(
Solution solution,
INamedTypeSymbol newType,
AnnotatedSymbolMapping symbolMapping,
ImmutableArray<ExtractClassMemberAnalysisResult> memberAnalysisResults,
CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<(ISymbol member, bool makeAbstract)>.GetInstance(out var pullMembersBuilder);
using var _1 = ArrayBuilder<ExtractClassMemberAnalysisResult>.GetInstance(memberAnalysisResults.Length, out var remainingResults);
remainingResults.AddRange(memberAnalysisResults);
// For each document in the symbol mappings, we want to find the annotated nodes
// of the members and get the current symbol that represents those after
// any changes we made before members get pulled up into the base class.
// We only need to worry about symbols that are actually being moved, so we track
// the symbols from the member analysis.
foreach (var (documentId, symbols) in symbolMapping.DocumentIdsToSymbolMap)
{
if (remainingResults.Count == 0)
{
// All symbols have been taken care of
break;
}
var document = solution.GetRequiredDocument(documentId);
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
using var _2 = ArrayBuilder<ExtractClassMemberAnalysisResult>.GetInstance(remainingResults.Count, out var resultsToRemove);
// Out of the remaining members that we need to move, does this
// document contain the definition for that symbol? If so, add it to the builder
// and remove it from the symbols we're looking for
var memberAnalysisForDocumentSymbols = remainingResults.Where(analysis => symbols.Contains(analysis.Member));
foreach (var memberAnalysis in memberAnalysisForDocumentSymbols)
{
var annotation = symbolMapping.SymbolToDeclarationAnnotationMap[memberAnalysis.Member];
var nodeOrToken = root.GetAnnotatedNodesAndTokens(annotation).SingleOrDefault();
var node = nodeOrToken.IsNode
? nodeOrToken.AsNode()
: nodeOrToken.AsToken().Parent;
// If the node is null then the symbol mapping was wrong about
// the document containing the symbol.
RoslynDebug.AssertNotNull(node);
var currentSymbol = semanticModel.GetDeclaredSymbol(node, cancellationToken);
// If currentSymbol is null then no symbol is declared at the node and
// symbol mapping state is not right.
RoslynDebug.AssertNotNull(currentSymbol);
pullMembersBuilder.Add((currentSymbol, memberAnalysis.MakeAbstract));
resultsToRemove.Add(memberAnalysis);
}
// Remove the symbols we found in this document from the list
// that we are looking for
foreach (var resultToRemove in resultsToRemove)
{
remainingResults.Remove(resultToRemove);
}
}
// If we didn't find all of the symbols then something went really wrong
Contract.ThrowIfFalse(remainingResults.Count == 0);
var pullMemberUpOptions = PullMembersUpOptionsBuilder.BuildPullMembersUpOptions(newType, pullMembersBuilder.ToImmutable());
var updatedOriginalDocument = solution.GetRequiredDocument(_document.Id);
return await MembersPuller.PullMembersUpAsync(updatedOriginalDocument, pullMemberUpOptions, cancellationToken).ConfigureAwait(false);
}
private static async Task<INamedTypeSymbol> GetNewTypeSymbolAsync(Document document, SyntaxAnnotation typeAnnotation, CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var declarationNode = root.GetAnnotatedNodes(typeAnnotation).Single();
return (INamedTypeSymbol)semanticModel.GetRequiredDeclaredSymbol(declarationNode, cancellationToken);
}
private static async Task<Solution> GetSolutionWithBaseAddedAsync(
Solution solution,
AnnotatedSymbolMapping symbolMapping,
INamedTypeSymbol newType,
ImmutableArray<ExtractClassMemberAnalysisResult> memberAnalysisResults,
CancellationToken cancellationToken)
{
var unformattedSolution = solution;
var remainingResults = new List<ExtractClassMemberAnalysisResult>(memberAnalysisResults);
foreach (var documentId in symbolMapping.DocumentIdsToSymbolMap.Keys)
{
if (remainingResults.IsEmpty())
{
// All results have been taken care of
break;
}
var document = solution.GetRequiredDocument(documentId);
var currentRoot = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var typeDeclaration = currentRoot.GetAnnotatedNodes(symbolMapping.TypeNodeAnnotation).SingleOrDefault();
if (typeDeclaration == null)
{
continue;
}
var syntaxGenerator = SyntaxGenerator.GetGenerator(document);
var typeReference = syntaxGenerator.TypeExpression(newType);
currentRoot = currentRoot.ReplaceNode(typeDeclaration,
syntaxGenerator.AddBaseType(typeDeclaration, typeReference));
unformattedSolution = document.WithSyntaxRoot(currentRoot).Project.Solution;
// Only need to update on declaration of the type
break;
}
return unformattedSolution;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.ExtractInterface;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExtractClass
{
internal class ExtractClassWithDialogCodeAction : CodeActionWithOptions
{
private readonly Document _document;
private readonly ISymbol? _selectedMember;
private readonly INamedTypeSymbol _selectedType;
private readonly SyntaxNode _selectedTypeDeclarationNode;
private readonly IExtractClassOptionsService _service;
public TextSpan Span { get; }
public override string Title => FeaturesResources.Extract_base_class;
public ExtractClassWithDialogCodeAction(
Document document,
TextSpan span,
IExtractClassOptionsService service,
INamedTypeSymbol selectedType,
SyntaxNode selectedTypeDeclarationNode,
ISymbol? selectedMember = null)
{
_document = document;
_service = service;
_selectedType = selectedType;
_selectedTypeDeclarationNode = selectedTypeDeclarationNode;
_selectedMember = selectedMember;
Span = span;
}
public override object? GetOptions(CancellationToken cancellationToken)
{
var extractClassService = _service ?? _document.Project.Solution.Workspace.Services.GetRequiredService<IExtractClassOptionsService>();
return extractClassService.GetExtractClassOptionsAsync(_document, _selectedType, _selectedMember)
.WaitAndGetResult_CanCallOnBackground(cancellationToken);
}
protected override async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(object options, CancellationToken cancellationToken)
{
if (options is ExtractClassOptions extractClassOptions)
{
// Map the symbols we're removing to annotations
// so we can find them easily
var codeGenerator = _document.GetRequiredLanguageService<ICodeGenerationService>();
var symbolMapping = await AnnotatedSymbolMapping.CreateAsync(
extractClassOptions.MemberAnalysisResults.Select(m => m.Member),
_document.Project.Solution,
_selectedTypeDeclarationNode,
cancellationToken).ConfigureAwait(false);
var namespaceService = _document.GetRequiredLanguageService<AbstractExtractInterfaceService>();
// Create the symbol for the new type
var newType = CodeGenerationSymbolFactory.CreateNamedTypeSymbol(
_selectedType.GetAttributes(),
_selectedType.DeclaredAccessibility,
_selectedType.GetSymbolModifiers(),
TypeKind.Class,
extractClassOptions.TypeName);
var containingNamespaceDisplay = namespaceService.GetContainingNamespaceDisplay(
_selectedType,
_document.Project.CompilationOptions);
// Add the new type to the solution. It can go in a new file or
// be added to an existing. The returned document is always the document
// containing the new type
var (updatedDocument, typeAnnotation) = extractClassOptions.SameFile
? await ExtractTypeHelpers.AddTypeToExistingFileAsync(
symbolMapping.AnnotatedSolution.GetRequiredDocument(_document.Id),
newType,
symbolMapping,
cancellationToken).ConfigureAwait(false)
: await ExtractTypeHelpers.AddTypeToNewFileAsync(
symbolMapping.AnnotatedSolution,
containingNamespaceDisplay,
extractClassOptions.FileName,
_document.Project.Id,
_document.Folders,
newType,
_document,
cancellationToken).ConfigureAwait(false);
// Update the original type to have the new base
var solutionWithUpdatedOriginalType = await GetSolutionWithBaseAddedAsync(
updatedDocument.Project.Solution,
symbolMapping,
newType,
extractClassOptions.MemberAnalysisResults,
cancellationToken).ConfigureAwait(false);
// After all the changes, make sure we're using the most up to date symbol
// as the destination for pulling members into
var documentWithTypeDeclaration = solutionWithUpdatedOriginalType.GetRequiredDocument(updatedDocument.Id);
var newTypeAfterEdits = await GetNewTypeSymbolAsync(documentWithTypeDeclaration, typeAnnotation, cancellationToken).ConfigureAwait(false);
// Use Members Puller to move the members to the new symbol
var finalSolution = await PullMembersUpAsync(
solutionWithUpdatedOriginalType,
newTypeAfterEdits,
symbolMapping,
extractClassOptions.MemberAnalysisResults,
cancellationToken).ConfigureAwait(false);
return new[] { new ApplyChangesOperation(finalSolution) };
}
else
{
// If user click cancel button, options will be null and hit this branch
return SpecializedCollections.EmptyEnumerable<CodeActionOperation>();
}
}
private async Task<Solution> PullMembersUpAsync(
Solution solution,
INamedTypeSymbol newType,
AnnotatedSymbolMapping symbolMapping,
ImmutableArray<ExtractClassMemberAnalysisResult> memberAnalysisResults,
CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<(ISymbol member, bool makeAbstract)>.GetInstance(out var pullMembersBuilder);
using var _1 = ArrayBuilder<ExtractClassMemberAnalysisResult>.GetInstance(memberAnalysisResults.Length, out var remainingResults);
remainingResults.AddRange(memberAnalysisResults);
// For each document in the symbol mappings, we want to find the annotated nodes
// of the members and get the current symbol that represents those after
// any changes we made before members get pulled up into the base class.
// We only need to worry about symbols that are actually being moved, so we track
// the symbols from the member analysis.
foreach (var (documentId, symbols) in symbolMapping.DocumentIdsToSymbolMap)
{
if (remainingResults.Count == 0)
{
// All symbols have been taken care of
break;
}
var document = solution.GetRequiredDocument(documentId);
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
using var _2 = ArrayBuilder<ExtractClassMemberAnalysisResult>.GetInstance(remainingResults.Count, out var resultsToRemove);
// Out of the remaining members that we need to move, does this
// document contain the definition for that symbol? If so, add it to the builder
// and remove it from the symbols we're looking for
var memberAnalysisForDocumentSymbols = remainingResults.Where(analysis => symbols.Contains(analysis.Member));
foreach (var memberAnalysis in memberAnalysisForDocumentSymbols)
{
var annotation = symbolMapping.SymbolToDeclarationAnnotationMap[memberAnalysis.Member];
var nodeOrToken = root.GetAnnotatedNodesAndTokens(annotation).SingleOrDefault();
var node = nodeOrToken.IsNode
? nodeOrToken.AsNode()
: nodeOrToken.AsToken().Parent;
// If the node is null then the symbol mapping was wrong about
// the document containing the symbol.
RoslynDebug.AssertNotNull(node);
var currentSymbol = semanticModel.GetDeclaredSymbol(node, cancellationToken);
// If currentSymbol is null then no symbol is declared at the node and
// symbol mapping state is not right.
RoslynDebug.AssertNotNull(currentSymbol);
pullMembersBuilder.Add((currentSymbol, memberAnalysis.MakeAbstract));
resultsToRemove.Add(memberAnalysis);
}
// Remove the symbols we found in this document from the list
// that we are looking for
foreach (var resultToRemove in resultsToRemove)
{
remainingResults.Remove(resultToRemove);
}
}
// If we didn't find all of the symbols then something went really wrong
Contract.ThrowIfFalse(remainingResults.Count == 0);
var pullMemberUpOptions = PullMembersUpOptionsBuilder.BuildPullMembersUpOptions(newType, pullMembersBuilder.ToImmutable());
var updatedOriginalDocument = solution.GetRequiredDocument(_document.Id);
return await MembersPuller.PullMembersUpAsync(updatedOriginalDocument, pullMemberUpOptions, cancellationToken).ConfigureAwait(false);
}
private static async Task<INamedTypeSymbol> GetNewTypeSymbolAsync(Document document, SyntaxAnnotation typeAnnotation, CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var declarationNode = root.GetAnnotatedNodes(typeAnnotation).Single();
return (INamedTypeSymbol)semanticModel.GetRequiredDeclaredSymbol(declarationNode, cancellationToken);
}
private static async Task<Solution> GetSolutionWithBaseAddedAsync(
Solution solution,
AnnotatedSymbolMapping symbolMapping,
INamedTypeSymbol newType,
ImmutableArray<ExtractClassMemberAnalysisResult> memberAnalysisResults,
CancellationToken cancellationToken)
{
var unformattedSolution = solution;
var remainingResults = new List<ExtractClassMemberAnalysisResult>(memberAnalysisResults);
foreach (var documentId in symbolMapping.DocumentIdsToSymbolMap.Keys)
{
if (remainingResults.IsEmpty())
{
// All results have been taken care of
break;
}
var document = solution.GetRequiredDocument(documentId);
var currentRoot = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var typeDeclaration = currentRoot.GetAnnotatedNodes(symbolMapping.TypeNodeAnnotation).SingleOrDefault();
if (typeDeclaration == null)
{
continue;
}
var syntaxGenerator = SyntaxGenerator.GetGenerator(document);
var typeReference = syntaxGenerator.TypeExpression(newType);
currentRoot = currentRoot.ReplaceNode(typeDeclaration,
syntaxGenerator.AddBaseType(typeDeclaration, typeReference));
unformattedSolution = document.WithSyntaxRoot(currentRoot).Project.Solution;
// Only need to update on declaration of the type
break;
}
return unformattedSolution;
}
}
}
| 1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Features/Core/Portable/ExtractInterface/AbstractExtractInterfaceService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExtractInterface
{
internal abstract class AbstractExtractInterfaceService : ILanguageService
{
protected abstract Task<SyntaxNode> GetTypeDeclarationAsync(
Document document,
int position,
TypeDiscoveryRule typeDiscoveryRule,
CancellationToken cancellationToken);
protected abstract Task<Solution> UpdateMembersWithExplicitImplementationsAsync(
Solution unformattedSolution,
IReadOnlyList<DocumentId> documentId,
INamedTypeSymbol extractedInterfaceSymbol,
INamedTypeSymbol typeToExtractFrom,
IEnumerable<ISymbol> includedMembers,
ImmutableDictionary<ISymbol, SyntaxAnnotation> symbolToDeclarationAnnotationMap,
CancellationToken cancellationToken);
internal abstract string GetContainingNamespaceDisplay(INamedTypeSymbol typeSymbol, CompilationOptions compilationOptions);
internal abstract bool ShouldIncludeAccessibilityModifier(SyntaxNode typeNode);
public async Task<ImmutableArray<ExtractInterfaceCodeAction>> GetExtractInterfaceCodeActionAsync(Document document, TextSpan span, CancellationToken cancellationToken)
{
var typeAnalysisResult = await AnalyzeTypeAtPositionAsync(document, span.Start, TypeDiscoveryRule.TypeNameOnly, cancellationToken).ConfigureAwait(false);
return typeAnalysisResult.CanExtractInterface
? ImmutableArray.Create(new ExtractInterfaceCodeAction(this, typeAnalysisResult))
: ImmutableArray<ExtractInterfaceCodeAction>.Empty;
}
public async Task<ExtractInterfaceResult> ExtractInterfaceAsync(
Document documentWithTypeToExtractFrom,
int position,
Action<string, NotificationSeverity> errorHandler,
CancellationToken cancellationToken)
{
var typeAnalysisResult = await AnalyzeTypeAtPositionAsync(
documentWithTypeToExtractFrom,
position,
TypeDiscoveryRule.TypeDeclaration,
cancellationToken).ConfigureAwait(false);
if (!typeAnalysisResult.CanExtractInterface)
{
errorHandler(typeAnalysisResult.ErrorMessage, NotificationSeverity.Error);
return new ExtractInterfaceResult(succeeded: false);
}
return await ExtractInterfaceFromAnalyzedTypeAsync(typeAnalysisResult, cancellationToken).ConfigureAwait(false);
}
public async Task<ExtractInterfaceTypeAnalysisResult> AnalyzeTypeAtPositionAsync(
Document document,
int position,
TypeDiscoveryRule typeDiscoveryRule,
CancellationToken cancellationToken)
{
var typeNode = await GetTypeDeclarationAsync(document, position, typeDiscoveryRule, cancellationToken).ConfigureAwait(false);
if (typeNode == null)
{
var errorMessage = FeaturesResources.Could_not_extract_interface_colon_The_selection_is_not_inside_a_class_interface_struct;
return new ExtractInterfaceTypeAnalysisResult(errorMessage);
}
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var type = semanticModel.GetDeclaredSymbol(typeNode, cancellationToken);
if (type == null || type.Kind != SymbolKind.NamedType)
{
var errorMessage = FeaturesResources.Could_not_extract_interface_colon_The_selection_is_not_inside_a_class_interface_struct;
return new ExtractInterfaceTypeAnalysisResult(errorMessage);
}
var typeToExtractFrom = type as INamedTypeSymbol;
var extractableMembers = typeToExtractFrom.GetMembers().Where(IsExtractableMember);
if (!extractableMembers.Any())
{
var errorMessage = FeaturesResources.Could_not_extract_interface_colon_The_type_does_not_contain_any_member_that_can_be_extracted_to_an_interface;
return new ExtractInterfaceTypeAnalysisResult(errorMessage);
}
return new ExtractInterfaceTypeAnalysisResult(document, typeNode, typeToExtractFrom, extractableMembers);
}
public async Task<ExtractInterfaceResult> ExtractInterfaceFromAnalyzedTypeAsync(ExtractInterfaceTypeAnalysisResult refactoringResult, CancellationToken cancellationToken)
{
var containingNamespaceDisplay = refactoringResult.TypeToExtractFrom.ContainingNamespace.IsGlobalNamespace
? string.Empty
: refactoringResult.TypeToExtractFrom.ContainingNamespace.ToDisplayString();
var extractInterfaceOptions = await GetExtractInterfaceOptionsAsync(
refactoringResult.DocumentToExtractFrom,
refactoringResult.TypeToExtractFrom,
refactoringResult.ExtractableMembers,
containingNamespaceDisplay,
cancellationToken).ConfigureAwait(false);
if (extractInterfaceOptions.IsCancelled)
{
return new ExtractInterfaceResult(succeeded: false);
}
return await ExtractInterfaceFromAnalyzedTypeAsync(refactoringResult, extractInterfaceOptions, cancellationToken).ConfigureAwait(false);
}
public async Task<ExtractInterfaceResult> ExtractInterfaceFromAnalyzedTypeAsync(
ExtractInterfaceTypeAnalysisResult refactoringResult,
ExtractInterfaceOptionsResult extractInterfaceOptions,
CancellationToken cancellationToken)
{
var solution = refactoringResult.DocumentToExtractFrom.Project.Solution;
var extractedInterfaceSymbol = CodeGenerationSymbolFactory.CreateNamedTypeSymbol(
attributes: default,
accessibility: ShouldIncludeAccessibilityModifier(refactoringResult.TypeNode) ? refactoringResult.TypeToExtractFrom.DeclaredAccessibility : Accessibility.NotApplicable,
modifiers: new DeclarationModifiers(),
typeKind: TypeKind.Interface,
name: extractInterfaceOptions.InterfaceName,
typeParameters: ExtractTypeHelpers.GetRequiredTypeParametersForMembers(refactoringResult.TypeToExtractFrom, extractInterfaceOptions.IncludedMembers),
members: CreateInterfaceMembers(extractInterfaceOptions.IncludedMembers));
switch (extractInterfaceOptions.Location)
{
case ExtractInterfaceOptionsResult.ExtractLocation.NewFile:
var containingNamespaceDisplay = GetContainingNamespaceDisplay(refactoringResult.TypeToExtractFrom, refactoringResult.DocumentToExtractFrom.Project.CompilationOptions);
return await ExtractInterfaceToNewFileAsync(
solution,
containingNamespaceDisplay,
extractedInterfaceSymbol,
refactoringResult,
extractInterfaceOptions,
cancellationToken).ConfigureAwait(false);
case ExtractInterfaceOptionsResult.ExtractLocation.SameFile:
return await ExtractInterfaceToSameFileAsync(
solution,
refactoringResult,
extractedInterfaceSymbol,
extractInterfaceOptions,
cancellationToken).ConfigureAwait(false);
default: throw new InvalidOperationException($"Unable to extract interface for operation of type {extractInterfaceOptions.GetType()}");
}
}
private async Task<ExtractInterfaceResult> ExtractInterfaceToNewFileAsync(
Solution solution, string containingNamespaceDisplay, INamedTypeSymbol extractedInterfaceSymbol,
ExtractInterfaceTypeAnalysisResult refactoringResult, ExtractInterfaceOptionsResult extractInterfaceOptions, CancellationToken cancellationToken)
{
var symbolMapping = await AnnotatedSymbolMapping.CreateAsync(
extractInterfaceOptions.IncludedMembers,
solution,
refactoringResult.TypeNode,
cancellationToken).ConfigureAwait(false);
var syntaxFactsService = refactoringResult.DocumentToExtractFrom.GetLanguageService<ISyntaxFactsService>();
var originalDocumentSyntaxRoot = await refactoringResult.DocumentToExtractFrom.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var fileBanner = syntaxFactsService.GetFileBanner(originalDocumentSyntaxRoot);
var (unformattedInterfaceDocument, _) = await ExtractTypeHelpers.AddTypeToNewFileAsync(
symbolMapping.AnnotatedSolution,
containingNamespaceDisplay,
extractInterfaceOptions.FileName,
refactoringResult.DocumentToExtractFrom.Project.Id,
refactoringResult.DocumentToExtractFrom.Folders,
extractedInterfaceSymbol,
fileBanner,
cancellationToken).ConfigureAwait(false);
var completedUnformattedSolution = await GetSolutionWithOriginalTypeUpdatedAsync(
unformattedInterfaceDocument.Project.Solution,
symbolMapping.DocumentIdsToSymbolMap.Keys.ToImmutableArray(),
symbolMapping.TypeNodeAnnotation,
refactoringResult.TypeToExtractFrom,
extractedInterfaceSymbol,
extractInterfaceOptions.IncludedMembers,
symbolMapping.SymbolToDeclarationAnnotationMap,
cancellationToken).ConfigureAwait(false);
var completedSolution = await GetFormattedSolutionAsync(
completedUnformattedSolution,
symbolMapping.DocumentIdsToSymbolMap.Keys.Concat(unformattedInterfaceDocument.Id),
cancellationToken).ConfigureAwait(false);
return new ExtractInterfaceResult(
succeeded: true,
updatedSolution: completedSolution,
navigationDocumentId: unformattedInterfaceDocument.Id);
}
private async Task<ExtractInterfaceResult> ExtractInterfaceToSameFileAsync(
Solution solution, ExtractInterfaceTypeAnalysisResult refactoringResult, INamedTypeSymbol extractedInterfaceSymbol,
ExtractInterfaceOptionsResult extractInterfaceOptions, CancellationToken cancellationToken)
{
// Track all of the symbols we need to modify, which includes the original type declaration being modified
var symbolMapping = await AnnotatedSymbolMapping.CreateAsync(
extractInterfaceOptions.IncludedMembers,
solution,
refactoringResult.TypeNode,
cancellationToken).ConfigureAwait(false);
var document = symbolMapping.AnnotatedSolution.GetDocument(refactoringResult.DocumentToExtractFrom.Id);
var (documentWithInterface, _) = await ExtractTypeHelpers.AddTypeToExistingFileAsync(
document,
extractedInterfaceSymbol,
symbolMapping,
cancellationToken).ConfigureAwait(false);
var unformattedSolution = documentWithInterface.Project.Solution;
// After the interface is inserted, update the original type to show it implements the new interface
var unformattedSolutionWithUpdatedType = await GetSolutionWithOriginalTypeUpdatedAsync(
unformattedSolution, symbolMapping.DocumentIdsToSymbolMap.Keys.ToImmutableArray(),
symbolMapping.TypeNodeAnnotation,
refactoringResult.TypeToExtractFrom, extractedInterfaceSymbol,
extractInterfaceOptions.IncludedMembers, symbolMapping.SymbolToDeclarationAnnotationMap, cancellationToken).ConfigureAwait(false);
var completedSolution = await GetFormattedSolutionAsync(
unformattedSolutionWithUpdatedType,
symbolMapping.DocumentIdsToSymbolMap.Keys.Concat(refactoringResult.DocumentToExtractFrom.Id),
cancellationToken).ConfigureAwait(false);
return new ExtractInterfaceResult(
succeeded: true,
updatedSolution: completedSolution,
navigationDocumentId: refactoringResult.DocumentToExtractFrom.Id);
}
internal static Task<ExtractInterfaceOptionsResult> GetExtractInterfaceOptionsAsync(
Document document,
INamedTypeSymbol type,
IEnumerable<ISymbol> extractableMembers,
string containingNamespace,
CancellationToken cancellationToken)
{
var conflictingTypeNames = type.ContainingNamespace.GetAllTypes(cancellationToken).Select(t => t.Name);
var candidateInterfaceName = type.TypeKind == TypeKind.Interface ? type.Name : "I" + type.Name;
var defaultInterfaceName = NameGenerator.GenerateUniqueName(candidateInterfaceName, name => !conflictingTypeNames.Contains(name));
var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>();
var notificationService = document.Project.Solution.Workspace.Services.GetService<INotificationService>();
var generatedNameTypeParameterSuffix = ExtractTypeHelpers.GetTypeParameterSuffix(document, type, extractableMembers);
var service = document.Project.Solution.Workspace.Services.GetService<IExtractInterfaceOptionsService>();
return service.GetExtractInterfaceOptionsAsync(
syntaxFactsService,
notificationService,
extractableMembers.ToList(),
defaultInterfaceName,
conflictingTypeNames.ToList(),
containingNamespace,
generatedNameTypeParameterSuffix,
document.Project.Language);
}
private static async Task<Solution> GetFormattedSolutionAsync(Solution unformattedSolution, IEnumerable<DocumentId> documentIds, CancellationToken cancellationToken)
{
// Since code action performs formatting and simplification on a single document,
// this ensures that anything marked with formatter or simplifier annotations gets
// correctly handled as long as it it's in the listed documents
var formattedSolution = unformattedSolution;
foreach (var documentId in documentIds)
{
var document = formattedSolution.GetDocument(documentId);
var formattedDocument = await Formatter.FormatAsync(
document,
Formatter.Annotation,
cancellationToken: cancellationToken).ConfigureAwait(false);
var simplifiedDocument = await Simplifier.ReduceAsync(
formattedDocument,
Simplifier.Annotation,
cancellationToken: cancellationToken).ConfigureAwait(false);
formattedSolution = simplifiedDocument.Project.Solution;
}
return formattedSolution;
}
private async Task<Solution> GetSolutionWithOriginalTypeUpdatedAsync(
Solution solution,
ImmutableArray<DocumentId> documentIds,
SyntaxAnnotation typeNodeAnnotation,
INamedTypeSymbol typeToExtractFrom,
INamedTypeSymbol extractedInterfaceSymbol,
IEnumerable<ISymbol> includedMembers,
ImmutableDictionary<ISymbol, SyntaxAnnotation> symbolToDeclarationAnnotationMap,
CancellationToken cancellationToken)
{
// If an interface "INewInterface" is extracted from an interface "IExistingInterface",
// then "INewInterface" is not marked as implementing "IExistingInterface" and its
// extracted members are also not updated.
if (typeToExtractFrom.TypeKind == TypeKind.Interface)
{
return solution;
}
var unformattedSolution = solution;
foreach (var documentId in documentIds)
{
var document = solution.GetDocument(documentId);
var currentRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var editor = new SyntaxEditor(currentRoot, solution.Workspace);
var syntaxGenerator = SyntaxGenerator.GetGenerator(document);
var typeReference = syntaxGenerator.TypeExpression(extractedInterfaceSymbol);
var typeDeclaration = currentRoot.GetAnnotatedNodes(typeNodeAnnotation).SingleOrDefault();
if (typeDeclaration == null)
{
continue;
}
var unformattedTypeDeclaration = syntaxGenerator.AddInterfaceType(typeDeclaration, typeReference).WithAdditionalAnnotations(Formatter.Annotation);
editor.ReplaceNode(typeDeclaration, unformattedTypeDeclaration);
unformattedSolution = document.WithSyntaxRoot(editor.GetChangedRoot()).Project.Solution;
// Only update the first instance of the typedeclaration,
// since it's not needed in all declarations
break;
}
var updatedUnformattedSolution = await UpdateMembersWithExplicitImplementationsAsync(
unformattedSolution,
documentIds,
extractedInterfaceSymbol,
typeToExtractFrom,
includedMembers,
symbolToDeclarationAnnotationMap,
cancellationToken).ConfigureAwait(false);
return updatedUnformattedSolution;
}
private static ImmutableArray<ISymbol> CreateInterfaceMembers(IEnumerable<ISymbol> includedMembers)
{
using var _ = ArrayBuilder<ISymbol>.GetInstance(out var interfaceMembers);
foreach (var member in includedMembers)
{
switch (member.Kind)
{
case SymbolKind.Event:
var @event = member as IEventSymbol;
interfaceMembers.Add(CodeGenerationSymbolFactory.CreateEventSymbol(
attributes: ImmutableArray<AttributeData>.Empty,
accessibility: Accessibility.Public,
modifiers: new DeclarationModifiers(isAbstract: true),
type: @event.Type,
explicitInterfaceImplementations: default,
name: @event.Name));
break;
case SymbolKind.Method:
var method = member as IMethodSymbol;
interfaceMembers.Add(CodeGenerationSymbolFactory.CreateMethodSymbol(
attributes: ImmutableArray<AttributeData>.Empty,
accessibility: Accessibility.Public,
modifiers: new DeclarationModifiers(isAbstract: true, isUnsafe: method.RequiresUnsafeModifier()),
returnType: method.ReturnType,
refKind: method.RefKind,
explicitInterfaceImplementations: default,
name: method.Name,
typeParameters: method.TypeParameters,
parameters: method.Parameters,
isInitOnly: method.IsInitOnly));
break;
case SymbolKind.Property:
var property = member as IPropertySymbol;
interfaceMembers.Add(CodeGenerationSymbolFactory.CreatePropertySymbol(
attributes: ImmutableArray<AttributeData>.Empty,
accessibility: Accessibility.Public,
modifiers: new DeclarationModifiers(isAbstract: true, isUnsafe: property.RequiresUnsafeModifier()),
type: property.Type,
refKind: property.RefKind,
explicitInterfaceImplementations: default,
name: property.Name,
parameters: property.Parameters,
getMethod: property.GetMethod == null ? null : (property.GetMethod.DeclaredAccessibility == Accessibility.Public ? property.GetMethod : null),
setMethod: property.SetMethod == null ? null : (property.SetMethod.DeclaredAccessibility == Accessibility.Public ? property.SetMethod : null),
isIndexer: property.IsIndexer));
break;
default:
Debug.Assert(false, string.Format(FeaturesResources.Unexpected_interface_member_kind_colon_0, member.Kind.ToString()));
break;
}
}
return interfaceMembers.ToImmutable();
}
internal virtual bool IsExtractableMember(ISymbol m)
{
if (m.IsStatic ||
m.DeclaredAccessibility != Accessibility.Public ||
m.Name == "<Clone>$") // TODO: Use WellKnownMemberNames.CloneMethodName when it's public.
{
return false;
}
if (m.Kind == SymbolKind.Event || m.IsOrdinaryMethod())
{
return true;
}
if (m.Kind == SymbolKind.Property)
{
var prop = m as IPropertySymbol;
return !prop.IsWithEvents &&
((prop.GetMethod != null && prop.GetMethod.DeclaredAccessibility == Accessibility.Public) ||
(prop.SetMethod != null && prop.SetMethod.DeclaredAccessibility == Accessibility.Public));
}
return false;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExtractInterface
{
internal abstract class AbstractExtractInterfaceService : ILanguageService
{
protected abstract Task<SyntaxNode> GetTypeDeclarationAsync(
Document document,
int position,
TypeDiscoveryRule typeDiscoveryRule,
CancellationToken cancellationToken);
protected abstract Task<Solution> UpdateMembersWithExplicitImplementationsAsync(
Solution unformattedSolution,
IReadOnlyList<DocumentId> documentId,
INamedTypeSymbol extractedInterfaceSymbol,
INamedTypeSymbol typeToExtractFrom,
IEnumerable<ISymbol> includedMembers,
ImmutableDictionary<ISymbol, SyntaxAnnotation> symbolToDeclarationAnnotationMap,
CancellationToken cancellationToken);
internal abstract string GetContainingNamespaceDisplay(INamedTypeSymbol typeSymbol, CompilationOptions compilationOptions);
internal abstract bool ShouldIncludeAccessibilityModifier(SyntaxNode typeNode);
public async Task<ImmutableArray<ExtractInterfaceCodeAction>> GetExtractInterfaceCodeActionAsync(Document document, TextSpan span, CancellationToken cancellationToken)
{
var typeAnalysisResult = await AnalyzeTypeAtPositionAsync(document, span.Start, TypeDiscoveryRule.TypeNameOnly, cancellationToken).ConfigureAwait(false);
return typeAnalysisResult.CanExtractInterface
? ImmutableArray.Create(new ExtractInterfaceCodeAction(this, typeAnalysisResult))
: ImmutableArray<ExtractInterfaceCodeAction>.Empty;
}
public async Task<ExtractInterfaceResult> ExtractInterfaceAsync(
Document documentWithTypeToExtractFrom,
int position,
Action<string, NotificationSeverity> errorHandler,
CancellationToken cancellationToken)
{
var typeAnalysisResult = await AnalyzeTypeAtPositionAsync(
documentWithTypeToExtractFrom,
position,
TypeDiscoveryRule.TypeDeclaration,
cancellationToken).ConfigureAwait(false);
if (!typeAnalysisResult.CanExtractInterface)
{
errorHandler(typeAnalysisResult.ErrorMessage, NotificationSeverity.Error);
return new ExtractInterfaceResult(succeeded: false);
}
return await ExtractInterfaceFromAnalyzedTypeAsync(typeAnalysisResult, cancellationToken).ConfigureAwait(false);
}
public async Task<ExtractInterfaceTypeAnalysisResult> AnalyzeTypeAtPositionAsync(
Document document,
int position,
TypeDiscoveryRule typeDiscoveryRule,
CancellationToken cancellationToken)
{
var typeNode = await GetTypeDeclarationAsync(document, position, typeDiscoveryRule, cancellationToken).ConfigureAwait(false);
if (typeNode == null)
{
var errorMessage = FeaturesResources.Could_not_extract_interface_colon_The_selection_is_not_inside_a_class_interface_struct;
return new ExtractInterfaceTypeAnalysisResult(errorMessage);
}
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var type = semanticModel.GetDeclaredSymbol(typeNode, cancellationToken);
if (type == null || type.Kind != SymbolKind.NamedType)
{
var errorMessage = FeaturesResources.Could_not_extract_interface_colon_The_selection_is_not_inside_a_class_interface_struct;
return new ExtractInterfaceTypeAnalysisResult(errorMessage);
}
var typeToExtractFrom = type as INamedTypeSymbol;
var extractableMembers = typeToExtractFrom.GetMembers().Where(IsExtractableMember);
if (!extractableMembers.Any())
{
var errorMessage = FeaturesResources.Could_not_extract_interface_colon_The_type_does_not_contain_any_member_that_can_be_extracted_to_an_interface;
return new ExtractInterfaceTypeAnalysisResult(errorMessage);
}
return new ExtractInterfaceTypeAnalysisResult(document, typeNode, typeToExtractFrom, extractableMembers);
}
public async Task<ExtractInterfaceResult> ExtractInterfaceFromAnalyzedTypeAsync(ExtractInterfaceTypeAnalysisResult refactoringResult, CancellationToken cancellationToken)
{
var containingNamespaceDisplay = refactoringResult.TypeToExtractFrom.ContainingNamespace.IsGlobalNamespace
? string.Empty
: refactoringResult.TypeToExtractFrom.ContainingNamespace.ToDisplayString();
var extractInterfaceOptions = await GetExtractInterfaceOptionsAsync(
refactoringResult.DocumentToExtractFrom,
refactoringResult.TypeToExtractFrom,
refactoringResult.ExtractableMembers,
containingNamespaceDisplay,
cancellationToken).ConfigureAwait(false);
if (extractInterfaceOptions.IsCancelled)
{
return new ExtractInterfaceResult(succeeded: false);
}
return await ExtractInterfaceFromAnalyzedTypeAsync(refactoringResult, extractInterfaceOptions, cancellationToken).ConfigureAwait(false);
}
public async Task<ExtractInterfaceResult> ExtractInterfaceFromAnalyzedTypeAsync(
ExtractInterfaceTypeAnalysisResult refactoringResult,
ExtractInterfaceOptionsResult extractInterfaceOptions,
CancellationToken cancellationToken)
{
var solution = refactoringResult.DocumentToExtractFrom.Project.Solution;
var extractedInterfaceSymbol = CodeGenerationSymbolFactory.CreateNamedTypeSymbol(
attributes: default,
accessibility: ShouldIncludeAccessibilityModifier(refactoringResult.TypeNode) ? refactoringResult.TypeToExtractFrom.DeclaredAccessibility : Accessibility.NotApplicable,
modifiers: new DeclarationModifiers(),
typeKind: TypeKind.Interface,
name: extractInterfaceOptions.InterfaceName,
typeParameters: ExtractTypeHelpers.GetRequiredTypeParametersForMembers(refactoringResult.TypeToExtractFrom, extractInterfaceOptions.IncludedMembers),
members: CreateInterfaceMembers(extractInterfaceOptions.IncludedMembers));
switch (extractInterfaceOptions.Location)
{
case ExtractInterfaceOptionsResult.ExtractLocation.NewFile:
var containingNamespaceDisplay = GetContainingNamespaceDisplay(refactoringResult.TypeToExtractFrom, refactoringResult.DocumentToExtractFrom.Project.CompilationOptions);
return await ExtractInterfaceToNewFileAsync(
solution,
containingNamespaceDisplay,
extractedInterfaceSymbol,
refactoringResult,
extractInterfaceOptions,
cancellationToken).ConfigureAwait(false);
case ExtractInterfaceOptionsResult.ExtractLocation.SameFile:
return await ExtractInterfaceToSameFileAsync(
solution,
refactoringResult,
extractedInterfaceSymbol,
extractInterfaceOptions,
cancellationToken).ConfigureAwait(false);
default: throw new InvalidOperationException($"Unable to extract interface for operation of type {extractInterfaceOptions.GetType()}");
}
}
private async Task<ExtractInterfaceResult> ExtractInterfaceToNewFileAsync(
Solution solution, string containingNamespaceDisplay, INamedTypeSymbol extractedInterfaceSymbol,
ExtractInterfaceTypeAnalysisResult refactoringResult, ExtractInterfaceOptionsResult extractInterfaceOptions, CancellationToken cancellationToken)
{
var symbolMapping = await AnnotatedSymbolMapping.CreateAsync(
extractInterfaceOptions.IncludedMembers,
solution,
refactoringResult.TypeNode,
cancellationToken).ConfigureAwait(false);
var (unformattedInterfaceDocument, _) = await ExtractTypeHelpers.AddTypeToNewFileAsync(
symbolMapping.AnnotatedSolution,
containingNamespaceDisplay,
extractInterfaceOptions.FileName,
refactoringResult.DocumentToExtractFrom.Project.Id,
refactoringResult.DocumentToExtractFrom.Folders,
extractedInterfaceSymbol,
refactoringResult.DocumentToExtractFrom,
cancellationToken).ConfigureAwait(false);
var completedUnformattedSolution = await GetSolutionWithOriginalTypeUpdatedAsync(
unformattedInterfaceDocument.Project.Solution,
symbolMapping.DocumentIdsToSymbolMap.Keys.ToImmutableArray(),
symbolMapping.TypeNodeAnnotation,
refactoringResult.TypeToExtractFrom,
extractedInterfaceSymbol,
extractInterfaceOptions.IncludedMembers,
symbolMapping.SymbolToDeclarationAnnotationMap,
cancellationToken).ConfigureAwait(false);
var completedSolution = await GetFormattedSolutionAsync(
completedUnformattedSolution,
symbolMapping.DocumentIdsToSymbolMap.Keys.Concat(unformattedInterfaceDocument.Id),
cancellationToken).ConfigureAwait(false);
return new ExtractInterfaceResult(
succeeded: true,
updatedSolution: completedSolution,
navigationDocumentId: unformattedInterfaceDocument.Id);
}
private async Task<ExtractInterfaceResult> ExtractInterfaceToSameFileAsync(
Solution solution, ExtractInterfaceTypeAnalysisResult refactoringResult, INamedTypeSymbol extractedInterfaceSymbol,
ExtractInterfaceOptionsResult extractInterfaceOptions, CancellationToken cancellationToken)
{
// Track all of the symbols we need to modify, which includes the original type declaration being modified
var symbolMapping = await AnnotatedSymbolMapping.CreateAsync(
extractInterfaceOptions.IncludedMembers,
solution,
refactoringResult.TypeNode,
cancellationToken).ConfigureAwait(false);
var document = symbolMapping.AnnotatedSolution.GetDocument(refactoringResult.DocumentToExtractFrom.Id);
var (documentWithInterface, _) = await ExtractTypeHelpers.AddTypeToExistingFileAsync(
document,
extractedInterfaceSymbol,
symbolMapping,
cancellationToken).ConfigureAwait(false);
var unformattedSolution = documentWithInterface.Project.Solution;
// After the interface is inserted, update the original type to show it implements the new interface
var unformattedSolutionWithUpdatedType = await GetSolutionWithOriginalTypeUpdatedAsync(
unformattedSolution, symbolMapping.DocumentIdsToSymbolMap.Keys.ToImmutableArray(),
symbolMapping.TypeNodeAnnotation,
refactoringResult.TypeToExtractFrom, extractedInterfaceSymbol,
extractInterfaceOptions.IncludedMembers, symbolMapping.SymbolToDeclarationAnnotationMap, cancellationToken).ConfigureAwait(false);
var completedSolution = await GetFormattedSolutionAsync(
unformattedSolutionWithUpdatedType,
symbolMapping.DocumentIdsToSymbolMap.Keys.Concat(refactoringResult.DocumentToExtractFrom.Id),
cancellationToken).ConfigureAwait(false);
return new ExtractInterfaceResult(
succeeded: true,
updatedSolution: completedSolution,
navigationDocumentId: refactoringResult.DocumentToExtractFrom.Id);
}
internal static Task<ExtractInterfaceOptionsResult> GetExtractInterfaceOptionsAsync(
Document document,
INamedTypeSymbol type,
IEnumerable<ISymbol> extractableMembers,
string containingNamespace,
CancellationToken cancellationToken)
{
var conflictingTypeNames = type.ContainingNamespace.GetAllTypes(cancellationToken).Select(t => t.Name);
var candidateInterfaceName = type.TypeKind == TypeKind.Interface ? type.Name : "I" + type.Name;
var defaultInterfaceName = NameGenerator.GenerateUniqueName(candidateInterfaceName, name => !conflictingTypeNames.Contains(name));
var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>();
var notificationService = document.Project.Solution.Workspace.Services.GetService<INotificationService>();
var generatedNameTypeParameterSuffix = ExtractTypeHelpers.GetTypeParameterSuffix(document, type, extractableMembers);
var service = document.Project.Solution.Workspace.Services.GetService<IExtractInterfaceOptionsService>();
return service.GetExtractInterfaceOptionsAsync(
syntaxFactsService,
notificationService,
extractableMembers.ToList(),
defaultInterfaceName,
conflictingTypeNames.ToList(),
containingNamespace,
generatedNameTypeParameterSuffix,
document.Project.Language);
}
private static async Task<Solution> GetFormattedSolutionAsync(Solution unformattedSolution, IEnumerable<DocumentId> documentIds, CancellationToken cancellationToken)
{
// Since code action performs formatting and simplification on a single document,
// this ensures that anything marked with formatter or simplifier annotations gets
// correctly handled as long as it it's in the listed documents
var formattedSolution = unformattedSolution;
foreach (var documentId in documentIds)
{
var document = formattedSolution.GetDocument(documentId);
var formattedDocument = await Formatter.FormatAsync(
document,
Formatter.Annotation,
cancellationToken: cancellationToken).ConfigureAwait(false);
var simplifiedDocument = await Simplifier.ReduceAsync(
formattedDocument,
Simplifier.Annotation,
cancellationToken: cancellationToken).ConfigureAwait(false);
formattedSolution = simplifiedDocument.Project.Solution;
}
return formattedSolution;
}
private async Task<Solution> GetSolutionWithOriginalTypeUpdatedAsync(
Solution solution,
ImmutableArray<DocumentId> documentIds,
SyntaxAnnotation typeNodeAnnotation,
INamedTypeSymbol typeToExtractFrom,
INamedTypeSymbol extractedInterfaceSymbol,
IEnumerable<ISymbol> includedMembers,
ImmutableDictionary<ISymbol, SyntaxAnnotation> symbolToDeclarationAnnotationMap,
CancellationToken cancellationToken)
{
// If an interface "INewInterface" is extracted from an interface "IExistingInterface",
// then "INewInterface" is not marked as implementing "IExistingInterface" and its
// extracted members are also not updated.
if (typeToExtractFrom.TypeKind == TypeKind.Interface)
{
return solution;
}
var unformattedSolution = solution;
foreach (var documentId in documentIds)
{
var document = solution.GetDocument(documentId);
var currentRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var editor = new SyntaxEditor(currentRoot, solution.Workspace);
var syntaxGenerator = SyntaxGenerator.GetGenerator(document);
var typeReference = syntaxGenerator.TypeExpression(extractedInterfaceSymbol);
var typeDeclaration = currentRoot.GetAnnotatedNodes(typeNodeAnnotation).SingleOrDefault();
if (typeDeclaration == null)
{
continue;
}
var unformattedTypeDeclaration = syntaxGenerator.AddInterfaceType(typeDeclaration, typeReference).WithAdditionalAnnotations(Formatter.Annotation);
editor.ReplaceNode(typeDeclaration, unformattedTypeDeclaration);
unformattedSolution = document.WithSyntaxRoot(editor.GetChangedRoot()).Project.Solution;
// Only update the first instance of the typedeclaration,
// since it's not needed in all declarations
break;
}
var updatedUnformattedSolution = await UpdateMembersWithExplicitImplementationsAsync(
unformattedSolution,
documentIds,
extractedInterfaceSymbol,
typeToExtractFrom,
includedMembers,
symbolToDeclarationAnnotationMap,
cancellationToken).ConfigureAwait(false);
return updatedUnformattedSolution;
}
private static ImmutableArray<ISymbol> CreateInterfaceMembers(IEnumerable<ISymbol> includedMembers)
{
using var _ = ArrayBuilder<ISymbol>.GetInstance(out var interfaceMembers);
foreach (var member in includedMembers)
{
switch (member.Kind)
{
case SymbolKind.Event:
var @event = member as IEventSymbol;
interfaceMembers.Add(CodeGenerationSymbolFactory.CreateEventSymbol(
attributes: ImmutableArray<AttributeData>.Empty,
accessibility: Accessibility.Public,
modifiers: new DeclarationModifiers(isAbstract: true),
type: @event.Type,
explicitInterfaceImplementations: default,
name: @event.Name));
break;
case SymbolKind.Method:
var method = member as IMethodSymbol;
interfaceMembers.Add(CodeGenerationSymbolFactory.CreateMethodSymbol(
attributes: ImmutableArray<AttributeData>.Empty,
accessibility: Accessibility.Public,
modifiers: new DeclarationModifiers(isAbstract: true, isUnsafe: method.RequiresUnsafeModifier()),
returnType: method.ReturnType,
refKind: method.RefKind,
explicitInterfaceImplementations: default,
name: method.Name,
typeParameters: method.TypeParameters,
parameters: method.Parameters,
isInitOnly: method.IsInitOnly));
break;
case SymbolKind.Property:
var property = member as IPropertySymbol;
interfaceMembers.Add(CodeGenerationSymbolFactory.CreatePropertySymbol(
attributes: ImmutableArray<AttributeData>.Empty,
accessibility: Accessibility.Public,
modifiers: new DeclarationModifiers(isAbstract: true, isUnsafe: property.RequiresUnsafeModifier()),
type: property.Type,
refKind: property.RefKind,
explicitInterfaceImplementations: default,
name: property.Name,
parameters: property.Parameters,
getMethod: property.GetMethod == null ? null : (property.GetMethod.DeclaredAccessibility == Accessibility.Public ? property.GetMethod : null),
setMethod: property.SetMethod == null ? null : (property.SetMethod.DeclaredAccessibility == Accessibility.Public ? property.SetMethod : null),
isIndexer: property.IsIndexer));
break;
default:
Debug.Assert(false, string.Format(FeaturesResources.Unexpected_interface_member_kind_colon_0, member.Kind.ToString()));
break;
}
}
return interfaceMembers.ToImmutable();
}
internal virtual bool IsExtractableMember(ISymbol m)
{
if (m.IsStatic ||
m.DeclaredAccessibility != Accessibility.Public ||
m.Name == "<Clone>$") // TODO: Use WellKnownMemberNames.CloneMethodName when it's public.
{
return false;
}
if (m.Kind == SymbolKind.Event || m.IsOrdinaryMethod())
{
return true;
}
if (m.Kind == SymbolKind.Property)
{
var prop = m as IPropertySymbol;
return !prop.IsWithEvents &&
((prop.GetMethod != null && prop.GetMethod.DeclaredAccessibility == Accessibility.Public) ||
(prop.SetMethod != null && prop.SetMethod.DeclaredAccessibility == Accessibility.Public));
}
return false;
}
}
}
| 1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./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,
ImmutableArray<SyntaxTrivia> fileBanner,
CancellationToken cancellationToken)
{
var newDocumentId = DocumentId.CreateNewId(projectId, debugName: fileName);
var solutionWithInterfaceDocument = solution.AddDocument(newDocumentId, fileName, text: "", folders: folders);
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 syntaxRoot = await newTypeDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var rootWithBanner = syntaxRoot.WithPrependedLeadingTrivia(fileBanner);
var typeAnnotation = new SyntaxAnnotation();
var syntaxFacts = newTypeDocument.GetRequiredLanguageService<ISyntaxFactsService>();
var declarationNode = rootWithBanner.DescendantNodes().First(syntaxFacts.IsTypeDeclaration);
var annotatedRoot = rootWithBanner.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 solutionWithInterfaceDocument = solution.AddDocument(newDocumentId, fileName, text: "", folders: folders);
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 | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/EditorFeatures/CSharpTest/ChangeSignature/ReorderParametersTests.InvocationErrors.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ChangeSignature;
using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature
{
public partial class ChangeSignatureTests : AbstractChangeSignatureTests
{
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ReorderMethodParameters_InvokeOnClassName_ShouldFail()
{
var markup = @"
using System;
class MyClass$$
{
public void Goo(int x, string y)
{
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.IncorrectKind);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ReorderMethodParameters_InvokeOnField_ShouldFail()
{
var markup = @"
using System;
class MyClass
{
int t$$ = 2;
public void Goo(int x, string y)
{
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.IncorrectKind);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ReorderMethodParameters_CanBeStartedEvenWithNoParameters()
{
var markup = @"class C { void $$M() { } }";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ReorderMethodParameters_InvokeOnOverloadedOperator_ShouldFail()
{
var markup = @"
class C
{
public static C $$operator +(C a, C b)
{
return null;
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.IncorrectKind);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ChangeSignature;
using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature
{
public partial class ChangeSignatureTests : AbstractChangeSignatureTests
{
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ReorderMethodParameters_InvokeOnClassName_ShouldFail()
{
var markup = @"
using System;
class MyClass$$
{
public void Goo(int x, string y)
{
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.IncorrectKind);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ReorderMethodParameters_InvokeOnField_ShouldFail()
{
var markup = @"
using System;
class MyClass
{
int t$$ = 2;
public void Goo(int x, string y)
{
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.IncorrectKind);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ReorderMethodParameters_CanBeStartedEvenWithNoParameters()
{
var markup = @"class C { void $$M() { } }";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task ReorderMethodParameters_InvokeOnOverloadedOperator_ShouldFail()
{
var markup = @"
class C
{
public static C $$operator +(C a, C b)
{
return null;
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.IncorrectKind);
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Workspaces/CSharp/Portable/Simplification/Reducers/AbstractCSharpReducer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.PooledObjects;
using Microsoft.CodeAnalysis.Simplification;
namespace Microsoft.CodeAnalysis.CSharp.Simplification
{
internal abstract partial class AbstractCSharpReducer : AbstractReducer
{
protected AbstractCSharpReducer(ObjectPool<IReductionRewriter> pool) : base(pool)
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.PooledObjects;
using Microsoft.CodeAnalysis.Simplification;
namespace Microsoft.CodeAnalysis.CSharp.Simplification
{
internal abstract partial class AbstractCSharpReducer : AbstractReducer
{
protected AbstractCSharpReducer(ObjectPool<IReductionRewriter> pool) : base(pool)
{
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedFieldSymbolBase.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Represents a compiler generated field or captured variable.
/// </summary>
internal abstract class SynthesizedFieldSymbolBase : FieldSymbol
{
private readonly NamedTypeSymbol _containingType;
private readonly string _name;
private readonly DeclarationModifiers _modifiers;
public SynthesizedFieldSymbolBase(
NamedTypeSymbol containingType,
string name,
bool isPublic,
bool isReadOnly,
bool isStatic)
{
Debug.Assert((object)containingType != null);
Debug.Assert(!string.IsNullOrEmpty(name));
_containingType = containingType;
_name = name;
_modifiers = (isPublic ? DeclarationModifiers.Public : DeclarationModifiers.Private) |
(isReadOnly ? DeclarationModifiers.ReadOnly : DeclarationModifiers.None) |
(isStatic ? DeclarationModifiers.Static : DeclarationModifiers.None);
}
internal abstract bool SuppressDynamicAttribute
{
get;
}
internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes)
{
base.AddSynthesizedAttributes(moduleBuilder, ref attributes);
CSharpCompilation compilation = this.DeclaringCompilation;
var typeWithAnnotations = this.TypeWithAnnotations;
var type = typeWithAnnotations.Type;
// do not emit CompilerGenerated attributes for fields inside compiler generated types:
if (!_containingType.IsImplicitlyDeclared)
{
AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor));
}
if (!this.SuppressDynamicAttribute &&
type.ContainsDynamic() &&
compilation.HasDynamicEmitAttributes(BindingDiagnosticBag.Discarded, Location.None) &&
compilation.CanEmitBoolean())
{
AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(type, typeWithAnnotations.CustomModifiers.Length));
}
if (type.ContainsNativeInteger())
{
AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, type));
}
if (type.ContainsTupleNames() &&
compilation.HasTupleNamesAttributes(BindingDiagnosticBag.Discarded, Location.None) &&
compilation.CanEmitSpecialType(SpecialType.System_String))
{
AddSynthesizedAttribute(ref attributes,
compilation.SynthesizeTupleNamesAttribute(Type));
}
if (compilation.ShouldEmitNullableAttributes(this))
{
AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, ContainingType.GetNullableContextValue(), typeWithAnnotations));
}
}
internal abstract override TypeWithAnnotations GetFieldType(ConsList<FieldSymbol> fieldsBeingBound);
public override FlowAnalysisAnnotations FlowAnalysisAnnotations
=> FlowAnalysisAnnotations.None;
public override string Name
{
get { return _name; }
}
public override Symbol AssociatedSymbol
{
get
{
return null;
}
}
public override bool IsReadOnly
{
get { return (_modifiers & DeclarationModifiers.ReadOnly) != 0; }
}
public override bool IsVolatile
{
get { return false; }
}
public override bool IsConst
{
get { return false; }
}
internal override bool IsNotSerialized
{
get { return false; }
}
internal override MarshalPseudoCustomAttributeData MarshallingInformation
{
get { return null; }
}
internal override int? TypeLayoutOffset
{
get { return null; }
}
internal override ConstantValue GetConstantValue(ConstantFieldsInProgress inProgress, bool earlyDecodingWellKnownAttributes)
{
return null;
}
internal sealed override ObsoleteAttributeData ObsoleteAttributeData
{
get { return null; }
}
public override Symbol ContainingSymbol
{
get { return _containingType; }
}
public override NamedTypeSymbol ContainingType
{
get
{
return _containingType;
}
}
public override ImmutableArray<Location> Locations
{
get { return ImmutableArray<Location>.Empty; }
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get
{
return ImmutableArray<SyntaxReference>.Empty;
}
}
public override Accessibility DeclaredAccessibility
{
get { return ModifierUtils.EffectiveAccessibility(_modifiers); }
}
public override bool IsStatic
{
get { return (_modifiers & DeclarationModifiers.Static) != 0; }
}
internal override bool HasSpecialName
{
get { return this.HasRuntimeSpecialName; }
}
internal override bool HasRuntimeSpecialName
{
get { return this.Name == WellKnownMemberNames.EnumBackingFieldName; }
}
public override bool IsImplicitlyDeclared
{
get { 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.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Represents a compiler generated field or captured variable.
/// </summary>
internal abstract class SynthesizedFieldSymbolBase : FieldSymbol
{
private readonly NamedTypeSymbol _containingType;
private readonly string _name;
private readonly DeclarationModifiers _modifiers;
public SynthesizedFieldSymbolBase(
NamedTypeSymbol containingType,
string name,
bool isPublic,
bool isReadOnly,
bool isStatic)
{
Debug.Assert((object)containingType != null);
Debug.Assert(!string.IsNullOrEmpty(name));
_containingType = containingType;
_name = name;
_modifiers = (isPublic ? DeclarationModifiers.Public : DeclarationModifiers.Private) |
(isReadOnly ? DeclarationModifiers.ReadOnly : DeclarationModifiers.None) |
(isStatic ? DeclarationModifiers.Static : DeclarationModifiers.None);
}
internal abstract bool SuppressDynamicAttribute
{
get;
}
internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes)
{
base.AddSynthesizedAttributes(moduleBuilder, ref attributes);
CSharpCompilation compilation = this.DeclaringCompilation;
var typeWithAnnotations = this.TypeWithAnnotations;
var type = typeWithAnnotations.Type;
// do not emit CompilerGenerated attributes for fields inside compiler generated types:
if (!_containingType.IsImplicitlyDeclared)
{
AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor));
}
if (!this.SuppressDynamicAttribute &&
type.ContainsDynamic() &&
compilation.HasDynamicEmitAttributes(BindingDiagnosticBag.Discarded, Location.None) &&
compilation.CanEmitBoolean())
{
AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(type, typeWithAnnotations.CustomModifiers.Length));
}
if (type.ContainsNativeInteger())
{
AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, type));
}
if (type.ContainsTupleNames() &&
compilation.HasTupleNamesAttributes(BindingDiagnosticBag.Discarded, Location.None) &&
compilation.CanEmitSpecialType(SpecialType.System_String))
{
AddSynthesizedAttribute(ref attributes,
compilation.SynthesizeTupleNamesAttribute(Type));
}
if (compilation.ShouldEmitNullableAttributes(this))
{
AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, ContainingType.GetNullableContextValue(), typeWithAnnotations));
}
}
internal abstract override TypeWithAnnotations GetFieldType(ConsList<FieldSymbol> fieldsBeingBound);
public override FlowAnalysisAnnotations FlowAnalysisAnnotations
=> FlowAnalysisAnnotations.None;
public override string Name
{
get { return _name; }
}
public override Symbol AssociatedSymbol
{
get
{
return null;
}
}
public override bool IsReadOnly
{
get { return (_modifiers & DeclarationModifiers.ReadOnly) != 0; }
}
public override bool IsVolatile
{
get { return false; }
}
public override bool IsConst
{
get { return false; }
}
internal override bool IsNotSerialized
{
get { return false; }
}
internal override MarshalPseudoCustomAttributeData MarshallingInformation
{
get { return null; }
}
internal override int? TypeLayoutOffset
{
get { return null; }
}
internal override ConstantValue GetConstantValue(ConstantFieldsInProgress inProgress, bool earlyDecodingWellKnownAttributes)
{
return null;
}
internal sealed override ObsoleteAttributeData ObsoleteAttributeData
{
get { return null; }
}
public override Symbol ContainingSymbol
{
get { return _containingType; }
}
public override NamedTypeSymbol ContainingType
{
get
{
return _containingType;
}
}
public override ImmutableArray<Location> Locations
{
get { return ImmutableArray<Location>.Empty; }
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get
{
return ImmutableArray<SyntaxReference>.Empty;
}
}
public override Accessibility DeclaredAccessibility
{
get { return ModifierUtils.EffectiveAccessibility(_modifiers); }
}
public override bool IsStatic
{
get { return (_modifiers & DeclarationModifiers.Static) != 0; }
}
internal override bool HasSpecialName
{
get { return this.HasRuntimeSpecialName; }
}
internal override bool HasRuntimeSpecialName
{
get { return this.Name == WellKnownMemberNames.EnumBackingFieldName; }
}
public override bool IsImplicitlyDeclared
{
get { return true; }
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Compilers/Test/Core/TestableFile.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using Microsoft.CodeAnalysis;
using Roslyn.Utilities;
namespace Roslyn.Test.Utilities
{
/// <summary>
/// This works with <see cref="TestableFileSystem"/> to have an "in memory" file that can
/// be manipulated by consumers of <see cref="ICommonCompilerFileSystem"/>
///
/// This isn't meant to handle complex file system interactions but the basic cases of open,
/// close, create, read and write.
/// </summary>
public sealed class TestableFile
{
private sealed class TestableFileStream : MemoryStream
{
public TestableFile MemoryFile { get; }
public bool CopyBack { get; }
public TestableFileStream(TestableFile memoryFile)
{
Debug.Assert(!memoryFile.Exists);
MemoryFile = memoryFile;
MemoryFile.Exists = true;
CopyBack = true;
}
public TestableFileStream(TestableFile memoryFile, byte[] bytes, bool writable)
: base(bytes, writable)
{
Debug.Assert(memoryFile.Exists);
MemoryFile = memoryFile;
CopyBack = writable;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (CopyBack)
{
MemoryFile.Contents.Clear();
MemoryFile.Contents.AddRange(this.ToArray());
}
}
base.Dispose(disposing);
}
}
public bool Exists { get; private set; }
public List<byte> Contents { get; } = new List<byte>();
public TestableFile()
{
}
public TestableFile(string contents)
{
Exists = true;
Contents.AddRange(Encoding.UTF8.GetBytes(contents));
}
public TestableFile(byte[] contents)
{
Exists = true;
Contents.AddRange(contents);
}
public MemoryStream GetStream(FileAccess access = FileAccess.ReadWrite)
{
var writable = access is FileAccess.Write or FileAccess.ReadWrite;
if (!Exists)
{
if (!writable)
{
throw new InvalidOperationException();
}
return new TestableFileStream(this);
}
return new TestableFileStream(this, Contents.ToArray(), writable);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using Microsoft.CodeAnalysis;
using Roslyn.Utilities;
namespace Roslyn.Test.Utilities
{
/// <summary>
/// This works with <see cref="TestableFileSystem"/> to have an "in memory" file that can
/// be manipulated by consumers of <see cref="ICommonCompilerFileSystem"/>
///
/// This isn't meant to handle complex file system interactions but the basic cases of open,
/// close, create, read and write.
/// </summary>
public sealed class TestableFile
{
private sealed class TestableFileStream : MemoryStream
{
public TestableFile MemoryFile { get; }
public bool CopyBack { get; }
public TestableFileStream(TestableFile memoryFile)
{
Debug.Assert(!memoryFile.Exists);
MemoryFile = memoryFile;
MemoryFile.Exists = true;
CopyBack = true;
}
public TestableFileStream(TestableFile memoryFile, byte[] bytes, bool writable)
: base(bytes, writable)
{
Debug.Assert(memoryFile.Exists);
MemoryFile = memoryFile;
CopyBack = writable;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (CopyBack)
{
MemoryFile.Contents.Clear();
MemoryFile.Contents.AddRange(this.ToArray());
}
}
base.Dispose(disposing);
}
}
public bool Exists { get; private set; }
public List<byte> Contents { get; } = new List<byte>();
public TestableFile()
{
}
public TestableFile(string contents)
{
Exists = true;
Contents.AddRange(Encoding.UTF8.GetBytes(contents));
}
public TestableFile(byte[] contents)
{
Exists = true;
Contents.AddRange(contents);
}
public MemoryStream GetStream(FileAccess access = FileAccess.ReadWrite)
{
var writable = access is FileAccess.Write or FileAccess.ReadWrite;
if (!Exists)
{
if (!writable)
{
throw new InvalidOperationException();
}
return new TestableFileStream(this);
}
return new TestableFileStream(this, Contents.ToArray(), writable);
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_ITypeOfExpression.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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 Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_ITypeOfExpression : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestTypeOfExpression()
{
string source = @"
using System;
class C
{
void M(Type t)
{
t = /*<bind>*/typeof(int)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITypeOfOperation (OperationKind.TypeOf, Type: System.Type) (Syntax: 'typeof(int)')
TypeOperand: System.Int32
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<TypeOfExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestTypeOfExpression_NonPrimitiveTypeArgument()
{
string source = @"
using System;
class C
{
void M(Type t)
{
t = /*<bind>*/typeof(C)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITypeOfOperation (OperationKind.TypeOf, Type: System.Type) (Syntax: 'typeof(C)')
TypeOperand: C
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<TypeOfExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestTypeOfExpression_ErrorTypeArgument()
{
string source = @"
using System;
class C
{
void M(Type t)
{
t = /*<bind>*/typeof(UndefinedType)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITypeOfOperation (OperationKind.TypeOf, Type: System.Type, IsInvalid) (Syntax: 'typeof(UndefinedType)')
TypeOperand: UndefinedType
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0246: The type or namespace name 'UndefinedType' could not be found (are you missing a using directive or an assembly reference?)
// t = /*<bind>*/typeof(UndefinedType)/*</bind>*/;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UndefinedType").WithArguments("UndefinedType").WithLocation(8, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<TypeOfExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestTypeOfExpression_IdentifierArgument()
{
string source = @"
using System;
class C
{
void M(Type t)
{
t = /*<bind>*/typeof(t)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITypeOfOperation (OperationKind.TypeOf, Type: System.Type, IsInvalid) (Syntax: 'typeof(t)')
TypeOperand: t
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0118: 't' is a variable but is used like a type
// t = /*<bind>*/typeof(t)/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadSKknown, "t").WithArguments("t", "variable", "type").WithLocation(8, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<TypeOfExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestTypeOfExpression_ExpressionArgument()
{
string source = @"
using System;
class C
{
void M(Type t)
{
t = /*<bind>*/typeof(M2()/*</bind>*/);
}
Type M2() => null;
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'typeof(M2()')
Children(1):
ITypeOfOperation (OperationKind.TypeOf, Type: System.Type, IsInvalid) (Syntax: 'typeof(M2')
TypeOperand: M2
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1026: ) expected
// t = /*<bind>*/typeof(M2()/*</bind>*/);
Diagnostic(ErrorCode.ERR_CloseParenExpected, "(").WithLocation(8, 32),
// CS1002: ; expected
// t = /*<bind>*/typeof(M2()/*</bind>*/);
Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(8, 45),
// CS1513: } expected
// t = /*<bind>*/typeof(M2()/*</bind>*/);
Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(8, 45),
// CS0246: The type or namespace name 'M2' could not be found (are you missing a using directive or an assembly reference?)
// t = /*<bind>*/typeof(M2()/*</bind>*/);
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "M2").WithArguments("M2").WithLocation(8, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestTypeOfExpression_MissingArgument()
{
string source = @"
using System;
class C
{
void M(Type t)
{
t = /*<bind>*/typeof()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITypeOfOperation (OperationKind.TypeOf, Type: System.Type, IsInvalid) (Syntax: 'typeof()')
TypeOperand: ?
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1031: Type expected
// t = /*<bind>*/typeof()/*</bind>*/;
Diagnostic(ErrorCode.ERR_TypeExpected, ")").WithLocation(8, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<TypeOfExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void TypeOfFlow_01()
{
string source = @"
class C
{
void M(System.Type t)
/*<bind>*/{
t = typeof(bool);
}/*</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: 't = typeof(bool);')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Type) (Syntax: 't = typeof(bool)')
Left:
IParameterReferenceOperation: t (OperationKind.ParameterReference, Type: System.Type) (Syntax: 't')
Right:
ITypeOfOperation (OperationKind.TypeOf, Type: System.Type) (Syntax: 'typeof(bool)')
TypeOperand: System.Boolean
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(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 Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_ITypeOfExpression : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestTypeOfExpression()
{
string source = @"
using System;
class C
{
void M(Type t)
{
t = /*<bind>*/typeof(int)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITypeOfOperation (OperationKind.TypeOf, Type: System.Type) (Syntax: 'typeof(int)')
TypeOperand: System.Int32
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<TypeOfExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestTypeOfExpression_NonPrimitiveTypeArgument()
{
string source = @"
using System;
class C
{
void M(Type t)
{
t = /*<bind>*/typeof(C)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITypeOfOperation (OperationKind.TypeOf, Type: System.Type) (Syntax: 'typeof(C)')
TypeOperand: C
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<TypeOfExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestTypeOfExpression_ErrorTypeArgument()
{
string source = @"
using System;
class C
{
void M(Type t)
{
t = /*<bind>*/typeof(UndefinedType)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITypeOfOperation (OperationKind.TypeOf, Type: System.Type, IsInvalid) (Syntax: 'typeof(UndefinedType)')
TypeOperand: UndefinedType
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0246: The type or namespace name 'UndefinedType' could not be found (are you missing a using directive or an assembly reference?)
// t = /*<bind>*/typeof(UndefinedType)/*</bind>*/;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UndefinedType").WithArguments("UndefinedType").WithLocation(8, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<TypeOfExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestTypeOfExpression_IdentifierArgument()
{
string source = @"
using System;
class C
{
void M(Type t)
{
t = /*<bind>*/typeof(t)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITypeOfOperation (OperationKind.TypeOf, Type: System.Type, IsInvalid) (Syntax: 'typeof(t)')
TypeOperand: t
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0118: 't' is a variable but is used like a type
// t = /*<bind>*/typeof(t)/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadSKknown, "t").WithArguments("t", "variable", "type").WithLocation(8, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<TypeOfExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestTypeOfExpression_ExpressionArgument()
{
string source = @"
using System;
class C
{
void M(Type t)
{
t = /*<bind>*/typeof(M2()/*</bind>*/);
}
Type M2() => null;
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'typeof(M2()')
Children(1):
ITypeOfOperation (OperationKind.TypeOf, Type: System.Type, IsInvalid) (Syntax: 'typeof(M2')
TypeOperand: M2
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1026: ) expected
// t = /*<bind>*/typeof(M2()/*</bind>*/);
Diagnostic(ErrorCode.ERR_CloseParenExpected, "(").WithLocation(8, 32),
// CS1002: ; expected
// t = /*<bind>*/typeof(M2()/*</bind>*/);
Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(8, 45),
// CS1513: } expected
// t = /*<bind>*/typeof(M2()/*</bind>*/);
Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(8, 45),
// CS0246: The type or namespace name 'M2' could not be found (are you missing a using directive or an assembly reference?)
// t = /*<bind>*/typeof(M2()/*</bind>*/);
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "M2").WithArguments("M2").WithLocation(8, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestTypeOfExpression_MissingArgument()
{
string source = @"
using System;
class C
{
void M(Type t)
{
t = /*<bind>*/typeof()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITypeOfOperation (OperationKind.TypeOf, Type: System.Type, IsInvalid) (Syntax: 'typeof()')
TypeOperand: ?
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1031: Type expected
// t = /*<bind>*/typeof()/*</bind>*/;
Diagnostic(ErrorCode.ERR_TypeExpected, ")").WithLocation(8, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<TypeOfExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void TypeOfFlow_01()
{
string source = @"
class C
{
void M(System.Type t)
/*<bind>*/{
t = typeof(bool);
}/*</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: 't = typeof(bool);')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Type) (Syntax: 't = typeof(bool)')
Left:
IParameterReferenceOperation: t (OperationKind.ParameterReference, Type: System.Type) (Syntax: 't')
Right:
ITypeOfOperation (OperationKind.TypeOf, Type: System.Type) (Syntax: 'typeof(bool)')
TypeOperand: System.Boolean
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Features/Core/Portable/MetadataAsSource/MetadataAsSourceWorkspace.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Host;
namespace Microsoft.CodeAnalysis.MetadataAsSource
{
internal class MetadataAsSourceWorkspace : Workspace
{
public readonly MetadataAsSourceFileService FileService;
public MetadataAsSourceWorkspace(MetadataAsSourceFileService fileService, HostServices hostServices)
: base(hostServices, WorkspaceKind.MetadataAsSource)
{
this.FileService = fileService;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Host;
namespace Microsoft.CodeAnalysis.MetadataAsSource
{
internal class MetadataAsSourceWorkspace : Workspace
{
public readonly MetadataAsSourceFileService FileService;
public MetadataAsSourceWorkspace(MetadataAsSourceFileService fileService, HostServices hostServices)
: base(hostServices, WorkspaceKind.MetadataAsSource)
{
this.FileService = fileService;
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Features/Core/Portable/CodeLens/ReferenceLocationDescriptor.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Runtime.Serialization;
namespace Microsoft.CodeAnalysis.CodeLens
{
/// <summary>
/// Holds information required to display and navigate to individual references
/// </summary>
[DataContract]
internal sealed class ReferenceLocationDescriptor
{
/// <summary>
/// Fully qualified name of the symbol containing the reference location
/// </summary>
[DataMember(Order = 0)]
public string LongDescription { get; }
/// <summary>
/// Language of the reference location
/// </summary>
[DataMember(Order = 1)]
public string Language { get; }
/// <summary>
/// The kind of symbol containing the reference location (such as type, method, property, etc.)
/// </summary>
[DataMember(Order = 2)]
public Glyph? Glyph { get; }
/// <summary>
/// Reference's span start based on the document content
/// </summary>
[DataMember(Order = 3)]
public int SpanStart { get; }
/// <summary>
/// Reference's span length based on the document content
/// </summary>
[DataMember(Order = 4)]
public int SpanLength { get; }
/// <summary>
/// Reference's line based on the document content
/// </summary>
[DataMember(Order = 5)]
public int LineNumber { get; }
/// <summary>
/// Reference's character based on the document content
/// </summary>
[DataMember(Order = 6)]
public int ColumnNumber { get; }
[DataMember(Order = 7)]
public Guid ProjectGuid { get; }
[DataMember(Order = 8)]
public Guid DocumentGuid { get; }
/// <summary>
/// Document's file path
/// </summary>
[DataMember(Order = 9)]
public string FilePath { get; }
/// <summary>
/// the full line of source that contained the reference
/// </summary>
[DataMember(Order = 10)]
public string ReferenceLineText { get; }
/// <summary>
/// the beginning of the span within reference text that was the use of the reference
/// </summary>
[DataMember(Order = 11)]
public int ReferenceStart { get; }
/// <summary>
/// the length of the span of the reference
/// </summary>
[DataMember(Order = 12)]
public int ReferenceLength { get; }
/// <summary>
/// Text above the line with the reference
/// </summary>
[DataMember(Order = 13)]
public string BeforeReferenceText1 { get; }
/// <summary>
/// Text above the line with the reference
/// </summary>
[DataMember(Order = 14)]
public string BeforeReferenceText2 { get; }
/// <summary>
/// Text below the line with the reference
/// </summary>
[DataMember(Order = 15)]
public string AfterReferenceText1 { get; }
/// <summary>
/// Text below the line with the reference
/// </summary>
[DataMember(Order = 16)]
public string AfterReferenceText2 { get; }
public ReferenceLocationDescriptor(
string longDescription,
string language,
Glyph? glyph,
int spanStart,
int spanLength,
int lineNumber,
int columnNumber,
Guid projectGuid,
Guid documentGuid,
string filePath,
string referenceLineText,
int referenceStart,
int referenceLength,
string beforeReferenceText1,
string beforeReferenceText2,
string afterReferenceText1,
string afterReferenceText2)
{
LongDescription = longDescription;
Language = language;
Glyph = glyph;
SpanStart = spanStart;
SpanLength = spanLength;
LineNumber = lineNumber;
ColumnNumber = columnNumber;
// We want to keep track of the location's document if it comes from a file in your solution.
ProjectGuid = projectGuid;
DocumentGuid = documentGuid;
FilePath = filePath;
ReferenceLineText = referenceLineText;
ReferenceStart = referenceStart;
ReferenceLength = referenceLength;
BeforeReferenceText1 = beforeReferenceText1;
BeforeReferenceText2 = beforeReferenceText2;
AfterReferenceText1 = afterReferenceText1;
AfterReferenceText2 = afterReferenceText2;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Runtime.Serialization;
namespace Microsoft.CodeAnalysis.CodeLens
{
/// <summary>
/// Holds information required to display and navigate to individual references
/// </summary>
[DataContract]
internal sealed class ReferenceLocationDescriptor
{
/// <summary>
/// Fully qualified name of the symbol containing the reference location
/// </summary>
[DataMember(Order = 0)]
public string LongDescription { get; }
/// <summary>
/// Language of the reference location
/// </summary>
[DataMember(Order = 1)]
public string Language { get; }
/// <summary>
/// The kind of symbol containing the reference location (such as type, method, property, etc.)
/// </summary>
[DataMember(Order = 2)]
public Glyph? Glyph { get; }
/// <summary>
/// Reference's span start based on the document content
/// </summary>
[DataMember(Order = 3)]
public int SpanStart { get; }
/// <summary>
/// Reference's span length based on the document content
/// </summary>
[DataMember(Order = 4)]
public int SpanLength { get; }
/// <summary>
/// Reference's line based on the document content
/// </summary>
[DataMember(Order = 5)]
public int LineNumber { get; }
/// <summary>
/// Reference's character based on the document content
/// </summary>
[DataMember(Order = 6)]
public int ColumnNumber { get; }
[DataMember(Order = 7)]
public Guid ProjectGuid { get; }
[DataMember(Order = 8)]
public Guid DocumentGuid { get; }
/// <summary>
/// Document's file path
/// </summary>
[DataMember(Order = 9)]
public string FilePath { get; }
/// <summary>
/// the full line of source that contained the reference
/// </summary>
[DataMember(Order = 10)]
public string ReferenceLineText { get; }
/// <summary>
/// the beginning of the span within reference text that was the use of the reference
/// </summary>
[DataMember(Order = 11)]
public int ReferenceStart { get; }
/// <summary>
/// the length of the span of the reference
/// </summary>
[DataMember(Order = 12)]
public int ReferenceLength { get; }
/// <summary>
/// Text above the line with the reference
/// </summary>
[DataMember(Order = 13)]
public string BeforeReferenceText1 { get; }
/// <summary>
/// Text above the line with the reference
/// </summary>
[DataMember(Order = 14)]
public string BeforeReferenceText2 { get; }
/// <summary>
/// Text below the line with the reference
/// </summary>
[DataMember(Order = 15)]
public string AfterReferenceText1 { get; }
/// <summary>
/// Text below the line with the reference
/// </summary>
[DataMember(Order = 16)]
public string AfterReferenceText2 { get; }
public ReferenceLocationDescriptor(
string longDescription,
string language,
Glyph? glyph,
int spanStart,
int spanLength,
int lineNumber,
int columnNumber,
Guid projectGuid,
Guid documentGuid,
string filePath,
string referenceLineText,
int referenceStart,
int referenceLength,
string beforeReferenceText1,
string beforeReferenceText2,
string afterReferenceText1,
string afterReferenceText2)
{
LongDescription = longDescription;
Language = language;
Glyph = glyph;
SpanStart = spanStart;
SpanLength = spanLength;
LineNumber = lineNumber;
ColumnNumber = columnNumber;
// We want to keep track of the location's document if it comes from a file in your solution.
ProjectGuid = projectGuid;
DocumentGuid = documentGuid;
FilePath = filePath;
ReferenceLineText = referenceLineText;
ReferenceStart = referenceStart;
ReferenceLength = referenceLength;
BeforeReferenceText1 = beforeReferenceText1;
BeforeReferenceText2 = beforeReferenceText2;
AfterReferenceText1 = afterReferenceText1;
AfterReferenceText2 = afterReferenceText2;
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Workspaces/Core/Portable/PatternMatching/AllLowerCamelCaseMatcher.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Globalization;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.PatternMatching
{
internal partial class PatternMatcher
{
/// <summary>
/// Encapsulated matches responsible for matching an all lowercase pattern against
/// a candidate using CamelCase matching. i.e. this code is responsible for finding the
/// match between "cofipro" and "CodeFixProvider".
/// </summary>
private readonly struct AllLowerCamelCaseMatcher
{
private readonly bool _includeMatchedSpans;
private readonly string _candidate;
private readonly string _patternText;
private readonly TextInfo _textInfo;
public AllLowerCamelCaseMatcher(
bool includeMatchedSpans,
string candidate,
string patternChunkText,
TextInfo textInfo)
{
_includeMatchedSpans = includeMatchedSpans;
_candidate = candidate;
_patternText = patternChunkText;
_textInfo = textInfo;
}
/// <summary>
/// Returns null if no match was found, 1 if a contiguous match was found, 2 if a
/// match as found that starts at the beginning of the candidate, and 3 if a contiguous
/// match was found that starts at the beginning of the candidate.
/// </summary>
public PatternMatchKind? TryMatch(
in TemporaryArray<TextSpan> candidateHumps, out ImmutableArray<TextSpan> matchedSpans)
{
// We have something like cofipro and we want to match CodeFixProvider.
//
// Note that this is incredibly ambiguous. We'd also want this to match
// CorporateOfficePartsRoom So, for example, if we were to consume the "co"
// as matching "Corporate", then "f" wouldn't match any camel hump. So we
// basically have to branch out and try all options at every character
// in the pattern chunk.
var result = TryMatch(
patternIndex: 0, candidateHumpIndex: 0, contiguous: null, candidateHumps);
if (result == null)
{
matchedSpans = ImmutableArray<TextSpan>.Empty;
return null;
}
matchedSpans = _includeMatchedSpans && result.Value.MatchedSpansInReverse != null
? new NormalizedTextSpanCollection(result.Value.MatchedSpansInReverse).ToImmutableArray()
: ImmutableArray<TextSpan>.Empty;
result?.Free();
return GetKind(result.Value, candidateHumps);
}
private static PatternMatchKind GetKind(CamelCaseResult result, in TemporaryArray<TextSpan> candidateHumps)
=> GetCamelCaseKind(result, candidateHumps);
private CamelCaseResult? TryMatch(
int patternIndex, int candidateHumpIndex, bool? contiguous, in TemporaryArray<TextSpan> candidateHumps)
{
if (patternIndex == _patternText.Length)
{
// We hit the end. So we were able to match against this candidate.
// We are contiguous if our contiguous tracker was not set to false.
var matchedSpansInReverse = _includeMatchedSpans ? ArrayBuilder<TextSpan>.GetInstance() : null;
return new CamelCaseResult(
fromStart: false,
contiguous: contiguous != false,
matchCount: 0,
matchedSpansInReverse: matchedSpansInReverse);
}
var bestResult = (CamelCaseResult?)null;
// Look for a hump in the candidate that matches the current letter we're on.
var patternCharacter = _patternText[patternIndex];
for (int humpIndex = candidateHumpIndex, n = candidateHumps.Count; humpIndex < n; humpIndex++)
{
// If we've been contiguous, but we jumped past a hump, then we're no longer contiguous.
if (contiguous.HasValue && contiguous.Value)
{
contiguous = humpIndex == candidateHumpIndex;
}
var candidateHump = candidateHumps[humpIndex];
if (ToLower(_candidate[candidateHump.Start], _textInfo) == patternCharacter)
{
// Found a hump in the candidate string that matches the current pattern
// character we're on. i.e. we matched the c in cofipro against the C in
// CodeFixProvider.
//
// Now, for each subsequent character, we need to both try to consume it
// as part of the current hump, or see if it should match the next hump.
//
// Note, if the candidate is something like CodeFixProvider and our pattern
// is cofipro, and we've matched the 'f' against the 'F', then the max of
// the pattern we'll want to consume is "fip" against "Fix". We don't want
// consume parts of the pattern once we reach the next hump.
// We matched something. If this was our first match, consider ourselves
// contiguous.
var localContiguous = contiguous == null ? true : contiguous.Value;
var result = TryConsumePatternOrMatchNextHump(
patternIndex, humpIndex, localContiguous, candidateHumps);
if (result == null)
{
continue;
}
if (UpdateBestResultIfBetter(result.Value, ref bestResult, matchSpanToAdd: null, candidateHumps))
{
// We found the best result so far. We can stop immediately.
break;
}
}
}
return bestResult;
}
private static char ToLower(char v, TextInfo textInfo)
{
return IsAscii(v)
? ToLowerAsciiInvariant(v)
: textInfo.ToLower(v);
}
private static bool IsAscii(char v)
=> v < 0x80;
private static char ToLowerAsciiInvariant(char c)
=> 'A' <= c && c <= 'Z'
? (char)(c | 0x20)
: c;
private CamelCaseResult? TryConsumePatternOrMatchNextHump(
int patternIndex, int humpIndex, bool contiguous, in TemporaryArray<TextSpan> candidateHumps)
{
var bestResult = (CamelCaseResult?)null;
var candidateHump = candidateHumps[humpIndex];
var maxPatternHumpLength = _patternText.Length - patternIndex;
var maxCandidateHumpLength = candidateHump.Length;
var maxHumpMatchLength = Math.Min(maxPatternHumpLength, maxCandidateHumpLength);
for (var possibleHumpMatchLength = 1; possibleHumpMatchLength <= maxHumpMatchLength; possibleHumpMatchLength++)
{
if (!LowercaseSubstringsMatch(
_candidate, candidateHump.Start,
_patternText, patternIndex, possibleHumpMatchLength))
{
// Stop trying to consume once the pattern contents no longer matches
// against the current candidate hump.
break;
}
// The pattern substring 'f' has matched against 'F', or 'fi' has matched
// against 'Fi'. recurse and let the rest of the pattern match the remainder
// of the candidate.
var resultOpt = TryMatch(
patternIndex + possibleHumpMatchLength, humpIndex + 1, contiguous, candidateHumps);
if (resultOpt == null)
{
// Didn't match. Try the next longer pattern chunk.
continue;
}
var result = resultOpt.Value;
// If this is our first hump add a 'from start' bonus.
if (humpIndex == 0)
{
result = result.WithFromStart(true);
}
// This is the span of the hump of the candidate we matched.
var matchSpanToAdd = new TextSpan(candidateHump.Start, possibleHumpMatchLength);
if (UpdateBestResultIfBetter(result, ref bestResult, matchSpanToAdd, candidateHumps))
{
// We found the best result so far. We can stop immediately.
break;
}
}
return bestResult;
}
/// <summary>
/// Updates the currently stored 'best result' if the current result is better.
/// Returns 'true' if no further work is required and we can break early, or
/// 'false' if we need to keep on going.
///
/// If 'weight' is better than 'bestWeight' and matchSpanToAdd is not null, then
/// matchSpanToAdd will be added to matchedSpansInReverse.
/// </summary>
private static bool UpdateBestResultIfBetter(
CamelCaseResult result, ref CamelCaseResult? bestResult, TextSpan? matchSpanToAdd, in TemporaryArray<TextSpan> candidateHumps)
{
if (matchSpanToAdd != null)
{
result = result.WithAddedMatchedSpan(matchSpanToAdd.Value);
}
if (!IsBetter(result, bestResult, candidateHumps))
{
// Even though we matched this current candidate hump we failed to match
// the remainder of the pattern. Continue to the next candidate hump
// to see if our pattern character will match it and potentially succeed.
result.Free();
// We need to keep going.
return false;
}
// This was result was better than whatever previous best result we had was.
// Free and overwrite the existing best results, and keep going.
bestResult?.Free();
bestResult = result;
// We found a path that allowed us to match everything contiguously
// from the beginning. This is the best match possible. So we can
// just break out now and return this result.
return GetKind(result, candidateHumps) == PatternMatchKind.CamelCaseExact;
}
private static bool IsBetter(CamelCaseResult result, CamelCaseResult? currentBestResult, in TemporaryArray<TextSpan> candidateHumps)
{
if (currentBestResult == null)
{
// We have no current best. So this result is the best.
return true;
}
return GetKind(result, candidateHumps) < GetKind(currentBestResult.Value, candidateHumps);
}
private bool LowercaseSubstringsMatch(
string s1, int start1, string s2, int start2, int length)
{
var textInfo = _textInfo;
for (var i = 0; i < length; i++)
{
if (ToLower(s1[start1 + i], textInfo) != ToLower(s2[start2 + i], textInfo))
{
return false;
}
}
return true;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Globalization;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.PatternMatching
{
internal partial class PatternMatcher
{
/// <summary>
/// Encapsulated matches responsible for matching an all lowercase pattern against
/// a candidate using CamelCase matching. i.e. this code is responsible for finding the
/// match between "cofipro" and "CodeFixProvider".
/// </summary>
private readonly struct AllLowerCamelCaseMatcher
{
private readonly bool _includeMatchedSpans;
private readonly string _candidate;
private readonly string _patternText;
private readonly TextInfo _textInfo;
public AllLowerCamelCaseMatcher(
bool includeMatchedSpans,
string candidate,
string patternChunkText,
TextInfo textInfo)
{
_includeMatchedSpans = includeMatchedSpans;
_candidate = candidate;
_patternText = patternChunkText;
_textInfo = textInfo;
}
/// <summary>
/// Returns null if no match was found, 1 if a contiguous match was found, 2 if a
/// match as found that starts at the beginning of the candidate, and 3 if a contiguous
/// match was found that starts at the beginning of the candidate.
/// </summary>
public PatternMatchKind? TryMatch(
in TemporaryArray<TextSpan> candidateHumps, out ImmutableArray<TextSpan> matchedSpans)
{
// We have something like cofipro and we want to match CodeFixProvider.
//
// Note that this is incredibly ambiguous. We'd also want this to match
// CorporateOfficePartsRoom So, for example, if we were to consume the "co"
// as matching "Corporate", then "f" wouldn't match any camel hump. So we
// basically have to branch out and try all options at every character
// in the pattern chunk.
var result = TryMatch(
patternIndex: 0, candidateHumpIndex: 0, contiguous: null, candidateHumps);
if (result == null)
{
matchedSpans = ImmutableArray<TextSpan>.Empty;
return null;
}
matchedSpans = _includeMatchedSpans && result.Value.MatchedSpansInReverse != null
? new NormalizedTextSpanCollection(result.Value.MatchedSpansInReverse).ToImmutableArray()
: ImmutableArray<TextSpan>.Empty;
result?.Free();
return GetKind(result.Value, candidateHumps);
}
private static PatternMatchKind GetKind(CamelCaseResult result, in TemporaryArray<TextSpan> candidateHumps)
=> GetCamelCaseKind(result, candidateHumps);
private CamelCaseResult? TryMatch(
int patternIndex, int candidateHumpIndex, bool? contiguous, in TemporaryArray<TextSpan> candidateHumps)
{
if (patternIndex == _patternText.Length)
{
// We hit the end. So we were able to match against this candidate.
// We are contiguous if our contiguous tracker was not set to false.
var matchedSpansInReverse = _includeMatchedSpans ? ArrayBuilder<TextSpan>.GetInstance() : null;
return new CamelCaseResult(
fromStart: false,
contiguous: contiguous != false,
matchCount: 0,
matchedSpansInReverse: matchedSpansInReverse);
}
var bestResult = (CamelCaseResult?)null;
// Look for a hump in the candidate that matches the current letter we're on.
var patternCharacter = _patternText[patternIndex];
for (int humpIndex = candidateHumpIndex, n = candidateHumps.Count; humpIndex < n; humpIndex++)
{
// If we've been contiguous, but we jumped past a hump, then we're no longer contiguous.
if (contiguous.HasValue && contiguous.Value)
{
contiguous = humpIndex == candidateHumpIndex;
}
var candidateHump = candidateHumps[humpIndex];
if (ToLower(_candidate[candidateHump.Start], _textInfo) == patternCharacter)
{
// Found a hump in the candidate string that matches the current pattern
// character we're on. i.e. we matched the c in cofipro against the C in
// CodeFixProvider.
//
// Now, for each subsequent character, we need to both try to consume it
// as part of the current hump, or see if it should match the next hump.
//
// Note, if the candidate is something like CodeFixProvider and our pattern
// is cofipro, and we've matched the 'f' against the 'F', then the max of
// the pattern we'll want to consume is "fip" against "Fix". We don't want
// consume parts of the pattern once we reach the next hump.
// We matched something. If this was our first match, consider ourselves
// contiguous.
var localContiguous = contiguous == null ? true : contiguous.Value;
var result = TryConsumePatternOrMatchNextHump(
patternIndex, humpIndex, localContiguous, candidateHumps);
if (result == null)
{
continue;
}
if (UpdateBestResultIfBetter(result.Value, ref bestResult, matchSpanToAdd: null, candidateHumps))
{
// We found the best result so far. We can stop immediately.
break;
}
}
}
return bestResult;
}
private static char ToLower(char v, TextInfo textInfo)
{
return IsAscii(v)
? ToLowerAsciiInvariant(v)
: textInfo.ToLower(v);
}
private static bool IsAscii(char v)
=> v < 0x80;
private static char ToLowerAsciiInvariant(char c)
=> 'A' <= c && c <= 'Z'
? (char)(c | 0x20)
: c;
private CamelCaseResult? TryConsumePatternOrMatchNextHump(
int patternIndex, int humpIndex, bool contiguous, in TemporaryArray<TextSpan> candidateHumps)
{
var bestResult = (CamelCaseResult?)null;
var candidateHump = candidateHumps[humpIndex];
var maxPatternHumpLength = _patternText.Length - patternIndex;
var maxCandidateHumpLength = candidateHump.Length;
var maxHumpMatchLength = Math.Min(maxPatternHumpLength, maxCandidateHumpLength);
for (var possibleHumpMatchLength = 1; possibleHumpMatchLength <= maxHumpMatchLength; possibleHumpMatchLength++)
{
if (!LowercaseSubstringsMatch(
_candidate, candidateHump.Start,
_patternText, patternIndex, possibleHumpMatchLength))
{
// Stop trying to consume once the pattern contents no longer matches
// against the current candidate hump.
break;
}
// The pattern substring 'f' has matched against 'F', or 'fi' has matched
// against 'Fi'. recurse and let the rest of the pattern match the remainder
// of the candidate.
var resultOpt = TryMatch(
patternIndex + possibleHumpMatchLength, humpIndex + 1, contiguous, candidateHumps);
if (resultOpt == null)
{
// Didn't match. Try the next longer pattern chunk.
continue;
}
var result = resultOpt.Value;
// If this is our first hump add a 'from start' bonus.
if (humpIndex == 0)
{
result = result.WithFromStart(true);
}
// This is the span of the hump of the candidate we matched.
var matchSpanToAdd = new TextSpan(candidateHump.Start, possibleHumpMatchLength);
if (UpdateBestResultIfBetter(result, ref bestResult, matchSpanToAdd, candidateHumps))
{
// We found the best result so far. We can stop immediately.
break;
}
}
return bestResult;
}
/// <summary>
/// Updates the currently stored 'best result' if the current result is better.
/// Returns 'true' if no further work is required and we can break early, or
/// 'false' if we need to keep on going.
///
/// If 'weight' is better than 'bestWeight' and matchSpanToAdd is not null, then
/// matchSpanToAdd will be added to matchedSpansInReverse.
/// </summary>
private static bool UpdateBestResultIfBetter(
CamelCaseResult result, ref CamelCaseResult? bestResult, TextSpan? matchSpanToAdd, in TemporaryArray<TextSpan> candidateHumps)
{
if (matchSpanToAdd != null)
{
result = result.WithAddedMatchedSpan(matchSpanToAdd.Value);
}
if (!IsBetter(result, bestResult, candidateHumps))
{
// Even though we matched this current candidate hump we failed to match
// the remainder of the pattern. Continue to the next candidate hump
// to see if our pattern character will match it and potentially succeed.
result.Free();
// We need to keep going.
return false;
}
// This was result was better than whatever previous best result we had was.
// Free and overwrite the existing best results, and keep going.
bestResult?.Free();
bestResult = result;
// We found a path that allowed us to match everything contiguously
// from the beginning. This is the best match possible. So we can
// just break out now and return this result.
return GetKind(result, candidateHumps) == PatternMatchKind.CamelCaseExact;
}
private static bool IsBetter(CamelCaseResult result, CamelCaseResult? currentBestResult, in TemporaryArray<TextSpan> candidateHumps)
{
if (currentBestResult == null)
{
// We have no current best. So this result is the best.
return true;
}
return GetKind(result, candidateHumps) < GetKind(currentBestResult.Value, candidateHumps);
}
private bool LowercaseSubstringsMatch(
string s1, int start1, string s2, int start2, int length)
{
var textInfo = _textInfo;
for (var i = 0; i < length; i++)
{
if (ToLower(s1[start1 + i], textInfo) != ToLower(s2[start2 + i], textInfo))
{
return false;
}
}
return true;
}
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/DebuggerDisplayAttributeTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests
{
/// <summary>
/// Compile expressions at type-scope to support
/// expressions in DebuggerDisplayAttribute values.
/// </summary>
public class DebuggerDisplayAttributeTests : ExpressionCompilerTestBase
{
[Fact]
public void FieldsAndProperties()
{
var source =
@"using System.Diagnostics;
[DebuggerDisplay(""{F}, {G}, {P}, {Q}"")]
class C
{
static object F = 1;
int G = 2;
static int P { get { return 3; } }
object Q { get { return 4; } }
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateTypeContext(runtime, "C");
// Static field.
AssertEx.AssertEqualToleratingWhitespaceDifferences(
CompileExpression(context, "F"),
@"{
// Code size 6 (0x6)
.maxstack 1
IL_0000: ldsfld ""object C.F""
IL_0005: ret
}");
// Instance field.
AssertEx.AssertEqualToleratingWhitespaceDifferences(
CompileExpression(context, "G"),
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""int C.G""
IL_0006: ret
}");
// Static property.
AssertEx.AssertEqualToleratingWhitespaceDifferences(
CompileExpression(context, "P"),
@"{
// Code size 6 (0x6)
.maxstack 1
IL_0000: call ""int C.P.get""
IL_0005: ret
}");
// Instance property.
AssertEx.AssertEqualToleratingWhitespaceDifferences(
CompileExpression(context, "Q"),
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: callvirt ""object C.Q.get""
IL_0006: ret
}");
});
}
[Fact]
public void Constants()
{
var source =
@"using System.Diagnostics;
[DebuggerDisplay(""{F[G]}"")]
class C
{
const string F = ""str"";
const int G = 2;
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName());
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateTypeContext(runtime, "C");
AssertEx.AssertEqualToleratingWhitespaceDifferences(
CompileExpression(context, "F[G]"),
@"{
// Code size 12 (0xc)
.maxstack 2
IL_0000: ldstr ""str""
IL_0005: ldc.i4.2
IL_0006: call ""char string.this[int].get""
IL_000b: ret
}");
});
}
[Fact]
public void This()
{
var source =
@"using System.Diagnostics;
[DebuggerDisplay(""{F(this)}"")]
class C
{
static object F(C c)
{
return c;
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName());
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateTypeContext(runtime, "C");
AssertEx.AssertEqualToleratingWhitespaceDifferences(
CompileExpression(context, "F(this)"),
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object C.F(C)""
IL_0006: ret
}");
});
}
[Fact]
public void Base()
{
var source =
@"using System.Diagnostics;
class A
{
internal object F()
{
return 1;
}
}
[DebuggerDisplay(""{base.F()}"")]
class B : A
{
new object F()
{
return 2;
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName());
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateTypeContext(runtime, "B");
AssertEx.AssertEqualToleratingWhitespaceDifferences(
CompileExpression(context, "base.F()"),
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object A.F()""
IL_0006: ret
}");
});
}
[Fact]
public void GenericType()
{
var source =
@"using System.Diagnostics;
class A<T> where T : class
{
[DebuggerDisplay(""{F(default(T), default(U))}"")]
internal class B<U>
{
static object F<X, Y>(X x, Y y) where X : class
{
return x ?? (object)y;
}
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName());
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateTypeContext(runtime, "A.B");
string error;
var testData = new CompilationTestData();
var result = context.CompileExpression("F(default(T), default(U))", out error, testData);
string actualIL = testData.GetMethodData("<>x<T, U>.<>m0").GetMethodIL();
AssertEx.AssertEqualToleratingWhitespaceDifferences(
actualIL,
@"{
// Code size 24 (0x18)
.maxstack 2
.locals init (T V_0,
U V_1)
IL_0000: ldloca.s V_0
IL_0002: initobj ""T""
IL_0008: ldloc.0
IL_0009: ldloca.s V_1
IL_000b: initobj ""U""
IL_0011: ldloc.1
IL_0012: call ""object A<T>.B<U>.F<T, U>(T, U)""
IL_0017: ret
}");
// Verify generated type is generic, but method is not.
using (var metadata = ModuleMetadata.CreateFromImage(ImmutableArray.CreateRange(result.Assembly)))
{
var reader = metadata.MetadataReader;
var typeDef = reader.GetTypeDef(result.TypeName);
reader.CheckTypeParameters(typeDef.GetGenericParameters(), "T", "U");
var methodDef = reader.GetMethodDef(typeDef, result.MethodName);
reader.CheckTypeParameters(methodDef.GetGenericParameters());
}
});
}
[Fact]
public void Usings()
{
var source =
@"using System.Diagnostics;
using A = N;
using B = N.C;
namespace N
{
[DebuggerDisplay(""{typeof(A.C) ?? typeof(B) ?? typeof(C)}"")]
class C
{
void M()
{
}
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName());
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateTypeContext(runtime, "N.C");
string error;
var testData = new CompilationTestData();
// Expression compilation should succeed without imports.
var result = context.CompileExpression("typeof(N.C) ?? typeof(C)", out error, testData);
Assert.Null(error);
AssertEx.AssertEqualToleratingWhitespaceDifferences(
testData.GetMethodData("<>x.<>m0").GetMethodIL(),
@"{
// Code size 25 (0x19)
.maxstack 2
IL_0000: ldtoken ""N.C""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: dup
IL_000b: brtrue.s IL_0018
IL_000d: pop
IL_000e: ldtoken ""N.C""
IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0018: ret
}");
// Expression compilation should fail using imports since there are no symbols.
context = CreateTypeContext(runtime, "N.C");
testData = new CompilationTestData();
result = context.CompileExpression("typeof(A.C) ?? typeof(B) ?? typeof(C)", out error, testData);
Assert.Equal("error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?)", error);
testData = new CompilationTestData();
result = context.CompileExpression("typeof(B) ?? typeof(C)", out error, testData);
Assert.Equal("error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?)", error);
});
}
[Fact]
public void PseudoVariable()
{
var source =
@"using System.Diagnostics;
[DebuggerDisplay(""{$ReturnValue}"")]
class C
{
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName());
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateTypeContext(runtime, "C");
string error;
var testData = new CompilationTestData();
var result = context.CompileExpression("$ReturnValue", out error, testData);
Assert.Equal("error CS0103: The name '$ReturnValue' does not exist in the current context", error);
});
}
[Fact]
public void LambdaClosedOverThis()
{
var source =
@"class C
{
object o;
static object F(System.Func<object> f)
{
return f();
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName());
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateTypeContext(runtime, "C");
AssertEx.AssertEqualToleratingWhitespaceDifferences(
@"{
// Code size 29 (0x1d)
.maxstack 3
IL_0000: newobj ""<>x.<>c__DisplayClass0_0..ctor()""
IL_0005: dup
IL_0006: ldarg.0
IL_0007: stfld ""C <>x.<>c__DisplayClass0_0.<>4__this""
IL_000c: ldftn ""object <>x.<>c__DisplayClass0_0.<<>m0>b__0()""
IL_0012: newobj ""System.Func<object>..ctor(object, System.IntPtr)""
IL_0017: call ""object C.F(System.Func<object>)""
IL_001c: ret
}",
CompileExpression(context, "F(() => this.o)"));
});
}
[Fact]
public void FormatSpecifiers()
{
var source =
@"using System.Diagnostics;
[DebuggerDisplay(""{F, nq}, {F}"")]
class C
{
object F = ""f"";
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName());
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateTypeContext(runtime, "C");
// No format specifiers.
string error;
var result = context.CompileExpression("F", out error);
Assert.NotNull(result.Assembly);
Assert.Null(result.FormatSpecifiers);
// Format specifiers.
result = context.CompileExpression("F, nq,ac", out error);
Assert.NotNull(result.Assembly);
Assert.Equal(2, result.FormatSpecifiers.Count);
Assert.Equal("nq", result.FormatSpecifiers[0]);
Assert.Equal("ac", result.FormatSpecifiers[1]);
});
}
[Fact]
public void VirtualMethod()
{
var source = @"
using System.Diagnostics;
[DebuggerDisplay(""{GetDebuggerDisplay()}"")]
public class Base
{
protected virtual string GetDebuggerDisplay()
{
return ""base"";
}
}
public class Derived : Base
{
protected override string GetDebuggerDisplay()
{
return ""derived"";
}
}
";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName());
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateTypeContext(runtime, "Derived");
string error;
var testData = new CompilationTestData();
var result = context.CompileExpression("GetDebuggerDisplay()", out error, testData);
Assert.Null(error);
var actualIL = testData.GetMethodData("<>x.<>m0").GetMethodIL();
var expectedIL =
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: callvirt ""string Derived.GetDebuggerDisplay()""
IL_0006: ret
}";
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL);
});
}
private static string CompileExpression(EvaluationContext context, string expr)
{
string error;
var testData = new CompilationTestData();
var result = context.CompileExpression(expr, out error, testData);
Assert.NotNull(result.Assembly);
Assert.Null(error);
return testData.GetMethodData(result.TypeName + "." + result.MethodName).GetMethodIL();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests
{
/// <summary>
/// Compile expressions at type-scope to support
/// expressions in DebuggerDisplayAttribute values.
/// </summary>
public class DebuggerDisplayAttributeTests : ExpressionCompilerTestBase
{
[Fact]
public void FieldsAndProperties()
{
var source =
@"using System.Diagnostics;
[DebuggerDisplay(""{F}, {G}, {P}, {Q}"")]
class C
{
static object F = 1;
int G = 2;
static int P { get { return 3; } }
object Q { get { return 4; } }
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateTypeContext(runtime, "C");
// Static field.
AssertEx.AssertEqualToleratingWhitespaceDifferences(
CompileExpression(context, "F"),
@"{
// Code size 6 (0x6)
.maxstack 1
IL_0000: ldsfld ""object C.F""
IL_0005: ret
}");
// Instance field.
AssertEx.AssertEqualToleratingWhitespaceDifferences(
CompileExpression(context, "G"),
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""int C.G""
IL_0006: ret
}");
// Static property.
AssertEx.AssertEqualToleratingWhitespaceDifferences(
CompileExpression(context, "P"),
@"{
// Code size 6 (0x6)
.maxstack 1
IL_0000: call ""int C.P.get""
IL_0005: ret
}");
// Instance property.
AssertEx.AssertEqualToleratingWhitespaceDifferences(
CompileExpression(context, "Q"),
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: callvirt ""object C.Q.get""
IL_0006: ret
}");
});
}
[Fact]
public void Constants()
{
var source =
@"using System.Diagnostics;
[DebuggerDisplay(""{F[G]}"")]
class C
{
const string F = ""str"";
const int G = 2;
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName());
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateTypeContext(runtime, "C");
AssertEx.AssertEqualToleratingWhitespaceDifferences(
CompileExpression(context, "F[G]"),
@"{
// Code size 12 (0xc)
.maxstack 2
IL_0000: ldstr ""str""
IL_0005: ldc.i4.2
IL_0006: call ""char string.this[int].get""
IL_000b: ret
}");
});
}
[Fact]
public void This()
{
var source =
@"using System.Diagnostics;
[DebuggerDisplay(""{F(this)}"")]
class C
{
static object F(C c)
{
return c;
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName());
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateTypeContext(runtime, "C");
AssertEx.AssertEqualToleratingWhitespaceDifferences(
CompileExpression(context, "F(this)"),
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object C.F(C)""
IL_0006: ret
}");
});
}
[Fact]
public void Base()
{
var source =
@"using System.Diagnostics;
class A
{
internal object F()
{
return 1;
}
}
[DebuggerDisplay(""{base.F()}"")]
class B : A
{
new object F()
{
return 2;
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName());
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateTypeContext(runtime, "B");
AssertEx.AssertEqualToleratingWhitespaceDifferences(
CompileExpression(context, "base.F()"),
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object A.F()""
IL_0006: ret
}");
});
}
[Fact]
public void GenericType()
{
var source =
@"using System.Diagnostics;
class A<T> where T : class
{
[DebuggerDisplay(""{F(default(T), default(U))}"")]
internal class B<U>
{
static object F<X, Y>(X x, Y y) where X : class
{
return x ?? (object)y;
}
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName());
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateTypeContext(runtime, "A.B");
string error;
var testData = new CompilationTestData();
var result = context.CompileExpression("F(default(T), default(U))", out error, testData);
string actualIL = testData.GetMethodData("<>x<T, U>.<>m0").GetMethodIL();
AssertEx.AssertEqualToleratingWhitespaceDifferences(
actualIL,
@"{
// Code size 24 (0x18)
.maxstack 2
.locals init (T V_0,
U V_1)
IL_0000: ldloca.s V_0
IL_0002: initobj ""T""
IL_0008: ldloc.0
IL_0009: ldloca.s V_1
IL_000b: initobj ""U""
IL_0011: ldloc.1
IL_0012: call ""object A<T>.B<U>.F<T, U>(T, U)""
IL_0017: ret
}");
// Verify generated type is generic, but method is not.
using (var metadata = ModuleMetadata.CreateFromImage(ImmutableArray.CreateRange(result.Assembly)))
{
var reader = metadata.MetadataReader;
var typeDef = reader.GetTypeDef(result.TypeName);
reader.CheckTypeParameters(typeDef.GetGenericParameters(), "T", "U");
var methodDef = reader.GetMethodDef(typeDef, result.MethodName);
reader.CheckTypeParameters(methodDef.GetGenericParameters());
}
});
}
[Fact]
public void Usings()
{
var source =
@"using System.Diagnostics;
using A = N;
using B = N.C;
namespace N
{
[DebuggerDisplay(""{typeof(A.C) ?? typeof(B) ?? typeof(C)}"")]
class C
{
void M()
{
}
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName());
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateTypeContext(runtime, "N.C");
string error;
var testData = new CompilationTestData();
// Expression compilation should succeed without imports.
var result = context.CompileExpression("typeof(N.C) ?? typeof(C)", out error, testData);
Assert.Null(error);
AssertEx.AssertEqualToleratingWhitespaceDifferences(
testData.GetMethodData("<>x.<>m0").GetMethodIL(),
@"{
// Code size 25 (0x19)
.maxstack 2
IL_0000: ldtoken ""N.C""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: dup
IL_000b: brtrue.s IL_0018
IL_000d: pop
IL_000e: ldtoken ""N.C""
IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0018: ret
}");
// Expression compilation should fail using imports since there are no symbols.
context = CreateTypeContext(runtime, "N.C");
testData = new CompilationTestData();
result = context.CompileExpression("typeof(A.C) ?? typeof(B) ?? typeof(C)", out error, testData);
Assert.Equal("error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?)", error);
testData = new CompilationTestData();
result = context.CompileExpression("typeof(B) ?? typeof(C)", out error, testData);
Assert.Equal("error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?)", error);
});
}
[Fact]
public void PseudoVariable()
{
var source =
@"using System.Diagnostics;
[DebuggerDisplay(""{$ReturnValue}"")]
class C
{
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName());
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateTypeContext(runtime, "C");
string error;
var testData = new CompilationTestData();
var result = context.CompileExpression("$ReturnValue", out error, testData);
Assert.Equal("error CS0103: The name '$ReturnValue' does not exist in the current context", error);
});
}
[Fact]
public void LambdaClosedOverThis()
{
var source =
@"class C
{
object o;
static object F(System.Func<object> f)
{
return f();
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName());
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateTypeContext(runtime, "C");
AssertEx.AssertEqualToleratingWhitespaceDifferences(
@"{
// Code size 29 (0x1d)
.maxstack 3
IL_0000: newobj ""<>x.<>c__DisplayClass0_0..ctor()""
IL_0005: dup
IL_0006: ldarg.0
IL_0007: stfld ""C <>x.<>c__DisplayClass0_0.<>4__this""
IL_000c: ldftn ""object <>x.<>c__DisplayClass0_0.<<>m0>b__0()""
IL_0012: newobj ""System.Func<object>..ctor(object, System.IntPtr)""
IL_0017: call ""object C.F(System.Func<object>)""
IL_001c: ret
}",
CompileExpression(context, "F(() => this.o)"));
});
}
[Fact]
public void FormatSpecifiers()
{
var source =
@"using System.Diagnostics;
[DebuggerDisplay(""{F, nq}, {F}"")]
class C
{
object F = ""f"";
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName());
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateTypeContext(runtime, "C");
// No format specifiers.
string error;
var result = context.CompileExpression("F", out error);
Assert.NotNull(result.Assembly);
Assert.Null(result.FormatSpecifiers);
// Format specifiers.
result = context.CompileExpression("F, nq,ac", out error);
Assert.NotNull(result.Assembly);
Assert.Equal(2, result.FormatSpecifiers.Count);
Assert.Equal("nq", result.FormatSpecifiers[0]);
Assert.Equal("ac", result.FormatSpecifiers[1]);
});
}
[Fact]
public void VirtualMethod()
{
var source = @"
using System.Diagnostics;
[DebuggerDisplay(""{GetDebuggerDisplay()}"")]
public class Base
{
protected virtual string GetDebuggerDisplay()
{
return ""base"";
}
}
public class Derived : Base
{
protected override string GetDebuggerDisplay()
{
return ""derived"";
}
}
";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName());
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateTypeContext(runtime, "Derived");
string error;
var testData = new CompilationTestData();
var result = context.CompileExpression("GetDebuggerDisplay()", out error, testData);
Assert.Null(error);
var actualIL = testData.GetMethodData("<>x.<>m0").GetMethodIL();
var expectedIL =
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: callvirt ""string Derived.GetDebuggerDisplay()""
IL_0006: ret
}";
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL);
});
}
private static string CompileExpression(EvaluationContext context, string expr)
{
string error;
var testData = new CompilationTestData();
var result = context.CompileExpression(expr, out error, testData);
Assert.NotNull(result.Assembly);
Assert.Null(error);
return testData.GetMethodData(result.TypeName + "." + result.MethodName).GetMethodIL();
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/VisualStudio/Core/Def/EditorConfigSettings/Common/RemoveSinkWhenDisposed.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.Shell.TableManager;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common
{
internal class RemoveSinkWhenDisposed : IDisposable
{
private readonly List<ITableDataSink> _tableSinks;
private readonly ITableDataSink _sink;
public RemoveSinkWhenDisposed(List<ITableDataSink> tableSinks, ITableDataSink sink)
{
_tableSinks = tableSinks;
_sink = sink;
}
public void Dispose()
{
// whoever subscribed is no longer interested in my data.
// Remove them from the list of sinks
_ = _tableSinks.Remove(_sink);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.Shell.TableManager;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common
{
internal class RemoveSinkWhenDisposed : IDisposable
{
private readonly List<ITableDataSink> _tableSinks;
private readonly ITableDataSink _sink;
public RemoveSinkWhenDisposed(List<ITableDataSink> tableSinks, ITableDataSink sink)
{
_tableSinks = tableSinks;
_sink = sink;
}
public void Dispose()
{
// whoever subscribed is no longer interested in my data.
// Remove them from the list of sinks
_ = _tableSinks.Remove(_sink);
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/ObjectPools/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.
using System.Collections.Generic;
using System.Text;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis
{
internal static class SharedPoolExtensions
{
private const int Threshold = 512;
public static PooledObject<StringBuilder> GetPooledObject(this ObjectPool<StringBuilder> pool)
=> PooledObject<StringBuilder>.Create(pool);
public static PooledObject<Stack<TItem>> GetPooledObject<TItem>(this ObjectPool<Stack<TItem>> pool)
=> PooledObject<Stack<TItem>>.Create(pool);
public static PooledObject<Queue<TItem>> GetPooledObject<TItem>(this ObjectPool<Queue<TItem>> pool)
=> PooledObject<Queue<TItem>>.Create(pool);
public static PooledObject<HashSet<TItem>> GetPooledObject<TItem>(this ObjectPool<HashSet<TItem>> pool)
=> PooledObject<HashSet<TItem>>.Create(pool);
public static PooledObject<Dictionary<TKey, TValue>> GetPooledObject<TKey, TValue>(this ObjectPool<Dictionary<TKey, TValue>> pool)
where TKey : notnull
=> PooledObject<Dictionary<TKey, TValue>>.Create(pool);
public static PooledObject<List<TItem>> GetPooledObject<TItem>(this ObjectPool<List<TItem>> pool)
=> PooledObject<List<TItem>>.Create(pool);
public static PooledObject<List<TItem>> GetPooledObject<TItem>(this ObjectPool<List<TItem>> pool, out List<TItem> list)
{
var pooledObject = PooledObject<List<TItem>>.Create(pool);
list = pooledObject.Object;
return pooledObject;
}
public static PooledObject<T> GetPooledObject<T>(this ObjectPool<T> pool) where T : class
=> new(pool, p => p.Allocate(), (p, o) => p.Free(o));
public static StringBuilder AllocateAndClear(this ObjectPool<StringBuilder> pool)
{
var sb = pool.Allocate();
sb.Clear();
return sb;
}
public static Stack<T> AllocateAndClear<T>(this ObjectPool<Stack<T>> pool)
{
var set = pool.Allocate();
set.Clear();
return set;
}
public static Queue<T> AllocateAndClear<T>(this ObjectPool<Queue<T>> pool)
{
var set = pool.Allocate();
set.Clear();
return set;
}
public static HashSet<T> AllocateAndClear<T>(this ObjectPool<HashSet<T>> pool)
{
var set = pool.Allocate();
set.Clear();
return set;
}
public static Dictionary<TKey, TValue> AllocateAndClear<TKey, TValue>(this ObjectPool<Dictionary<TKey, TValue>> pool)
where TKey : notnull
{
var map = pool.Allocate();
map.Clear();
return map;
}
public static List<T> AllocateAndClear<T>(this ObjectPool<List<T>> pool)
{
var list = pool.Allocate();
list.Clear();
return list;
}
public static void ClearAndFree(this ObjectPool<StringBuilder> pool, StringBuilder sb)
{
if (sb == null)
{
return;
}
sb.Clear();
if (sb.Capacity > Threshold)
{
sb.Capacity = Threshold;
}
pool.Free(sb);
}
public static void ClearAndFree<T>(this ObjectPool<HashSet<T>> pool, HashSet<T> set)
{
if (set == null)
{
return;
}
var count = set.Count;
set.Clear();
if (count > Threshold)
{
set.TrimExcess();
}
pool.Free(set);
}
public static void ClearAndFree<T>(this ObjectPool<Stack<T>> pool, Stack<T> set)
{
if (set == null)
{
return;
}
var count = set.Count;
set.Clear();
if (count > Threshold)
{
set.TrimExcess();
}
pool.Free(set);
}
public static void ClearAndFree<T>(this ObjectPool<Queue<T>> pool, Queue<T> set)
{
if (set == null)
{
return;
}
var count = set.Count;
set.Clear();
if (count > Threshold)
{
set.TrimExcess();
}
pool.Free(set);
}
public static void ClearAndFree<TKey, TValue>(this ObjectPool<Dictionary<TKey, TValue>> pool, Dictionary<TKey, TValue> map)
where TKey : notnull
{
if (map == null)
{
return;
}
// if map grew too big, don't put it back to pool
if (map.Count > Threshold)
{
pool.ForgetTrackedObject(map);
return;
}
map.Clear();
pool.Free(map);
}
public static void ClearAndFree<T>(this ObjectPool<List<T>> pool, List<T> list)
{
if (list == null)
{
return;
}
list.Clear();
if (list.Capacity > Threshold)
{
list.Capacity = Threshold;
}
pool.Free(list);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Text;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis
{
internal static class SharedPoolExtensions
{
private const int Threshold = 512;
public static PooledObject<StringBuilder> GetPooledObject(this ObjectPool<StringBuilder> pool)
=> PooledObject<StringBuilder>.Create(pool);
public static PooledObject<Stack<TItem>> GetPooledObject<TItem>(this ObjectPool<Stack<TItem>> pool)
=> PooledObject<Stack<TItem>>.Create(pool);
public static PooledObject<Queue<TItem>> GetPooledObject<TItem>(this ObjectPool<Queue<TItem>> pool)
=> PooledObject<Queue<TItem>>.Create(pool);
public static PooledObject<HashSet<TItem>> GetPooledObject<TItem>(this ObjectPool<HashSet<TItem>> pool)
=> PooledObject<HashSet<TItem>>.Create(pool);
public static PooledObject<Dictionary<TKey, TValue>> GetPooledObject<TKey, TValue>(this ObjectPool<Dictionary<TKey, TValue>> pool)
where TKey : notnull
=> PooledObject<Dictionary<TKey, TValue>>.Create(pool);
public static PooledObject<List<TItem>> GetPooledObject<TItem>(this ObjectPool<List<TItem>> pool)
=> PooledObject<List<TItem>>.Create(pool);
public static PooledObject<List<TItem>> GetPooledObject<TItem>(this ObjectPool<List<TItem>> pool, out List<TItem> list)
{
var pooledObject = PooledObject<List<TItem>>.Create(pool);
list = pooledObject.Object;
return pooledObject;
}
public static PooledObject<T> GetPooledObject<T>(this ObjectPool<T> pool) where T : class
=> new(pool, p => p.Allocate(), (p, o) => p.Free(o));
public static StringBuilder AllocateAndClear(this ObjectPool<StringBuilder> pool)
{
var sb = pool.Allocate();
sb.Clear();
return sb;
}
public static Stack<T> AllocateAndClear<T>(this ObjectPool<Stack<T>> pool)
{
var set = pool.Allocate();
set.Clear();
return set;
}
public static Queue<T> AllocateAndClear<T>(this ObjectPool<Queue<T>> pool)
{
var set = pool.Allocate();
set.Clear();
return set;
}
public static HashSet<T> AllocateAndClear<T>(this ObjectPool<HashSet<T>> pool)
{
var set = pool.Allocate();
set.Clear();
return set;
}
public static Dictionary<TKey, TValue> AllocateAndClear<TKey, TValue>(this ObjectPool<Dictionary<TKey, TValue>> pool)
where TKey : notnull
{
var map = pool.Allocate();
map.Clear();
return map;
}
public static List<T> AllocateAndClear<T>(this ObjectPool<List<T>> pool)
{
var list = pool.Allocate();
list.Clear();
return list;
}
public static void ClearAndFree(this ObjectPool<StringBuilder> pool, StringBuilder sb)
{
if (sb == null)
{
return;
}
sb.Clear();
if (sb.Capacity > Threshold)
{
sb.Capacity = Threshold;
}
pool.Free(sb);
}
public static void ClearAndFree<T>(this ObjectPool<HashSet<T>> pool, HashSet<T> set)
{
if (set == null)
{
return;
}
var count = set.Count;
set.Clear();
if (count > Threshold)
{
set.TrimExcess();
}
pool.Free(set);
}
public static void ClearAndFree<T>(this ObjectPool<Stack<T>> pool, Stack<T> set)
{
if (set == null)
{
return;
}
var count = set.Count;
set.Clear();
if (count > Threshold)
{
set.TrimExcess();
}
pool.Free(set);
}
public static void ClearAndFree<T>(this ObjectPool<Queue<T>> pool, Queue<T> set)
{
if (set == null)
{
return;
}
var count = set.Count;
set.Clear();
if (count > Threshold)
{
set.TrimExcess();
}
pool.Free(set);
}
public static void ClearAndFree<TKey, TValue>(this ObjectPool<Dictionary<TKey, TValue>> pool, Dictionary<TKey, TValue> map)
where TKey : notnull
{
if (map == null)
{
return;
}
// if map grew too big, don't put it back to pool
if (map.Count > Threshold)
{
pool.ForgetTrackedObject(map);
return;
}
map.Clear();
pool.Free(map);
}
public static void ClearAndFree<T>(this ObjectPool<List<T>> pool, List<T> list)
{
if (list == null)
{
return;
}
list.Clear();
if (list.Capacity > Threshold)
{
list.Capacity = Threshold;
}
pool.Free(list);
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/VisualStudio/Core/Impl/CodeModel/Collections/ExternalNamespaceEnumerator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections
{
public sealed class ExternalNamespaceEnumerator : IEnumerator, ICloneable
{
internal static IEnumerator Create(CodeModelState state, ProjectId projectId, SymbolKey namespaceSymbolId)
{
var newEnumerator = new ExternalNamespaceEnumerator(state, projectId, namespaceSymbolId);
return (IEnumerator)ComAggregate.CreateAggregatedObject(newEnumerator);
}
private ExternalNamespaceEnumerator(CodeModelState state, ProjectId projectId, SymbolKey namespaceSymbolId)
{
_state = state;
_projectId = projectId;
_namespaceSymbolId = namespaceSymbolId;
_childEnumerator = ChildrenOfNamespace(state, projectId, namespaceSymbolId).GetEnumerator();
}
private readonly CodeModelState _state;
private readonly ProjectId _projectId;
private readonly SymbolKey _namespaceSymbolId;
private readonly IEnumerator<EnvDTE.CodeElement> _childEnumerator;
public object Current
{
get
{
return _childEnumerator.Current;
}
}
public object Clone()
=> Create(_state, _projectId, _namespaceSymbolId);
public bool MoveNext()
=> _childEnumerator.MoveNext();
public void Reset()
=> _childEnumerator.Reset();
internal static IEnumerable<EnvDTE.CodeElement> ChildrenOfNamespace(CodeModelState state, ProjectId projectId, SymbolKey namespaceSymbolId)
{
var project = state.Workspace.CurrentSolution.GetProject(projectId);
if (project == null)
{
throw Exceptions.ThrowEFail();
}
if (!(namespaceSymbolId.Resolve(project.GetCompilationAsync().Result).Symbol is INamespaceSymbol namespaceSymbol))
{
throw Exceptions.ThrowEFail();
}
var containingAssembly = project.GetCompilationAsync().Result.Assembly;
foreach (var child in namespaceSymbol.GetMembers())
{
if (child is INamespaceSymbol namespaceChild)
{
yield return (EnvDTE.CodeElement)ExternalCodeNamespace.Create(state, projectId, namespaceChild);
}
else
{
var namedType = (INamedTypeSymbol)child;
if (namedType.IsAccessibleWithin(containingAssembly))
{
if (namedType.Locations.Any(l => l.IsInMetadata || l.IsInSource))
{
yield return state.CodeModelService.CreateCodeType(state, projectId, namedType);
}
}
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections
{
public sealed class ExternalNamespaceEnumerator : IEnumerator, ICloneable
{
internal static IEnumerator Create(CodeModelState state, ProjectId projectId, SymbolKey namespaceSymbolId)
{
var newEnumerator = new ExternalNamespaceEnumerator(state, projectId, namespaceSymbolId);
return (IEnumerator)ComAggregate.CreateAggregatedObject(newEnumerator);
}
private ExternalNamespaceEnumerator(CodeModelState state, ProjectId projectId, SymbolKey namespaceSymbolId)
{
_state = state;
_projectId = projectId;
_namespaceSymbolId = namespaceSymbolId;
_childEnumerator = ChildrenOfNamespace(state, projectId, namespaceSymbolId).GetEnumerator();
}
private readonly CodeModelState _state;
private readonly ProjectId _projectId;
private readonly SymbolKey _namespaceSymbolId;
private readonly IEnumerator<EnvDTE.CodeElement> _childEnumerator;
public object Current
{
get
{
return _childEnumerator.Current;
}
}
public object Clone()
=> Create(_state, _projectId, _namespaceSymbolId);
public bool MoveNext()
=> _childEnumerator.MoveNext();
public void Reset()
=> _childEnumerator.Reset();
internal static IEnumerable<EnvDTE.CodeElement> ChildrenOfNamespace(CodeModelState state, ProjectId projectId, SymbolKey namespaceSymbolId)
{
var project = state.Workspace.CurrentSolution.GetProject(projectId);
if (project == null)
{
throw Exceptions.ThrowEFail();
}
if (!(namespaceSymbolId.Resolve(project.GetCompilationAsync().Result).Symbol is INamespaceSymbol namespaceSymbol))
{
throw Exceptions.ThrowEFail();
}
var containingAssembly = project.GetCompilationAsync().Result.Assembly;
foreach (var child in namespaceSymbol.GetMembers())
{
if (child is INamespaceSymbol namespaceChild)
{
yield return (EnvDTE.CodeElement)ExternalCodeNamespace.Create(state, projectId, namespaceChild);
}
else
{
var namedType = (INamedTypeSymbol)child;
if (namedType.IsAccessibleWithin(containingAssembly))
{
if (namedType.Locations.Any(l => l.IsInMetadata || l.IsInSource))
{
yield return state.CodeModelService.CreateCodeType(state, projectId, namedType);
}
}
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Analyzers/Core/CodeFixes/UseInferredMemberName/AbstractUseInferredMemberNameCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.UseInferredMemberName
{
internal abstract class AbstractUseInferredMemberNameCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
protected abstract void LanguageSpecificRemoveSuggestedNode(SyntaxEditor editor, SyntaxNode node);
public override ImmutableArray<string> FixableDiagnosticIds { get; }
= ImmutableArray.Create(IDEDiagnosticIds.UseInferredMemberNameDiagnosticId);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
context.RegisterCodeFix(new MyCodeAction(
c => FixAsync(context.Document, context.Diagnostics.First(), c)),
context.Diagnostics);
return Task.CompletedTask;
}
protected override Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
{
var root = editor.OriginalRoot;
foreach (var diagnostic in diagnostics)
{
var node = root.FindNode(diagnostic.Location.SourceSpan);
LanguageSpecificRemoveSuggestedNode(editor, node);
}
return Task.CompletedTask;
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(AnalyzersResources.Use_inferred_member_name, createChangedDocument, AnalyzersResources.Use_inferred_member_name)
{
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.UseInferredMemberName
{
internal abstract class AbstractUseInferredMemberNameCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
protected abstract void LanguageSpecificRemoveSuggestedNode(SyntaxEditor editor, SyntaxNode node);
public override ImmutableArray<string> FixableDiagnosticIds { get; }
= ImmutableArray.Create(IDEDiagnosticIds.UseInferredMemberNameDiagnosticId);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
context.RegisterCodeFix(new MyCodeAction(
c => FixAsync(context.Document, context.Diagnostics.First(), c)),
context.Diagnostics);
return Task.CompletedTask;
}
protected override Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
{
var root = editor.OriginalRoot;
foreach (var diagnostic in diagnostics)
{
var node = root.FindNode(diagnostic.Location.SourceSpan);
LanguageSpecificRemoveSuggestedNode(editor, node);
}
return Task.CompletedTask;
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(AnalyzersResources.Use_inferred_member_name, createChangedDocument, AnalyzersResources.Use_inferred_member_name)
{
}
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Workspaces/Core/MSBuild/MSBuild/ProjectFile/ProjectFileInfo.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.MSBuild.Logging;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.MSBuild
{
/// <summary>
/// Provides information about a project that has been loaded from disk and
/// built with MSBuild. If the project is multi-targeting, this represents
/// the information from a single target framework.
/// </summary>
internal sealed class ProjectFileInfo
{
public bool IsEmpty { get; }
/// <summary>
/// The language of this project.
/// </summary>
public string Language { get; }
/// <summary>
/// The path to the project file for this project.
/// </summary>
public string? FilePath { get; }
/// <summary>
/// The path to the output file this project generates.
/// </summary>
public string? OutputFilePath { get; }
/// <summary>
/// The path to the reference assembly output file this project generates.
/// </summary>
public string? OutputRefFilePath { get; }
/// <summary>
/// The default namespace of the project ("" if not defined, which means global namespace),
/// or null if it is unknown or not applicable.
/// </summary>
/// <remarks>
/// Right now VB doesn't have the concept of "default namespace". But we conjure one in workspace
/// by assigning the value of the project's root namespace to it. So various feature can choose to
/// use it for their own purpose.
/// In the future, we might consider officially exposing "default namespace" for VB project
/// (e.g. through a "defaultnamespace" msbuild property)
/// </remarks>
public string? DefaultNamespace { get; }
/// <summary>
/// The target framework of this project.
/// This takes the form of the 'short name' form used by NuGet (e.g. net46, netcoreapp2.0, etc.)
/// </summary>
public string? TargetFramework { get; }
/// <summary>
/// The command line args used to compile the project.
/// </summary>
public ImmutableArray<string> CommandLineArgs { get; }
/// <summary>
/// The source documents.
/// </summary>
public ImmutableArray<DocumentFileInfo> Documents { get; }
/// <summary>
/// The additional documents.
/// </summary>
public ImmutableArray<DocumentFileInfo> AdditionalDocuments { get; }
/// <summary>
/// The analyzer config documents.
/// </summary>
public ImmutableArray<DocumentFileInfo> AnalyzerConfigDocuments { get; }
/// <summary>
/// References to other projects.
/// </summary>
public ImmutableArray<ProjectFileReference> ProjectReferences { get; }
/// <summary>
/// The error message produced when a failure occurred attempting to get the info.
/// If a failure occurred some or all of the information may be inaccurate or incomplete.
/// </summary>
public DiagnosticLog Log { get; }
public override string ToString()
=> RoslynString.IsNullOrWhiteSpace(TargetFramework)
? FilePath ?? string.Empty
: $"{FilePath} ({TargetFramework})";
private ProjectFileInfo(
bool isEmpty,
string language,
string? filePath,
string? outputFilePath,
string? outputRefFilePath,
string? defaultNamespace,
string? targetFramework,
ImmutableArray<string> commandLineArgs,
ImmutableArray<DocumentFileInfo> documents,
ImmutableArray<DocumentFileInfo> additionalDocuments,
ImmutableArray<DocumentFileInfo> analyzerConfigDocuments,
ImmutableArray<ProjectFileReference> projectReferences,
DiagnosticLog log)
{
RoslynDebug.Assert(filePath != null);
this.IsEmpty = isEmpty;
this.Language = language;
this.FilePath = filePath;
this.OutputFilePath = outputFilePath;
this.OutputRefFilePath = outputRefFilePath;
this.DefaultNamespace = defaultNamespace;
this.TargetFramework = targetFramework;
this.CommandLineArgs = commandLineArgs;
this.Documents = documents;
this.AdditionalDocuments = additionalDocuments;
this.AnalyzerConfigDocuments = analyzerConfigDocuments;
this.ProjectReferences = projectReferences;
this.Log = log;
}
public static ProjectFileInfo Create(
string language,
string? filePath,
string? outputFilePath,
string? outputRefFilePath,
string? defaultNamespace,
string? targetFramework,
ImmutableArray<string> commandLineArgs,
ImmutableArray<DocumentFileInfo> documents,
ImmutableArray<DocumentFileInfo> additionalDocuments,
ImmutableArray<DocumentFileInfo> analyzerConfigDocuments,
ImmutableArray<ProjectFileReference> projectReferences,
DiagnosticLog log)
=> new(
isEmpty: false,
language,
filePath,
outputFilePath,
outputRefFilePath,
defaultNamespace,
targetFramework,
commandLineArgs,
documents,
additionalDocuments,
analyzerConfigDocuments,
projectReferences,
log);
public static ProjectFileInfo CreateEmpty(string language, string? filePath, DiagnosticLog log)
=> new(
isEmpty: true,
language,
filePath,
outputFilePath: null,
outputRefFilePath: null,
defaultNamespace: null,
targetFramework: null,
commandLineArgs: ImmutableArray<string>.Empty,
documents: ImmutableArray<DocumentFileInfo>.Empty,
additionalDocuments: ImmutableArray<DocumentFileInfo>.Empty,
analyzerConfigDocuments: ImmutableArray<DocumentFileInfo>.Empty,
projectReferences: ImmutableArray<ProjectFileReference>.Empty,
log);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.MSBuild.Logging;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.MSBuild
{
/// <summary>
/// Provides information about a project that has been loaded from disk and
/// built with MSBuild. If the project is multi-targeting, this represents
/// the information from a single target framework.
/// </summary>
internal sealed class ProjectFileInfo
{
public bool IsEmpty { get; }
/// <summary>
/// The language of this project.
/// </summary>
public string Language { get; }
/// <summary>
/// The path to the project file for this project.
/// </summary>
public string? FilePath { get; }
/// <summary>
/// The path to the output file this project generates.
/// </summary>
public string? OutputFilePath { get; }
/// <summary>
/// The path to the reference assembly output file this project generates.
/// </summary>
public string? OutputRefFilePath { get; }
/// <summary>
/// The default namespace of the project ("" if not defined, which means global namespace),
/// or null if it is unknown or not applicable.
/// </summary>
/// <remarks>
/// Right now VB doesn't have the concept of "default namespace". But we conjure one in workspace
/// by assigning the value of the project's root namespace to it. So various feature can choose to
/// use it for their own purpose.
/// In the future, we might consider officially exposing "default namespace" for VB project
/// (e.g. through a "defaultnamespace" msbuild property)
/// </remarks>
public string? DefaultNamespace { get; }
/// <summary>
/// The target framework of this project.
/// This takes the form of the 'short name' form used by NuGet (e.g. net46, netcoreapp2.0, etc.)
/// </summary>
public string? TargetFramework { get; }
/// <summary>
/// The command line args used to compile the project.
/// </summary>
public ImmutableArray<string> CommandLineArgs { get; }
/// <summary>
/// The source documents.
/// </summary>
public ImmutableArray<DocumentFileInfo> Documents { get; }
/// <summary>
/// The additional documents.
/// </summary>
public ImmutableArray<DocumentFileInfo> AdditionalDocuments { get; }
/// <summary>
/// The analyzer config documents.
/// </summary>
public ImmutableArray<DocumentFileInfo> AnalyzerConfigDocuments { get; }
/// <summary>
/// References to other projects.
/// </summary>
public ImmutableArray<ProjectFileReference> ProjectReferences { get; }
/// <summary>
/// The error message produced when a failure occurred attempting to get the info.
/// If a failure occurred some or all of the information may be inaccurate or incomplete.
/// </summary>
public DiagnosticLog Log { get; }
public override string ToString()
=> RoslynString.IsNullOrWhiteSpace(TargetFramework)
? FilePath ?? string.Empty
: $"{FilePath} ({TargetFramework})";
private ProjectFileInfo(
bool isEmpty,
string language,
string? filePath,
string? outputFilePath,
string? outputRefFilePath,
string? defaultNamespace,
string? targetFramework,
ImmutableArray<string> commandLineArgs,
ImmutableArray<DocumentFileInfo> documents,
ImmutableArray<DocumentFileInfo> additionalDocuments,
ImmutableArray<DocumentFileInfo> analyzerConfigDocuments,
ImmutableArray<ProjectFileReference> projectReferences,
DiagnosticLog log)
{
RoslynDebug.Assert(filePath != null);
this.IsEmpty = isEmpty;
this.Language = language;
this.FilePath = filePath;
this.OutputFilePath = outputFilePath;
this.OutputRefFilePath = outputRefFilePath;
this.DefaultNamespace = defaultNamespace;
this.TargetFramework = targetFramework;
this.CommandLineArgs = commandLineArgs;
this.Documents = documents;
this.AdditionalDocuments = additionalDocuments;
this.AnalyzerConfigDocuments = analyzerConfigDocuments;
this.ProjectReferences = projectReferences;
this.Log = log;
}
public static ProjectFileInfo Create(
string language,
string? filePath,
string? outputFilePath,
string? outputRefFilePath,
string? defaultNamespace,
string? targetFramework,
ImmutableArray<string> commandLineArgs,
ImmutableArray<DocumentFileInfo> documents,
ImmutableArray<DocumentFileInfo> additionalDocuments,
ImmutableArray<DocumentFileInfo> analyzerConfigDocuments,
ImmutableArray<ProjectFileReference> projectReferences,
DiagnosticLog log)
=> new(
isEmpty: false,
language,
filePath,
outputFilePath,
outputRefFilePath,
defaultNamespace,
targetFramework,
commandLineArgs,
documents,
additionalDocuments,
analyzerConfigDocuments,
projectReferences,
log);
public static ProjectFileInfo CreateEmpty(string language, string? filePath, DiagnosticLog log)
=> new(
isEmpty: true,
language,
filePath,
outputFilePath: null,
outputRefFilePath: null,
defaultNamespace: null,
targetFramework: null,
commandLineArgs: ImmutableArray<string>.Empty,
documents: ImmutableArray<DocumentFileInfo>.Empty,
additionalDocuments: ImmutableArray<DocumentFileInfo>.Empty,
analyzerConfigDocuments: ImmutableArray<DocumentFileInfo>.Empty,
projectReferences: ImmutableArray<ProjectFileReference>.Empty,
log);
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Compilers/Core/Portable/Diagnostic/ProgrammaticSuppressionInfo.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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;
namespace Microsoft.CodeAnalysis.Diagnostics
{
/// <summary>
/// Contains information about the source of a programmatic diagnostic suppression produced by an <see cref="DiagnosticSuppressor"/>.
/// </summary>
internal sealed class ProgrammaticSuppressionInfo : IEquatable<ProgrammaticSuppressionInfo?>
{
public ImmutableHashSet<(string Id, LocalizableString Justification)> Suppressions { get; }
internal ProgrammaticSuppressionInfo(ImmutableHashSet<(string Id, LocalizableString Justification)> suppressions)
{
Suppressions = suppressions;
}
public bool Equals(ProgrammaticSuppressionInfo? other)
{
if (ReferenceEquals(this, other))
{
return true;
}
return other != null &&
this.Suppressions.SetEquals(other.Suppressions);
}
public override bool Equals(object? obj)
{
return Equals(obj as ProgrammaticSuppressionInfo);
}
public override int GetHashCode()
{
return Suppressions.Count;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.Diagnostics
{
/// <summary>
/// Contains information about the source of a programmatic diagnostic suppression produced by an <see cref="DiagnosticSuppressor"/>.
/// </summary>
internal sealed class ProgrammaticSuppressionInfo : IEquatable<ProgrammaticSuppressionInfo?>
{
public ImmutableHashSet<(string Id, LocalizableString Justification)> Suppressions { get; }
internal ProgrammaticSuppressionInfo(ImmutableHashSet<(string Id, LocalizableString Justification)> suppressions)
{
Suppressions = suppressions;
}
public bool Equals(ProgrammaticSuppressionInfo? other)
{
if (ReferenceEquals(this, other))
{
return true;
}
return other != null &&
this.Suppressions.SetEquals(other.Suppressions);
}
public override bool Equals(object? obj)
{
return Equals(obj as ProgrammaticSuppressionInfo);
}
public override int GetHashCode()
{
return Suppressions.Count;
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/VisualStudio/Core/Def/Implementation/TableDataSource/MiscellaneousTodoListTable.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Shell.TableManager;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource
{
[ExportEventListener(WellKnownEventListeners.TodoListProvider, WorkspaceKind.MiscellaneousFiles), Shared]
internal sealed class MiscellaneousTodoListTableWorkspaceEventListener : IEventListener<ITodoListProvider>
{
internal const string IdentifierString = nameof(MiscellaneousTodoListTable);
private readonly ITableManagerProvider _tableManagerProvider;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public MiscellaneousTodoListTableWorkspaceEventListener(ITableManagerProvider tableManagerProvider)
=> _tableManagerProvider = tableManagerProvider;
public void StartListening(Workspace workspace, ITodoListProvider service)
=> new MiscellaneousTodoListTable(workspace, service, _tableManagerProvider);
private sealed class MiscellaneousTodoListTable : VisualStudioBaseTodoListTable
{
public MiscellaneousTodoListTable(Workspace workspace, ITodoListProvider todoListProvider, ITableManagerProvider provider)
: base(workspace, todoListProvider, IdentifierString, provider)
{
ConnectWorkspaceEvents();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Shell.TableManager;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource
{
[ExportEventListener(WellKnownEventListeners.TodoListProvider, WorkspaceKind.MiscellaneousFiles), Shared]
internal sealed class MiscellaneousTodoListTableWorkspaceEventListener : IEventListener<ITodoListProvider>
{
internal const string IdentifierString = nameof(MiscellaneousTodoListTable);
private readonly ITableManagerProvider _tableManagerProvider;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public MiscellaneousTodoListTableWorkspaceEventListener(ITableManagerProvider tableManagerProvider)
=> _tableManagerProvider = tableManagerProvider;
public void StartListening(Workspace workspace, ITodoListProvider service)
=> new MiscellaneousTodoListTable(workspace, service, _tableManagerProvider);
private sealed class MiscellaneousTodoListTable : VisualStudioBaseTodoListTable
{
public MiscellaneousTodoListTable(Workspace workspace, ITodoListProvider todoListProvider, ITableManagerProvider provider)
: base(workspace, todoListProvider, IdentifierString, provider)
{
ConnectWorkspaceEvents();
}
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/EditorFeatures/CSharpTest/CodeActions/AddAwait/AddAwaitTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.AddAwait;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.AddAwait
{
[Trait(Traits.Feature, Traits.Features.AddAwait)]
public class AddAwaitTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new CSharpAddAwaitCodeRefactoringProvider();
[Fact]
public async Task Simple()
{
await TestInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = GetNumberAsync()[||];
}
}", @"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = await GetNumberAsync();
}
}");
}
[Fact]
public async Task SimpleWithConfigureAwait()
{
await TestInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = GetNumberAsync()[||];
}
}", @"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = await GetNumberAsync().ConfigureAwait(false);
}
}", index: 1);
}
[Fact]
public async Task InArgument()
{
await TestInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync(int argument)
{
var x = GetNumberAsync(arg[||]ument);
}
}", @"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync(int argument)
{
var x = await GetNumberAsync(argument);
}
}");
}
[Fact]
public async Task InvocationInArgument()
{
await TestInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
M(GetNumberAsync()[||]);
}
}", @"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
M(await GetNumberAsync());
}
}");
}
[Fact]
public async Task InvocationInArgumentWithConfigureAwait()
{
await TestInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
M(GetNumberAsync()[||]);
}
}", @"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
M(await GetNumberAsync().ConfigureAwait(false));
}
}", index: 1);
}
[Fact]
public async Task AlreadyAwaited()
{
await TestMissingInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = await GetNumberAsync()[||];
}
}");
}
[Fact]
public async Task AlreadyAwaitedAndConfigured()
{
await TestMissingInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = await GetNumberAsync()[||].ConfigureAwait(false);
}
}");
}
[Fact]
public async Task AlreadyAwaitedAndConfigured2()
{
await TestMissingInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = await GetNumberAsync().ConfigureAwait(false)[||];
}
}");
}
[Fact]
public async Task SimpleWithTrivia()
{
await TestInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = // comment
GetNumberAsync()[||] /* comment */
}
}", @"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = // comment
await GetNumberAsync()[||] /* comment */
}
}");
}
[Fact]
public async Task SimpleWithTrivia2()
{
await TestInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = /* comment */ GetNumberAsync()[||] // comment
}
}", @"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = /* comment */ await GetNumberAsync()[||] // comment
}
}");
}
[Fact]
public async Task SimpleWithTriviaWithConfigureAwait()
{
await TestInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = // comment
GetNumberAsync()[||] /* comment */
}
}", @"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = // comment
await GetNumberAsync().ConfigureAwait(false) /* comment */
}
}", index: 1);
}
[Fact]
public async Task SimpleWithTrivia2WithConfigureAwait()
{
await TestInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = /* comment */ GetNumberAsync()[||] // comment
}
}", @"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = /* comment */ await GetNumberAsync().ConfigureAwait(false) // comment
}
}", index: 1);
}
[Fact]
[WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")]
public async Task OnSemiColon()
{
await TestInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = GetNumberAsync();[||]
}
}", @"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = await GetNumberAsync();
}
}");
}
[Fact]
[WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")]
public async Task Selection()
{
await TestInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = [|GetNumberAsync()|];
}
}", @"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = await GetNumberAsync();
}
}");
}
[Fact]
[WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")]
public async Task Selection2()
{
await TestInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
[|var x = GetNumberAsync();|]
}
}", @"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = await GetNumberAsync();
}
}");
}
[Fact]
public async Task ChainedInvocation()
{
await TestMissingInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
Task<int> GetNumberAsync() => throw null;
async void M()
{
var x = GetNumberAsync()[||].ToString();
}
}");
}
[Fact]
public async Task ChainedInvocation_ExpressionOfInvalidInvocation()
{
await TestInRegularAndScript1Async(@"
using System.Threading.Tasks;
class Program
{
Task<int> GetNumberAsync() => throw null;
async void M()
{
var x = GetNumberAsync()[||].Invalid();
}
}", @"
using System.Threading.Tasks;
class Program
{
Task<int> GetNumberAsync() => throw null;
async void M()
{
var x = (await GetNumberAsync()).Invalid();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task BadAsyncReturnOperand1()
{
var initial =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test()
{
return 3;
}
async Task<int> Test2()
{
return [|Test()|];
}
}";
var expected =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test()
{
return 3;
}
async Task<int> Test2()
{
return await Test();
}
}";
await TestInRegularAndScriptAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task BadAsyncReturnOperand_WithLeadingTrivia1()
{
var initial =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test()
{
return 3;
}
async Task<int> Test2()
{
return
// Useful comment
[|Test()|];
}
}";
var expected =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test()
{
return 3;
}
async Task<int> Test2()
{
return
// Useful comment
await Test();
}
}";
await TestInRegularAndScriptAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task BadAsyncReturnOperand_ConditionalExpressionWithTrailingTrivia_SingleLine()
{
var initial =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test() => 3;
async Task<int> Test2()
{
return [|true ? Test() /* true */ : Test()|] /* false */;
}
}";
var expected =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test() => 3;
async Task<int> Test2()
{
return await (true ? Test() /* true */ : Test()) /* false */;
}
}";
await TestInRegularAndScriptAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task BadAsyncReturnOperand_ConditionalExpressionWithTrailingTrivia_Multiline()
{
var initial =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test() => 3;
async Task<int> Test2()
{
return [|true ? Test() // aaa
: Test()|] // bbb
;
}
}";
var expected =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test() => 3;
async Task<int> Test2()
{
return await (true ? Test() // aaa
: Test()) // bbb
;
}
}";
await TestInRegularAndScriptAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task BadAsyncReturnOperand_NullCoalescingExpressionWithTrailingTrivia_SingleLine()
{
var initial =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test() => 3;
async Task<int> Test2()
{
return [|null /* 0 */ ?? Test()|] /* 1 */;
}
}";
var expected =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test() => 3;
async Task<int> Test2()
{
return await (null /* 0 */ ?? Test()) /* 1 */;
}
}";
await TestInRegularAndScriptAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task BadAsyncReturnOperand_NullCoalescingExpressionWithTrailingTrivia_Multiline()
{
var initial =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test() => 3;
async Task<int> Test2()
{
return [|null // aaa
?? Test()|] // bbb
;
}
}";
var expected =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test() => 3;
async Task<int> Test2()
{
return await (null // aaa
?? Test()) // bbb
;
}
}";
await TestInRegularAndScriptAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task BadAsyncReturnOperand_AsExpressionWithTrailingTrivia_SingleLine()
{
var initial =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test2()
{
return [|null /* 0 */ as Task<int>|] /* 1 */;
}
}";
var expected =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test2()
{
return await (null /* 0 */ as Task<int>) /* 1 */;
}
}";
await TestInRegularAndScriptAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task BadAsyncReturnOperand_AsExpressionWithTrailingTrivia_Multiline()
{
var initial =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test() => 3;
async Task<int> Test2()
{
return [|null // aaa
as Task<int>|] // bbb
;
}
}";
var expected =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test() => 3;
async Task<int> Test2()
{
return await (null // aaa
as Task<int>) // bbb
;
}
}";
await TestInRegularAndScriptAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TaskNotAwaited()
{
var initial =
@"using System;
using System.Threading.Tasks;
class Program
{
async void Test()
{
[|Task.Delay(3)|];
}
}";
var expected =
@"using System;
using System.Threading.Tasks;
class Program
{
async void Test()
{
await Task.Delay(3);
}
}";
await TestInRegularAndScriptAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TaskNotAwaited_WithLeadingTrivia()
{
var initial =
@"using System;
using System.Threading.Tasks;
class Program
{
async void Test()
{
// Useful comment
[|Task.Delay(3)|];
}
}";
var expected =
@"using System;
using System.Threading.Tasks;
class Program
{
async void Test()
{
// Useful comment
await Task.Delay(3);
}
}";
await TestInRegularAndScriptAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task FunctionNotAwaited()
{
var initial =
@"using System;
using System.Threading.Tasks;
class Program
{
Task AwaitableFunction()
{
return Task.FromResult(true);
}
async void Test()
{
[|AwaitableFunction()|];
}
}";
var expected =
@"using System;
using System.Threading.Tasks;
class Program
{
Task AwaitableFunction()
{
return Task.FromResult(true);
}
async void Test()
{
await AwaitableFunction();
}
}";
await TestInRegularAndScriptAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task FunctionNotAwaited_WithLeadingTrivia()
{
var initial =
@"using System;
using System.Threading.Tasks;
class Program
{
Task AwaitableFunction()
{
return Task.FromResult(true);
}
async void Test()
{
// Useful comment
[|AwaitableFunction()|];
}
}";
var expected =
@"using System;
using System.Threading.Tasks;
class Program
{
Task AwaitableFunction()
{
return Task.FromResult(true);
}
async void Test()
{
// Useful comment
await AwaitableFunction();
}
}";
await TestInRegularAndScriptAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task FunctionNotAwaited_WithLeadingTrivia1()
{
var initial =
@"using System;
using System.Threading.Tasks;
class Program
{
Task AwaitableFunction()
{
return Task.FromResult(true);
}
async void Test()
{
var i = 0;
[|AwaitableFunction()|];
}
}";
var expected =
@"using System;
using System.Threading.Tasks;
class Program
{
Task AwaitableFunction()
{
return Task.FromResult(true);
}
async void Test()
{
var i = 0;
await AwaitableFunction();
}
}";
await TestInRegularAndScriptAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpression()
{
await TestInRegularAndScriptAsync(
@"using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
int myInt = [|MyIntMethodAsync()|];
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}",
@"using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
int myInt = await MyIntMethodAsync();
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpressionWithConversion()
{
await TestInRegularAndScriptAsync(
@"using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
long myInt = [|MyIntMethodAsync()|];
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}",
@"using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
long myInt = await MyIntMethodAsync();
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpressionWithConversionInNonAsyncFunction()
{
await TestMissingAsync(@"using System.Threading.Tasks;
class TestClass
{
private Task MyTestMethod1Async()
{
long myInt = [|MyIntMethodAsync()|];
return Task.CompletedTask;
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpressionWithConversionInAsyncFunction()
{
await TestInRegularAndScriptAsync(
@"using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
long myInt = [|MyIntMethodAsync()|];
}
private Task<object> MyIntMethodAsync()
{
return Task.FromResult(new object());
}
}",
@"using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
long myInt = [|await MyIntMethodAsync()|];
}
private Task<object> MyIntMethodAsync()
{
return Task.FromResult(new object());
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpression1()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Action lambda = async () => {
int myInt = [|MyIntMethodAsync()|];
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}",
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Action lambda = async () => {
int myInt = await MyIntMethodAsync();
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpression2()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Func<Task> lambda = async () => {
int myInt = [|MyIntMethodAsync()|];
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}",
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Func<Task> lambda = async () => {
int myInt = await MyIntMethodAsync();
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpression3()
{
await TestMissingAsync(
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Func<Task> lambda = () => {
int myInt = [|MyIntMethodAsync()|];
return Task.CompletedTask;
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpression3_1()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Func<Task> lambda = async () => {
int myInt = [|MyIntMethodAsync()|];
return Task.CompletedTask;
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}",
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Func<Task> lambda = async () => {
int myInt = await MyIntMethodAsync();
return Task.CompletedTask;
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpression4()
{
await TestMissingAsync(
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Action lambda = () => {
int myInt = [|MyIntMethodAsync()|];
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpression4_1()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Action lambda = async () => {
int myInt = [|MyIntMethodAsync()|];
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}",
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Action lambda = async () => {
int myInt = await MyIntMethodAsync();
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpression5()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Action @delegate = async delegate {
int myInt = [|MyIntMethodAsync()|];
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}",
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Action @delegate = async delegate {
int myInt = await MyIntMethodAsync();
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpression6()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Func<Task> @delegate = async delegate {
int myInt = [|MyIntMethodAsync()|];
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}",
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Func<Task> @delegate = async delegate {
int myInt = await MyIntMethodAsync();
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpression7()
{
await TestMissingAsync(
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Action @delegate = delegate {
int myInt = [|MyIntMethodAsync()|];
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpression7_1()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Action @delegate = async delegate {
int myInt = [|MyIntMethodAsync()|];
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}",
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Action @delegate = async delegate {
int myInt = await MyIntMethodAsync();
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpression8()
{
await TestMissingAsync(
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Func<Task> @delegate = delegate {
int myInt = [|MyIntMethodAsync()|];
return Task.CompletedTask;
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpression8_1()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Func<Task> @delegate = async delegate {
int myInt = [|MyIntMethodAsync()|];
return Task.CompletedTask;
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}",
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Func<Task> @delegate = async delegate {
int myInt = [|await MyIntMethodAsync()|];
return Task.CompletedTask;
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestTernaryOperator()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> A()
{
return [|true ? Task.FromResult(0) : Task.FromResult(1)|];
}
}",
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> A()
{
return await (true ? Task.FromResult(0) : Task.FromResult(1));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestNullCoalescingOperator()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> A()
{
return [|null ?? Task.FromResult(1)|]; }
}",
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> A()
{
return await (null ?? Task.FromResult(1)); }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAsExpression()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> A()
{
return [|null as Task<int>|]; }
}",
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> A()
{
return await (null as Task<int>); }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
[WorkItem(1345322, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1345322")]
public async Task TestOnTaskTypeItself()
{
await TestMissingAsync(
@"using System.Threading.Tasks;
class Program
{
static async [||]Task Main(string[] args)
{
}
}
");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.AddAwait;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.AddAwait
{
[Trait(Traits.Feature, Traits.Features.AddAwait)]
public class AddAwaitTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new CSharpAddAwaitCodeRefactoringProvider();
[Fact]
public async Task Simple()
{
await TestInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = GetNumberAsync()[||];
}
}", @"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = await GetNumberAsync();
}
}");
}
[Fact]
public async Task SimpleWithConfigureAwait()
{
await TestInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = GetNumberAsync()[||];
}
}", @"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = await GetNumberAsync().ConfigureAwait(false);
}
}", index: 1);
}
[Fact]
public async Task InArgument()
{
await TestInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync(int argument)
{
var x = GetNumberAsync(arg[||]ument);
}
}", @"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync(int argument)
{
var x = await GetNumberAsync(argument);
}
}");
}
[Fact]
public async Task InvocationInArgument()
{
await TestInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
M(GetNumberAsync()[||]);
}
}", @"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
M(await GetNumberAsync());
}
}");
}
[Fact]
public async Task InvocationInArgumentWithConfigureAwait()
{
await TestInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
M(GetNumberAsync()[||]);
}
}", @"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
M(await GetNumberAsync().ConfigureAwait(false));
}
}", index: 1);
}
[Fact]
public async Task AlreadyAwaited()
{
await TestMissingInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = await GetNumberAsync()[||];
}
}");
}
[Fact]
public async Task AlreadyAwaitedAndConfigured()
{
await TestMissingInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = await GetNumberAsync()[||].ConfigureAwait(false);
}
}");
}
[Fact]
public async Task AlreadyAwaitedAndConfigured2()
{
await TestMissingInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = await GetNumberAsync().ConfigureAwait(false)[||];
}
}");
}
[Fact]
public async Task SimpleWithTrivia()
{
await TestInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = // comment
GetNumberAsync()[||] /* comment */
}
}", @"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = // comment
await GetNumberAsync()[||] /* comment */
}
}");
}
[Fact]
public async Task SimpleWithTrivia2()
{
await TestInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = /* comment */ GetNumberAsync()[||] // comment
}
}", @"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = /* comment */ await GetNumberAsync()[||] // comment
}
}");
}
[Fact]
public async Task SimpleWithTriviaWithConfigureAwait()
{
await TestInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = // comment
GetNumberAsync()[||] /* comment */
}
}", @"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = // comment
await GetNumberAsync().ConfigureAwait(false) /* comment */
}
}", index: 1);
}
[Fact]
public async Task SimpleWithTrivia2WithConfigureAwait()
{
await TestInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = /* comment */ GetNumberAsync()[||] // comment
}
}", @"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = /* comment */ await GetNumberAsync().ConfigureAwait(false) // comment
}
}", index: 1);
}
[Fact]
[WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")]
public async Task OnSemiColon()
{
await TestInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = GetNumberAsync();[||]
}
}", @"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = await GetNumberAsync();
}
}");
}
[Fact]
[WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")]
public async Task Selection()
{
await TestInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = [|GetNumberAsync()|];
}
}", @"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = await GetNumberAsync();
}
}");
}
[Fact]
[WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")]
public async Task Selection2()
{
await TestInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
[|var x = GetNumberAsync();|]
}
}", @"
using System.Threading.Tasks;
class Program
{
async Task<int> GetNumberAsync()
{
var x = await GetNumberAsync();
}
}");
}
[Fact]
public async Task ChainedInvocation()
{
await TestMissingInRegularAndScriptAsync(@"
using System.Threading.Tasks;
class Program
{
Task<int> GetNumberAsync() => throw null;
async void M()
{
var x = GetNumberAsync()[||].ToString();
}
}");
}
[Fact]
public async Task ChainedInvocation_ExpressionOfInvalidInvocation()
{
await TestInRegularAndScript1Async(@"
using System.Threading.Tasks;
class Program
{
Task<int> GetNumberAsync() => throw null;
async void M()
{
var x = GetNumberAsync()[||].Invalid();
}
}", @"
using System.Threading.Tasks;
class Program
{
Task<int> GetNumberAsync() => throw null;
async void M()
{
var x = (await GetNumberAsync()).Invalid();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task BadAsyncReturnOperand1()
{
var initial =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test()
{
return 3;
}
async Task<int> Test2()
{
return [|Test()|];
}
}";
var expected =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test()
{
return 3;
}
async Task<int> Test2()
{
return await Test();
}
}";
await TestInRegularAndScriptAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task BadAsyncReturnOperand_WithLeadingTrivia1()
{
var initial =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test()
{
return 3;
}
async Task<int> Test2()
{
return
// Useful comment
[|Test()|];
}
}";
var expected =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test()
{
return 3;
}
async Task<int> Test2()
{
return
// Useful comment
await Test();
}
}";
await TestInRegularAndScriptAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task BadAsyncReturnOperand_ConditionalExpressionWithTrailingTrivia_SingleLine()
{
var initial =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test() => 3;
async Task<int> Test2()
{
return [|true ? Test() /* true */ : Test()|] /* false */;
}
}";
var expected =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test() => 3;
async Task<int> Test2()
{
return await (true ? Test() /* true */ : Test()) /* false */;
}
}";
await TestInRegularAndScriptAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task BadAsyncReturnOperand_ConditionalExpressionWithTrailingTrivia_Multiline()
{
var initial =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test() => 3;
async Task<int> Test2()
{
return [|true ? Test() // aaa
: Test()|] // bbb
;
}
}";
var expected =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test() => 3;
async Task<int> Test2()
{
return await (true ? Test() // aaa
: Test()) // bbb
;
}
}";
await TestInRegularAndScriptAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task BadAsyncReturnOperand_NullCoalescingExpressionWithTrailingTrivia_SingleLine()
{
var initial =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test() => 3;
async Task<int> Test2()
{
return [|null /* 0 */ ?? Test()|] /* 1 */;
}
}";
var expected =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test() => 3;
async Task<int> Test2()
{
return await (null /* 0 */ ?? Test()) /* 1 */;
}
}";
await TestInRegularAndScriptAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task BadAsyncReturnOperand_NullCoalescingExpressionWithTrailingTrivia_Multiline()
{
var initial =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test() => 3;
async Task<int> Test2()
{
return [|null // aaa
?? Test()|] // bbb
;
}
}";
var expected =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test() => 3;
async Task<int> Test2()
{
return await (null // aaa
?? Test()) // bbb
;
}
}";
await TestInRegularAndScriptAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task BadAsyncReturnOperand_AsExpressionWithTrailingTrivia_SingleLine()
{
var initial =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test2()
{
return [|null /* 0 */ as Task<int>|] /* 1 */;
}
}";
var expected =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test2()
{
return await (null /* 0 */ as Task<int>) /* 1 */;
}
}";
await TestInRegularAndScriptAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task BadAsyncReturnOperand_AsExpressionWithTrailingTrivia_Multiline()
{
var initial =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test() => 3;
async Task<int> Test2()
{
return [|null // aaa
as Task<int>|] // bbb
;
}
}";
var expected =
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> Test() => 3;
async Task<int> Test2()
{
return await (null // aaa
as Task<int>) // bbb
;
}
}";
await TestInRegularAndScriptAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TaskNotAwaited()
{
var initial =
@"using System;
using System.Threading.Tasks;
class Program
{
async void Test()
{
[|Task.Delay(3)|];
}
}";
var expected =
@"using System;
using System.Threading.Tasks;
class Program
{
async void Test()
{
await Task.Delay(3);
}
}";
await TestInRegularAndScriptAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TaskNotAwaited_WithLeadingTrivia()
{
var initial =
@"using System;
using System.Threading.Tasks;
class Program
{
async void Test()
{
// Useful comment
[|Task.Delay(3)|];
}
}";
var expected =
@"using System;
using System.Threading.Tasks;
class Program
{
async void Test()
{
// Useful comment
await Task.Delay(3);
}
}";
await TestInRegularAndScriptAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task FunctionNotAwaited()
{
var initial =
@"using System;
using System.Threading.Tasks;
class Program
{
Task AwaitableFunction()
{
return Task.FromResult(true);
}
async void Test()
{
[|AwaitableFunction()|];
}
}";
var expected =
@"using System;
using System.Threading.Tasks;
class Program
{
Task AwaitableFunction()
{
return Task.FromResult(true);
}
async void Test()
{
await AwaitableFunction();
}
}";
await TestInRegularAndScriptAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task FunctionNotAwaited_WithLeadingTrivia()
{
var initial =
@"using System;
using System.Threading.Tasks;
class Program
{
Task AwaitableFunction()
{
return Task.FromResult(true);
}
async void Test()
{
// Useful comment
[|AwaitableFunction()|];
}
}";
var expected =
@"using System;
using System.Threading.Tasks;
class Program
{
Task AwaitableFunction()
{
return Task.FromResult(true);
}
async void Test()
{
// Useful comment
await AwaitableFunction();
}
}";
await TestInRegularAndScriptAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task FunctionNotAwaited_WithLeadingTrivia1()
{
var initial =
@"using System;
using System.Threading.Tasks;
class Program
{
Task AwaitableFunction()
{
return Task.FromResult(true);
}
async void Test()
{
var i = 0;
[|AwaitableFunction()|];
}
}";
var expected =
@"using System;
using System.Threading.Tasks;
class Program
{
Task AwaitableFunction()
{
return Task.FromResult(true);
}
async void Test()
{
var i = 0;
await AwaitableFunction();
}
}";
await TestInRegularAndScriptAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpression()
{
await TestInRegularAndScriptAsync(
@"using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
int myInt = [|MyIntMethodAsync()|];
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}",
@"using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
int myInt = await MyIntMethodAsync();
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpressionWithConversion()
{
await TestInRegularAndScriptAsync(
@"using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
long myInt = [|MyIntMethodAsync()|];
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}",
@"using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
long myInt = await MyIntMethodAsync();
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpressionWithConversionInNonAsyncFunction()
{
await TestMissingAsync(@"using System.Threading.Tasks;
class TestClass
{
private Task MyTestMethod1Async()
{
long myInt = [|MyIntMethodAsync()|];
return Task.CompletedTask;
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpressionWithConversionInAsyncFunction()
{
await TestInRegularAndScriptAsync(
@"using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
long myInt = [|MyIntMethodAsync()|];
}
private Task<object> MyIntMethodAsync()
{
return Task.FromResult(new object());
}
}",
@"using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
long myInt = [|await MyIntMethodAsync()|];
}
private Task<object> MyIntMethodAsync()
{
return Task.FromResult(new object());
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpression1()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Action lambda = async () => {
int myInt = [|MyIntMethodAsync()|];
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}",
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Action lambda = async () => {
int myInt = await MyIntMethodAsync();
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpression2()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Func<Task> lambda = async () => {
int myInt = [|MyIntMethodAsync()|];
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}",
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Func<Task> lambda = async () => {
int myInt = await MyIntMethodAsync();
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpression3()
{
await TestMissingAsync(
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Func<Task> lambda = () => {
int myInt = [|MyIntMethodAsync()|];
return Task.CompletedTask;
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpression3_1()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Func<Task> lambda = async () => {
int myInt = [|MyIntMethodAsync()|];
return Task.CompletedTask;
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}",
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Func<Task> lambda = async () => {
int myInt = await MyIntMethodAsync();
return Task.CompletedTask;
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpression4()
{
await TestMissingAsync(
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Action lambda = () => {
int myInt = [|MyIntMethodAsync()|];
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpression4_1()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Action lambda = async () => {
int myInt = [|MyIntMethodAsync()|];
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}",
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Action lambda = async () => {
int myInt = await MyIntMethodAsync();
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpression5()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Action @delegate = async delegate {
int myInt = [|MyIntMethodAsync()|];
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}",
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Action @delegate = async delegate {
int myInt = await MyIntMethodAsync();
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpression6()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Func<Task> @delegate = async delegate {
int myInt = [|MyIntMethodAsync()|];
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}",
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Func<Task> @delegate = async delegate {
int myInt = await MyIntMethodAsync();
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpression7()
{
await TestMissingAsync(
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Action @delegate = delegate {
int myInt = [|MyIntMethodAsync()|];
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpression7_1()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Action @delegate = async delegate {
int myInt = [|MyIntMethodAsync()|];
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}",
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Action @delegate = async delegate {
int myInt = await MyIntMethodAsync();
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpression8()
{
await TestMissingAsync(
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Func<Task> @delegate = delegate {
int myInt = [|MyIntMethodAsync()|];
return Task.CompletedTask;
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAssignmentExpression8_1()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Func<Task> @delegate = async delegate {
int myInt = [|MyIntMethodAsync()|];
return Task.CompletedTask;
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}",
@"using System;
using System.Threading.Tasks;
class TestClass
{
private async Task MyTestMethod1Async()
{
Func<Task> @delegate = async delegate {
int myInt = [|await MyIntMethodAsync()|];
return Task.CompletedTask;
};
}
private Task<int> MyIntMethodAsync()
{
return Task.FromResult(result: 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestTernaryOperator()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> A()
{
return [|true ? Task.FromResult(0) : Task.FromResult(1)|];
}
}",
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> A()
{
return await (true ? Task.FromResult(0) : Task.FromResult(1));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestNullCoalescingOperator()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> A()
{
return [|null ?? Task.FromResult(1)|]; }
}",
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> A()
{
return await (null ?? Task.FromResult(1)); }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
public async Task TestAsExpression()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> A()
{
return [|null as Task<int>|]; }
}",
@"using System;
using System.Threading.Tasks;
class Program
{
async Task<int> A()
{
return await (null as Task<int>); }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)]
[WorkItem(1345322, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1345322")]
public async Task TestOnTaskTypeItself()
{
await TestMissingAsync(
@"using System.Threading.Tasks;
class Program
{
static async [||]Task Main(string[] args)
{
}
}
");
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/GeneratedCodeRecognition/IGeneratedCodeRecognitionService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.GeneratedCodeRecognition
{
internal interface IGeneratedCodeRecognitionService : ILanguageService
{
#if !CODE_STYLE
bool IsGeneratedCode(Document document, CancellationToken cancellationToken);
#endif
Task<bool> IsGeneratedCodeAsync(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.
#nullable disable
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.GeneratedCodeRecognition
{
internal interface IGeneratedCodeRecognitionService : ILanguageService
{
#if !CODE_STYLE
bool IsGeneratedCode(Document document, CancellationToken cancellationToken);
#endif
Task<bool> IsGeneratedCodeAsync(Document document, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Features/CSharp/Portable/GenerateVariable/CSharpGenerateVariableCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.GenerateMember;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.GenerateMember.GenerateVariable;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.GenerateVariable
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.GenerateVariable), Shared]
[ExtensionOrder(After = PredefinedCodeFixProviderNames.GenerateMethod)]
internal class CSharpGenerateVariableCodeFixProvider : AbstractGenerateMemberCodeFixProvider
{
private const string CS1061 = nameof(CS1061); // error CS1061: 'C' does not contain a definition for 'Goo' and no extension method 'Goo' accepting a first argument of type 'C' could be found
private const string CS0103 = nameof(CS0103); // error CS0103: The name 'Goo' does not exist in the current context
private const string CS0117 = nameof(CS0117); // error CS0117: 'TestNs.Program' does not contain a definition for 'blah'
private const string CS0539 = nameof(CS0539); // error CS0539: 'Class.SomeProp' in explicit interface declaration is not a member of interface
private const string CS0246 = nameof(CS0246); // error CS0246: The type or namespace name 'Version' could not be found
private const string CS0120 = nameof(CS0120); // error CS0120: An object reference is required for the non-static field, method, or property 'A'
private const string CS0118 = nameof(CS0118); // error CS0118: 'C' is a type but is used like a variable
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpGenerateVariableCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds =>
ImmutableArray.Create(CS1061, CS0103, CS0117, CS0539, CS0246, CS0120, CS0118);
protected override bool IsCandidate(SyntaxNode node, SyntaxToken token, Diagnostic diagnostic)
=> node is SimpleNameSyntax || node is PropertyDeclarationSyntax || node is MemberBindingExpressionSyntax;
protected override SyntaxNode GetTargetNode(SyntaxNode node)
{
if (node.IsKind(SyntaxKind.MemberBindingExpression))
{
var nameNode = node.ChildNodes().FirstOrDefault(n => n.IsKind(SyntaxKind.IdentifierName));
if (nameNode != null)
{
return nameNode;
}
}
return base.GetTargetNode(node);
}
protected override Task<ImmutableArray<CodeAction>> GetCodeActionsAsync(
Document document, SyntaxNode node, CancellationToken cancellationToken)
{
var service = document.GetLanguageService<IGenerateVariableService>();
return service.GenerateVariableAsync(document, node, cancellationToken);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.GenerateMember;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.GenerateMember.GenerateVariable;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.GenerateVariable
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.GenerateVariable), Shared]
[ExtensionOrder(After = PredefinedCodeFixProviderNames.GenerateMethod)]
internal class CSharpGenerateVariableCodeFixProvider : AbstractGenerateMemberCodeFixProvider
{
private const string CS1061 = nameof(CS1061); // error CS1061: 'C' does not contain a definition for 'Goo' and no extension method 'Goo' accepting a first argument of type 'C' could be found
private const string CS0103 = nameof(CS0103); // error CS0103: The name 'Goo' does not exist in the current context
private const string CS0117 = nameof(CS0117); // error CS0117: 'TestNs.Program' does not contain a definition for 'blah'
private const string CS0539 = nameof(CS0539); // error CS0539: 'Class.SomeProp' in explicit interface declaration is not a member of interface
private const string CS0246 = nameof(CS0246); // error CS0246: The type or namespace name 'Version' could not be found
private const string CS0120 = nameof(CS0120); // error CS0120: An object reference is required for the non-static field, method, or property 'A'
private const string CS0118 = nameof(CS0118); // error CS0118: 'C' is a type but is used like a variable
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpGenerateVariableCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds =>
ImmutableArray.Create(CS1061, CS0103, CS0117, CS0539, CS0246, CS0120, CS0118);
protected override bool IsCandidate(SyntaxNode node, SyntaxToken token, Diagnostic diagnostic)
=> node is SimpleNameSyntax || node is PropertyDeclarationSyntax || node is MemberBindingExpressionSyntax;
protected override SyntaxNode GetTargetNode(SyntaxNode node)
{
if (node.IsKind(SyntaxKind.MemberBindingExpression))
{
var nameNode = node.ChildNodes().FirstOrDefault(n => n.IsKind(SyntaxKind.IdentifierName));
if (nameNode != null)
{
return nameNode;
}
}
return base.GetTargetNode(node);
}
protected override Task<ImmutableArray<CodeAction>> GetCodeActionsAsync(
Document document, SyntaxNode node, CancellationToken cancellationToken)
{
var service = document.GetLanguageService<IGenerateVariableService>();
return service.GenerateVariableAsync(document, node, cancellationToken);
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Compilers/Core/Portable/NativePdbWriter/PdbWriter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Security.Cryptography;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.DiaSymReader;
using Roslyn.Utilities;
namespace Microsoft.Cci
{
internal sealed class PdbWriter : IDisposable
{
internal const uint Age = 1;
private readonly HashAlgorithmName _hashAlgorithmNameOpt;
private readonly string _fileName;
private readonly Func<ISymWriterMetadataProvider, SymUnmanagedWriter> _symWriterFactory;
private readonly Dictionary<DebugSourceDocument, int> _documentIndex;
private MetadataWriter _metadataWriter;
private SymUnmanagedWriter _symWriter;
private SymUnmanagedSequencePointsWriter _sequencePointsWriter;
// { INamespace or ITypeReference -> qualified name }
private readonly Dictionary<object, string> _qualifiedNameCache;
// in support of determinism
private bool IsDeterministic { get => _hashAlgorithmNameOpt.Name != null; }
public PdbWriter(string fileName, Func<ISymWriterMetadataProvider, SymUnmanagedWriter> symWriterFactory, HashAlgorithmName hashAlgorithmNameOpt)
{
_fileName = fileName;
_symWriterFactory = symWriterFactory;
_hashAlgorithmNameOpt = hashAlgorithmNameOpt;
_documentIndex = new Dictionary<DebugSourceDocument, int>();
_qualifiedNameCache = new Dictionary<object, string>(ReferenceEqualityComparer.Instance);
}
public void WriteTo(Stream stream)
{
_symWriter.WriteTo(stream);
}
public void Dispose()
{
_symWriter?.Dispose();
}
private CommonPEModuleBuilder Module => Context.Module;
private EmitContext Context => _metadataWriter.Context;
public void SerializeDebugInfo(IMethodBody methodBody, StandaloneSignatureHandle localSignatureHandleOpt, CustomDebugInfoWriter customDebugInfoWriter)
{
Debug.Assert(_metadataWriter != null);
var methodHandle = (MethodDefinitionHandle)_metadataWriter.GetMethodHandle(methodBody.MethodDefinition);
// A state machine kickoff method doesn't have sequence points as it only contains generated code.
// We could avoid emitting debug info for it if the corresponding MoveNext method had no sequence points,
// but there is no real need for such optimization.
//
// Special case a hidden entry point (#line hidden applied) that would otherwise have no debug info.
// This is to accommodate for a requirement of Windows PDB writer that the entry point method must have some debug information.
bool isKickoffMethod = methodBody.StateMachineTypeName != null;
bool emitAllDebugInfo = isKickoffMethod || !methodBody.SequencePoints.IsEmpty ||
methodBody.MethodDefinition == (Context.Module.DebugEntryPoint ?? Context.Module.PEEntryPoint);
var compilationOptions = Context.Module.CommonCompilation.Options;
// We need to avoid emitting CDI DynamicLocals = 5 and EditAndContinueLocalSlotMap = 6 for files processed by WinMDExp until
// bug #1067635 is fixed and available in SDK.
bool suppressNewCustomDebugInfo = compilationOptions.OutputKind == OutputKind.WindowsRuntimeMetadata;
bool emitDynamicAndTupleInfo = emitAllDebugInfo && !suppressNewCustomDebugInfo;
// Emit EnC info for all methods even if they do not have sequence points.
// The information facilitates reusing lambdas and closures. The reuse is important for runtimes that can't add new members (e.g. Mono).
bool emitEncInfo = compilationOptions.EnableEditAndContinue && _metadataWriter.IsFullMetadata && !suppressNewCustomDebugInfo;
byte[] blob = customDebugInfoWriter.SerializeMethodDebugInfo(Context, methodBody, methodHandle, emitStateMachineInfo: emitAllDebugInfo, emitEncInfo, emitDynamicAndTupleInfo, out bool emitExternNamespaces);
if (!emitAllDebugInfo && blob.Length == 0)
{
return;
}
int methodToken = MetadataTokens.GetToken(methodHandle);
OpenMethod(methodToken, methodBody.MethodDefinition);
if (emitAllDebugInfo)
{
var localScopes = methodBody.LocalScopes;
// Define locals, constants and namespaces in the outermost local scope (opened in OpenMethod):
if (localScopes.Length > 0)
{
DefineScopeLocals(localScopes[0], localSignatureHandleOpt);
}
if (!isKickoffMethod && methodBody.ImportScope != null)
{
if (customDebugInfoWriter.ShouldForwardNamespaceScopes(Context, methodBody, methodHandle, out IMethodDefinition forwardToMethod))
{
if (forwardToMethod != null)
{
UsingNamespace("@" + MetadataTokens.GetToken(_metadataWriter.GetMethodHandle(forwardToMethod)), methodBody.MethodDefinition);
}
// otherwise, the forwarding is done via custom debug info
}
else
{
DefineNamespaceScopes(methodBody);
}
}
DefineLocalScopes(localScopes, localSignatureHandleOpt);
EmitSequencePoints(methodBody.SequencePoints);
if (methodBody.MoveNextBodyInfo is AsyncMoveNextBodyDebugInfo asyncMoveNextInfo)
{
_symWriter.SetAsyncInfo(
methodToken,
MetadataTokens.GetToken(_metadataWriter.GetMethodHandle(asyncMoveNextInfo.KickoffMethod)),
asyncMoveNextInfo.CatchHandlerOffset,
asyncMoveNextInfo.YieldOffsets.AsSpan(),
asyncMoveNextInfo.ResumeOffsets.AsSpan());
}
if (emitExternNamespaces)
{
DefineAssemblyReferenceAliases();
}
}
if (blob.Length > 0)
{
_symWriter.DefineCustomMetadata(blob);
}
CloseMethod(methodBody.IL.Length);
}
private void DefineNamespaceScopes(IMethodBody methodBody)
{
var module = Module;
bool isVisualBasic = module.GenerateVisualBasicStylePdb;
IMethodDefinition method = methodBody.MethodDefinition;
var namespaceScopes = methodBody.ImportScope;
PooledHashSet<string> lazyDeclaredExternAliases = null;
if (!isVisualBasic)
{
for (var scope = namespaceScopes; scope != null; scope = scope.Parent)
{
foreach (var import in scope.GetUsedNamespaces())
{
if (import.TargetNamespaceOpt == null && import.TargetTypeOpt == null)
{
Debug.Assert(import.AliasOpt != null);
Debug.Assert(import.TargetAssemblyOpt == null);
if (lazyDeclaredExternAliases == null)
{
lazyDeclaredExternAliases = PooledHashSet<string>.GetInstance();
}
lazyDeclaredExternAliases.Add(import.AliasOpt);
}
}
}
}
// file and namespace level
for (IImportScope scope = namespaceScopes; scope != null; scope = scope.Parent)
{
foreach (UsedNamespaceOrType import in scope.GetUsedNamespaces())
{
var importString = TryEncodeImport(import, lazyDeclaredExternAliases, isProjectLevel: false);
if (importString != null)
{
UsingNamespace(importString, method);
}
}
}
lazyDeclaredExternAliases?.Free();
// project level
if (isVisualBasic)
{
string defaultNamespace = module.DefaultNamespace;
if (!string.IsNullOrEmpty(defaultNamespace))
{
// VB marks the default/root namespace with an asterisk
UsingNamespace("*" + defaultNamespace, module);
}
foreach (string assemblyName in module.LinkedAssembliesDebugInfo)
{
UsingNamespace("&" + assemblyName, module);
}
foreach (UsedNamespaceOrType import in module.GetImports())
{
var importString = TryEncodeImport(import, null, isProjectLevel: true);
if (importString != null)
{
UsingNamespace(importString, method);
}
}
// VB current namespace -- VB appends the namespace of the container without prefixes
UsingNamespace(GetOrCreateSerializedNamespaceName(method.ContainingNamespace), method);
}
}
private void DefineAssemblyReferenceAliases()
{
foreach (AssemblyReferenceAlias alias in Module.GetAssemblyReferenceAliases(Context))
{
UsingNamespace("Z" + alias.Name + " " + alias.Assembly.Identity.GetDisplayName(), Module);
}
}
private string TryEncodeImport(UsedNamespaceOrType import, HashSet<string> declaredExternAliasesOpt, bool isProjectLevel)
{
// NOTE: Dev12 has related cases "I" and "O" in EMITTER::ComputeDebugNamespace,
// but they were probably implementation details that do not affect Roslyn.
if (Module.GenerateVisualBasicStylePdb)
{
// VB doesn't support extern aliases
Debug.Assert(import.TargetAssemblyOpt == null);
Debug.Assert(declaredExternAliasesOpt == null);
if (import.TargetTypeOpt != null)
{
Debug.Assert(import.TargetNamespaceOpt == null);
Debug.Assert(import.TargetAssemblyOpt == null);
// Native compiler doesn't write imports with generic types to PDB.
if (import.TargetTypeOpt.IsTypeSpecification())
{
return null;
}
string typeName = GetOrCreateSerializedTypeName(import.TargetTypeOpt);
if (import.AliasOpt != null)
{
return (isProjectLevel ? "@PA:" : "@FA:") + import.AliasOpt + "=" + typeName;
}
else
{
return (isProjectLevel ? "@PT:" : "@FT:") + typeName;
}
}
if (import.TargetNamespaceOpt != null)
{
string namespaceName = GetOrCreateSerializedNamespaceName(import.TargetNamespaceOpt);
if (import.AliasOpt == null)
{
return (isProjectLevel ? "@P:" : "@F:") + namespaceName;
}
else
{
return (isProjectLevel ? "@PA:" : "@FA:") + import.AliasOpt + "=" + namespaceName;
}
}
Debug.Assert(import.AliasOpt != null);
Debug.Assert(import.TargetXmlNamespaceOpt != null);
return (isProjectLevel ? "@PX:" : "@FX:") + import.AliasOpt + "=" + import.TargetXmlNamespaceOpt;
}
Debug.Assert(import.TargetXmlNamespaceOpt == null);
if (import.TargetTypeOpt != null)
{
Debug.Assert(import.TargetNamespaceOpt == null);
Debug.Assert(import.TargetAssemblyOpt == null);
string typeName = GetOrCreateSerializedTypeName(import.TargetTypeOpt);
return (import.AliasOpt != null) ?
"A" + import.AliasOpt + " T" + typeName :
"T" + typeName;
}
if (import.TargetNamespaceOpt != null)
{
string namespaceName = GetOrCreateSerializedNamespaceName(import.TargetNamespaceOpt);
if (import.AliasOpt != null)
{
return (import.TargetAssemblyOpt != null) ?
"A" + import.AliasOpt + " E" + namespaceName + " " + GetAssemblyReferenceAlias(import.TargetAssemblyOpt, declaredExternAliasesOpt) :
"A" + import.AliasOpt + " U" + namespaceName;
}
else
{
return (import.TargetAssemblyOpt != null) ?
"E" + namespaceName + " " + GetAssemblyReferenceAlias(import.TargetAssemblyOpt, declaredExternAliasesOpt) :
"U" + namespaceName;
}
}
Debug.Assert(import.AliasOpt != null);
Debug.Assert(import.TargetAssemblyOpt == null);
return "X" + import.AliasOpt;
}
internal string GetOrCreateSerializedNamespaceName(INamespace @namespace)
{
string result;
if (!_qualifiedNameCache.TryGetValue(@namespace, out result))
{
result = TypeNameSerializer.BuildQualifiedNamespaceName(@namespace);
_qualifiedNameCache.Add(@namespace, result);
}
return result;
}
internal string GetOrCreateSerializedTypeName(ITypeReference typeReference)
{
string result;
if (!_qualifiedNameCache.TryGetValue(typeReference, out result))
{
if (Module.GenerateVisualBasicStylePdb)
{
result = SerializeVisualBasicImportTypeReference(typeReference);
}
else
{
result = typeReference.GetSerializedTypeName(Context);
}
_qualifiedNameCache.Add(typeReference, result);
}
return result;
}
private string SerializeVisualBasicImportTypeReference(ITypeReference typeReference)
{
Debug.Assert(!(typeReference is IArrayTypeReference));
Debug.Assert(!(typeReference is IPointerTypeReference));
Debug.Assert(!typeReference.IsTypeSpecification());
var result = PooledStringBuilder.GetInstance();
ArrayBuilder<string> nestedNamesReversed;
INestedTypeReference nestedType = typeReference.AsNestedTypeReference;
if (nestedType != null)
{
nestedNamesReversed = ArrayBuilder<string>.GetInstance();
while (nestedType != null)
{
nestedNamesReversed.Add(nestedType.Name);
typeReference = nestedType.GetContainingType(_metadataWriter.Context);
nestedType = typeReference.AsNestedTypeReference;
}
}
else
{
nestedNamesReversed = null;
}
INamespaceTypeReference namespaceType = typeReference.AsNamespaceTypeReference;
Debug.Assert(namespaceType != null);
string namespaceName = namespaceType.NamespaceName;
if (namespaceName.Length != 0)
{
result.Builder.Append(namespaceName);
result.Builder.Append('.');
}
result.Builder.Append(namespaceType.Name);
if (nestedNamesReversed != null)
{
for (int i = nestedNamesReversed.Count - 1; i >= 0; i--)
{
result.Builder.Append('.');
result.Builder.Append(nestedNamesReversed[i]);
}
nestedNamesReversed.Free();
}
return result.ToStringAndFree();
}
private string GetAssemblyReferenceAlias(IAssemblyReference assembly, HashSet<string> declaredExternAliases)
{
// no extern alias defined in scope at all -> error in compiler
Debug.Assert(declaredExternAliases != null);
var allAliases = _metadataWriter.Context.Module.GetAssemblyReferenceAliases(_metadataWriter.Context);
foreach (AssemblyReferenceAlias alias in allAliases)
{
// Multiple aliases may be given to an assembly reference.
// We find one that is in scope (was imported via extern alias directive).
// If multiple are in scope then use the first one.
// NOTE: Dev12 uses the one that appeared in source, whereas we use
// the first one that COULD have appeared in source. (DevDiv #913022)
// The reason we're not just using the alias from the syntax is that
// it is non-trivial to locate. In particular, since "." may be used in
// place of "::", determining whether the first identifier in the name is
// the alias requires binding. For example, "using A.B;" could refer to
// either "A::B" or "global::A.B".
if (assembly == alias.Assembly && declaredExternAliases.Contains(alias.Name))
{
return alias.Name;
}
}
// no alias defined in scope for given assembly -> error in compiler
throw ExceptionUtilities.Unreachable;
}
private void DefineLocalScopes(ImmutableArray<LocalScope> scopes, StandaloneSignatureHandle localSignatureHandleOpt)
{
// VB scope ranges are end-inclusive
bool endInclusive = this.Module.GenerateVisualBasicStylePdb;
// The order of OpenScope and CloseScope calls must follow the scope nesting.
var scopeStack = ArrayBuilder<LocalScope>.GetInstance();
for (int i = 1; i < scopes.Length; i++)
{
var currentScope = scopes[i];
// Close any scopes that have finished.
while (scopeStack.Count > 0)
{
LocalScope topScope = scopeStack.Last();
if (currentScope.StartOffset < topScope.StartOffset + topScope.Length)
{
break;
}
scopeStack.RemoveLast();
_symWriter.CloseScope(endInclusive ? topScope.EndOffset - 1 : topScope.EndOffset);
}
// Open this scope.
scopeStack.Add(currentScope);
_symWriter.OpenScope(currentScope.StartOffset);
DefineScopeLocals(currentScope, localSignatureHandleOpt);
}
// Close remaining scopes.
for (int i = scopeStack.Count - 1; i >= 0; i--)
{
LocalScope scope = scopeStack[i];
_symWriter.CloseScope(endInclusive ? scope.EndOffset - 1 : scope.EndOffset);
}
scopeStack.Free();
}
private void DefineScopeLocals(LocalScope currentScope, StandaloneSignatureHandle localSignatureHandleOpt)
{
foreach (ILocalDefinition scopeConstant in currentScope.Constants)
{
var signatureHandle = _metadataWriter.SerializeLocalConstantStandAloneSignature(scopeConstant);
if (!_metadataWriter.IsLocalNameTooLong(scopeConstant))
{
_symWriter.DefineLocalConstant(
scopeConstant.Name,
scopeConstant.CompileTimeValue.Value,
MetadataTokens.GetToken(signatureHandle));
}
}
foreach (ILocalDefinition scopeLocal in currentScope.Variables)
{
if (!_metadataWriter.IsLocalNameTooLong(scopeLocal))
{
Debug.Assert(scopeLocal.SlotIndex >= 0);
_symWriter.DefineLocalVariable(
scopeLocal.SlotIndex,
scopeLocal.Name,
(int)scopeLocal.PdbAttributes,
localSignatureHandleOpt.IsNil ? 0 : MetadataTokens.GetToken(localSignatureHandleOpt));
}
}
}
public void SetMetadataEmitter(MetadataWriter metadataWriter)
{
// Do not look for COM registered diasymreader when determinism is needed as it doesn't support it.
var options =
(IsDeterministic ? SymUnmanagedWriterCreationOptions.Deterministic : SymUnmanagedWriterCreationOptions.UseComRegistry) |
SymUnmanagedWriterCreationOptions.UseAlternativeLoadPath;
var metadataProvider = new SymWriterMetadataProvider(metadataWriter);
SymUnmanagedWriter symWriter;
try
{
symWriter = (_symWriterFactory != null) ? _symWriterFactory(metadataProvider) : SymUnmanagedWriterFactory.CreateWriter(metadataProvider, options);
}
catch (DllNotFoundException e)
{
throw new SymUnmanagedWriterException(e.Message);
}
catch (SymUnmanagedWriterException e) when (e.InnerException is NotSupportedException)
{
var message = IsDeterministic ? CodeAnalysisResources.SymWriterNotDeterministic : CodeAnalysisResources.SymWriterOlderVersionThanRequired;
throw new SymUnmanagedWriterException(string.Format(message, e.ImplementationModuleName));
}
_metadataWriter = metadataWriter;
_symWriter = symWriter;
_sequencePointsWriter = new SymUnmanagedSequencePointsWriter(symWriter, capacity: 64);
}
public BlobContentId GetContentId()
{
BlobContentId contentId;
if (IsDeterministic)
{
// Calculate hash of the stream content.
// Note: all bits of the signature currently stored in the PDB stream were initialized to 1 by InitializeDeterministic.
contentId = BlobContentId.FromHash(CryptographicHashProvider.ComputeHash(_hashAlgorithmNameOpt, _symWriter.GetUnderlyingData()));
_symWriter.UpdateSignature(contentId.Guid, contentId.Stamp, age: 1);
}
else
{
_symWriter.GetSignature(out Guid guid, out uint stamp, out int age);
Debug.Assert(age == Age);
contentId = new BlobContentId(guid, stamp);
}
// Once we calculate the content id we shall not write more data to the writer.
// Note that the underlying stream is accessible for reading even after the writer is disposed.
_symWriter.Dispose();
return contentId;
}
public void SetEntryPoint(int entryMethodToken)
{
_symWriter.SetEntryPoint(entryMethodToken);
}
private int GetDocumentIndex(DebugSourceDocument document)
{
if (_documentIndex.TryGetValue(document, out int documentIndex))
{
return documentIndex;
}
return AddDocumentIndex(document);
}
private int AddDocumentIndex(DebugSourceDocument document)
{
Guid algorithmId;
ReadOnlySpan<byte> checksum;
ReadOnlySpan<byte> embeddedSource;
DebugSourceInfo info = document.GetSourceInfo();
if (!info.Checksum.IsDefault)
{
algorithmId = info.ChecksumAlgorithmId;
checksum = info.Checksum.AsSpan();
}
else
{
algorithmId = default;
checksum = null;
}
if (!info.EmbeddedTextBlob.IsDefault)
{
embeddedSource = info.EmbeddedTextBlob.AsSpan();
}
else
{
embeddedSource = null;
}
int documentIndex = _symWriter.DefineDocument(
document.Location,
document.Language,
document.LanguageVendor,
document.DocumentType,
algorithmId,
checksum,
embeddedSource);
_documentIndex.Add(document, documentIndex);
return documentIndex;
}
private void OpenMethod(int methodToken, IMethodDefinition method)
{
_symWriter.OpenMethod(methodToken);
// open outermost scope:
_symWriter.OpenScope(startOffset: 0);
}
private void CloseMethod(int ilLength)
{
// close the root scope:
_symWriter.CloseScope(endOffset: ilLength);
_symWriter.CloseMethod();
}
private void UsingNamespace(string fullName, INamedEntity errorEntity)
{
if (!_metadataWriter.IsUsingStringTooLong(fullName, errorEntity))
{
_symWriter.UsingNamespace(fullName);
}
}
private void EmitSequencePoints(ImmutableArray<SequencePoint> sequencePoints)
{
int lastDocumentIndex = -1;
DebugSourceDocument lastDocument = null;
foreach (var sequencePoint in sequencePoints)
{
Debug.Assert(sequencePoint.Document != null);
var document = sequencePoint.Document;
int documentIndex;
if (lastDocument == document)
{
documentIndex = lastDocumentIndex;
}
else
{
lastDocument = document;
documentIndex = lastDocumentIndex = GetDocumentIndex(lastDocument);
}
_sequencePointsWriter.Add(
documentIndex,
sequencePoint.Offset,
sequencePoint.StartLine,
sequencePoint.StartColumn,
sequencePoint.EndLine,
sequencePoint.EndColumn);
}
_sequencePointsWriter.Flush();
}
[Conditional("DEBUG")]
// Used to catch cases where file2definitions contain nonwritable definitions early
// If left unfixed, such scenarios will lead to crashes if happen in winmdobj projects
public void AssertAllDefinitionsHaveTokens(MultiDictionary<DebugSourceDocument, DefinitionWithLocation> file2definitions)
{
foreach (var kvp in file2definitions)
{
foreach (var definition in kvp.Value)
{
EntityHandle handle = _metadataWriter.GetDefinitionHandle(definition.Definition);
Debug.Assert(!handle.IsNil);
}
}
}
// Note: only used for WinMD
public void WriteDefinitionLocations(MultiDictionary<DebugSourceDocument, DefinitionWithLocation> file2definitions)
{
// Only open and close the map if we have any mapping.
bool open = false;
foreach (var kvp in file2definitions)
{
foreach (var definition in kvp.Value)
{
if (!open)
{
_symWriter.OpenTokensToSourceSpansMap();
open = true;
}
int token = MetadataTokens.GetToken(_metadataWriter.GetDefinitionHandle(definition.Definition));
Debug.Assert(token != 0);
_symWriter.MapTokenToSourceSpan(
token,
GetDocumentIndex(kvp.Key),
definition.StartLine + 1,
definition.StartColumn + 1,
definition.EndLine + 1,
definition.EndColumn + 1);
}
}
if (open)
{
_symWriter.CloseTokensToSourceSpansMap();
}
}
public void EmbedSourceLink(Stream stream)
{
byte[] bytes;
try
{
bytes = stream.ReadAllBytes();
}
catch (Exception e)
{
throw new SymUnmanagedWriterException(e.Message, e);
}
try
{
_symWriter.SetSourceLinkData(bytes);
}
catch (SymUnmanagedWriterException e) when (e.InnerException is NotSupportedException)
{
throw new SymUnmanagedWriterException(string.Format(CodeAnalysisResources.SymWriterDoesNotSupportSourceLink, e.ImplementationModuleName));
}
}
/// <summary>
/// Write document entries for all debug documents that do not yet have an entry.
/// </summary>
/// <remarks>
/// This is done after serializing method debug info to ensure that we embed all requested
/// text even if there are no corresponding sequence points.
/// </remarks>
public void WriteRemainingDebugDocuments(IReadOnlyDictionary<string, DebugSourceDocument> documents)
{
foreach (var kvp in documents
.Where(kvp => !_documentIndex.ContainsKey(kvp.Value))
.OrderBy(kvp => kvp.Key))
{
AddDocumentIndex(kvp.Value);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Security.Cryptography;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.DiaSymReader;
using Roslyn.Utilities;
namespace Microsoft.Cci
{
internal sealed class PdbWriter : IDisposable
{
internal const uint Age = 1;
private readonly HashAlgorithmName _hashAlgorithmNameOpt;
private readonly string _fileName;
private readonly Func<ISymWriterMetadataProvider, SymUnmanagedWriter> _symWriterFactory;
private readonly Dictionary<DebugSourceDocument, int> _documentIndex;
private MetadataWriter _metadataWriter;
private SymUnmanagedWriter _symWriter;
private SymUnmanagedSequencePointsWriter _sequencePointsWriter;
// { INamespace or ITypeReference -> qualified name }
private readonly Dictionary<object, string> _qualifiedNameCache;
// in support of determinism
private bool IsDeterministic { get => _hashAlgorithmNameOpt.Name != null; }
public PdbWriter(string fileName, Func<ISymWriterMetadataProvider, SymUnmanagedWriter> symWriterFactory, HashAlgorithmName hashAlgorithmNameOpt)
{
_fileName = fileName;
_symWriterFactory = symWriterFactory;
_hashAlgorithmNameOpt = hashAlgorithmNameOpt;
_documentIndex = new Dictionary<DebugSourceDocument, int>();
_qualifiedNameCache = new Dictionary<object, string>(ReferenceEqualityComparer.Instance);
}
public void WriteTo(Stream stream)
{
_symWriter.WriteTo(stream);
}
public void Dispose()
{
_symWriter?.Dispose();
}
private CommonPEModuleBuilder Module => Context.Module;
private EmitContext Context => _metadataWriter.Context;
public void SerializeDebugInfo(IMethodBody methodBody, StandaloneSignatureHandle localSignatureHandleOpt, CustomDebugInfoWriter customDebugInfoWriter)
{
Debug.Assert(_metadataWriter != null);
var methodHandle = (MethodDefinitionHandle)_metadataWriter.GetMethodHandle(methodBody.MethodDefinition);
// A state machine kickoff method doesn't have sequence points as it only contains generated code.
// We could avoid emitting debug info for it if the corresponding MoveNext method had no sequence points,
// but there is no real need for such optimization.
//
// Special case a hidden entry point (#line hidden applied) that would otherwise have no debug info.
// This is to accommodate for a requirement of Windows PDB writer that the entry point method must have some debug information.
bool isKickoffMethod = methodBody.StateMachineTypeName != null;
bool emitAllDebugInfo = isKickoffMethod || !methodBody.SequencePoints.IsEmpty ||
methodBody.MethodDefinition == (Context.Module.DebugEntryPoint ?? Context.Module.PEEntryPoint);
var compilationOptions = Context.Module.CommonCompilation.Options;
// We need to avoid emitting CDI DynamicLocals = 5 and EditAndContinueLocalSlotMap = 6 for files processed by WinMDExp until
// bug #1067635 is fixed and available in SDK.
bool suppressNewCustomDebugInfo = compilationOptions.OutputKind == OutputKind.WindowsRuntimeMetadata;
bool emitDynamicAndTupleInfo = emitAllDebugInfo && !suppressNewCustomDebugInfo;
// Emit EnC info for all methods even if they do not have sequence points.
// The information facilitates reusing lambdas and closures. The reuse is important for runtimes that can't add new members (e.g. Mono).
bool emitEncInfo = compilationOptions.EnableEditAndContinue && _metadataWriter.IsFullMetadata && !suppressNewCustomDebugInfo;
byte[] blob = customDebugInfoWriter.SerializeMethodDebugInfo(Context, methodBody, methodHandle, emitStateMachineInfo: emitAllDebugInfo, emitEncInfo, emitDynamicAndTupleInfo, out bool emitExternNamespaces);
if (!emitAllDebugInfo && blob.Length == 0)
{
return;
}
int methodToken = MetadataTokens.GetToken(methodHandle);
OpenMethod(methodToken, methodBody.MethodDefinition);
if (emitAllDebugInfo)
{
var localScopes = methodBody.LocalScopes;
// Define locals, constants and namespaces in the outermost local scope (opened in OpenMethod):
if (localScopes.Length > 0)
{
DefineScopeLocals(localScopes[0], localSignatureHandleOpt);
}
if (!isKickoffMethod && methodBody.ImportScope != null)
{
if (customDebugInfoWriter.ShouldForwardNamespaceScopes(Context, methodBody, methodHandle, out IMethodDefinition forwardToMethod))
{
if (forwardToMethod != null)
{
UsingNamespace("@" + MetadataTokens.GetToken(_metadataWriter.GetMethodHandle(forwardToMethod)), methodBody.MethodDefinition);
}
// otherwise, the forwarding is done via custom debug info
}
else
{
DefineNamespaceScopes(methodBody);
}
}
DefineLocalScopes(localScopes, localSignatureHandleOpt);
EmitSequencePoints(methodBody.SequencePoints);
if (methodBody.MoveNextBodyInfo is AsyncMoveNextBodyDebugInfo asyncMoveNextInfo)
{
_symWriter.SetAsyncInfo(
methodToken,
MetadataTokens.GetToken(_metadataWriter.GetMethodHandle(asyncMoveNextInfo.KickoffMethod)),
asyncMoveNextInfo.CatchHandlerOffset,
asyncMoveNextInfo.YieldOffsets.AsSpan(),
asyncMoveNextInfo.ResumeOffsets.AsSpan());
}
if (emitExternNamespaces)
{
DefineAssemblyReferenceAliases();
}
}
if (blob.Length > 0)
{
_symWriter.DefineCustomMetadata(blob);
}
CloseMethod(methodBody.IL.Length);
}
private void DefineNamespaceScopes(IMethodBody methodBody)
{
var module = Module;
bool isVisualBasic = module.GenerateVisualBasicStylePdb;
IMethodDefinition method = methodBody.MethodDefinition;
var namespaceScopes = methodBody.ImportScope;
PooledHashSet<string> lazyDeclaredExternAliases = null;
if (!isVisualBasic)
{
for (var scope = namespaceScopes; scope != null; scope = scope.Parent)
{
foreach (var import in scope.GetUsedNamespaces())
{
if (import.TargetNamespaceOpt == null && import.TargetTypeOpt == null)
{
Debug.Assert(import.AliasOpt != null);
Debug.Assert(import.TargetAssemblyOpt == null);
if (lazyDeclaredExternAliases == null)
{
lazyDeclaredExternAliases = PooledHashSet<string>.GetInstance();
}
lazyDeclaredExternAliases.Add(import.AliasOpt);
}
}
}
}
// file and namespace level
for (IImportScope scope = namespaceScopes; scope != null; scope = scope.Parent)
{
foreach (UsedNamespaceOrType import in scope.GetUsedNamespaces())
{
var importString = TryEncodeImport(import, lazyDeclaredExternAliases, isProjectLevel: false);
if (importString != null)
{
UsingNamespace(importString, method);
}
}
}
lazyDeclaredExternAliases?.Free();
// project level
if (isVisualBasic)
{
string defaultNamespace = module.DefaultNamespace;
if (!string.IsNullOrEmpty(defaultNamespace))
{
// VB marks the default/root namespace with an asterisk
UsingNamespace("*" + defaultNamespace, module);
}
foreach (string assemblyName in module.LinkedAssembliesDebugInfo)
{
UsingNamespace("&" + assemblyName, module);
}
foreach (UsedNamespaceOrType import in module.GetImports())
{
var importString = TryEncodeImport(import, null, isProjectLevel: true);
if (importString != null)
{
UsingNamespace(importString, method);
}
}
// VB current namespace -- VB appends the namespace of the container without prefixes
UsingNamespace(GetOrCreateSerializedNamespaceName(method.ContainingNamespace), method);
}
}
private void DefineAssemblyReferenceAliases()
{
foreach (AssemblyReferenceAlias alias in Module.GetAssemblyReferenceAliases(Context))
{
UsingNamespace("Z" + alias.Name + " " + alias.Assembly.Identity.GetDisplayName(), Module);
}
}
private string TryEncodeImport(UsedNamespaceOrType import, HashSet<string> declaredExternAliasesOpt, bool isProjectLevel)
{
// NOTE: Dev12 has related cases "I" and "O" in EMITTER::ComputeDebugNamespace,
// but they were probably implementation details that do not affect Roslyn.
if (Module.GenerateVisualBasicStylePdb)
{
// VB doesn't support extern aliases
Debug.Assert(import.TargetAssemblyOpt == null);
Debug.Assert(declaredExternAliasesOpt == null);
if (import.TargetTypeOpt != null)
{
Debug.Assert(import.TargetNamespaceOpt == null);
Debug.Assert(import.TargetAssemblyOpt == null);
// Native compiler doesn't write imports with generic types to PDB.
if (import.TargetTypeOpt.IsTypeSpecification())
{
return null;
}
string typeName = GetOrCreateSerializedTypeName(import.TargetTypeOpt);
if (import.AliasOpt != null)
{
return (isProjectLevel ? "@PA:" : "@FA:") + import.AliasOpt + "=" + typeName;
}
else
{
return (isProjectLevel ? "@PT:" : "@FT:") + typeName;
}
}
if (import.TargetNamespaceOpt != null)
{
string namespaceName = GetOrCreateSerializedNamespaceName(import.TargetNamespaceOpt);
if (import.AliasOpt == null)
{
return (isProjectLevel ? "@P:" : "@F:") + namespaceName;
}
else
{
return (isProjectLevel ? "@PA:" : "@FA:") + import.AliasOpt + "=" + namespaceName;
}
}
Debug.Assert(import.AliasOpt != null);
Debug.Assert(import.TargetXmlNamespaceOpt != null);
return (isProjectLevel ? "@PX:" : "@FX:") + import.AliasOpt + "=" + import.TargetXmlNamespaceOpt;
}
Debug.Assert(import.TargetXmlNamespaceOpt == null);
if (import.TargetTypeOpt != null)
{
Debug.Assert(import.TargetNamespaceOpt == null);
Debug.Assert(import.TargetAssemblyOpt == null);
string typeName = GetOrCreateSerializedTypeName(import.TargetTypeOpt);
return (import.AliasOpt != null) ?
"A" + import.AliasOpt + " T" + typeName :
"T" + typeName;
}
if (import.TargetNamespaceOpt != null)
{
string namespaceName = GetOrCreateSerializedNamespaceName(import.TargetNamespaceOpt);
if (import.AliasOpt != null)
{
return (import.TargetAssemblyOpt != null) ?
"A" + import.AliasOpt + " E" + namespaceName + " " + GetAssemblyReferenceAlias(import.TargetAssemblyOpt, declaredExternAliasesOpt) :
"A" + import.AliasOpt + " U" + namespaceName;
}
else
{
return (import.TargetAssemblyOpt != null) ?
"E" + namespaceName + " " + GetAssemblyReferenceAlias(import.TargetAssemblyOpt, declaredExternAliasesOpt) :
"U" + namespaceName;
}
}
Debug.Assert(import.AliasOpt != null);
Debug.Assert(import.TargetAssemblyOpt == null);
return "X" + import.AliasOpt;
}
internal string GetOrCreateSerializedNamespaceName(INamespace @namespace)
{
string result;
if (!_qualifiedNameCache.TryGetValue(@namespace, out result))
{
result = TypeNameSerializer.BuildQualifiedNamespaceName(@namespace);
_qualifiedNameCache.Add(@namespace, result);
}
return result;
}
internal string GetOrCreateSerializedTypeName(ITypeReference typeReference)
{
string result;
if (!_qualifiedNameCache.TryGetValue(typeReference, out result))
{
if (Module.GenerateVisualBasicStylePdb)
{
result = SerializeVisualBasicImportTypeReference(typeReference);
}
else
{
result = typeReference.GetSerializedTypeName(Context);
}
_qualifiedNameCache.Add(typeReference, result);
}
return result;
}
private string SerializeVisualBasicImportTypeReference(ITypeReference typeReference)
{
Debug.Assert(!(typeReference is IArrayTypeReference));
Debug.Assert(!(typeReference is IPointerTypeReference));
Debug.Assert(!typeReference.IsTypeSpecification());
var result = PooledStringBuilder.GetInstance();
ArrayBuilder<string> nestedNamesReversed;
INestedTypeReference nestedType = typeReference.AsNestedTypeReference;
if (nestedType != null)
{
nestedNamesReversed = ArrayBuilder<string>.GetInstance();
while (nestedType != null)
{
nestedNamesReversed.Add(nestedType.Name);
typeReference = nestedType.GetContainingType(_metadataWriter.Context);
nestedType = typeReference.AsNestedTypeReference;
}
}
else
{
nestedNamesReversed = null;
}
INamespaceTypeReference namespaceType = typeReference.AsNamespaceTypeReference;
Debug.Assert(namespaceType != null);
string namespaceName = namespaceType.NamespaceName;
if (namespaceName.Length != 0)
{
result.Builder.Append(namespaceName);
result.Builder.Append('.');
}
result.Builder.Append(namespaceType.Name);
if (nestedNamesReversed != null)
{
for (int i = nestedNamesReversed.Count - 1; i >= 0; i--)
{
result.Builder.Append('.');
result.Builder.Append(nestedNamesReversed[i]);
}
nestedNamesReversed.Free();
}
return result.ToStringAndFree();
}
private string GetAssemblyReferenceAlias(IAssemblyReference assembly, HashSet<string> declaredExternAliases)
{
// no extern alias defined in scope at all -> error in compiler
Debug.Assert(declaredExternAliases != null);
var allAliases = _metadataWriter.Context.Module.GetAssemblyReferenceAliases(_metadataWriter.Context);
foreach (AssemblyReferenceAlias alias in allAliases)
{
// Multiple aliases may be given to an assembly reference.
// We find one that is in scope (was imported via extern alias directive).
// If multiple are in scope then use the first one.
// NOTE: Dev12 uses the one that appeared in source, whereas we use
// the first one that COULD have appeared in source. (DevDiv #913022)
// The reason we're not just using the alias from the syntax is that
// it is non-trivial to locate. In particular, since "." may be used in
// place of "::", determining whether the first identifier in the name is
// the alias requires binding. For example, "using A.B;" could refer to
// either "A::B" or "global::A.B".
if (assembly == alias.Assembly && declaredExternAliases.Contains(alias.Name))
{
return alias.Name;
}
}
// no alias defined in scope for given assembly -> error in compiler
throw ExceptionUtilities.Unreachable;
}
private void DefineLocalScopes(ImmutableArray<LocalScope> scopes, StandaloneSignatureHandle localSignatureHandleOpt)
{
// VB scope ranges are end-inclusive
bool endInclusive = this.Module.GenerateVisualBasicStylePdb;
// The order of OpenScope and CloseScope calls must follow the scope nesting.
var scopeStack = ArrayBuilder<LocalScope>.GetInstance();
for (int i = 1; i < scopes.Length; i++)
{
var currentScope = scopes[i];
// Close any scopes that have finished.
while (scopeStack.Count > 0)
{
LocalScope topScope = scopeStack.Last();
if (currentScope.StartOffset < topScope.StartOffset + topScope.Length)
{
break;
}
scopeStack.RemoveLast();
_symWriter.CloseScope(endInclusive ? topScope.EndOffset - 1 : topScope.EndOffset);
}
// Open this scope.
scopeStack.Add(currentScope);
_symWriter.OpenScope(currentScope.StartOffset);
DefineScopeLocals(currentScope, localSignatureHandleOpt);
}
// Close remaining scopes.
for (int i = scopeStack.Count - 1; i >= 0; i--)
{
LocalScope scope = scopeStack[i];
_symWriter.CloseScope(endInclusive ? scope.EndOffset - 1 : scope.EndOffset);
}
scopeStack.Free();
}
private void DefineScopeLocals(LocalScope currentScope, StandaloneSignatureHandle localSignatureHandleOpt)
{
foreach (ILocalDefinition scopeConstant in currentScope.Constants)
{
var signatureHandle = _metadataWriter.SerializeLocalConstantStandAloneSignature(scopeConstant);
if (!_metadataWriter.IsLocalNameTooLong(scopeConstant))
{
_symWriter.DefineLocalConstant(
scopeConstant.Name,
scopeConstant.CompileTimeValue.Value,
MetadataTokens.GetToken(signatureHandle));
}
}
foreach (ILocalDefinition scopeLocal in currentScope.Variables)
{
if (!_metadataWriter.IsLocalNameTooLong(scopeLocal))
{
Debug.Assert(scopeLocal.SlotIndex >= 0);
_symWriter.DefineLocalVariable(
scopeLocal.SlotIndex,
scopeLocal.Name,
(int)scopeLocal.PdbAttributes,
localSignatureHandleOpt.IsNil ? 0 : MetadataTokens.GetToken(localSignatureHandleOpt));
}
}
}
public void SetMetadataEmitter(MetadataWriter metadataWriter)
{
// Do not look for COM registered diasymreader when determinism is needed as it doesn't support it.
var options =
(IsDeterministic ? SymUnmanagedWriterCreationOptions.Deterministic : SymUnmanagedWriterCreationOptions.UseComRegistry) |
SymUnmanagedWriterCreationOptions.UseAlternativeLoadPath;
var metadataProvider = new SymWriterMetadataProvider(metadataWriter);
SymUnmanagedWriter symWriter;
try
{
symWriter = (_symWriterFactory != null) ? _symWriterFactory(metadataProvider) : SymUnmanagedWriterFactory.CreateWriter(metadataProvider, options);
}
catch (DllNotFoundException e)
{
throw new SymUnmanagedWriterException(e.Message);
}
catch (SymUnmanagedWriterException e) when (e.InnerException is NotSupportedException)
{
var message = IsDeterministic ? CodeAnalysisResources.SymWriterNotDeterministic : CodeAnalysisResources.SymWriterOlderVersionThanRequired;
throw new SymUnmanagedWriterException(string.Format(message, e.ImplementationModuleName));
}
_metadataWriter = metadataWriter;
_symWriter = symWriter;
_sequencePointsWriter = new SymUnmanagedSequencePointsWriter(symWriter, capacity: 64);
}
public BlobContentId GetContentId()
{
BlobContentId contentId;
if (IsDeterministic)
{
// Calculate hash of the stream content.
// Note: all bits of the signature currently stored in the PDB stream were initialized to 1 by InitializeDeterministic.
contentId = BlobContentId.FromHash(CryptographicHashProvider.ComputeHash(_hashAlgorithmNameOpt, _symWriter.GetUnderlyingData()));
_symWriter.UpdateSignature(contentId.Guid, contentId.Stamp, age: 1);
}
else
{
_symWriter.GetSignature(out Guid guid, out uint stamp, out int age);
Debug.Assert(age == Age);
contentId = new BlobContentId(guid, stamp);
}
// Once we calculate the content id we shall not write more data to the writer.
// Note that the underlying stream is accessible for reading even after the writer is disposed.
_symWriter.Dispose();
return contentId;
}
public void SetEntryPoint(int entryMethodToken)
{
_symWriter.SetEntryPoint(entryMethodToken);
}
private int GetDocumentIndex(DebugSourceDocument document)
{
if (_documentIndex.TryGetValue(document, out int documentIndex))
{
return documentIndex;
}
return AddDocumentIndex(document);
}
private int AddDocumentIndex(DebugSourceDocument document)
{
Guid algorithmId;
ReadOnlySpan<byte> checksum;
ReadOnlySpan<byte> embeddedSource;
DebugSourceInfo info = document.GetSourceInfo();
if (!info.Checksum.IsDefault)
{
algorithmId = info.ChecksumAlgorithmId;
checksum = info.Checksum.AsSpan();
}
else
{
algorithmId = default;
checksum = null;
}
if (!info.EmbeddedTextBlob.IsDefault)
{
embeddedSource = info.EmbeddedTextBlob.AsSpan();
}
else
{
embeddedSource = null;
}
int documentIndex = _symWriter.DefineDocument(
document.Location,
document.Language,
document.LanguageVendor,
document.DocumentType,
algorithmId,
checksum,
embeddedSource);
_documentIndex.Add(document, documentIndex);
return documentIndex;
}
private void OpenMethod(int methodToken, IMethodDefinition method)
{
_symWriter.OpenMethod(methodToken);
// open outermost scope:
_symWriter.OpenScope(startOffset: 0);
}
private void CloseMethod(int ilLength)
{
// close the root scope:
_symWriter.CloseScope(endOffset: ilLength);
_symWriter.CloseMethod();
}
private void UsingNamespace(string fullName, INamedEntity errorEntity)
{
if (!_metadataWriter.IsUsingStringTooLong(fullName, errorEntity))
{
_symWriter.UsingNamespace(fullName);
}
}
private void EmitSequencePoints(ImmutableArray<SequencePoint> sequencePoints)
{
int lastDocumentIndex = -1;
DebugSourceDocument lastDocument = null;
foreach (var sequencePoint in sequencePoints)
{
Debug.Assert(sequencePoint.Document != null);
var document = sequencePoint.Document;
int documentIndex;
if (lastDocument == document)
{
documentIndex = lastDocumentIndex;
}
else
{
lastDocument = document;
documentIndex = lastDocumentIndex = GetDocumentIndex(lastDocument);
}
_sequencePointsWriter.Add(
documentIndex,
sequencePoint.Offset,
sequencePoint.StartLine,
sequencePoint.StartColumn,
sequencePoint.EndLine,
sequencePoint.EndColumn);
}
_sequencePointsWriter.Flush();
}
[Conditional("DEBUG")]
// Used to catch cases where file2definitions contain nonwritable definitions early
// If left unfixed, such scenarios will lead to crashes if happen in winmdobj projects
public void AssertAllDefinitionsHaveTokens(MultiDictionary<DebugSourceDocument, DefinitionWithLocation> file2definitions)
{
foreach (var kvp in file2definitions)
{
foreach (var definition in kvp.Value)
{
EntityHandle handle = _metadataWriter.GetDefinitionHandle(definition.Definition);
Debug.Assert(!handle.IsNil);
}
}
}
// Note: only used for WinMD
public void WriteDefinitionLocations(MultiDictionary<DebugSourceDocument, DefinitionWithLocation> file2definitions)
{
// Only open and close the map if we have any mapping.
bool open = false;
foreach (var kvp in file2definitions)
{
foreach (var definition in kvp.Value)
{
if (!open)
{
_symWriter.OpenTokensToSourceSpansMap();
open = true;
}
int token = MetadataTokens.GetToken(_metadataWriter.GetDefinitionHandle(definition.Definition));
Debug.Assert(token != 0);
_symWriter.MapTokenToSourceSpan(
token,
GetDocumentIndex(kvp.Key),
definition.StartLine + 1,
definition.StartColumn + 1,
definition.EndLine + 1,
definition.EndColumn + 1);
}
}
if (open)
{
_symWriter.CloseTokensToSourceSpansMap();
}
}
public void EmbedSourceLink(Stream stream)
{
byte[] bytes;
try
{
bytes = stream.ReadAllBytes();
}
catch (Exception e)
{
throw new SymUnmanagedWriterException(e.Message, e);
}
try
{
_symWriter.SetSourceLinkData(bytes);
}
catch (SymUnmanagedWriterException e) when (e.InnerException is NotSupportedException)
{
throw new SymUnmanagedWriterException(string.Format(CodeAnalysisResources.SymWriterDoesNotSupportSourceLink, e.ImplementationModuleName));
}
}
/// <summary>
/// Write document entries for all debug documents that do not yet have an entry.
/// </summary>
/// <remarks>
/// This is done after serializing method debug info to ensure that we embed all requested
/// text even if there are no corresponding sequence points.
/// </remarks>
public void WriteRemainingDebugDocuments(IReadOnlyDictionary<string, DebugSourceDocument> documents)
{
foreach (var kvp in documents
.Where(kvp => !_documentIndex.ContainsKey(kvp.Value))
.OrderBy(kvp => kvp.Key))
{
AddDocumentIndex(kvp.Value);
}
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/EditorFeatures/Core/Implementation/InlineRename/AbstractEditorInlineRenameService.SymbolRenameInfo.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Rename;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename
{
internal abstract partial class AbstractEditorInlineRenameService
{
/// <summary>
/// Represents information about the ability to rename a particular location.
/// </summary>
private partial class SymbolInlineRenameInfo : IInlineRenameInfoWithFileRename
{
private const string AttributeSuffix = "Attribute";
private readonly Document _document;
private readonly IEnumerable<IRefactorNotifyService> _refactorNotifyServices;
/// <summary>
/// Whether or not we shortened the trigger span (say because we were renaming an attribute,
/// and we didn't select the 'Attribute' portion of the name).
/// </summary>
private readonly bool _isRenamingAttributePrefix;
public bool CanRename { get; }
public string? LocalizedErrorMessage { get; }
public TextSpan TriggerSpan { get; }
public bool HasOverloads { get; }
public bool ForceRenameOverloads { get; }
/// <summary>
/// The locations of the potential rename candidates for the symbol.
/// </summary>
public ImmutableArray<DocumentSpan> DefinitionLocations { get; }
public ISymbol RenameSymbol { get; }
public SymbolInlineRenameInfo(
IEnumerable<IRefactorNotifyService> refactorNotifyServices,
Document document,
TextSpan triggerSpan,
string triggerText,
ISymbol renameSymbol,
bool forceRenameOverloads,
ImmutableArray<DocumentSpan> definitionLocations,
CancellationToken cancellationToken)
{
this.CanRename = true;
_refactorNotifyServices = refactorNotifyServices;
_document = document;
this.RenameSymbol = renameSymbol;
this.HasOverloads = RenameLocations.GetOverloadedSymbols(this.RenameSymbol).Any();
this.ForceRenameOverloads = forceRenameOverloads;
_isRenamingAttributePrefix = CanRenameAttributePrefix(triggerText);
this.TriggerSpan = GetReferenceEditSpan(new InlineRenameLocation(document, triggerSpan), triggerText, cancellationToken);
this.DefinitionLocations = definitionLocations;
}
private bool CanRenameAttributePrefix(string triggerText)
{
// if this isn't an attribute, or it doesn't have the 'Attribute' suffix, then clearly
// we can't rename just the attribute prefix.
if (!this.IsRenamingAttributeTypeWithAttributeSuffix())
{
return false;
}
// Ok, the symbol is good. Now, make sure that the trigger text starts with the prefix
// of the attribute. If it does, then we can rename just the attribute prefix (otherwise
// we need to rename the entire attribute).
#pragma warning disable IDE0059 // Unnecessary assignment of a value - https://github.com/dotnet/roslyn/issues/45895
var nameWithoutAttribute = GetWithoutAttributeSuffix(this.RenameSymbol.Name);
return triggerText.StartsWith(triggerText); // TODO: Always true? What was it supposed to do?
#pragma warning restore IDE0059 // Unnecessary assignment of a value
}
/// <summary>
/// Given a span of text, we need to return the subspan that is editable and
/// contains the current replacementText.
///
/// These cases are currently handled:
/// - Escaped identifiers [goo] => goo
/// - Type suffixes in VB goo$ => goo
/// - Qualified names from complexification A.goo => goo
/// - Optional Attribute suffixes XAttribute => X
/// Careful here: XAttribute => XAttribute if renamesymbol is XAttributeAttribute
/// - Compiler-generated EventHandler suffix XEventHandler => X
/// - Compiler-generated get_ and set_ prefixes get_X => X
/// </summary>
public TextSpan GetReferenceEditSpan(InlineRenameLocation location, string triggerText, CancellationToken cancellationToken)
{
var searchName = this.RenameSymbol.Name;
if (_isRenamingAttributePrefix)
{
// We're only renaming the attribute prefix part. We want to adjust the span of
// the reference we've found to only update the prefix portion.
searchName = GetWithoutAttributeSuffix(this.RenameSymbol.Name);
}
var index = triggerText.LastIndexOf(searchName, StringComparison.Ordinal);
if (index < 0)
{
// Couldn't even find the search text at this reference location. This might happen
// if the user used things like unicode escapes. IN that case, we'll have to rename
// the entire identifier.
return location.TextSpan;
}
return new TextSpan(location.TextSpan.Start + index, searchName.Length);
}
public TextSpan? GetConflictEditSpan(InlineRenameLocation location, string triggerText, string replacementText, CancellationToken cancellationToken)
{
var position = triggerText.LastIndexOf(replacementText, StringComparison.Ordinal);
if (_isRenamingAttributePrefix)
{
// We're only renaming the attribute prefix part. We want to adjust the span of
// the reference we've found to only update the prefix portion.
var index = triggerText.LastIndexOf(replacementText + AttributeSuffix, StringComparison.Ordinal);
position = index >= 0 ? index : position;
}
if (position < 0)
{
return null;
}
return new TextSpan(location.TextSpan.Start + position, replacementText.Length);
}
private string GetWithoutAttributeSuffix(string value)
=> value.GetWithoutAttributeSuffix(isCaseSensitive: _document.GetRequiredLanguageService<ISyntaxFactsService>().IsCaseSensitive)!;
private bool HasAttributeSuffix(string value)
=> value.TryGetWithoutAttributeSuffix(isCaseSensitive: _document.GetRequiredLanguageService<ISyntaxFactsService>().IsCaseSensitive, result: out var _);
internal bool IsRenamingAttributeTypeWithAttributeSuffix()
{
if (this.RenameSymbol.IsAttribute() || (this.RenameSymbol.Kind == SymbolKind.Alias && ((IAliasSymbol)this.RenameSymbol).Target.IsAttribute()))
{
if (HasAttributeSuffix(this.RenameSymbol.Name))
{
return true;
}
}
return false;
}
public string DisplayName => RenameSymbol.Name;
public string FullDisplayName => RenameSymbol.ToDisplayString();
public Glyph Glyph => RenameSymbol.GetGlyph();
public string GetFinalSymbolName(string replacementText)
{
if (_isRenamingAttributePrefix && !HasAttributeSuffix(replacementText))
{
return replacementText + AttributeSuffix;
}
return replacementText;
}
public async Task<IInlineRenameLocationSet> FindRenameLocationsAsync(OptionSet? optionSet, CancellationToken cancellationToken)
{
var solution = _document.Project.Solution;
var locations = await Renamer.FindRenameLocationsAsync(
solution, this.RenameSymbol, RenameOptionSet.From(solution, optionSet), cancellationToken).ConfigureAwait(false);
return new InlineRenameLocationSet(this, locations);
}
public bool TryOnBeforeGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText)
{
return _refactorNotifyServices.TryOnBeforeGlobalSymbolRenamed(workspace, changedDocumentIDs, RenameSymbol,
this.GetFinalSymbolName(replacementText), throwOnFailure: false);
}
public bool TryOnAfterGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText)
{
return _refactorNotifyServices.TryOnAfterGlobalSymbolRenamed(workspace, changedDocumentIDs, RenameSymbol,
this.GetFinalSymbolName(replacementText), throwOnFailure: false);
}
public InlineRenameFileRenameInfo GetFileRenameInfo()
{
if (RenameSymbol.Kind == SymbolKind.NamedType &&
_document.Project.Solution.Workspace.CanApplyChange(ApplyChangesKind.ChangeDocumentInfo))
{
if (RenameSymbol.Locations.Length > 1)
{
return InlineRenameFileRenameInfo.TypeWithMultipleLocations;
}
// Get the document that the symbol is defined in to compare
// the name with the symbol name. If they match allow
// rename file rename as part of the symbol rename
var symbolSourceDocument = _document.Project.Solution.GetDocument(RenameSymbol.Locations.Single().SourceTree);
if (symbolSourceDocument != null && WorkspacePathUtilities.TypeNameMatchesDocumentName(symbolSourceDocument, RenameSymbol.Name))
{
return InlineRenameFileRenameInfo.Allowed;
}
return InlineRenameFileRenameInfo.TypeDoesNotMatchFileName;
}
return InlineRenameFileRenameInfo.NotAllowed;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Rename;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename
{
internal abstract partial class AbstractEditorInlineRenameService
{
/// <summary>
/// Represents information about the ability to rename a particular location.
/// </summary>
private partial class SymbolInlineRenameInfo : IInlineRenameInfoWithFileRename
{
private const string AttributeSuffix = "Attribute";
private readonly Document _document;
private readonly IEnumerable<IRefactorNotifyService> _refactorNotifyServices;
/// <summary>
/// Whether or not we shortened the trigger span (say because we were renaming an attribute,
/// and we didn't select the 'Attribute' portion of the name).
/// </summary>
private readonly bool _isRenamingAttributePrefix;
public bool CanRename { get; }
public string? LocalizedErrorMessage { get; }
public TextSpan TriggerSpan { get; }
public bool HasOverloads { get; }
public bool ForceRenameOverloads { get; }
/// <summary>
/// The locations of the potential rename candidates for the symbol.
/// </summary>
public ImmutableArray<DocumentSpan> DefinitionLocations { get; }
public ISymbol RenameSymbol { get; }
public SymbolInlineRenameInfo(
IEnumerable<IRefactorNotifyService> refactorNotifyServices,
Document document,
TextSpan triggerSpan,
string triggerText,
ISymbol renameSymbol,
bool forceRenameOverloads,
ImmutableArray<DocumentSpan> definitionLocations,
CancellationToken cancellationToken)
{
this.CanRename = true;
_refactorNotifyServices = refactorNotifyServices;
_document = document;
this.RenameSymbol = renameSymbol;
this.HasOverloads = RenameLocations.GetOverloadedSymbols(this.RenameSymbol).Any();
this.ForceRenameOverloads = forceRenameOverloads;
_isRenamingAttributePrefix = CanRenameAttributePrefix(triggerText);
this.TriggerSpan = GetReferenceEditSpan(new InlineRenameLocation(document, triggerSpan), triggerText, cancellationToken);
this.DefinitionLocations = definitionLocations;
}
private bool CanRenameAttributePrefix(string triggerText)
{
// if this isn't an attribute, or it doesn't have the 'Attribute' suffix, then clearly
// we can't rename just the attribute prefix.
if (!this.IsRenamingAttributeTypeWithAttributeSuffix())
{
return false;
}
// Ok, the symbol is good. Now, make sure that the trigger text starts with the prefix
// of the attribute. If it does, then we can rename just the attribute prefix (otherwise
// we need to rename the entire attribute).
#pragma warning disable IDE0059 // Unnecessary assignment of a value - https://github.com/dotnet/roslyn/issues/45895
var nameWithoutAttribute = GetWithoutAttributeSuffix(this.RenameSymbol.Name);
return triggerText.StartsWith(triggerText); // TODO: Always true? What was it supposed to do?
#pragma warning restore IDE0059 // Unnecessary assignment of a value
}
/// <summary>
/// Given a span of text, we need to return the subspan that is editable and
/// contains the current replacementText.
///
/// These cases are currently handled:
/// - Escaped identifiers [goo] => goo
/// - Type suffixes in VB goo$ => goo
/// - Qualified names from complexification A.goo => goo
/// - Optional Attribute suffixes XAttribute => X
/// Careful here: XAttribute => XAttribute if renamesymbol is XAttributeAttribute
/// - Compiler-generated EventHandler suffix XEventHandler => X
/// - Compiler-generated get_ and set_ prefixes get_X => X
/// </summary>
public TextSpan GetReferenceEditSpan(InlineRenameLocation location, string triggerText, CancellationToken cancellationToken)
{
var searchName = this.RenameSymbol.Name;
if (_isRenamingAttributePrefix)
{
// We're only renaming the attribute prefix part. We want to adjust the span of
// the reference we've found to only update the prefix portion.
searchName = GetWithoutAttributeSuffix(this.RenameSymbol.Name);
}
var index = triggerText.LastIndexOf(searchName, StringComparison.Ordinal);
if (index < 0)
{
// Couldn't even find the search text at this reference location. This might happen
// if the user used things like unicode escapes. IN that case, we'll have to rename
// the entire identifier.
return location.TextSpan;
}
return new TextSpan(location.TextSpan.Start + index, searchName.Length);
}
public TextSpan? GetConflictEditSpan(InlineRenameLocation location, string triggerText, string replacementText, CancellationToken cancellationToken)
{
var position = triggerText.LastIndexOf(replacementText, StringComparison.Ordinal);
if (_isRenamingAttributePrefix)
{
// We're only renaming the attribute prefix part. We want to adjust the span of
// the reference we've found to only update the prefix portion.
var index = triggerText.LastIndexOf(replacementText + AttributeSuffix, StringComparison.Ordinal);
position = index >= 0 ? index : position;
}
if (position < 0)
{
return null;
}
return new TextSpan(location.TextSpan.Start + position, replacementText.Length);
}
private string GetWithoutAttributeSuffix(string value)
=> value.GetWithoutAttributeSuffix(isCaseSensitive: _document.GetRequiredLanguageService<ISyntaxFactsService>().IsCaseSensitive)!;
private bool HasAttributeSuffix(string value)
=> value.TryGetWithoutAttributeSuffix(isCaseSensitive: _document.GetRequiredLanguageService<ISyntaxFactsService>().IsCaseSensitive, result: out var _);
internal bool IsRenamingAttributeTypeWithAttributeSuffix()
{
if (this.RenameSymbol.IsAttribute() || (this.RenameSymbol.Kind == SymbolKind.Alias && ((IAliasSymbol)this.RenameSymbol).Target.IsAttribute()))
{
if (HasAttributeSuffix(this.RenameSymbol.Name))
{
return true;
}
}
return false;
}
public string DisplayName => RenameSymbol.Name;
public string FullDisplayName => RenameSymbol.ToDisplayString();
public Glyph Glyph => RenameSymbol.GetGlyph();
public string GetFinalSymbolName(string replacementText)
{
if (_isRenamingAttributePrefix && !HasAttributeSuffix(replacementText))
{
return replacementText + AttributeSuffix;
}
return replacementText;
}
public async Task<IInlineRenameLocationSet> FindRenameLocationsAsync(OptionSet? optionSet, CancellationToken cancellationToken)
{
var solution = _document.Project.Solution;
var locations = await Renamer.FindRenameLocationsAsync(
solution, this.RenameSymbol, RenameOptionSet.From(solution, optionSet), cancellationToken).ConfigureAwait(false);
return new InlineRenameLocationSet(this, locations);
}
public bool TryOnBeforeGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText)
{
return _refactorNotifyServices.TryOnBeforeGlobalSymbolRenamed(workspace, changedDocumentIDs, RenameSymbol,
this.GetFinalSymbolName(replacementText), throwOnFailure: false);
}
public bool TryOnAfterGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText)
{
return _refactorNotifyServices.TryOnAfterGlobalSymbolRenamed(workspace, changedDocumentIDs, RenameSymbol,
this.GetFinalSymbolName(replacementText), throwOnFailure: false);
}
public InlineRenameFileRenameInfo GetFileRenameInfo()
{
if (RenameSymbol.Kind == SymbolKind.NamedType &&
_document.Project.Solution.Workspace.CanApplyChange(ApplyChangesKind.ChangeDocumentInfo))
{
if (RenameSymbol.Locations.Length > 1)
{
return InlineRenameFileRenameInfo.TypeWithMultipleLocations;
}
// Get the document that the symbol is defined in to compare
// the name with the symbol name. If they match allow
// rename file rename as part of the symbol rename
var symbolSourceDocument = _document.Project.Solution.GetDocument(RenameSymbol.Locations.Single().SourceTree);
if (symbolSourceDocument != null && WorkspacePathUtilities.TypeNameMatchesDocumentName(symbolSourceDocument, RenameSymbol.Name))
{
return InlineRenameFileRenameInfo.Allowed;
}
return InlineRenameFileRenameInfo.TypeDoesNotMatchFileName;
}
return InlineRenameFileRenameInfo.NotAllowed;
}
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Compilers/Core/Portable/Syntax/LineDirectiveMap.LineMappingEntry.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
internal partial class LineDirectiveMap<TDirective>
{
/// <summary>
/// Enum that describes the state related to the #line or #externalsource directives at a position in source.
/// </summary>
public enum PositionState : byte
{
/// <summary>
/// Used in VB when the position is not hidden, but it's not known yet that there is a (nonempty) <c>#ExternalSource</c>
/// following.
/// </summary>
Unknown,
/// <summary>
/// Used in C# for spans preceding the first <c>#line</c> directive (if any) and for <c>#line default</c> spans
/// </summary>
Unmapped,
/// <summary>
/// Used in C# for spans inside of <c>#line linenumber</c> directive
/// </summary>
Remapped,
/// <summary>
/// Used in C# for spans inside of <c>#line (startLine, startChar) - (endLine, endChar) charOffset</c> directive
/// </summary>
RemappedSpan,
/// <summary>
/// Used in VB for spans inside of a <c>#ExternalSource</c> directive that followed an unknown span
/// </summary>
RemappedAfterUnknown,
/// <summary>
/// Used in VB for spans inside of a <c>#ExternalSource</c> directive that followed a hidden span
/// </summary>
RemappedAfterHidden,
/// <summary>
/// Used in C# and VB for spans that are inside of <c>#line hidden</c> (C#) or outside of <c>#ExternalSource</c> (VB)
/// directives
/// </summary>
Hidden
}
// Struct that represents an entry in the line mapping table. Entries sort by the unmapped
// line.
internal readonly struct LineMappingEntry : IComparable<LineMappingEntry>
{
// 0-based line in this tree
public readonly int UnmappedLine;
// 0-based line it maps to.
public readonly int MappedLine;
// 0-based mapped span from enhanced #line directive.
public readonly LinePositionSpan MappedSpan;
// optional 0-based character offset from enhanced #line directive.
public readonly int? UnmappedCharacterOffset;
// raw value from #line or #ExternalDirective, may be null
public readonly string? MappedPathOpt;
// the state of this line
public readonly PositionState State;
public LineMappingEntry(int unmappedLine)
{
this.UnmappedLine = unmappedLine;
this.MappedLine = unmappedLine;
this.MappedSpan = default;
this.UnmappedCharacterOffset = null;
this.MappedPathOpt = null;
this.State = PositionState.Unmapped;
}
public LineMappingEntry(
int unmappedLine,
int mappedLine,
string? mappedPathOpt,
PositionState state)
{
Debug.Assert(state != PositionState.RemappedSpan);
this.UnmappedLine = unmappedLine;
this.MappedLine = mappedLine;
this.MappedSpan = default;
this.UnmappedCharacterOffset = null;
this.MappedPathOpt = mappedPathOpt;
this.State = state;
}
public LineMappingEntry(
int unmappedLine,
LinePositionSpan mappedSpan,
int? unmappedCharacterOffset,
string? mappedPathOpt)
{
this.UnmappedLine = unmappedLine;
this.MappedLine = -1;
this.MappedSpan = mappedSpan;
this.UnmappedCharacterOffset = unmappedCharacterOffset;
this.MappedPathOpt = mappedPathOpt;
this.State = PositionState.RemappedSpan;
}
public int CompareTo(LineMappingEntry other)
=> UnmappedLine.CompareTo(other.UnmappedLine);
public bool IsHidden
=> State == PositionState.Hidden;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
internal partial class LineDirectiveMap<TDirective>
{
/// <summary>
/// Enum that describes the state related to the #line or #externalsource directives at a position in source.
/// </summary>
public enum PositionState : byte
{
/// <summary>
/// Used in VB when the position is not hidden, but it's not known yet that there is a (nonempty) <c>#ExternalSource</c>
/// following.
/// </summary>
Unknown,
/// <summary>
/// Used in C# for spans preceding the first <c>#line</c> directive (if any) and for <c>#line default</c> spans
/// </summary>
Unmapped,
/// <summary>
/// Used in C# for spans inside of <c>#line linenumber</c> directive
/// </summary>
Remapped,
/// <summary>
/// Used in C# for spans inside of <c>#line (startLine, startChar) - (endLine, endChar) charOffset</c> directive
/// </summary>
RemappedSpan,
/// <summary>
/// Used in VB for spans inside of a <c>#ExternalSource</c> directive that followed an unknown span
/// </summary>
RemappedAfterUnknown,
/// <summary>
/// Used in VB for spans inside of a <c>#ExternalSource</c> directive that followed a hidden span
/// </summary>
RemappedAfterHidden,
/// <summary>
/// Used in C# and VB for spans that are inside of <c>#line hidden</c> (C#) or outside of <c>#ExternalSource</c> (VB)
/// directives
/// </summary>
Hidden
}
// Struct that represents an entry in the line mapping table. Entries sort by the unmapped
// line.
internal readonly struct LineMappingEntry : IComparable<LineMappingEntry>
{
// 0-based line in this tree
public readonly int UnmappedLine;
// 0-based line it maps to.
public readonly int MappedLine;
// 0-based mapped span from enhanced #line directive.
public readonly LinePositionSpan MappedSpan;
// optional 0-based character offset from enhanced #line directive.
public readonly int? UnmappedCharacterOffset;
// raw value from #line or #ExternalDirective, may be null
public readonly string? MappedPathOpt;
// the state of this line
public readonly PositionState State;
public LineMappingEntry(int unmappedLine)
{
this.UnmappedLine = unmappedLine;
this.MappedLine = unmappedLine;
this.MappedSpan = default;
this.UnmappedCharacterOffset = null;
this.MappedPathOpt = null;
this.State = PositionState.Unmapped;
}
public LineMappingEntry(
int unmappedLine,
int mappedLine,
string? mappedPathOpt,
PositionState state)
{
Debug.Assert(state != PositionState.RemappedSpan);
this.UnmappedLine = unmappedLine;
this.MappedLine = mappedLine;
this.MappedSpan = default;
this.UnmappedCharacterOffset = null;
this.MappedPathOpt = mappedPathOpt;
this.State = state;
}
public LineMappingEntry(
int unmappedLine,
LinePositionSpan mappedSpan,
int? unmappedCharacterOffset,
string? mappedPathOpt)
{
this.UnmappedLine = unmappedLine;
this.MappedLine = -1;
this.MappedSpan = mappedSpan;
this.UnmappedCharacterOffset = unmappedCharacterOffset;
this.MappedPathOpt = mappedPathOpt;
this.State = PositionState.RemappedSpan;
}
public int CompareTo(LineMappingEntry other)
=> UnmappedLine.CompareTo(other.UnmappedLine);
public bool IsHidden
=> State == PositionState.Hidden;
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/EditorFeatures/CSharpTest/Structure/BlockSyntaxStructureTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Structure;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure
{
public class BlockSyntaxStructureTests : AbstractCSharpSyntaxNodeStructureTests<BlockSyntax>
{
internal override AbstractSyntaxStructureProvider CreateProvider() => new BlockSyntaxStructureProvider();
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestTryBlock1()
{
const string code = @"
class C
{
void M()
{
{|hint:try{|textspan:
{$$
}
catch
{
}
finally
{
}|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestUnsafe1()
{
const string code = @"
class C
{
void M()
{
{|hint:unsafe{|textspan:
{$$
}|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestFixed1()
{
const string code = @"
class C
{
void M()
{
{|hint:fixed(int* i = &j){|textspan:
{$$
}|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestUsing1()
{
const string code = @"
class C
{
void M()
{
{|hint:using (goo){|textspan:
{$$
}|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestLock1()
{
const string code = @"
class C
{
void M()
{
{|hint:lock (goo){|textspan:
{$$
}|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestForStatement1()
{
const string code = @"
class C
{
void M()
{
{|hint:for (;;){|textspan:
{$$
}|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestForEachStatement1()
{
const string code = @"
class C
{
void M()
{
{|hint:foreach (var v in e){|textspan:
{$$
}|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestCompoundForEachStatement1()
{
const string code = @"
class C
{
void M()
{
{|hint:foreach ((var v, var x) in e){|textspan:
{$$
}|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestWhileStatement1()
{
const string code = @"
class C
{
void M()
{
{|hint:while (true){|textspan:
{$$
}|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestDoStatement1()
{
const string code = @"
class C
{
void M()
{
{|hint:do{|textspan:
{$$
}
while (true);|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestIfStatement1()
{
const string code = @"
class C
{
void M()
{
{|hint:if (true){|textspan:
{$$
}|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestIfStatement2()
{
const string code = @"
class C
{
void M()
{
{|hint:if (true){|textspan:
{$$
}|}|}
else
{
}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestIfStatement3()
{
const string code = @"
class C
{
void M()
{
{|hint:if (true){|textspan:
{$$
}|}|}
else
return;
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestElseClause1()
{
const string code = @"
class C
{
void M()
{
if (true)
{
}
{|hint:else{|textspan:
{$$
}|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestIfElse1()
{
const string code = @"
class C
{
void M()
{
if (true)
{
}
{|hint:else if (false){|textspan:
{$$
}|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestIfElse2()
{
const string code = @"
class C
{
void M()
{
if (true)
{
}
{|hint:else
if (false ||
true){|textspan:
{$$
}|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestIfElse3()
{
const string code = @"
class C
{
void M()
{
if (true)
{
}
{|hint:else if (false ||
true){|textspan:
{$$
}|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestNestedBlock()
{
const string code = @"
class C
{
void M()
{
{|hint:{|textspan:{$$
}|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestNestedBlockInSwitchSection1()
{
const string code = @"
class C
{
void M()
{
switch (e)
{
case 0:
{|hint:{|textspan:{$$
}|}|}
}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestNestedBlockInSwitchSection2()
{
const string code = @"
class C
{
void M()
{
switch (e)
{
case 0:
int i = 0;
{|hint:{|textspan:{$$
}|}|}
}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[WorkItem(52493, "https://github.com/dotnet/roslyn/issues/")]
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task LocalFunctionInTopLevelStatement_AutoCollapse()
{
const string code = @"
Foo();
Bar();
{|hint:static void Foo(){|textspan:
{$$
// ...
}|}|}
";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Structure;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure
{
public class BlockSyntaxStructureTests : AbstractCSharpSyntaxNodeStructureTests<BlockSyntax>
{
internal override AbstractSyntaxStructureProvider CreateProvider() => new BlockSyntaxStructureProvider();
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestTryBlock1()
{
const string code = @"
class C
{
void M()
{
{|hint:try{|textspan:
{$$
}
catch
{
}
finally
{
}|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestUnsafe1()
{
const string code = @"
class C
{
void M()
{
{|hint:unsafe{|textspan:
{$$
}|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestFixed1()
{
const string code = @"
class C
{
void M()
{
{|hint:fixed(int* i = &j){|textspan:
{$$
}|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestUsing1()
{
const string code = @"
class C
{
void M()
{
{|hint:using (goo){|textspan:
{$$
}|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestLock1()
{
const string code = @"
class C
{
void M()
{
{|hint:lock (goo){|textspan:
{$$
}|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestForStatement1()
{
const string code = @"
class C
{
void M()
{
{|hint:for (;;){|textspan:
{$$
}|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestForEachStatement1()
{
const string code = @"
class C
{
void M()
{
{|hint:foreach (var v in e){|textspan:
{$$
}|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestCompoundForEachStatement1()
{
const string code = @"
class C
{
void M()
{
{|hint:foreach ((var v, var x) in e){|textspan:
{$$
}|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestWhileStatement1()
{
const string code = @"
class C
{
void M()
{
{|hint:while (true){|textspan:
{$$
}|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestDoStatement1()
{
const string code = @"
class C
{
void M()
{
{|hint:do{|textspan:
{$$
}
while (true);|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestIfStatement1()
{
const string code = @"
class C
{
void M()
{
{|hint:if (true){|textspan:
{$$
}|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestIfStatement2()
{
const string code = @"
class C
{
void M()
{
{|hint:if (true){|textspan:
{$$
}|}|}
else
{
}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestIfStatement3()
{
const string code = @"
class C
{
void M()
{
{|hint:if (true){|textspan:
{$$
}|}|}
else
return;
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestElseClause1()
{
const string code = @"
class C
{
void M()
{
if (true)
{
}
{|hint:else{|textspan:
{$$
}|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestIfElse1()
{
const string code = @"
class C
{
void M()
{
if (true)
{
}
{|hint:else if (false){|textspan:
{$$
}|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestIfElse2()
{
const string code = @"
class C
{
void M()
{
if (true)
{
}
{|hint:else
if (false ||
true){|textspan:
{$$
}|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestIfElse3()
{
const string code = @"
class C
{
void M()
{
if (true)
{
}
{|hint:else if (false ||
true){|textspan:
{$$
}|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestNestedBlock()
{
const string code = @"
class C
{
void M()
{
{|hint:{|textspan:{$$
}|}|}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestNestedBlockInSwitchSection1()
{
const string code = @"
class C
{
void M()
{
switch (e)
{
case 0:
{|hint:{|textspan:{$$
}|}|}
}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestNestedBlockInSwitchSection2()
{
const string code = @"
class C
{
void M()
{
switch (e)
{
case 0:
int i = 0;
{|hint:{|textspan:{$$
}|}|}
}
}
}";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false));
}
[WorkItem(52493, "https://github.com/dotnet/roslyn/issues/")]
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task LocalFunctionInTopLevelStatement_AutoCollapse()
{
const string code = @"
Foo();
Bar();
{|hint:static void Foo(){|textspan:
{$$
// ...
}|}|}
";
await VerifyBlockSpansAsync(code,
Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Compilers/Core/Portable/TreeDumper.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection;
using System.Linq;
using System.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
// These classes are for debug and testing purposes only. It is frequently handy to be
// able to create a string representation of a complex tree-based data type. The idea
// here is to first transform your tree into a standard "tree dumper node" tree, where
// each node in the tree has a name, some optional data, and a sequence of child nodes.
// Once in a standard format the tree can then be rendered in a variety of ways
// depending on what is most useful to you.
//
// I've started with two string formats. First, a "compact" format in which there is
// exactly one line per node of the tree:
//
// root
// ├─a1
// │ └─a1b1
// ├─a2
// │ ├─a2b1
// │ │ └─a2b1c1
// │ └─a2b2
// │ ├─a2b2c1
// │ │ └─a2b2c1d1
// │ └─a2b2c2
// └─a3
// └─a3b1
//
// And second, an XML format:
//
// <root>
// <children>
// <child>
// value1
// </child>
// <child>
// value2
// </child>
// </children>
// </root>
//
// The XML format is much more verbose, but handy if you want to then pipe it into an XML tree viewer.
/// <summary>
/// This is ONLY used id BoundNode.cs Debug method - Dump()
/// </summary>
internal class TreeDumper
{
private readonly StringBuilder _sb;
protected TreeDumper()
{
_sb = new StringBuilder();
}
public static string DumpCompact(TreeDumperNode root)
{
return new TreeDumper().DoDumpCompact(root);
}
protected string DoDumpCompact(TreeDumperNode root)
{
DoDumpCompact(root, string.Empty);
return _sb.ToString();
}
private void DoDumpCompact(TreeDumperNode node, string indent)
{
RoslynDebug.Assert(node != null);
RoslynDebug.Assert(indent != null);
// Precondition: indentation and prefix has already been output
// Precondition: indent is correct for node's *children*
_sb.Append(node.Text);
if (node.Value != null)
{
_sb.AppendFormat(": {0}", DumperString(node.Value));
}
_sb.AppendLine();
var children = node.Children.ToList();
for (int i = 0; i < children.Count; ++i)
{
var child = children[i];
if (child == null)
{
continue;
}
_sb.Append(indent);
_sb.Append(i == children.Count - 1 ? '\u2514' : '\u251C');
_sb.Append('\u2500');
// First precondition met; now work out the string needed to indent
// the child node's children:
DoDumpCompact(child, indent + (i == children.Count - 1 ? " " : "\u2502 "));
}
}
public static string DumpXML(TreeDumperNode root, string? indent = null)
{
var dumper = new TreeDumper();
dumper.DoDumpXML(root, string.Empty, indent ?? string.Empty);
return dumper._sb.ToString();
}
private void DoDumpXML(TreeDumperNode node, string indent, string relativeIndent)
{
RoslynDebug.Assert(node != null);
if (node.Children.All(child => child == null))
{
_sb.Append(indent);
if (node.Value != null)
{
_sb.AppendFormat("<{0}>{1}</{0}>", node.Text, DumperString(node.Value));
}
else
{
_sb.AppendFormat("<{0} />", node.Text);
}
_sb.AppendLine();
}
else
{
_sb.Append(indent);
_sb.AppendFormat("<{0}>", node.Text);
_sb.AppendLine();
if (node.Value != null)
{
_sb.Append(indent);
_sb.AppendFormat("{0}", DumperString(node.Value));
_sb.AppendLine();
}
var childIndent = indent + relativeIndent;
foreach (var child in node.Children)
{
if (child == null)
{
continue;
}
DoDumpXML(child, childIndent, relativeIndent);
}
_sb.Append(indent);
_sb.AppendFormat("</{0}>", node.Text);
_sb.AppendLine();
}
}
// an (awful) test for a null read-only-array. Is there no better way to do this?
private static bool IsDefaultImmutableArray(Object o)
{
var ti = o.GetType().GetTypeInfo();
if (ti.IsGenericType && ti.GetGenericTypeDefinition() == typeof(ImmutableArray<>))
{
var result = ti?.GetDeclaredMethod("get_IsDefault")?.Invoke(o, Array.Empty<object>());
return result is bool b && b;
}
return false;
}
protected virtual string DumperString(object o)
{
if (o == null)
{
return "(null)";
}
var str = o as string;
if (str != null)
{
return str;
}
if (IsDefaultImmutableArray(o))
{
return "(null)";
}
var seq = o as IEnumerable;
if (seq != null)
{
return string.Format("{{{0}}}", string.Join(", ", seq.Cast<object>().Select(DumperString).ToArray()));
}
var symbol = o as ISymbol;
if (symbol != null)
{
return symbol.ToDisplayString(SymbolDisplayFormat.TestFormat);
}
return o.ToString() ?? "";
}
}
/// <summary>
/// This is ONLY used for debugging purpose
/// </summary>
internal sealed class TreeDumperNode
{
public TreeDumperNode(string text, object? value, IEnumerable<TreeDumperNode>? children)
{
this.Text = text;
this.Value = value;
this.Children = children ?? SpecializedCollections.EmptyEnumerable<TreeDumperNode>();
}
public TreeDumperNode(string text) : this(text, null, null) { }
public object? Value { get; }
public string Text { get; }
public IEnumerable<TreeDumperNode> Children { get; }
public TreeDumperNode? this[string child]
{
get
{
return Children.FirstOrDefault(c => c.Text == child);
}
}
// enumerates all edges of the tree yielding (parent, node) pairs. The first yielded value is (null, this).
public IEnumerable<KeyValuePair<TreeDumperNode?, TreeDumperNode>> PreorderTraversal()
{
var stack = new Stack<KeyValuePair<TreeDumperNode?, TreeDumperNode>>();
stack.Push(new KeyValuePair<TreeDumperNode?, TreeDumperNode>(null, this));
while (stack.Count != 0)
{
var currentEdge = stack.Pop();
yield return currentEdge;
var currentNode = currentEdge.Value;
foreach (var child in currentNode.Children.Where(x => x != null).Reverse())
{
stack.Push(new KeyValuePair<TreeDumperNode?, TreeDumperNode>(currentNode, child));
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection;
using System.Linq;
using System.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
// These classes are for debug and testing purposes only. It is frequently handy to be
// able to create a string representation of a complex tree-based data type. The idea
// here is to first transform your tree into a standard "tree dumper node" tree, where
// each node in the tree has a name, some optional data, and a sequence of child nodes.
// Once in a standard format the tree can then be rendered in a variety of ways
// depending on what is most useful to you.
//
// I've started with two string formats. First, a "compact" format in which there is
// exactly one line per node of the tree:
//
// root
// ├─a1
// │ └─a1b1
// ├─a2
// │ ├─a2b1
// │ │ └─a2b1c1
// │ └─a2b2
// │ ├─a2b2c1
// │ │ └─a2b2c1d1
// │ └─a2b2c2
// └─a3
// └─a3b1
//
// And second, an XML format:
//
// <root>
// <children>
// <child>
// value1
// </child>
// <child>
// value2
// </child>
// </children>
// </root>
//
// The XML format is much more verbose, but handy if you want to then pipe it into an XML tree viewer.
/// <summary>
/// This is ONLY used id BoundNode.cs Debug method - Dump()
/// </summary>
internal class TreeDumper
{
private readonly StringBuilder _sb;
protected TreeDumper()
{
_sb = new StringBuilder();
}
public static string DumpCompact(TreeDumperNode root)
{
return new TreeDumper().DoDumpCompact(root);
}
protected string DoDumpCompact(TreeDumperNode root)
{
DoDumpCompact(root, string.Empty);
return _sb.ToString();
}
private void DoDumpCompact(TreeDumperNode node, string indent)
{
RoslynDebug.Assert(node != null);
RoslynDebug.Assert(indent != null);
// Precondition: indentation and prefix has already been output
// Precondition: indent is correct for node's *children*
_sb.Append(node.Text);
if (node.Value != null)
{
_sb.AppendFormat(": {0}", DumperString(node.Value));
}
_sb.AppendLine();
var children = node.Children.ToList();
for (int i = 0; i < children.Count; ++i)
{
var child = children[i];
if (child == null)
{
continue;
}
_sb.Append(indent);
_sb.Append(i == children.Count - 1 ? '\u2514' : '\u251C');
_sb.Append('\u2500');
// First precondition met; now work out the string needed to indent
// the child node's children:
DoDumpCompact(child, indent + (i == children.Count - 1 ? " " : "\u2502 "));
}
}
public static string DumpXML(TreeDumperNode root, string? indent = null)
{
var dumper = new TreeDumper();
dumper.DoDumpXML(root, string.Empty, indent ?? string.Empty);
return dumper._sb.ToString();
}
private void DoDumpXML(TreeDumperNode node, string indent, string relativeIndent)
{
RoslynDebug.Assert(node != null);
if (node.Children.All(child => child == null))
{
_sb.Append(indent);
if (node.Value != null)
{
_sb.AppendFormat("<{0}>{1}</{0}>", node.Text, DumperString(node.Value));
}
else
{
_sb.AppendFormat("<{0} />", node.Text);
}
_sb.AppendLine();
}
else
{
_sb.Append(indent);
_sb.AppendFormat("<{0}>", node.Text);
_sb.AppendLine();
if (node.Value != null)
{
_sb.Append(indent);
_sb.AppendFormat("{0}", DumperString(node.Value));
_sb.AppendLine();
}
var childIndent = indent + relativeIndent;
foreach (var child in node.Children)
{
if (child == null)
{
continue;
}
DoDumpXML(child, childIndent, relativeIndent);
}
_sb.Append(indent);
_sb.AppendFormat("</{0}>", node.Text);
_sb.AppendLine();
}
}
// an (awful) test for a null read-only-array. Is there no better way to do this?
private static bool IsDefaultImmutableArray(Object o)
{
var ti = o.GetType().GetTypeInfo();
if (ti.IsGenericType && ti.GetGenericTypeDefinition() == typeof(ImmutableArray<>))
{
var result = ti?.GetDeclaredMethod("get_IsDefault")?.Invoke(o, Array.Empty<object>());
return result is bool b && b;
}
return false;
}
protected virtual string DumperString(object o)
{
if (o == null)
{
return "(null)";
}
var str = o as string;
if (str != null)
{
return str;
}
if (IsDefaultImmutableArray(o))
{
return "(null)";
}
var seq = o as IEnumerable;
if (seq != null)
{
return string.Format("{{{0}}}", string.Join(", ", seq.Cast<object>().Select(DumperString).ToArray()));
}
var symbol = o as ISymbol;
if (symbol != null)
{
return symbol.ToDisplayString(SymbolDisplayFormat.TestFormat);
}
return o.ToString() ?? "";
}
}
/// <summary>
/// This is ONLY used for debugging purpose
/// </summary>
internal sealed class TreeDumperNode
{
public TreeDumperNode(string text, object? value, IEnumerable<TreeDumperNode>? children)
{
this.Text = text;
this.Value = value;
this.Children = children ?? SpecializedCollections.EmptyEnumerable<TreeDumperNode>();
}
public TreeDumperNode(string text) : this(text, null, null) { }
public object? Value { get; }
public string Text { get; }
public IEnumerable<TreeDumperNode> Children { get; }
public TreeDumperNode? this[string child]
{
get
{
return Children.FirstOrDefault(c => c.Text == child);
}
}
// enumerates all edges of the tree yielding (parent, node) pairs. The first yielded value is (null, this).
public IEnumerable<KeyValuePair<TreeDumperNode?, TreeDumperNode>> PreorderTraversal()
{
var stack = new Stack<KeyValuePair<TreeDumperNode?, TreeDumperNode>>();
stack.Push(new KeyValuePair<TreeDumperNode?, TreeDumperNode>(null, this));
while (stack.Count != 0)
{
var currentEdge = stack.Pop();
yield return currentEdge;
var currentNode = currentEdge.Value;
foreach (var child in currentNode.Children.Where(x => x != null).Reverse())
{
stack.Push(new KeyValuePair<TreeDumperNode?, TreeDumperNode>(currentNode, child));
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Workspaces/Remote/Core/SolutionChecksumUpdater.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.VisualStudio.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Remote
{
/// <summary>
/// This class runs against the in-process workspace, and when it sees changes proactively pushes them to
/// the out-of-process workspace through the <see cref="IRemoteAssetSynchronizationService"/>.
/// </summary>
internal sealed class SolutionChecksumUpdater : GlobalOperationAwareIdleProcessor
{
private readonly Workspace _workspace;
private readonly TaskQueue _textChangeQueue;
private readonly AsyncQueue<IAsyncToken> _workQueue;
private readonly object _gate;
private CancellationTokenSource _globalOperationCancellationSource;
// hold the async token from WaitAsync so ExecuteAsync can complete it
private IAsyncToken _currentToken;
public SolutionChecksumUpdater(Workspace workspace, IAsynchronousOperationListenerProvider listenerProvider, CancellationToken shutdownToken)
: base(listenerProvider.GetListener(FeatureAttribute.SolutionChecksumUpdater),
workspace.Services.GetService<IGlobalOperationNotificationService>(),
TimeSpan.FromMilliseconds(workspace.Options.GetOption(RemoteHostOptions.SolutionChecksumMonitorBackOffTimeSpanInMS)), shutdownToken)
{
_workspace = workspace;
_textChangeQueue = new TaskQueue(Listener, TaskScheduler.Default);
_workQueue = new AsyncQueue<IAsyncToken>();
_gate = new object();
// start listening workspace change event
_workspace.WorkspaceChanged += OnWorkspaceChanged;
// create its own cancellation token source
_globalOperationCancellationSource = CancellationTokenSource.CreateLinkedTokenSource(shutdownToken);
Start();
}
private CancellationToken ShutdownCancellationToken => CancellationToken;
protected override async Task ExecuteAsync()
{
lock (_gate)
{
Contract.ThrowIfNull(_currentToken);
_currentToken.Dispose();
_currentToken = null;
}
// wait for global operation to finish
await GlobalOperationTask.ConfigureAwait(false);
// update primary solution in remote host
await SynchronizePrimaryWorkspaceAsync(_globalOperationCancellationSource.Token).ConfigureAwait(false);
}
protected override void PauseOnGlobalOperation()
{
var previousCancellationSource = _globalOperationCancellationSource;
// create new cancellation token source linked with given shutdown cancellation token
_globalOperationCancellationSource = CancellationTokenSource.CreateLinkedTokenSource(ShutdownCancellationToken);
CancelAndDispose(previousCancellationSource);
}
protected override async Task WaitAsync(CancellationToken cancellationToken)
{
var currentToken = await _workQueue.DequeueAsync(cancellationToken).ConfigureAwait(false);
lock (_gate)
{
Contract.ThrowIfFalse(_currentToken is null);
_currentToken = currentToken;
}
}
public override void Shutdown()
{
base.Shutdown();
// stop listening workspace change event
_workspace.WorkspaceChanged -= OnWorkspaceChanged;
CancelAndDispose(_globalOperationCancellationSource);
}
private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs e)
{
if (e.Kind == WorkspaceChangeKind.DocumentChanged)
{
PushTextChanges(e.OldSolution.GetDocument(e.DocumentId), e.NewSolution.GetDocument(e.DocumentId));
}
// record that we are busy
UpdateLastAccessTime();
EnqueueChecksumUpdate();
}
private void EnqueueChecksumUpdate()
{
// event will raised sequencially. no concurrency on this handler
if (_workQueue.TryPeek(out _))
{
return;
}
_workQueue.Enqueue(Listener.BeginAsyncOperation(nameof(SolutionChecksumUpdater)));
}
private async Task SynchronizePrimaryWorkspaceAsync(CancellationToken cancellationToken)
{
var solution = _workspace.CurrentSolution;
if (solution.BranchId != _workspace.PrimaryBranchId)
{
return;
}
var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false);
if (client == null)
{
return;
}
using (Logger.LogBlock(FunctionId.SolutionChecksumUpdater_SynchronizePrimaryWorkspace, cancellationToken))
{
var checksum = await solution.State.GetChecksumAsync(cancellationToken).ConfigureAwait(false);
await client.TryInvokeAsync<IRemoteAssetSynchronizationService>(
solution,
(service, solution, cancellationToken) => service.SynchronizePrimaryWorkspaceAsync(solution, checksum, solution.WorkspaceVersion, cancellationToken),
cancellationToken).ConfigureAwait(false);
}
}
private static void CancelAndDispose(CancellationTokenSource cancellationSource)
{
// cancel running tasks
cancellationSource.Cancel();
// dispose cancellation token source
cancellationSource.Dispose();
}
private void PushTextChanges(Document oldDocument, Document newDocument)
{
// this pushes text changes to the remote side if it can.
// this is purely perf optimization. whether this pushing text change
// worked or not doesn't affect feature's functionality.
//
// this basically see whether it can cheaply find out text changes
// between 2 snapshots, if it can, it will send out that text changes to
// remote side.
//
// the remote side, once got the text change, will again see whether
// it can use that text change information without any high cost and
// create new snapshot from it.
//
// otherwise, it will do the normal behavior of getting full text from
// VS side. this optimization saves times we need to do full text
// synchronization for typing scenario.
if ((oldDocument.TryGetText(out var oldText) == false) ||
(newDocument.TryGetText(out var newText) == false))
{
// we only support case where text already exist
return;
}
// get text changes
var textChanges = newText.GetTextChanges(oldText);
if (textChanges.Count == 0)
{
// no changes
return;
}
// whole document case
if (textChanges.Count == 1 && textChanges[0].Span.Length == oldText.Length)
{
// no benefit here. pulling from remote host is more efficient
return;
}
// only cancelled when remote host gets shutdown
_textChangeQueue.ScheduleTask(nameof(PushTextChanges), async () =>
{
var client = await RemoteHostClient.TryGetClientAsync(_workspace, CancellationToken).ConfigureAwait(false);
if (client == null)
{
return;
}
var state = await oldDocument.State.GetStateChecksumsAsync(CancellationToken).ConfigureAwait(false);
await client.TryInvokeAsync<IRemoteAssetSynchronizationService>(
(service, cancellationToken) => service.SynchronizeTextAsync(oldDocument.Id, state.Text, textChanges, cancellationToken),
CancellationToken).ConfigureAwait(false);
}, CancellationToken);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.VisualStudio.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Remote
{
/// <summary>
/// This class runs against the in-process workspace, and when it sees changes proactively pushes them to
/// the out-of-process workspace through the <see cref="IRemoteAssetSynchronizationService"/>.
/// </summary>
internal sealed class SolutionChecksumUpdater : GlobalOperationAwareIdleProcessor
{
private readonly Workspace _workspace;
private readonly TaskQueue _textChangeQueue;
private readonly AsyncQueue<IAsyncToken> _workQueue;
private readonly object _gate;
private CancellationTokenSource _globalOperationCancellationSource;
// hold the async token from WaitAsync so ExecuteAsync can complete it
private IAsyncToken _currentToken;
public SolutionChecksumUpdater(Workspace workspace, IAsynchronousOperationListenerProvider listenerProvider, CancellationToken shutdownToken)
: base(listenerProvider.GetListener(FeatureAttribute.SolutionChecksumUpdater),
workspace.Services.GetService<IGlobalOperationNotificationService>(),
TimeSpan.FromMilliseconds(workspace.Options.GetOption(RemoteHostOptions.SolutionChecksumMonitorBackOffTimeSpanInMS)), shutdownToken)
{
_workspace = workspace;
_textChangeQueue = new TaskQueue(Listener, TaskScheduler.Default);
_workQueue = new AsyncQueue<IAsyncToken>();
_gate = new object();
// start listening workspace change event
_workspace.WorkspaceChanged += OnWorkspaceChanged;
// create its own cancellation token source
_globalOperationCancellationSource = CancellationTokenSource.CreateLinkedTokenSource(shutdownToken);
Start();
}
private CancellationToken ShutdownCancellationToken => CancellationToken;
protected override async Task ExecuteAsync()
{
lock (_gate)
{
Contract.ThrowIfNull(_currentToken);
_currentToken.Dispose();
_currentToken = null;
}
// wait for global operation to finish
await GlobalOperationTask.ConfigureAwait(false);
// update primary solution in remote host
await SynchronizePrimaryWorkspaceAsync(_globalOperationCancellationSource.Token).ConfigureAwait(false);
}
protected override void PauseOnGlobalOperation()
{
var previousCancellationSource = _globalOperationCancellationSource;
// create new cancellation token source linked with given shutdown cancellation token
_globalOperationCancellationSource = CancellationTokenSource.CreateLinkedTokenSource(ShutdownCancellationToken);
CancelAndDispose(previousCancellationSource);
}
protected override async Task WaitAsync(CancellationToken cancellationToken)
{
var currentToken = await _workQueue.DequeueAsync(cancellationToken).ConfigureAwait(false);
lock (_gate)
{
Contract.ThrowIfFalse(_currentToken is null);
_currentToken = currentToken;
}
}
public override void Shutdown()
{
base.Shutdown();
// stop listening workspace change event
_workspace.WorkspaceChanged -= OnWorkspaceChanged;
CancelAndDispose(_globalOperationCancellationSource);
}
private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs e)
{
if (e.Kind == WorkspaceChangeKind.DocumentChanged)
{
PushTextChanges(e.OldSolution.GetDocument(e.DocumentId), e.NewSolution.GetDocument(e.DocumentId));
}
// record that we are busy
UpdateLastAccessTime();
EnqueueChecksumUpdate();
}
private void EnqueueChecksumUpdate()
{
// event will raised sequencially. no concurrency on this handler
if (_workQueue.TryPeek(out _))
{
return;
}
_workQueue.Enqueue(Listener.BeginAsyncOperation(nameof(SolutionChecksumUpdater)));
}
private async Task SynchronizePrimaryWorkspaceAsync(CancellationToken cancellationToken)
{
var solution = _workspace.CurrentSolution;
if (solution.BranchId != _workspace.PrimaryBranchId)
{
return;
}
var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false);
if (client == null)
{
return;
}
using (Logger.LogBlock(FunctionId.SolutionChecksumUpdater_SynchronizePrimaryWorkspace, cancellationToken))
{
var checksum = await solution.State.GetChecksumAsync(cancellationToken).ConfigureAwait(false);
await client.TryInvokeAsync<IRemoteAssetSynchronizationService>(
solution,
(service, solution, cancellationToken) => service.SynchronizePrimaryWorkspaceAsync(solution, checksum, solution.WorkspaceVersion, cancellationToken),
cancellationToken).ConfigureAwait(false);
}
}
private static void CancelAndDispose(CancellationTokenSource cancellationSource)
{
// cancel running tasks
cancellationSource.Cancel();
// dispose cancellation token source
cancellationSource.Dispose();
}
private void PushTextChanges(Document oldDocument, Document newDocument)
{
// this pushes text changes to the remote side if it can.
// this is purely perf optimization. whether this pushing text change
// worked or not doesn't affect feature's functionality.
//
// this basically see whether it can cheaply find out text changes
// between 2 snapshots, if it can, it will send out that text changes to
// remote side.
//
// the remote side, once got the text change, will again see whether
// it can use that text change information without any high cost and
// create new snapshot from it.
//
// otherwise, it will do the normal behavior of getting full text from
// VS side. this optimization saves times we need to do full text
// synchronization for typing scenario.
if ((oldDocument.TryGetText(out var oldText) == false) ||
(newDocument.TryGetText(out var newText) == false))
{
// we only support case where text already exist
return;
}
// get text changes
var textChanges = newText.GetTextChanges(oldText);
if (textChanges.Count == 0)
{
// no changes
return;
}
// whole document case
if (textChanges.Count == 1 && textChanges[0].Span.Length == oldText.Length)
{
// no benefit here. pulling from remote host is more efficient
return;
}
// only cancelled when remote host gets shutdown
_textChangeQueue.ScheduleTask(nameof(PushTextChanges), async () =>
{
var client = await RemoteHostClient.TryGetClientAsync(_workspace, CancellationToken).ConfigureAwait(false);
if (client == null)
{
return;
}
var state = await oldDocument.State.GetStateChecksumsAsync(CancellationToken).ConfigureAwait(false);
await client.TryInvokeAsync<IRemoteAssetSynchronizationService>(
(service, cancellationToken) => service.SynchronizeTextAsync(oldDocument.Id, state.Text, textChanges, cancellationToken),
CancellationToken).ConfigureAwait(false);
}, CancellationToken);
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Workspaces/Core/Portable/Shared/TestHooks/AsynchronousOperationListenerProvider+NullOperationListener.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.TestHooks
{
internal sealed partial class AsynchronousOperationListenerProvider
{
private sealed class NullOperationListener : IAsynchronousOperationListener
{
public IAsyncToken BeginAsyncOperation(
string name,
object? tag = null,
[CallerFilePath] string filePath = "",
[CallerLineNumber] int lineNumber = 0) => EmptyAsyncToken.Instance;
public Task<bool> Delay(TimeSpan delay, CancellationToken cancellationToken)
{
// This could be as simple as:
// await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
// return true;
// However, whereas in general cancellation is expected to be rare and thus throwing
// an exception in response isn't very impactful, here it's expected to be the case
// more often than not as the operation is being used to delay an operation because
// it's expected something else is going to happen to obviate the need for that
// operation. Thus, we can spend a little more code avoiding the additional throw
// for the common case of an exception occurring.
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<bool>(cancellationToken);
}
var t = Task.Delay(delay, cancellationToken);
if (t.IsCompleted)
{
// Avoid ContinueWith overheads for a 0 delay or if race conditions resulted
// in the delay task being complete by the time we checked.
return t.Status == TaskStatus.RanToCompletion
? SpecializedTasks.True
: Task.FromCanceled<bool>(cancellationToken);
}
return t.ContinueWith(
_ => true,
CancellationToken.None,
TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.NotOnCanceled,
TaskScheduler.Default);
// Note the above passes CancellationToken.None and TaskContinuationOptions.NotOnCanceled.
// That's cheaper than passing cancellationToken and with the same semantics except
// that if the returned task does end up being canceled, any operation canceled exception
// thrown won't contain the cancellationToken. If that ends up being impactful, it can
// be switched to use `cancellationToken, TaskContinuationOptions.ExecuteSynchronously`.
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.TestHooks
{
internal sealed partial class AsynchronousOperationListenerProvider
{
private sealed class NullOperationListener : IAsynchronousOperationListener
{
public IAsyncToken BeginAsyncOperation(
string name,
object? tag = null,
[CallerFilePath] string filePath = "",
[CallerLineNumber] int lineNumber = 0) => EmptyAsyncToken.Instance;
public Task<bool> Delay(TimeSpan delay, CancellationToken cancellationToken)
{
// This could be as simple as:
// await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
// return true;
// However, whereas in general cancellation is expected to be rare and thus throwing
// an exception in response isn't very impactful, here it's expected to be the case
// more often than not as the operation is being used to delay an operation because
// it's expected something else is going to happen to obviate the need for that
// operation. Thus, we can spend a little more code avoiding the additional throw
// for the common case of an exception occurring.
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<bool>(cancellationToken);
}
var t = Task.Delay(delay, cancellationToken);
if (t.IsCompleted)
{
// Avoid ContinueWith overheads for a 0 delay or if race conditions resulted
// in the delay task being complete by the time we checked.
return t.Status == TaskStatus.RanToCompletion
? SpecializedTasks.True
: Task.FromCanceled<bool>(cancellationToken);
}
return t.ContinueWith(
_ => true,
CancellationToken.None,
TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.NotOnCanceled,
TaskScheduler.Default);
// Note the above passes CancellationToken.None and TaskContinuationOptions.NotOnCanceled.
// That's cheaper than passing cancellationToken and with the same semantics except
// that if the returned task does end up being canceled, any operation canceled exception
// thrown won't contain the cancellationToken. If that ends up being impactful, it can
// be switched to use `cancellationToken, TaskContinuationOptions.ExecuteSynchronously`.
}
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/VisualStudio/CSharp/Impl/CodeModel/Extenders/ExtenderNames.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel.Extenders
{
internal static class ExtenderNames
{
public static string ExternalLocation = nameof(ExternalLocation);
public static string PartialMethod = nameof(PartialMethod);
public static string ExtensionMethod = nameof(ExtensionMethod);
public static string AutoImplementedProperty = nameof(AutoImplementedProperty);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel.Extenders
{
internal static class ExtenderNames
{
public static string ExternalLocation = nameof(ExternalLocation);
public static string PartialMethod = nameof(PartialMethod);
public static string ExtensionMethod = nameof(ExtensionMethod);
public static string AutoImplementedProperty = nameof(AutoImplementedProperty);
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Compilers/Core/Portable/Syntax/SyntaxTreeExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
internal static class SyntaxTreeExtensions
{
/// <summary>
/// Verify nodes match source.
/// </summary>
[Conditional("DEBUG")]
internal static void VerifySource(this SyntaxTree tree, IEnumerable<TextChangeRange>? changes = null)
{
var root = tree.GetRoot();
var text = tree.GetText();
var fullSpan = new TextSpan(0, text.Length);
SyntaxNode? node = null;
// If only a subset of the document has changed,
// just check that subset to reduce verification cost.
if (changes != null)
{
var change = TextChangeRange.Collapse(changes).Span;
if (change != fullSpan)
{
// Find the lowest node in the tree that contains the changed region.
node = root.DescendantNodes(n => n.FullSpan.Contains(change)).LastOrDefault();
}
}
if (node == null)
{
node = root;
}
var span = node.FullSpan;
var textSpanOpt = span.Intersection(fullSpan);
int index;
char found = default;
char expected = default;
if (textSpanOpt == null)
{
index = 0;
}
else
{
var fromText = text.ToString(textSpanOpt.Value);
var fromNode = node.ToFullString();
index = FindFirstDifference(fromText, fromNode);
if (index >= 0)
{
found = fromNode[index];
expected = fromText[index];
}
}
if (index >= 0)
{
index += span.Start;
string message;
if (index < text.Length)
{
var position = text.Lines.GetLinePosition(index);
var line = text.Lines[position.Line];
var allText = text.ToString(); // Entire document as string to allow inspecting the text in the debugger.
message = $"Unexpected difference at offset {index}: Line {position.Line + 1}, Column {position.Character + 1} \"{line.ToString()}\" (Found: [{found}] Expected: [{expected}])";
}
else
{
message = "Unexpected difference past end of the file";
}
Debug.Assert(false, message);
}
}
/// <summary>
/// Return the index of the first difference between
/// the two strings, or -1 if the strings are the same.
/// </summary>
private static int FindFirstDifference(string s1, string s2)
{
var n1 = s1.Length;
var n2 = s2.Length;
var n = Math.Min(n1, n2);
for (int i = 0; i < n; i++)
{
if (s1[i] != s2[i])
{
return i;
}
}
return (n1 == n2) ? -1 : n + 1;
}
/// <summary>
/// Returns <c>true</c> if the provided position is in a hidden region inaccessible to the user.
/// </summary>
public static bool IsHiddenPosition(this SyntaxTree tree, int position, CancellationToken cancellationToken = default)
{
if (!tree.HasHiddenRegions())
{
return false;
}
var lineVisibility = tree.GetLineVisibility(position, cancellationToken);
return lineVisibility == LineVisibility.Hidden || lineVisibility == LineVisibility.BeforeFirstLineDirective;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
internal static class SyntaxTreeExtensions
{
/// <summary>
/// Verify nodes match source.
/// </summary>
[Conditional("DEBUG")]
internal static void VerifySource(this SyntaxTree tree, IEnumerable<TextChangeRange>? changes = null)
{
var root = tree.GetRoot();
var text = tree.GetText();
var fullSpan = new TextSpan(0, text.Length);
SyntaxNode? node = null;
// If only a subset of the document has changed,
// just check that subset to reduce verification cost.
if (changes != null)
{
var change = TextChangeRange.Collapse(changes).Span;
if (change != fullSpan)
{
// Find the lowest node in the tree that contains the changed region.
node = root.DescendantNodes(n => n.FullSpan.Contains(change)).LastOrDefault();
}
}
if (node == null)
{
node = root;
}
var span = node.FullSpan;
var textSpanOpt = span.Intersection(fullSpan);
int index;
char found = default;
char expected = default;
if (textSpanOpt == null)
{
index = 0;
}
else
{
var fromText = text.ToString(textSpanOpt.Value);
var fromNode = node.ToFullString();
index = FindFirstDifference(fromText, fromNode);
if (index >= 0)
{
found = fromNode[index];
expected = fromText[index];
}
}
if (index >= 0)
{
index += span.Start;
string message;
if (index < text.Length)
{
var position = text.Lines.GetLinePosition(index);
var line = text.Lines[position.Line];
var allText = text.ToString(); // Entire document as string to allow inspecting the text in the debugger.
message = $"Unexpected difference at offset {index}: Line {position.Line + 1}, Column {position.Character + 1} \"{line.ToString()}\" (Found: [{found}] Expected: [{expected}])";
}
else
{
message = "Unexpected difference past end of the file";
}
Debug.Assert(false, message);
}
}
/// <summary>
/// Return the index of the first difference between
/// the two strings, or -1 if the strings are the same.
/// </summary>
private static int FindFirstDifference(string s1, string s2)
{
var n1 = s1.Length;
var n2 = s2.Length;
var n = Math.Min(n1, n2);
for (int i = 0; i < n; i++)
{
if (s1[i] != s2[i])
{
return i;
}
}
return (n1 == n2) ? -1 : n + 1;
}
/// <summary>
/// Returns <c>true</c> if the provided position is in a hidden region inaccessible to the user.
/// </summary>
public static bool IsHiddenPosition(this SyntaxTree tree, int position, CancellationToken cancellationToken = default)
{
if (!tree.HasHiddenRegions())
{
return false;
}
var lineVisibility = tree.GetLineVisibility(position, cancellationToken);
return lineVisibility == LineVisibility.Hidden || lineVisibility == LineVisibility.BeforeFirstLineDirective;
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Compilers/Core/Portable/SymbolDisplay/SymbolDisplayMiscellaneousOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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
{
/// <summary>
/// Specifies miscellaneous options about the format of symbol descriptions.
/// </summary>
[Flags]
public enum SymbolDisplayMiscellaneousOptions
{
/// <summary>
/// Specifies that no miscellaneous options should be applied.
/// </summary>
None = 0,
/// <summary>
/// Uses keywords for predefined types.
/// For example, "int" instead of "System.Int32" in C#
/// or "Integer" instead of "System.Integer" in Visual Basic.
/// </summary>
UseSpecialTypes = 1 << 0,
/// <summary>
/// Escapes identifiers that are also keywords.
/// For example, "@true" instead of "true" in C# or
/// "[True]" instead of "True" in Visual Basic.
/// </summary>
EscapeKeywordIdentifiers = 1 << 1,
/// <summary>
/// Displays asterisks between commas in multi-dimensional arrays.
/// For example, "int[][*,*]" instead of "int[][,]" in C# or
/// "Integer()(*,*)" instead of "Integer()(*,*) in Visual Basic.
/// </summary>
UseAsterisksInMultiDimensionalArrays = 1 << 2,
/// <summary>
/// Displays "?" for erroneous types that lack names (perhaps due to faulty metadata).
/// </summary>
UseErrorTypeSymbolName = 1 << 3,
/// <summary>
/// Displays attributes names without the "Attribute" suffix, if possible.
/// </summary>
/// <remarks>
/// Has no effect outside <see cref="ISymbol.ToMinimalDisplayString"/> and only applies
/// if the context location is one where an attribute ca be referenced without the suffix.
/// </remarks>
RemoveAttributeSuffix = 1 << 4,
/// <summary>
/// Displays <see cref="Nullable{T}"/> as a normal generic type, rather than with
/// the special question mark syntax.
/// </summary>
ExpandNullable = 1 << 5,
/// <summary>
/// Append '?' to nullable reference types.
/// </summary>
IncludeNullableReferenceTypeModifier = 1 << 6,
/// <summary>
/// Allow the use of <c>default</c> instead of <c>default(T)</c> where applicable.
/// </summary>
AllowDefaultLiteral = 1 << 7,
/// <summary>
/// Append '!' to non-nullable reference types.
/// </summary>
IncludeNotNullableReferenceTypeModifier = 1 << 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.
using System;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Specifies miscellaneous options about the format of symbol descriptions.
/// </summary>
[Flags]
public enum SymbolDisplayMiscellaneousOptions
{
/// <summary>
/// Specifies that no miscellaneous options should be applied.
/// </summary>
None = 0,
/// <summary>
/// Uses keywords for predefined types.
/// For example, "int" instead of "System.Int32" in C#
/// or "Integer" instead of "System.Integer" in Visual Basic.
/// </summary>
UseSpecialTypes = 1 << 0,
/// <summary>
/// Escapes identifiers that are also keywords.
/// For example, "@true" instead of "true" in C# or
/// "[True]" instead of "True" in Visual Basic.
/// </summary>
EscapeKeywordIdentifiers = 1 << 1,
/// <summary>
/// Displays asterisks between commas in multi-dimensional arrays.
/// For example, "int[][*,*]" instead of "int[][,]" in C# or
/// "Integer()(*,*)" instead of "Integer()(*,*) in Visual Basic.
/// </summary>
UseAsterisksInMultiDimensionalArrays = 1 << 2,
/// <summary>
/// Displays "?" for erroneous types that lack names (perhaps due to faulty metadata).
/// </summary>
UseErrorTypeSymbolName = 1 << 3,
/// <summary>
/// Displays attributes names without the "Attribute" suffix, if possible.
/// </summary>
/// <remarks>
/// Has no effect outside <see cref="ISymbol.ToMinimalDisplayString"/> and only applies
/// if the context location is one where an attribute ca be referenced without the suffix.
/// </remarks>
RemoveAttributeSuffix = 1 << 4,
/// <summary>
/// Displays <see cref="Nullable{T}"/> as a normal generic type, rather than with
/// the special question mark syntax.
/// </summary>
ExpandNullable = 1 << 5,
/// <summary>
/// Append '?' to nullable reference types.
/// </summary>
IncludeNullableReferenceTypeModifier = 1 << 6,
/// <summary>
/// Allow the use of <c>default</c> instead of <c>default(T)</c> where applicable.
/// </summary>
AllowDefaultLiteral = 1 << 7,
/// <summary>
/// Append '!' to non-nullable reference types.
/// </summary>
IncludeNotNullableReferenceTypeModifier = 1 << 8,
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Compilers/Core/Portable/MetadataReader/UnsupportedSignatureContent.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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
{
internal class UnsupportedSignatureContent
: 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.
#nullable disable
using System;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
internal class UnsupportedSignatureContent
: Exception
{
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/VisualStudio/Core/Def/Implementation/ProjectSystem/MetadataReferences/VisualStudioMetadataReferenceManager.Factory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
// TODO: Remove this type. This factory is needed just to instantiate a singleton of VisualStudioMetadataReferenceProvider.
// We should be able to MEF-instantiate a singleton of VisualStudioMetadataReferenceProvider without creating this factory.
[ExportWorkspaceServiceFactory(typeof(VisualStudioMetadataReferenceManager), ServiceLayer.Host), Shared]
internal class VisualStudioMetadataReferenceManagerFactory : IWorkspaceServiceFactory
{
private VisualStudioMetadataReferenceManager _singleton;
private readonly IServiceProvider _serviceProvider;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public VisualStudioMetadataReferenceManagerFactory(SVsServiceProvider serviceProvider)
=> _serviceProvider = serviceProvider;
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
{
if (_singleton == null)
{
var temporaryStorage = workspaceServices.GetService<ITemporaryStorageService>();
Interlocked.CompareExchange(ref _singleton, new VisualStudioMetadataReferenceManager(_serviceProvider, temporaryStorage), null);
}
return _singleton;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
// TODO: Remove this type. This factory is needed just to instantiate a singleton of VisualStudioMetadataReferenceProvider.
// We should be able to MEF-instantiate a singleton of VisualStudioMetadataReferenceProvider without creating this factory.
[ExportWorkspaceServiceFactory(typeof(VisualStudioMetadataReferenceManager), ServiceLayer.Host), Shared]
internal class VisualStudioMetadataReferenceManagerFactory : IWorkspaceServiceFactory
{
private VisualStudioMetadataReferenceManager _singleton;
private readonly IServiceProvider _serviceProvider;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public VisualStudioMetadataReferenceManagerFactory(SVsServiceProvider serviceProvider)
=> _serviceProvider = serviceProvider;
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
{
if (_singleton == null)
{
var temporaryStorage = workspaceServices.GetService<ITemporaryStorageService>();
Interlocked.CompareExchange(ref _singleton, new VisualStudioMetadataReferenceManager(_serviceProvider, temporaryStorage), null);
}
return _singleton;
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/EditorFeatures/TestUtilities/AbstractTypingCommandHandlerTest.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests
{
[UseExportProvider]
public abstract class AbstractTypingCommandHandlerTest<TCommandArgs> where TCommandArgs : CommandArgs
{
internal abstract ICommandHandler<TCommandArgs> GetCommandHandler(TestWorkspace workspace);
protected abstract TestWorkspace CreateTestWorkspace(string initialMarkup);
protected abstract (TCommandArgs, string insertionText) CreateCommandArgs(ITextView textView, ITextBuffer textBuffer);
protected void Verify(string initialMarkup, string expectedMarkup, Action<TestWorkspace> initializeWorkspace = null)
{
using (var workspace = CreateTestWorkspace(initialMarkup))
{
initializeWorkspace?.Invoke(workspace);
var testDocument = workspace.Documents.Single();
var view = testDocument.GetTextView();
view.Caret.MoveTo(new SnapshotPoint(view.TextSnapshot, testDocument.CursorPosition.Value));
var commandHandler = GetCommandHandler(workspace);
var (args, insertionText) = CreateCommandArgs(view, view.TextBuffer);
var nextHandler = CreateInsertTextHandler(view, insertionText);
if (!commandHandler.ExecuteCommand(args, TestCommandExecutionContext.Create()))
{
nextHandler();
}
MarkupTestFile.GetPosition(expectedMarkup, out var expectedCode, out int expectedPosition);
Assert.Equal(expectedCode, view.TextSnapshot.GetText());
var caretPosition = view.Caret.Position.BufferPosition.Position;
Assert.True(expectedPosition == caretPosition,
string.Format("Caret positioned incorrectly. Should have been {0}, but was {1}.", expectedPosition, caretPosition));
}
}
protected void VerifyTabs(string initialMarkup, string expectedMarkup)
=> Verify(ReplaceTabTags(initialMarkup), ReplaceTabTags(expectedMarkup));
private static string ReplaceTabTags(string markup) => markup.Replace("<tab>", "\t");
private static Action CreateInsertTextHandler(ITextView textView, string text)
{
return () =>
{
var caretPosition = textView.Caret.Position.BufferPosition;
var newSpanshot = textView.TextBuffer.Insert(caretPosition, text);
textView.Caret.MoveTo(new SnapshotPoint(newSpanshot, (int)caretPosition + text.Length));
};
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests
{
[UseExportProvider]
public abstract class AbstractTypingCommandHandlerTest<TCommandArgs> where TCommandArgs : CommandArgs
{
internal abstract ICommandHandler<TCommandArgs> GetCommandHandler(TestWorkspace workspace);
protected abstract TestWorkspace CreateTestWorkspace(string initialMarkup);
protected abstract (TCommandArgs, string insertionText) CreateCommandArgs(ITextView textView, ITextBuffer textBuffer);
protected void Verify(string initialMarkup, string expectedMarkup, Action<TestWorkspace> initializeWorkspace = null)
{
using (var workspace = CreateTestWorkspace(initialMarkup))
{
initializeWorkspace?.Invoke(workspace);
var testDocument = workspace.Documents.Single();
var view = testDocument.GetTextView();
view.Caret.MoveTo(new SnapshotPoint(view.TextSnapshot, testDocument.CursorPosition.Value));
var commandHandler = GetCommandHandler(workspace);
var (args, insertionText) = CreateCommandArgs(view, view.TextBuffer);
var nextHandler = CreateInsertTextHandler(view, insertionText);
if (!commandHandler.ExecuteCommand(args, TestCommandExecutionContext.Create()))
{
nextHandler();
}
MarkupTestFile.GetPosition(expectedMarkup, out var expectedCode, out int expectedPosition);
Assert.Equal(expectedCode, view.TextSnapshot.GetText());
var caretPosition = view.Caret.Position.BufferPosition.Position;
Assert.True(expectedPosition == caretPosition,
string.Format("Caret positioned incorrectly. Should have been {0}, but was {1}.", expectedPosition, caretPosition));
}
}
protected void VerifyTabs(string initialMarkup, string expectedMarkup)
=> Verify(ReplaceTabTags(initialMarkup), ReplaceTabTags(expectedMarkup));
private static string ReplaceTabTags(string markup) => markup.Replace("<tab>", "\t");
private static Action CreateInsertTextHandler(ITextView textView, string text)
{
return () =>
{
var caretPosition = textView.Caret.Position.BufferPosition;
var newSpanshot = textView.TextBuffer.Insert(caretPosition, text);
textView.Caret.MoveTo(new SnapshotPoint(newSpanshot, (int)caretPosition + text.Length));
};
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Compilers/CSharp/Test/Emit/CodeGen/UnsafeTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class UnsafeTests : EmitMetadataTestBase
{
#region AddressOf tests
[Fact]
public void AddressOfLocal_Unused()
{
var text = @"
unsafe class C
{
void M()
{
int x;
int* p = &x;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes);
compVerifier.VerifyIL("C.M", @"
{
// Code size 4 (0x4)
.maxstack 1
.locals init (int V_0) //x
IL_0000: ldloca.s V_0
IL_0002: pop
IL_0003: ret
}
");
}
[Fact]
public void AddressOfLocal_Used()
{
var text = @"
unsafe class C
{
void M(int* param)
{
int x;
int* p = &x;
M(p);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails);
compVerifier.VerifyIL("C.M", @"
{
// Code size 12 (0xc)
.maxstack 2
.locals init (int V_0, //x
int* V_1) //p
IL_0000: ldloca.s V_0
IL_0002: conv.u
IL_0003: stloc.1
IL_0004: ldarg.0
IL_0005: ldloc.1
IL_0006: call ""void C.M(int*)""
IL_000b: ret
}
");
}
[Fact]
public void AddressOfParameter_Unused()
{
var text = @"
unsafe class C
{
void M(int x)
{
int* p = &x;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes);
compVerifier.VerifyIL("C.M", @"
{
// Code size 4 (0x4)
.maxstack 1
IL_0000: ldarga.s V_1
IL_0002: pop
IL_0003: ret
}
");
}
[Fact]
public void AddressOfParameter_Used()
{
var text = @"
unsafe class C
{
void M(int x, int* param)
{
int* p = &x;
M(x, p);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails);
compVerifier.VerifyIL("C.M", @"
{
// Code size 13 (0xd)
.maxstack 3
.locals init (int* V_0) //p
IL_0000: ldarga.s V_1
IL_0002: conv.u
IL_0003: stloc.0
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: ldloc.0
IL_0007: call ""void C.M(int, int*)""
IL_000c: ret
}
");
}
[Fact]
public void AddressOfStructField()
{
var text = @"
unsafe class C
{
void M()
{
S1 s;
S1* p1 = &s;
S2* p2 = &s.s;
int* p3 = &s.s.x;
Goo(s, p1, p2, p3);
}
void Goo(S1 s, S1* p1, S2* p2, int* p3) { }
}
struct S1
{
public S2 s;
}
struct S2
{
public int x;
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails);
compVerifier.VerifyIL("C.M", @"
{
// Code size 38 (0x26)
.maxstack 5
.locals init (S1 V_0, //s
S1* V_1, //p1
S2* V_2, //p2
int* V_3) //p3
IL_0000: ldloca.s V_0
IL_0002: conv.u
IL_0003: stloc.1
IL_0004: ldloca.s V_0
IL_0006: ldflda ""S2 S1.s""
IL_000b: conv.u
IL_000c: stloc.2
IL_000d: ldloca.s V_0
IL_000f: ldflda ""S2 S1.s""
IL_0014: ldflda ""int S2.x""
IL_0019: conv.u
IL_001a: stloc.3
IL_001b: ldarg.0
IL_001c: ldloc.0
IL_001d: ldloc.1
IL_001e: ldloc.2
IL_001f: ldloc.3
IL_0020: call ""void C.Goo(S1, S1*, S2*, int*)""
IL_0025: ret
}
");
}
[Fact]
public void AddressOfSuppressOptimization()
{
var text = @"
unsafe class C
{
static void M()
{
int x = 123;
Goo(&x); // should not optimize into 'Goo(&123)'
}
static void Goo(int* p) { }
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails);
compVerifier.VerifyIL("C.M", @"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (int V_0) //x
IL_0000: ldc.i4.s 123
IL_0002: stloc.0
IL_0003: ldloca.s V_0
IL_0005: conv.u
IL_0006: call ""void C.Goo(int*)""
IL_000b: ret
}
");
}
#endregion AddressOf tests
#region Dereference tests
[Fact]
public void DereferenceLocal()
{
var text = @"
unsafe class C
{
static void Main()
{
int x = 123;
int* p = &x;
System.Console.WriteLine(*p);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "123", verify: Verification.Fails);
// NOTE: p is optimized away, but & and * aren't.
compVerifier.VerifyIL("C.Main", @"
{
// Code size 13 (0xd)
.maxstack 1
.locals init (int V_0) //x
IL_0000: ldc.i4.s 123
IL_0002: stloc.0
IL_0003: ldloca.s V_0
IL_0005: conv.u
IL_0006: ldind.i4
IL_0007: call ""void System.Console.WriteLine(int)""
IL_000c: ret
}
");
}
[Fact]
public void DereferenceParameter()
{
var text = @"
unsafe class C
{
static void Main()
{
long x = 456;
System.Console.WriteLine(Dereference(&x));
}
static long Dereference(long* p)
{
return *p;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "456", verify: Verification.Fails);
compVerifier.VerifyIL("C.Dereference", @"
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldind.i8
IL_0002: ret
}
");
}
[Fact]
public void DereferenceWrite()
{
var text = @"
unsafe class C
{
static void Main()
{
int x = 1;
int* p = &x;
*p = 2;
System.Console.WriteLine(x);
}
}
";
var compVerifierOptimized = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "2", verify: Verification.Fails);
// NOTE: p is optimized away, but & and * aren't.
compVerifierOptimized.VerifyIL("C.Main", @"
{
// Code size 14 (0xe)
.maxstack 2
.locals init (int V_0) //x
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: conv.u
IL_0005: ldc.i4.2
IL_0006: stind.i4
IL_0007: ldloc.0
IL_0008: call ""void System.Console.WriteLine(int)""
IL_000d: ret
}
");
var compVerifierUnoptimized = CompileAndVerify(text, options: TestOptions.UnsafeDebugExe, expectedOutput: "2", verify: Verification.Fails);
compVerifierUnoptimized.VerifyIL("C.Main", @"
{
// Code size 18 (0x12)
.maxstack 2
.locals init (int V_0, //x
int* V_1) //p
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldloca.s V_0
IL_0005: conv.u
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: ldc.i4.2
IL_0009: stind.i4
IL_000a: ldloc.0
IL_000b: call ""void System.Console.WriteLine(int)""
IL_0010: nop
IL_0011: ret
}
");
}
[Fact]
public void DereferenceStruct()
{
var text = @"
unsafe struct S
{
S* p;
byte x;
static void Main()
{
S s;
S* sp = &s;
(*sp).p = sp;
(*sp).x = 1;
System.Console.WriteLine((*(s.p)).x);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "1", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 35 (0x23)
.maxstack 2
.locals init (S V_0, //s
S* V_1) //sp
IL_0000: ldloca.s V_0
IL_0002: conv.u
IL_0003: stloc.1
IL_0004: ldloc.1
IL_0005: ldloc.1
IL_0006: stfld ""S* S.p""
IL_000b: ldloc.1
IL_000c: ldc.i4.1
IL_000d: stfld ""byte S.x""
IL_0012: ldloc.0
IL_0013: ldfld ""S* S.p""
IL_0018: ldfld ""byte S.x""
IL_001d: call ""void System.Console.WriteLine(int)""
IL_0022: ret
}
");
}
[Fact]
public void DereferenceSwap()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
byte b1 = 2;
byte b2 = 7;
Console.WriteLine(""Before: {0} {1}"", b1, b2);
Swap(&b1, &b2);
Console.WriteLine(""After: {0} {1}"", b1, b2);
}
static void Swap(byte* p1, byte* p2)
{
byte tmp = *p1;
*p1 = *p2;
*p2 = tmp;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"Before: 2 7
After: 7 2", verify: Verification.Fails);
compVerifier.VerifyIL("C.Swap", @"
{
// Code size 11 (0xb)
.maxstack 2
.locals init (byte V_0) //tmp
IL_0000: ldarg.0
IL_0001: ldind.u1
IL_0002: stloc.0
IL_0003: ldarg.0
IL_0004: ldarg.1
IL_0005: ldind.u1
IL_0006: stind.i1
IL_0007: ldarg.1
IL_0008: ldloc.0
IL_0009: stind.i1
IL_000a: ret
}
");
}
[Fact]
public void DereferenceIsLValue1()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
char c = 'a';
char* p = &c;
Console.Write(c);
Incr(ref *p);
Console.Write(c);
}
static void Incr(ref char c)
{
c++;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"ab", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 24 (0x18)
.maxstack 2
.locals init (char V_0) //c
IL_0000: ldc.i4.s 97
IL_0002: stloc.0
IL_0003: ldloca.s V_0
IL_0005: conv.u
IL_0006: ldloc.0
IL_0007: call ""void System.Console.Write(char)""
IL_000c: call ""void C.Incr(ref char)""
IL_0011: ldloc.0
IL_0012: call ""void System.Console.Write(char)""
IL_0017: ret
}
");
}
[Fact]
public void DereferenceIsLValue2()
{
var text = @"
using System;
unsafe struct S
{
int x;
static void Main()
{
S s;
s.x = 1;
S* p = &s;
Console.Write(s.x);
(*p).Mutate();
Console.Write(s.x);
}
void Mutate()
{
x++;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"12", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 39 (0x27)
.maxstack 2
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: stfld ""int S.x""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldloc.0
IL_000c: ldfld ""int S.x""
IL_0011: call ""void System.Console.Write(int)""
IL_0016: call ""void S.Mutate()""
IL_001b: ldloc.0
IL_001c: ldfld ""int S.x""
IL_0021: call ""void System.Console.Write(int)""
IL_0026: ret
}
");
}
#endregion Dereference tests
#region Pointer member access tests
[Fact]
public void PointerMemberAccessRead()
{
var text = @"
using System;
unsafe struct S
{
int x;
static void Main()
{
S s;
s.x = 3;
S* p = &s;
Console.Write(p->x);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"3", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.3
IL_0003: stfld ""int S.x""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldfld ""int S.x""
IL_0010: call ""void System.Console.Write(int)""
IL_0015: ret
}
");
compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"3", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.3
IL_0003: stfld ""int S.x""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldfld ""int S.x""
IL_0010: call ""void System.Console.Write(int)""
IL_0015: ret
}
");
}
[Fact]
public void PointerMemberAccessWrite()
{
var text = @"
using System;
unsafe struct S
{
int x;
static void Main()
{
S s;
s.x = 3;
S* p = &s;
Console.Write(s.x);
p->x = 4;
Console.Write(s.x);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"34", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 40 (0x28)
.maxstack 2
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.3
IL_0003: stfld ""int S.x""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldloc.0
IL_000c: ldfld ""int S.x""
IL_0011: call ""void System.Console.Write(int)""
IL_0016: ldc.i4.4
IL_0017: stfld ""int S.x""
IL_001c: ldloc.0
IL_001d: ldfld ""int S.x""
IL_0022: call ""void System.Console.Write(int)""
IL_0027: ret
}
");
compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"34", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 40 (0x28)
.maxstack 2
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.3
IL_0003: stfld ""int S.x""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldloc.0
IL_000c: ldfld ""int S.x""
IL_0011: call ""void System.Console.Write(int)""
IL_0016: ldc.i4.4
IL_0017: stfld ""int S.x""
IL_001c: ldloc.0
IL_001d: ldfld ""int S.x""
IL_0022: call ""void System.Console.Write(int)""
IL_0027: ret
}
");
}
[Fact]
public void PointerMemberAccessInvoke()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S s;
S* p = &s;
p->M();
p->M(1);
p->M(1, 2);
}
void M() { Console.Write(1); }
void M(int x) { Console.Write(2); }
}
static class Extensions
{
public static void M(this S s, int x, int y) { Console.Write(3); }
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"123", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 29 (0x1d)
.maxstack 3
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: conv.u
IL_0003: dup
IL_0004: call ""void S.M()""
IL_0009: dup
IL_000a: ldc.i4.1
IL_000b: call ""void S.M(int)""
IL_0010: ldobj ""S""
IL_0015: ldc.i4.1
IL_0016: ldc.i4.2
IL_0017: call ""void Extensions.M(S, int, int)""
IL_001c: ret
}
");
compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"123", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 29 (0x1d)
.maxstack 3
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: conv.u
IL_0003: dup
IL_0004: call ""void S.M()""
IL_0009: dup
IL_000a: ldc.i4.1
IL_000b: call ""void S.M(int)""
IL_0010: ldobj ""S""
IL_0015: ldc.i4.1
IL_0016: ldc.i4.2
IL_0017: call ""void Extensions.M(S, int, int)""
IL_001c: ret
}
");
}
[Fact]
public void PointerMemberAccessInvoke001()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S s;
S* p = &s;
Test(ref p);
}
static void Test(ref S* p)
{
p->M();
p->M(1);
p->M(1, 2);
}
void M() { Console.Write(1); }
void M(int x) { Console.Write(2); }
}
static class Extensions
{
public static void M(this S s, int x, int y) { Console.Write(3); }
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"123", verify: Verification.Fails);
compVerifier.VerifyIL("S.Test(ref S*)", @"
{
// Code size 30 (0x1e)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldind.i
IL_0002: call ""void S.M()""
IL_0007: ldarg.0
IL_0008: ldind.i
IL_0009: ldc.i4.1
IL_000a: call ""void S.M(int)""
IL_000f: ldarg.0
IL_0010: ldind.i
IL_0011: ldobj ""S""
IL_0016: ldc.i4.1
IL_0017: ldc.i4.2
IL_0018: call ""void Extensions.M(S, int, int)""
IL_001d: ret
}
");
compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"123", verify: Verification.Fails);
compVerifier.VerifyIL("S.Test(ref S*)", @"
{
// Code size 30 (0x1e)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldind.i
IL_0002: call ""void S.M()""
IL_0007: ldarg.0
IL_0008: ldind.i
IL_0009: ldc.i4.1
IL_000a: call ""void S.M(int)""
IL_000f: ldarg.0
IL_0010: ldind.i
IL_0011: ldobj ""S""
IL_0016: ldc.i4.1
IL_0017: ldc.i4.2
IL_0018: call ""void Extensions.M(S, int, int)""
IL_001d: ret
}
");
}
[Fact]
public void PointerMemberAccessMutate()
{
var text = @"
using System;
unsafe struct S
{
int x;
static void Main()
{
S s;
s.x = 3;
S* p = &s;
Console.Write((p->x)++);
Console.Write((p->x)++);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"34", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 49 (0x31)
.maxstack 4
.locals init (S V_0, //s
int V_1)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.3
IL_0003: stfld ""int S.x""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: dup
IL_000c: ldflda ""int S.x""
IL_0011: dup
IL_0012: ldind.i4
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: ldc.i4.1
IL_0016: add
IL_0017: stind.i4
IL_0018: ldloc.1
IL_0019: call ""void System.Console.Write(int)""
IL_001e: ldflda ""int S.x""
IL_0023: dup
IL_0024: ldind.i4
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: ldc.i4.1
IL_0028: add
IL_0029: stind.i4
IL_002a: ldloc.1
IL_002b: call ""void System.Console.Write(int)""
IL_0030: ret
}
");
compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"34", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 49 (0x31)
.maxstack 4
.locals init (S V_0, //s
int V_1)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.3
IL_0003: stfld ""int S.x""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: dup
IL_000c: ldflda ""int S.x""
IL_0011: dup
IL_0012: ldind.i4
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: ldc.i4.1
IL_0016: add
IL_0017: stind.i4
IL_0018: ldloc.1
IL_0019: call ""void System.Console.Write(int)""
IL_001e: ldflda ""int S.x""
IL_0023: dup
IL_0024: ldind.i4
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: ldc.i4.1
IL_0028: add
IL_0029: stind.i4
IL_002a: ldloc.1
IL_002b: call ""void System.Console.Write(int)""
IL_0030: ret
}
");
}
#endregion Pointer member access tests
#region Pointer element access tests
[Fact]
public void PointerElementAccessCheckedAndUnchecked()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S s = new S();
S* p = &s;
int i = (int)p;
uint ui = (uint)p;
long l = (long)p;
ulong ul = (ulong)p;
checked
{
s = p[i];
s = p[ui];
s = p[l];
s = p[ul];
}
unchecked
{
s = p[i];
s = p[ui];
s = p[l];
s = p[ul];
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails);
// The conversions differ from dev10 in the same way as for numeric addition.
// Note that, unlike for numeric addition, the add operation is never checked.
compVerifier.VerifyIL("S.Main", @"
{
// Code size 170 (0xaa)
.maxstack 4
.locals init (S V_0, //s
int V_1, //i
uint V_2, //ui
long V_3, //l
ulong V_4) //ul
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: dup
IL_000c: conv.i4
IL_000d: stloc.1
IL_000e: dup
IL_000f: conv.u4
IL_0010: stloc.2
IL_0011: dup
IL_0012: conv.u8
IL_0013: stloc.3
IL_0014: dup
IL_0015: conv.u8
IL_0016: stloc.s V_4
IL_0018: dup
IL_0019: ldloc.1
IL_001a: conv.i
IL_001b: sizeof ""S""
IL_0021: mul.ovf
IL_0022: add
IL_0023: ldobj ""S""
IL_0028: stloc.0
IL_0029: dup
IL_002a: ldloc.2
IL_002b: conv.u8
IL_002c: sizeof ""S""
IL_0032: conv.i8
IL_0033: mul.ovf
IL_0034: conv.i
IL_0035: add
IL_0036: ldobj ""S""
IL_003b: stloc.0
IL_003c: dup
IL_003d: ldloc.3
IL_003e: sizeof ""S""
IL_0044: conv.i8
IL_0045: mul.ovf
IL_0046: conv.i
IL_0047: add
IL_0048: ldobj ""S""
IL_004d: stloc.0
IL_004e: dup
IL_004f: ldloc.s V_4
IL_0051: sizeof ""S""
IL_0057: conv.ovf.u8
IL_0058: mul.ovf.un
IL_0059: conv.u
IL_005a: add
IL_005b: ldobj ""S""
IL_0060: stloc.0
IL_0061: dup
IL_0062: ldloc.1
IL_0063: conv.i
IL_0064: sizeof ""S""
IL_006a: mul
IL_006b: add
IL_006c: ldobj ""S""
IL_0071: stloc.0
IL_0072: dup
IL_0073: ldloc.2
IL_0074: conv.u8
IL_0075: sizeof ""S""
IL_007b: conv.i8
IL_007c: mul
IL_007d: conv.i
IL_007e: add
IL_007f: ldobj ""S""
IL_0084: stloc.0
IL_0085: dup
IL_0086: ldloc.3
IL_0087: sizeof ""S""
IL_008d: conv.i8
IL_008e: mul
IL_008f: conv.i
IL_0090: add
IL_0091: ldobj ""S""
IL_0096: stloc.0
IL_0097: ldloc.s V_4
IL_0099: sizeof ""S""
IL_009f: conv.i8
IL_00a0: mul
IL_00a1: conv.u
IL_00a2: add
IL_00a3: ldobj ""S""
IL_00a8: stloc.0
IL_00a9: ret
}
");
}
[Fact]
public void PointerElementAccessWrite()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
int* p = null;
p[1] = 2;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 9 (0x9)
.maxstack 2
.locals init (int* V_0) //p
IL_0000: ldc.i4.0
IL_0001: conv.u
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldc.i4.4
IL_0005: add
IL_0006: ldc.i4.2
IL_0007: stind.i4
IL_0008: ret
}
");
}
[Fact]
public void PointerElementAccessMutate()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
int[] array = new int[3];
fixed (int* p = array)
{
p[1] += ++p[0];
p[2] -= p[1]--;
}
foreach (int element in array)
{
Console.WriteLine(element);
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"
1
0
-1", verify: Verification.Fails);
}
[Fact]
public void PointerElementAccessNested()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
fixed (int* q = new int[3])
{
q[0] = 2;
q[1] = 0;
q[2] = 1;
Console.Write(q[q[q[q[q[q[*q]]]]]]);
Console.Write(q[q[q[q[q[q[q[*q]]]]]]]);
Console.Write(q[q[q[q[q[q[q[q[*q]]]]]]]]);
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "210", verify: Verification.Fails);
}
[Fact]
public void PointerElementAccessZero()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
int x = 1;
int* p = &x;
Console.WriteLine(p[0]);
}
}
";
// NOTE: no pointer arithmetic - just dereference p.
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "1", verify: Verification.Fails).VerifyIL("C.Main", @"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (int V_0) //x
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: conv.u
IL_0005: ldind.i4
IL_0006: call ""void System.Console.WriteLine(int)""
IL_000b: ret
}
");
}
#endregion Pointer element access tests
#region Fixed statement tests
[Fact]
public void FixedStatementField()
{
var text = @"
using System;
unsafe class C
{
int x;
static void Main()
{
C c = new C();
fixed (int* p = &c.x)
{
*p = 1;
}
Console.WriteLine(c.x);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"1", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 30 (0x1e)
.maxstack 3
.locals init (pinned int& V_0)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: ldflda ""int C.x""
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: conv.u
IL_000e: ldc.i4.1
IL_000f: stind.i4
IL_0010: ldc.i4.0
IL_0011: conv.u
IL_0012: stloc.0
IL_0013: ldfld ""int C.x""
IL_0018: call ""void System.Console.WriteLine(int)""
IL_001d: ret
}
");
}
[Fact]
public void FixedStatementThis()
{
var text = @"
public class Program
{
public static void Main()
{
S1 s = default;
s.Test();
}
unsafe readonly struct S1
{
readonly int x;
public void Test()
{
fixed(void* p = &this)
{
*(int*)p = 123;
}
ref readonly S1 r = ref this;
fixed (S1* p = &r)
{
System.Console.WriteLine(p->x);
}
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"123", verify: Verification.Fails);
compVerifier.VerifyIL("Program.S1.Test()", @"
{
// Code size 30 (0x1e)
.maxstack 2
.locals init (void* V_0, //p
pinned Program.S1& V_1)
IL_0000: ldarg.0
IL_0001: stloc.1
IL_0002: ldloc.1
IL_0003: conv.u
IL_0004: stloc.0
IL_0005: ldloc.0
IL_0006: ldc.i4.s 123
IL_0008: stind.i4
IL_0009: ldc.i4.0
IL_000a: conv.u
IL_000b: stloc.1
IL_000c: ldarg.0
IL_000d: stloc.1
IL_000e: ldloc.1
IL_000f: conv.u
IL_0010: ldfld ""int Program.S1.x""
IL_0015: call ""void System.Console.WriteLine(int)""
IL_001a: ldc.i4.0
IL_001b: conv.u
IL_001c: stloc.1
IL_001d: ret
}
");
}
[WorkItem(22306, "https://github.com/dotnet/roslyn/issues/22306")]
[Fact]
public void FixedStatementMultipleFields()
{
var text = @"
using System;
unsafe class C
{
int x;
readonly int y;
static void Main()
{
C c = new C();
fixed (int* p = &c.x, q = &c.y)
{
*p = 1;
*q = 2;
}
Console.Write(c.x);
Console.Write(c.y);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"12", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 57 (0x39)
.maxstack 4
.locals init (int* V_0, //p
pinned int& V_1,
pinned int& V_2)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: ldflda ""int C.x""
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: conv.u
IL_000e: stloc.0
IL_000f: dup
IL_0010: ldflda ""int C.y""
IL_0015: stloc.2
IL_0016: ldloc.2
IL_0017: conv.u
IL_0018: ldloc.0
IL_0019: ldc.i4.1
IL_001a: stind.i4
IL_001b: ldc.i4.2
IL_001c: stind.i4
IL_001d: ldc.i4.0
IL_001e: conv.u
IL_001f: stloc.1
IL_0020: ldc.i4.0
IL_0021: conv.u
IL_0022: stloc.2
IL_0023: dup
IL_0024: ldfld ""int C.x""
IL_0029: call ""void System.Console.Write(int)""
IL_002e: ldfld ""int C.y""
IL_0033: call ""void System.Console.Write(int)""
IL_0038: ret
}
");
}
[WorkItem(22306, "https://github.com/dotnet/roslyn/issues/22306")]
[Fact]
public void FixedStatementMultipleMethods()
{
var text = @"
using System;
unsafe class C
{
int x;
readonly int y;
ref int X()=>ref x;
ref readonly int this[int i]=>ref y;
static void Main()
{
C c = new C();
fixed (int* p = &c.X(), q = &c[3])
{
*p = 1;
*q = 2;
}
Console.Write(c.x);
Console.Write(c.y);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"12", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 58 (0x3a)
.maxstack 4
.locals init (int* V_0, //p
pinned int& V_1,
pinned int& V_2)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: callvirt ""ref int C.X()""
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: conv.u
IL_000e: stloc.0
IL_000f: dup
IL_0010: ldc.i4.3
IL_0011: callvirt ""ref readonly int C.this[int].get""
IL_0016: stloc.2
IL_0017: ldloc.2
IL_0018: conv.u
IL_0019: ldloc.0
IL_001a: ldc.i4.1
IL_001b: stind.i4
IL_001c: ldc.i4.2
IL_001d: stind.i4
IL_001e: ldc.i4.0
IL_001f: conv.u
IL_0020: stloc.1
IL_0021: ldc.i4.0
IL_0022: conv.u
IL_0023: stloc.2
IL_0024: dup
IL_0025: ldfld ""int C.x""
IL_002a: call ""void System.Console.Write(int)""
IL_002f: ldfld ""int C.y""
IL_0034: call ""void System.Console.Write(int)""
IL_0039: ret
}
");
}
[WorkItem(546866, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546866")]
[Fact]
public void FixedStatementProperty()
{
var text =
@"class C
{
string P { get { return null; } }
char[] Q { get { return null; } }
unsafe static void M(C c)
{
fixed (char* o = c.P)
{
}
fixed (char* o = c.Q)
{
}
}
}";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails);
compVerifier.VerifyIL("C.M(C)",
@"
{
// Code size 55 (0x37)
.maxstack 2
.locals init (char* V_0, //o
pinned string V_1,
char* V_2, //o
pinned char[] V_3)
IL_0000: ldarg.0
IL_0001: callvirt ""string C.P.get""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_0015
IL_000d: ldloc.0
IL_000e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0013: add
IL_0014: stloc.0
IL_0015: ldnull
IL_0016: stloc.1
IL_0017: ldarg.0
IL_0018: callvirt ""char[] C.Q.get""
IL_001d: dup
IL_001e: stloc.3
IL_001f: brfalse.s IL_0026
IL_0021: ldloc.3
IL_0022: ldlen
IL_0023: conv.i4
IL_0024: brtrue.s IL_002b
IL_0026: ldc.i4.0
IL_0027: conv.u
IL_0028: stloc.2
IL_0029: br.s IL_0034
IL_002b: ldloc.3
IL_002c: ldc.i4.0
IL_002d: ldelema ""char""
IL_0032: conv.u
IL_0033: stloc.2
IL_0034: ldnull
IL_0035: stloc.3
IL_0036: ret
}
");
}
[Fact]
public void FixedStatementMultipleOptimized()
{
var text = @"
using System;
unsafe class C
{
int x;
int y;
static void Main()
{
C c = new C();
fixed (int* p = &c.x, q = &c.y)
{
*p = 1;
*q = 2;
}
Console.Write(c.x);
Console.Write(c.y);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"12", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 57 (0x39)
.maxstack 4
.locals init (int* V_0, //p
pinned int& V_1,
pinned int& V_2)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: ldflda ""int C.x""
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: conv.u
IL_000e: stloc.0
IL_000f: dup
IL_0010: ldflda ""int C.y""
IL_0015: stloc.2
IL_0016: ldloc.2
IL_0017: conv.u
IL_0018: ldloc.0
IL_0019: ldc.i4.1
IL_001a: stind.i4
IL_001b: ldc.i4.2
IL_001c: stind.i4
IL_001d: ldc.i4.0
IL_001e: conv.u
IL_001f: stloc.1
IL_0020: ldc.i4.0
IL_0021: conv.u
IL_0022: stloc.2
IL_0023: dup
IL_0024: ldfld ""int C.x""
IL_0029: call ""void System.Console.Write(int)""
IL_002e: ldfld ""int C.y""
IL_0033: call ""void System.Console.Write(int)""
IL_0038: ret
}
");
}
[Fact]
public void FixedStatementReferenceParameter()
{
var text = @"
using System;
class C
{
static void Main()
{
char ch;
M(out ch);
Console.WriteLine(ch);
}
unsafe static void M(out char ch)
{
fixed (char* p = &ch)
{
*p = 'a';
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"a", verify: Verification.Fails);
compVerifier.VerifyIL("C.M", @"
{
// Code size 11 (0xb)
.maxstack 2
.locals init (pinned char& V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: conv.u
IL_0004: ldc.i4.s 97
IL_0006: stind.i2
IL_0007: ldc.i4.0
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ret
}
");
}
[Fact]
public void FixedStatementReferenceParameterDebug()
{
var text = @"
using System;
class C
{
static void Main()
{
char ch;
M(out ch);
Console.WriteLine(ch);
}
unsafe static void M(out char ch)
{
fixed (char* p = &ch)
{
*p = 'a';
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeDebugExe, expectedOutput: @"a", verify: Verification.Fails);
compVerifier.VerifyIL("C.M", @"
{
// Code size 16 (0x10)
.maxstack 2
.locals init (char* V_0, //p
pinned char& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.1
IL_0003: ldloc.1
IL_0004: conv.u
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldc.i4.s 97
IL_000a: stind.i2
IL_000b: nop
IL_000c: ldc.i4.0
IL_000d: conv.u
IL_000e: stloc.1
IL_000f: ret
}
");
}
[Fact]
public void FixedStatementStringLiteral()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
fixed (char* p = ""hello"")
{
Console.WriteLine(*p);
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeDebugExe, expectedOutput: @"h", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 34 (0x22)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
-IL_0000: nop
IL_0001: ldstr ""hello""
IL_0006: stloc.1
-IL_0007: ldloc.1
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_0015
IL_000d: ldloc.0
IL_000e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0013: add
IL_0014: stloc.0
-IL_0015: nop
-IL_0016: ldloc.0
IL_0017: ldind.u2
IL_0018: call ""void System.Console.WriteLine(char)""
IL_001d: nop
-IL_001e: nop
~IL_001f: ldnull
IL_0020: stloc.1
-IL_0021: ret
}
", sequencePoints: "C.Main");
}
[Fact]
public void FixedStatementStringVariable()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
string s = ""hello"";
fixed (char* p = s)
{
Console.Write(*p);
}
s = null;
fixed (char* p = s)
{
Console.Write(p == null);
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeDebugExe, expectedOutput: @"hTrue", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 72 (0x48)
.maxstack 2
.locals init (string V_0, //s
char* V_1, //p
pinned string V_2,
char* V_3, //p
pinned string V_4)
-IL_0000: nop
-IL_0001: ldstr ""hello""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: stloc.2
-IL_0009: ldloc.2
IL_000a: conv.u
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: brfalse.s IL_0017
IL_000f: ldloc.1
IL_0010: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0015: add
IL_0016: stloc.1
-IL_0017: nop
-IL_0018: ldloc.1
IL_0019: ldind.u2
IL_001a: call ""void System.Console.Write(char)""
IL_001f: nop
-IL_0020: nop
~IL_0021: ldnull
IL_0022: stloc.2
-IL_0023: ldnull
IL_0024: stloc.0
IL_0025: ldloc.0
IL_0026: stloc.s V_4
-IL_0028: ldloc.s V_4
IL_002a: conv.u
IL_002b: stloc.3
IL_002c: ldloc.3
IL_002d: brfalse.s IL_0037
IL_002f: ldloc.3
IL_0030: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0035: add
IL_0036: stloc.3
-IL_0037: nop
-IL_0038: ldloc.3
IL_0039: ldc.i4.0
IL_003a: conv.u
IL_003b: ceq
IL_003d: call ""void System.Console.Write(bool)""
IL_0042: nop
-IL_0043: nop
~IL_0044: ldnull
IL_0045: stloc.s V_4
-IL_0047: ret
}
", sequencePoints: "C.Main");
}
[Fact]
public void FixedStatementStringVariableOptimized()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
string s = ""hello"";
fixed (char* p = s)
{
Console.Write(*p);
}
s = null;
fixed (char* p = s)
{
Console.Write(p == null);
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"hTrue", verify: Verification.Fails);
// Null checks and branches are much simpler, but string temps are NOT optimized away.
compVerifier.VerifyIL("C.Main", @"
{
// Code size 58 (0x3a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1,
char* V_2) //p
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldloc.0
IL_0015: ldind.u2
IL_0016: call ""void System.Console.Write(char)""
IL_001b: ldnull
IL_001c: stloc.1
IL_001d: ldnull
IL_001e: stloc.1
IL_001f: ldloc.1
IL_0020: conv.u
IL_0021: stloc.2
IL_0022: ldloc.2
IL_0023: brfalse.s IL_002d
IL_0025: ldloc.2
IL_0026: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_002b: add
IL_002c: stloc.2
IL_002d: ldloc.2
IL_002e: ldc.i4.0
IL_002f: conv.u
IL_0030: ceq
IL_0032: call ""void System.Console.Write(bool)""
IL_0037: ldnull
IL_0038: stloc.1
IL_0039: ret
}
");
}
[Fact]
public void FixedStatementOneDimensionalArray()
{
var text = @"
using System;
unsafe class C
{
int[] a = new int[1];
static void Main()
{
C c = new C();
Console.Write(c.a[0]);
fixed (int* p = c.a)
{
*p = 1;
}
Console.Write(c.a[0]);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"01", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 65 (0x41)
.maxstack 3
.locals init (int* V_0, //p
pinned int[] V_1)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: ldfld ""int[] C.a""
IL_000b: ldc.i4.0
IL_000c: ldelem.i4
IL_000d: call ""void System.Console.Write(int)""
IL_0012: dup
IL_0013: ldfld ""int[] C.a""
IL_0018: dup
IL_0019: stloc.1
IL_001a: brfalse.s IL_0021
IL_001c: ldloc.1
IL_001d: ldlen
IL_001e: conv.i4
IL_001f: brtrue.s IL_0026
IL_0021: ldc.i4.0
IL_0022: conv.u
IL_0023: stloc.0
IL_0024: br.s IL_002f
IL_0026: ldloc.1
IL_0027: ldc.i4.0
IL_0028: ldelema ""int""
IL_002d: conv.u
IL_002e: stloc.0
IL_002f: ldloc.0
IL_0030: ldc.i4.1
IL_0031: stind.i4
IL_0032: ldnull
IL_0033: stloc.1
IL_0034: ldfld ""int[] C.a""
IL_0039: ldc.i4.0
IL_003a: ldelem.i4
IL_003b: call ""void System.Console.Write(int)""
IL_0040: ret
}
");
}
[Fact]
public void FixedStatementOneDimensionalArrayOptimized()
{
var text = @"
using System;
unsafe class C
{
int[] a = new int[1];
static void Main()
{
C c = new C();
Console.Write(c.a[0]);
fixed (int* p = c.a)
{
*p = 1;
}
Console.Write(c.a[0]);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"01", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 65 (0x41)
.maxstack 3
.locals init (int* V_0, //p
pinned int[] V_1)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: ldfld ""int[] C.a""
IL_000b: ldc.i4.0
IL_000c: ldelem.i4
IL_000d: call ""void System.Console.Write(int)""
IL_0012: dup
IL_0013: ldfld ""int[] C.a""
IL_0018: dup
IL_0019: stloc.1
IL_001a: brfalse.s IL_0021
IL_001c: ldloc.1
IL_001d: ldlen
IL_001e: conv.i4
IL_001f: brtrue.s IL_0026
IL_0021: ldc.i4.0
IL_0022: conv.u
IL_0023: stloc.0
IL_0024: br.s IL_002f
IL_0026: ldloc.1
IL_0027: ldc.i4.0
IL_0028: ldelema ""int""
IL_002d: conv.u
IL_002e: stloc.0
IL_002f: ldloc.0
IL_0030: ldc.i4.1
IL_0031: stind.i4
IL_0032: ldnull
IL_0033: stloc.1
IL_0034: ldfld ""int[] C.a""
IL_0039: ldc.i4.0
IL_003a: ldelem.i4
IL_003b: call ""void System.Console.Write(int)""
IL_0040: ret
}
");
}
[Fact]
public void FixedStatementMultiDimensionalArrayOptimized()
{
var text = @"
using System;
unsafe class C
{
int[,] a = new int[1,1];
static void Main()
{
C c = new C();
Console.Write(c.a[0, 0]);
fixed (int* p = c.a)
{
*p = 1;
}
Console.Write(c.a[0, 0]);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"01", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 79 (0x4f)
.maxstack 4
.locals init (int* V_0, //p
pinned int[,] V_1)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: ldfld ""int[,] C.a""
IL_000b: ldc.i4.0
IL_000c: ldc.i4.0
IL_000d: call ""int[*,*].Get""
IL_0012: call ""void System.Console.Write(int)""
IL_0017: dup
IL_0018: ldfld ""int[,] C.a""
IL_001d: dup
IL_001e: stloc.1
IL_001f: brfalse.s IL_0029
IL_0021: ldloc.1
IL_0022: callvirt ""int System.Array.Length.get""
IL_0027: brtrue.s IL_002e
IL_0029: ldc.i4.0
IL_002a: conv.u
IL_002b: stloc.0
IL_002c: br.s IL_0038
IL_002e: ldloc.1
IL_002f: ldc.i4.0
IL_0030: ldc.i4.0
IL_0031: call ""int[*,*].Address""
IL_0036: conv.u
IL_0037: stloc.0
IL_0038: ldloc.0
IL_0039: ldc.i4.1
IL_003a: stind.i4
IL_003b: ldnull
IL_003c: stloc.1
IL_003d: ldfld ""int[,] C.a""
IL_0042: ldc.i4.0
IL_0043: ldc.i4.0
IL_0044: call ""int[*,*].Get""
IL_0049: call ""void System.Console.Write(int)""
IL_004e: ret
}
");
}
[Fact]
public void FixedStatementMixed()
{
var text = @"
using System;
unsafe class C
{
char c = 'a';
char[] a = new char[1];
static void Main()
{
C c = new C();
fixed (char* p = &c.c, q = c.a, r = ""hello"")
{
Console.Write((int)*p);
Console.Write((int)*q);
Console.Write((int)*r);
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"970104", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 99 (0x63)
.maxstack 2
.locals init (char* V_0, //p
char* V_1, //q
char* V_2, //r
pinned char& V_3,
pinned char[] V_4,
pinned string V_5)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: ldflda ""char C.c""
IL_000b: stloc.3
IL_000c: ldloc.3
IL_000d: conv.u
IL_000e: stloc.0
IL_000f: ldfld ""char[] C.a""
IL_0014: dup
IL_0015: stloc.s V_4
IL_0017: brfalse.s IL_001f
IL_0019: ldloc.s V_4
IL_001b: ldlen
IL_001c: conv.i4
IL_001d: brtrue.s IL_0024
IL_001f: ldc.i4.0
IL_0020: conv.u
IL_0021: stloc.1
IL_0022: br.s IL_002e
IL_0024: ldloc.s V_4
IL_0026: ldc.i4.0
IL_0027: ldelema ""char""
IL_002c: conv.u
IL_002d: stloc.1
IL_002e: ldstr ""hello""
IL_0033: stloc.s V_5
IL_0035: ldloc.s V_5
IL_0037: conv.u
IL_0038: stloc.2
IL_0039: ldloc.2
IL_003a: brfalse.s IL_0044
IL_003c: ldloc.2
IL_003d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0042: add
IL_0043: stloc.2
IL_0044: ldloc.0
IL_0045: ldind.u2
IL_0046: call ""void System.Console.Write(int)""
IL_004b: ldloc.1
IL_004c: ldind.u2
IL_004d: call ""void System.Console.Write(int)""
IL_0052: ldloc.2
IL_0053: ldind.u2
IL_0054: call ""void System.Console.Write(int)""
IL_0059: ldc.i4.0
IL_005a: conv.u
IL_005b: stloc.3
IL_005c: ldnull
IL_005d: stloc.s V_4
IL_005f: ldnull
IL_0060: stloc.s V_5
IL_0062: ret
}
");
}
[Fact]
public void FixedStatementInTryOfTryFinally()
{
var text = @"
unsafe class C
{
static void nop() { }
void Test()
{
try
{
fixed (char* p = ""hello"")
{
}
}
finally
{
nop();
}
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 32 (0x20)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_001f
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
}
finally
{
IL_0019: call ""void C.nop()""
IL_001e: endfinally
}
IL_001f: ret
}
");
}
[Fact]
public void FixedStatementInTryOfTryCatch()
{
var text = @"
unsafe class C
{
void Test()
{
try
{
fixed (char* p = ""hello"")
{
}
}
catch
{
}
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 31 (0x1f)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_0019
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: leave.s IL_001e
}
catch object
{
IL_001b: pop
IL_001c: leave.s IL_001e
}
IL_001e: ret
}
");
}
[Fact]
public void FixedStatementInFinally()
{
var text = @"
unsafe class C
{
void Test()
{
try
{
}
finally
{
fixed (char* p = ""hello"")
{
}
}
}
}
";
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: leave.s IL_0019
}
finally
{
IL_0002: ldstr ""hello""
IL_0007: stloc.1
IL_0008: ldloc.1
IL_0009: conv.u
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0016
IL_000e: ldloc.0
IL_000f: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0014: add
IL_0015: stloc.0
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: ret
}
");
}
[Fact]
public void FixedStatementInCatchOfTryCatch()
{
var text = @"
unsafe class C
{
void nop() { }
void Test()
{
try
{
nop();
}
catch
{
fixed (char* p = ""hello"")
{
}
}
}
}
";
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test",
@"{
// Code size 34 (0x22)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: ldarg.0
IL_0001: call ""void C.nop()""
IL_0006: leave.s IL_0021
}
catch object
{
IL_0008: pop
IL_0009: ldstr ""hello""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: conv.u
IL_0011: stloc.0
IL_0012: ldloc.0
IL_0013: brfalse.s IL_001d
IL_0015: ldloc.0
IL_0016: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_001b: add
IL_001c: stloc.0
IL_001d: ldnull
IL_001e: stloc.1
IL_001f: leave.s IL_0021
}
IL_0021: ret
}");
}
[Fact]
public void FixedStatementInCatchOfTryCatchFinally()
{
var text = @"
unsafe class C
{
static void nop() { }
void Test()
{
try
{
nop();
}
catch
{
fixed (char* p = ""hello"")
{
}
}
finally
{
}
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 36 (0x24)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: call ""void C.nop()""
IL_0005: leave.s IL_0023
}
catch object
{
IL_0007: pop
.try
{
IL_0008: ldstr ""hello""
IL_000d: stloc.1
IL_000e: ldloc.1
IL_000f: conv.u
IL_0010: stloc.0
IL_0011: ldloc.0
IL_0012: brfalse.s IL_001c
IL_0014: ldloc.0
IL_0015: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_001a: add
IL_001b: stloc.0
IL_001c: leave.s IL_0021
}
finally
{
IL_001e: ldnull
IL_001f: stloc.1
IL_0020: endfinally
}
IL_0021: leave.s IL_0023
}
IL_0023: ret
}
");
}
[Fact]
public void FixedStatementInFixed_NoBranch()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* q = ""goodbye"")
{
fixed (char* p = ""hello"")
{
}
}
}
}
";
// Neither inner nor outer has finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 45 (0x2d)
.maxstack 2
.locals init (char* V_0, //q
pinned string V_1,
char* V_2, //p
pinned string V_3)
IL_0000: ldstr ""goodbye""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldstr ""hello""
IL_0019: stloc.3
IL_001a: ldloc.3
IL_001b: conv.u
IL_001c: stloc.2
IL_001d: ldloc.2
IL_001e: brfalse.s IL_0028
IL_0020: ldloc.2
IL_0021: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0026: add
IL_0027: stloc.2
IL_0028: ldnull
IL_0029: stloc.3
IL_002a: ldnull
IL_002b: stloc.1
IL_002c: ret
}
");
}
[Fact]
public void FixedStatementInFixed_InnerBranch()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* q = ""goodbye"")
{
fixed (char* p = ""hello"")
{
goto label;
}
}
label: ;
}
}
";
// Inner and outer both have finally blocks.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 50 (0x32)
.maxstack 2
.locals init (char* V_0, //q
pinned string V_1,
char* V_2, //p
pinned string V_3)
.try
{
IL_0000: ldstr ""goodbye""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: nop
.try
{
IL_0015: ldstr ""hello""
IL_001a: stloc.3
IL_001b: ldloc.3
IL_001c: conv.u
IL_001d: stloc.2
IL_001e: ldloc.2
IL_001f: brfalse.s IL_0029
IL_0021: ldloc.2
IL_0022: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0027: add
IL_0028: stloc.2
IL_0029: leave.s IL_0031
}
finally
{
IL_002b: ldnull
IL_002c: stloc.3
IL_002d: endfinally
}
}
finally
{
IL_002e: ldnull
IL_002f: stloc.1
IL_0030: endfinally
}
IL_0031: ret
}
");
}
[Fact]
public void FixedStatementInFixed_OuterBranch()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* q = ""goodbye"")
{
fixed (char* p = ""hello"")
{
}
goto label;
}
label: ;
}
}
";
// Outer has finally, inner does not.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 48 (0x30)
.maxstack 2
.locals init (char* V_0, //q
pinned string V_1,
char* V_2, //p
pinned string V_3)
.try
{
IL_0000: ldstr ""goodbye""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldstr ""hello""
IL_0019: stloc.3
IL_001a: ldloc.3
IL_001b: conv.u
IL_001c: stloc.2
IL_001d: ldloc.2
IL_001e: brfalse.s IL_0028
IL_0020: ldloc.2
IL_0021: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0026: add
IL_0027: stloc.2
IL_0028: ldnull
IL_0029: stloc.3
IL_002a: leave.s IL_002f
}
finally
{
IL_002c: ldnull
IL_002d: stloc.1
IL_002e: endfinally
}
IL_002f: ret
}
");
}
[Fact]
public void FixedStatementInFixed_Nesting()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p1 = ""A"")
{
fixed (char* p2 = ""B"")
{
fixed (char* p3 = ""C"")
{
}
fixed (char* p4 = ""D"")
{
}
}
fixed (char* p5 = ""E"")
{
fixed (char* p6 = ""F"")
{
}
fixed (char* p7 = ""G"")
{
}
}
}
}
}
";
// This test checks two things:
// 1) nothing blows up with triple-nesting, and
// 2) none of the fixed statements has a try-finally.
// CONSIDER: Shorter test that performs the same checks.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 187 (0xbb)
.maxstack 2
.locals init (char* V_0, //p1
pinned string V_1,
char* V_2, //p2
pinned string V_3,
char* V_4, //p3
pinned string V_5,
char* V_6, //p4
char* V_7, //p5
char* V_8, //p6
char* V_9) //p7
IL_0000: ldstr ""A""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldstr ""B""
IL_0019: stloc.3
IL_001a: ldloc.3
IL_001b: conv.u
IL_001c: stloc.2
IL_001d: ldloc.2
IL_001e: brfalse.s IL_0028
IL_0020: ldloc.2
IL_0021: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0026: add
IL_0027: stloc.2
IL_0028: ldstr ""C""
IL_002d: stloc.s V_5
IL_002f: ldloc.s V_5
IL_0031: conv.u
IL_0032: stloc.s V_4
IL_0034: ldloc.s V_4
IL_0036: brfalse.s IL_0042
IL_0038: ldloc.s V_4
IL_003a: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_003f: add
IL_0040: stloc.s V_4
IL_0042: ldnull
IL_0043: stloc.s V_5
IL_0045: ldstr ""D""
IL_004a: stloc.s V_5
IL_004c: ldloc.s V_5
IL_004e: conv.u
IL_004f: stloc.s V_6
IL_0051: ldloc.s V_6
IL_0053: brfalse.s IL_005f
IL_0055: ldloc.s V_6
IL_0057: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_005c: add
IL_005d: stloc.s V_6
IL_005f: ldnull
IL_0060: stloc.s V_5
IL_0062: ldnull
IL_0063: stloc.3
IL_0064: ldstr ""E""
IL_0069: stloc.3
IL_006a: ldloc.3
IL_006b: conv.u
IL_006c: stloc.s V_7
IL_006e: ldloc.s V_7
IL_0070: brfalse.s IL_007c
IL_0072: ldloc.s V_7
IL_0074: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0079: add
IL_007a: stloc.s V_7
IL_007c: ldstr ""F""
IL_0081: stloc.s V_5
IL_0083: ldloc.s V_5
IL_0085: conv.u
IL_0086: stloc.s V_8
IL_0088: ldloc.s V_8
IL_008a: brfalse.s IL_0096
IL_008c: ldloc.s V_8
IL_008e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0093: add
IL_0094: stloc.s V_8
IL_0096: ldnull
IL_0097: stloc.s V_5
IL_0099: ldstr ""G""
IL_009e: stloc.s V_5
IL_00a0: ldloc.s V_5
IL_00a2: conv.u
IL_00a3: stloc.s V_9
IL_00a5: ldloc.s V_9
IL_00a7: brfalse.s IL_00b3
IL_00a9: ldloc.s V_9
IL_00ab: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_00b0: add
IL_00b1: stloc.s V_9
IL_00b3: ldnull
IL_00b4: stloc.s V_5
IL_00b6: ldnull
IL_00b7: stloc.3
IL_00b8: ldnull
IL_00b9: stloc.1
IL_00ba: ret
}
");
}
[Fact]
public void FixedStatementInUsing()
{
var text = @"
unsafe class C
{
void Test()
{
using (System.IDisposable d = null)
{
fixed (char* p = ""hello"")
{
}
}
}
}
";
// CONSIDER: This is sort of silly since the using is optimized away.
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_0019
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: ret
}
");
}
[Fact]
public void FixedStatementInLock()
{
var text = @"
unsafe class C
{
void Test()
{
lock (this)
{
fixed (char* p = ""hello"")
{
}
}
}
}
";
// Cleanup not in finally (matches dev11, but not clear why).
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 47 (0x2f)
.maxstack 2
.locals init (C V_0,
bool V_1,
char* V_2, //p
pinned string V_3)
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 ""void System.Threading.Monitor.Enter(object, ref bool)""
IL_000c: ldstr ""hello""
IL_0011: stloc.3
IL_0012: ldloc.3
IL_0013: conv.u
IL_0014: stloc.2
IL_0015: ldloc.2
IL_0016: brfalse.s IL_0020
IL_0018: ldloc.2
IL_0019: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_001e: add
IL_001f: stloc.2
IL_0020: ldnull
IL_0021: stloc.3
IL_0022: leave.s IL_002e
}
finally
{
IL_0024: ldloc.1
IL_0025: brfalse.s IL_002d
IL_0027: ldloc.0
IL_0028: call ""void System.Threading.Monitor.Exit(object)""
IL_002d: endfinally
}
IL_002e: ret
}
");
}
[Fact]
public void FixedStatementInForEach_NoDispose()
{
var text = @"
unsafe class C
{
void Test(int[] array)
{
foreach (int i in array)
{
fixed (char* p = ""hello"")
{
}
}
}
}
";
// Cleanup in finally.
// CONSIDER: dev11 is smarter and skips the try-finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 46 (0x2e)
.maxstack 2
.locals init (int[] V_0,
int V_1,
char* V_2, //p
pinned string V_3)
IL_0000: ldarg.1
IL_0001: stloc.0
IL_0002: ldc.i4.0
IL_0003: stloc.1
IL_0004: br.s IL_0027
IL_0006: ldloc.0
IL_0007: ldloc.1
IL_0008: ldelem.i4
IL_0009: pop
.try
{
IL_000a: ldstr ""hello""
IL_000f: stloc.3
IL_0010: ldloc.3
IL_0011: conv.u
IL_0012: stloc.2
IL_0013: ldloc.2
IL_0014: brfalse.s IL_001e
IL_0016: ldloc.2
IL_0017: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_001c: add
IL_001d: stloc.2
IL_001e: leave.s IL_0023
}
finally
{
IL_0020: ldnull
IL_0021: stloc.3
IL_0022: endfinally
}
IL_0023: ldloc.1
IL_0024: ldc.i4.1
IL_0025: add
IL_0026: stloc.1
IL_0027: ldloc.1
IL_0028: ldloc.0
IL_0029: ldlen
IL_002a: conv.i4
IL_002b: blt.s IL_0006
IL_002d: ret
}
");
}
[Fact]
public void FixedStatementInForEach_Dispose()
{
var text = @"
unsafe class C
{
void Test(Enumerable e)
{
foreach (var x in e)
{
fixed (char* p = ""hello"")
{
}
}
}
}
class Enumerable
{
public Enumerator GetEnumerator() { return new Enumerator(); }
}
class Enumerator : System.IDisposable
{
int x;
public int Current { get { return x; } }
public bool MoveNext() { return ++x < 4; }
void System.IDisposable.Dispose() { }
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 62 (0x3e)
.maxstack 2
.locals init (Enumerator V_0,
char* V_1, //p
pinned string V_2)
IL_0000: ldarg.1
IL_0001: callvirt ""Enumerator Enumerable.GetEnumerator()""
IL_0006: stloc.0
.try
{
IL_0007: br.s IL_0029
IL_0009: ldloc.0
IL_000a: callvirt ""int Enumerator.Current.get""
IL_000f: pop
.try
{
IL_0010: ldstr ""hello""
IL_0015: stloc.2
IL_0016: ldloc.2
IL_0017: conv.u
IL_0018: stloc.1
IL_0019: ldloc.1
IL_001a: brfalse.s IL_0024
IL_001c: ldloc.1
IL_001d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0022: add
IL_0023: stloc.1
IL_0024: leave.s IL_0029
}
finally
{
IL_0026: ldnull
IL_0027: stloc.2
IL_0028: endfinally
}
IL_0029: ldloc.0
IL_002a: callvirt ""bool Enumerator.MoveNext()""
IL_002f: brtrue.s IL_0009
IL_0031: leave.s IL_003d
}
finally
{
IL_0033: ldloc.0
IL_0034: brfalse.s IL_003c
IL_0036: ldloc.0
IL_0037: callvirt ""void System.IDisposable.Dispose()""
IL_003c: endfinally
}
IL_003d: ret
}
");
}
[Fact]
public void FixedStatementInLambda1()
{
var text = @"
unsafe class C
{
void Test()
{
System.Action a = () =>
{
try
{
fixed (char* p = ""hello"")
{
}
}
finally
{
}
};
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.<>c.<Test>b__0_0()", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_0019
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: ret
}");
}
[Fact]
public void FixedStatementInLambda2()
{
var text = @"
unsafe class C
{
void Test()
{
try
{
System.Action a = () =>
{
fixed (char* p = ""hello"")
{
}
};
}
finally
{
}
}
}
";
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.<>c.<Test>b__0_0()", @"
{
// Code size 23 (0x17)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldnull
IL_0015: stloc.1
IL_0016: ret
}
");
}
[Fact]
public void FixedStatementInLambda3()
{
var text = @"
unsafe class C
{
void Test()
{
System.Action a = () =>
{
fixed (char* p = ""hello"")
{
goto label;
}
label: ;
};
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.<>c.<Test>b__0_0()", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_0019
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: ret
}
");
}
[Fact]
public void FixedStatementInFieldInitializer1()
{
var text = @"
unsafe class C
{
System.Action a = () =>
{
try
{
fixed (char* p = ""hello"")
{
}
}
finally
{
}
};
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.<>c.<.ctor>b__1_0()", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_0019
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: ret
}
");
}
[Fact]
public void FixedStatementInFieldInitializer2()
{
var text = @"
unsafe class C
{
System.Action a = () =>
{
fixed (char* p = ""hello"")
{
goto label;
}
label: ;
};
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.<>c.<.ctor>b__1_0()", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_0019
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: ret
}
");
}
[Fact]
public void FixedStatementWithBranchOut_LoopBreak()
{
var text = @"
unsafe class C
{
void Test()
{
while(true)
{
fixed (char* p = ""hello"")
{
break;
}
}
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 27 (0x1b)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: nop
.try
{
IL_0001: ldstr ""hello""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_0015
IL_000d: ldloc.0
IL_000e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0013: add
IL_0014: stloc.0
IL_0015: leave.s IL_001a
}
finally
{
IL_0017: ldnull
IL_0018: stloc.1
IL_0019: endfinally
}
IL_001a: ret
}
");
}
[Fact]
public void FixedStatementWithBranchOut_LoopContinue()
{
var text = @"
unsafe class C
{
void Test()
{
while(true)
{
fixed (char* p = ""hello"")
{
continue;
}
}
}
}
";
// Cleanup in finally.
// CONSIDER: dev11 doesn't have a finally here, but that seems incorrect.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: nop
.try
{
IL_0001: ldstr ""hello""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_0015
IL_000d: ldloc.0
IL_000e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0013: add
IL_0014: stloc.0
IL_0015: leave.s IL_0000
}
finally
{
IL_0017: ldnull
IL_0018: stloc.1
IL_0019: endfinally
}
}
");
}
[Fact]
public void FixedStatementWithBranchOut_SwitchBreak()
{
var text = @"
unsafe class C
{
void Test()
{
switch (1)
{
case 1:
fixed (char* p = ""hello"")
{
break;
}
}
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 27 (0x1b)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: nop
.try
{
IL_0001: ldstr ""hello""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_0015
IL_000d: ldloc.0
IL_000e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0013: add
IL_0014: stloc.0
IL_0015: leave.s IL_001a
}
finally
{
IL_0017: ldnull
IL_0018: stloc.1
IL_0019: endfinally
}
IL_001a: ret
}
");
}
[Fact]
public void FixedStatementWithBranchOut_SwitchGoto()
{
var text = @"
unsafe class C
{
void Test()
{
switch (1)
{
case 1:
fixed (char* p = ""hello"")
{
goto case 1;
}
}
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: nop
.try
{
IL_0001: ldstr ""hello""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_0015
IL_000d: ldloc.0
IL_000e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0013: add
IL_0014: stloc.0
IL_0015: leave.s IL_0000
}
finally
{
IL_0017: ldnull
IL_0018: stloc.1
IL_0019: endfinally
}
}
");
}
[Fact]
public void FixedStatementWithBranchOut_BackwardGoto()
{
var text = @"
unsafe class C
{
void Test()
{
label:
fixed (char* p = ""hello"")
{
goto label;
}
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: nop
.try
{
IL_0001: ldstr ""hello""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_0015
IL_000d: ldloc.0
IL_000e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0013: add
IL_0014: stloc.0
IL_0015: leave.s IL_0000
}
finally
{
IL_0017: ldnull
IL_0018: stloc.1
IL_0019: endfinally
}
}
");
}
[Fact]
public void FixedStatementWithBranchOut_ForwardGoto()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p = ""hello"")
{
goto label;
}
label: ;
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_0019
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: ret
}
");
}
[Fact]
public void FixedStatementWithBranchOut_Throw()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p = ""hello"")
{
throw null;
}
}
}
";
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldnull
IL_0015: throw
}
");
}
[Fact]
public void FixedStatementWithBranchOut_Return()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p = ""hello"")
{
return;
}
}
}
";
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 21 (0x15)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ret
}
");
}
[Fact]
public void FixedStatementWithNoBranchOut_Loop()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p = ""hello"")
{
for (int i = 0; i < 10; i++)
{
}
}
}
}
";
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 36 (0x24)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1,
int V_2) //i
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldc.i4.0
IL_0015: stloc.2
IL_0016: br.s IL_001c
IL_0018: ldloc.2
IL_0019: ldc.i4.1
IL_001a: add
IL_001b: stloc.2
IL_001c: ldloc.2
IL_001d: ldc.i4.s 10
IL_001f: blt.s IL_0018
IL_0021: ldnull
IL_0022: stloc.1
IL_0023: ret
}
");
}
[Fact]
public void FixedStatementWithNoBranchOut_InternalGoto()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p = ""hello"")
{
goto label;
label: ;
}
}
}
";
// NOTE: Dev11 uses a finally here, but it's unnecessary.
// From GotoChecker::VisitGOTO:
// We have an unrealized goto, so we do not know whether it
// branches out or not. We should be conservative and assume that
// it does.
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 23 (0x17)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldnull
IL_0015: stloc.1
IL_0016: ret
}
");
}
[Fact]
public void FixedStatementWithNoBranchOut_Switch()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p = ""hello"")
{
switch(*p)
{
case 'a':
Test();
goto case 'b';
case 'b':
Test();
goto case 'c';
case 'c':
Test();
goto case 'd';
case 'd':
Test();
goto case 'e';
case 'e':
Test();
goto case 'f';
case 'f':
Test();
goto default;
default:
Test();
break;
}
}
}
}
";
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 103 (0x67)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1,
char V_2)
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldloc.0
IL_0015: ldind.u2
IL_0016: stloc.2
IL_0017: ldloc.2
IL_0018: ldc.i4.s 97
IL_001a: sub
IL_001b: switch (
IL_003a,
IL_0040,
IL_0046,
IL_004c,
IL_0052,
IL_0058)
IL_0038: br.s IL_005e
IL_003a: ldarg.0
IL_003b: call ""void C.Test()""
IL_0040: ldarg.0
IL_0041: call ""void C.Test()""
IL_0046: ldarg.0
IL_0047: call ""void C.Test()""
IL_004c: ldarg.0
IL_004d: call ""void C.Test()""
IL_0052: ldarg.0
IL_0053: call ""void C.Test()""
IL_0058: ldarg.0
IL_0059: call ""void C.Test()""
IL_005e: ldarg.0
IL_005f: call ""void C.Test()""
IL_0064: ldnull
IL_0065: stloc.1
IL_0066: ret
}
");
}
[Fact]
public void FixedStatementWithParenthesizedStringExpression()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p = ((""hello"")))
{
}
}
}";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 23 (0x17)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldnull
IL_0015: stloc.1
IL_0016: ret
}
");
}
#endregion Fixed statement tests
#region Custom fixed statement tests
[Fact]
public void SimpleCaseOfCustomFixed()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable())
{
System.Console.WriteLine(p[1]);
}
}
}
class Fixable
{
public ref int GetPinnableReference()
{
return ref (new int[]{1,2,3})[0];
}
}
static class FixableExt
{
public static ref int GetPinnableReference(this Fixable self)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"2", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (pinned int& V_0)
IL_0000: newobj ""Fixable..ctor()""
IL_0005: dup
IL_0006: brtrue.s IL_000d
IL_0008: pop
IL_0009: ldc.i4.0
IL_000a: conv.u
IL_000b: br.s IL_0015
IL_000d: call ""ref int Fixable.GetPinnableReference()""
IL_0012: stloc.0
IL_0013: ldloc.0
IL_0014: conv.u
IL_0015: ldc.i4.4
IL_0016: add
IL_0017: ldind.i4
IL_0018: call ""void System.Console.WriteLine(int)""
IL_001d: ldc.i4.0
IL_001e: conv.u
IL_001f: stloc.0
IL_0020: ret
}
");
}
[Fact]
public void SimpleCaseOfCustomFixedExt()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable())
{
System.Console.WriteLine(p[1]);
}
}
}
class Fixable
{
public ref int GetPinnableReference<T>() => throw null;
}
static class FixableExt
{
public static ref int GetPinnableReference<T>(this T self)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"2", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (pinned int& V_0)
IL_0000: newobj ""Fixable..ctor()""
IL_0005: dup
IL_0006: brtrue.s IL_000d
IL_0008: pop
IL_0009: ldc.i4.0
IL_000a: conv.u
IL_000b: br.s IL_0015
IL_000d: call ""ref int FixableExt.GetPinnableReference<Fixable>(Fixable)""
IL_0012: stloc.0
IL_0013: ldloc.0
IL_0014: conv.u
IL_0015: ldc.i4.4
IL_0016: add
IL_0017: ldind.i4
IL_0018: call ""void System.Console.WriteLine(int)""
IL_001d: ldc.i4.0
IL_001e: conv.u
IL_001f: stloc.0
IL_0020: ret
}
");
}
[Fact]
public void SimpleCaseOfCustomFixed_oldVersion()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable())
{
System.Console.WriteLine(p[1]);
}
}
class Fixable
{
public ref int GetPinnableReference()
{
return ref (new int[]{1,2,3})[0];
}
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe, parseOptions: TestOptions.Regular7_2);
compVerifier.VerifyDiagnostics(
// (6,25): error CS8320: Feature 'extensible fixed statement' is not available in C# 7.2. Please use language version 7.3 or greater.
// fixed (int* p = new Fixable())
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "new Fixable()").WithArguments("extensible fixed statement", "7.3").WithLocation(6, 25)
);
}
[Fact]
public void SimpleCaseOfCustomFixedNull()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = (Fixable)null)
{
System.Console.WriteLine((int)p);
}
}
class Fixable
{
public ref int GetPinnableReference()
{
return ref (new int[]{1,2,3})[0];
}
}
}";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"0", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 26 (0x1a)
.maxstack 1
.locals init (pinned int& V_0)
IL_0000: ldnull
IL_0001: brtrue.s IL_0007
IL_0003: ldc.i4.0
IL_0004: conv.u
IL_0005: br.s IL_0010
IL_0007: ldnull
IL_0008: call ""ref int C.Fixable.GetPinnableReference()""
IL_000d: stloc.0
IL_000e: ldloc.0
IL_000f: conv.u
IL_0010: conv.i4
IL_0011: call ""void System.Console.WriteLine(int)""
IL_0016: ldc.i4.0
IL_0017: conv.u
IL_0018: stloc.0
IL_0019: ret
}
");
}
[Fact]
public void SimpleCaseOfCustomFixedStruct()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable())
{
System.Console.WriteLine(p[1]);
}
}
struct Fixable
{
public ref int GetPinnableReference()
{
return ref (new int[]{1,2,3})[0];
}
}
}";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"2", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 29 (0x1d)
.maxstack 2
.locals init (pinned int& V_0,
C.Fixable V_1)
IL_0000: ldloca.s V_1
IL_0002: dup
IL_0003: initobj ""C.Fixable""
IL_0009: call ""ref int C.Fixable.GetPinnableReference()""
IL_000e: stloc.0
IL_000f: ldloc.0
IL_0010: conv.u
IL_0011: ldc.i4.4
IL_0012: add
IL_0013: ldind.i4
IL_0014: call ""void System.Console.WriteLine(int)""
IL_0019: ldc.i4.0
IL_001a: conv.u
IL_001b: stloc.0
IL_001c: ret
}
");
}
[Fact]
public void CustomFixedStructNullable()
{
var text = @"
unsafe class C
{
public static void Main()
{
Fixable? f = new Fixable();
fixed (int* p = f)
{
System.Console.WriteLine(p[1]);
}
}
}
public struct Fixable
{
public ref int GetPinnableReference()
{
return ref (new int[]{1,2,3})[0];
}
}
public static class FixableExt
{
public static ref int GetPinnableReference(this Fixable? f)
{
return ref f.Value.GetPinnableReference();
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"2", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 34 (0x22)
.maxstack 2
.locals init (Fixable V_0,
pinned int& V_1)
IL_0000: ldloca.s V_0
IL_0002: initobj ""Fixable""
IL_0008: ldloc.0
IL_0009: newobj ""Fixable?..ctor(Fixable)""
IL_000e: call ""ref int FixableExt.GetPinnableReference(Fixable?)""
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: conv.u
IL_0016: ldc.i4.4
IL_0017: add
IL_0018: ldind.i4
IL_0019: call ""void System.Console.WriteLine(int)""
IL_001e: ldc.i4.0
IL_001f: conv.u
IL_0020: stloc.1
IL_0021: ret
}
");
}
[Fact]
public void CustomFixedStructNullableErr()
{
var text = @"
unsafe class C
{
public static void Main()
{
Fixable? f = new Fixable();
fixed (int* p = f)
{
System.Console.WriteLine(p[1]);
}
}
}
public struct Fixable
{
public ref int GetPinnableReference()
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (8,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = f)
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "f").WithLocation(8, 25)
);
}
[Fact]
public void CustomFixedErrAmbiguous()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
var f = new Fixable(1);
fixed (int* p = f)
{
System.Console.Write(p[2]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
public static ref readonly int GetPinnableReference(in this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
public static class FixableExt1
{
public static ref readonly int GetPinnableReference(in this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS0121: The call is ambiguous between the following methods or properties: 'FixableExt.GetPinnableReference(in Fixable)' and 'FixableExt1.GetPinnableReference(in Fixable)'
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_AmbigCall, "new Fixable(1)").WithArguments("FixableExt.GetPinnableReference(in Fixable)", "FixableExt1.GetPinnableReference(in Fixable)").WithLocation(6, 25),
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25),
// (12,25): error CS0121: The call is ambiguous between the following methods or properties: 'FixableExt.GetPinnableReference(in Fixable)' and 'FixableExt1.GetPinnableReference(in Fixable)'
// fixed (int* p = f)
Diagnostic(ErrorCode.ERR_AmbigCall, "f").WithArguments("FixableExt.GetPinnableReference(in Fixable)", "FixableExt1.GetPinnableReference(in Fixable)").WithLocation(12, 25),
// (12,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = f)
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "f").WithLocation(12, 25)
);
}
[Fact]
public void CustomFixedErrDynamic()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = (dynamic)(new Fixable(1)))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
public static ref readonly int GetPinnableReference(in this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = (dynamic)(new Fixable(1)))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "(dynamic)(new Fixable(1))").WithLocation(6, 25)
);
}
[Fact]
public void CustomFixedErrBad()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = (HocusPocus)(new Fixable(1)))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
public static ref readonly int GetPinnableReference(in this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,26): error CS0246: The type or namespace name 'HocusPocus' could not be found (are you missing a using directive or an assembly reference?)
// fixed (int* p = (HocusPocus)(new Fixable(1)))
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "HocusPocus").WithArguments("HocusPocus").WithLocation(6, 26)
);
}
[Fact]
public void SimpleCaseOfCustomFixedGeneric()
{
var text = @"
unsafe class C
{
public static void Main()
{
Test(42);
Test((object)null);
}
public static void Test<T>(T arg)
{
fixed (int* p = arg)
{
System.Console.Write(p == null? 0: p[1]);
}
}
}
static class FixAllExt
{
public static ref int GetPinnableReference<T>(this T dummy)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"20", verify: Verification.Fails);
compVerifier.VerifyIL("C.Test<T>(T)", @"
{
// Code size 49 (0x31)
.maxstack 2
.locals init (int* V_0, //p
pinned int& V_1)
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: brtrue.s IL_000c
IL_0008: ldc.i4.0
IL_0009: conv.u
IL_000a: br.s IL_001b
IL_000c: ldarga.s V_0
IL_000e: ldobj ""T""
IL_0013: call ""ref int FixAllExt.GetPinnableReference<T>(T)""
IL_0018: stloc.1
IL_0019: ldloc.1
IL_001a: conv.u
IL_001b: stloc.0
IL_001c: ldloc.0
IL_001d: ldc.i4.0
IL_001e: conv.u
IL_001f: beq.s IL_0027
IL_0021: ldloc.0
IL_0022: ldc.i4.4
IL_0023: add
IL_0024: ldind.i4
IL_0025: br.s IL_0028
IL_0027: ldc.i4.0
IL_0028: call ""void System.Console.Write(int)""
IL_002d: ldc.i4.0
IL_002e: conv.u
IL_002f: stloc.1
IL_0030: ret
}
");
}
[Fact]
public void CustomFixedStructSideeffects()
{
var text = @"
unsafe class C
{
public static void Main()
{
var b = new FixableStruct();
Test(ref b);
System.Console.WriteLine(b.x);
}
public static void Test(ref FixableStruct arg)
{
fixed (int* p = arg)
{
System.Console.Write(p[1]);
}
}
}
struct FixableStruct
{
public int x;
public ref int GetPinnableReference()
{
x = 456;
return ref (new int[] { 4, 5, 6 })[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"5456");
compVerifier.VerifyIL("C.Test(ref FixableStruct)", @"
{
// Code size 21 (0x15)
.maxstack 2
.locals init (pinned int& V_0)
IL_0000: ldarg.0
IL_0001: call ""ref int FixableStruct.GetPinnableReference()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: conv.u
IL_0009: ldc.i4.4
IL_000a: add
IL_000b: ldind.i4
IL_000c: call ""void System.Console.Write(int)""
IL_0011: ldc.i4.0
IL_0012: conv.u
IL_0013: stloc.0
IL_0014: ret
}
");
}
[Fact]
public void CustomFixedClassSideeffects()
{
var text = @"
using System;
unsafe class C
{
public static void Main()
{
var b = new FixableClass();
Test(ref b);
System.Console.WriteLine(b.x);
}
public static void Test(ref FixableClass arg)
{
fixed (int* p = arg)
{
System.Console.Write(p[1]);
}
}
}
class FixableClass
{
public int x;
[Obsolete]
public ref int GetPinnableReference()
{
x = 456;
return ref (new int[] { 4, 5, 6 })[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"5456");
compVerifier.VerifyDiagnostics(
// (14,29): warning CS0612: 'FixableClass.GetPinnableReference()' is obsolete
// fixed (int* p = arg)
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "arg").WithArguments("FixableClass.GetPinnableReference()").WithLocation(14, 29)
);
// note that defensive copy is created
compVerifier.VerifyIL("C.Test(ref FixableClass)", @"
{
// Code size 30 (0x1e)
.maxstack 2
.locals init (pinned int& V_0)
IL_0000: ldarg.0
IL_0001: ldind.ref
IL_0002: dup
IL_0003: brtrue.s IL_000a
IL_0005: pop
IL_0006: ldc.i4.0
IL_0007: conv.u
IL_0008: br.s IL_0012
IL_000a: call ""ref int FixableClass.GetPinnableReference()""
IL_000f: stloc.0
IL_0010: ldloc.0
IL_0011: conv.u
IL_0012: ldc.i4.4
IL_0013: add
IL_0014: ldind.i4
IL_0015: call ""void System.Console.Write(int)""
IL_001a: ldc.i4.0
IL_001b: conv.u
IL_001c: stloc.0
IL_001d: ret
}
");
}
[Fact]
public void CustomFixedGenericSideeffects()
{
var text = @"
unsafe class C
{
public static void Main()
{
var a = new FixableClass();
Test(ref a);
System.Console.WriteLine(a.x);
var b = new FixableStruct();
Test(ref b);
System.Console.WriteLine(b.x);
}
public static void Test<T>(ref T arg) where T: IFixable
{
fixed (int* p = arg)
{
System.Console.Write(p[1]);
}
}
}
interface IFixable
{
ref int GetPinnableReference();
}
class FixableClass : IFixable
{
public int x;
public ref int GetPinnableReference()
{
x = 123;
return ref (new int[] { 1, 2, 3 })[0];
}
}
struct FixableStruct : IFixable
{
public int x;
public ref int GetPinnableReference()
{
x = 456;
return ref (new int[] { 4, 5, 6 })[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"2123
5456");
compVerifier.VerifyIL("C.Test<T>(ref T)", @"
{
// Code size 64 (0x40)
.maxstack 2
.locals init (pinned int& V_0,
T V_1)
IL_0000: ldarg.0
IL_0001: ldloca.s V_1
IL_0003: initobj ""T""
IL_0009: ldloc.1
IL_000a: box ""T""
IL_000f: brtrue.s IL_0026
IL_0011: ldobj ""T""
IL_0016: stloc.1
IL_0017: ldloca.s V_1
IL_0019: ldloc.1
IL_001a: box ""T""
IL_001f: brtrue.s IL_0026
IL_0021: pop
IL_0022: ldc.i4.0
IL_0023: conv.u
IL_0024: br.s IL_0034
IL_0026: constrained. ""T""
IL_002c: callvirt ""ref int IFixable.GetPinnableReference()""
IL_0031: stloc.0
IL_0032: ldloc.0
IL_0033: conv.u
IL_0034: ldc.i4.4
IL_0035: add
IL_0036: ldind.i4
IL_0037: call ""void System.Console.Write(int)""
IL_003c: ldc.i4.0
IL_003d: conv.u
IL_003e: stloc.0
IL_003f: ret
}
");
}
[Fact]
public void CustomFixedGenericRefExtension()
{
var text = @"
unsafe class C
{
public static void Main()
{
var b = new FixableStruct();
Test(ref b);
System.Console.WriteLine(b.x);
}
public static void Test<T>(ref T arg) where T: struct, IFixable
{
fixed (int* p = arg)
{
System.Console.Write(p[1]);
}
}
}
public interface IFixable
{
ref int GetPinnableReferenceImpl();
}
public struct FixableStruct : IFixable
{
public int x;
public ref int GetPinnableReferenceImpl()
{
x = 456;
return ref (new int[] { 4, 5, 6 })[0];
}
}
public static class FixableExt
{
public static ref int GetPinnableReference<T>(ref this T f) where T: struct, IFixable
{
return ref f.GetPinnableReferenceImpl();
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"5456");
compVerifier.VerifyIL("C.Test<T>(ref T)", @"
{
// Code size 21 (0x15)
.maxstack 2
.locals init (pinned int& V_0)
IL_0000: ldarg.0
IL_0001: call ""ref int FixableExt.GetPinnableReference<T>(ref T)""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: conv.u
IL_0009: ldc.i4.4
IL_000a: add
IL_000b: ldind.i4
IL_000c: call ""void System.Console.Write(int)""
IL_0011: ldc.i4.0
IL_0012: conv.u
IL_0013: stloc.0
IL_0014: ret
}
");
}
[Fact]
public void CustomFixedStructInExtension()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
var f = new Fixable(1);
fixed (int* p = f)
{
System.Console.Write(p[2]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
public static ref readonly int GetPinnableReference(in this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"23", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 61 (0x3d)
.maxstack 3
.locals init (Fixable V_0, //f
pinned int& V_1,
Fixable V_2)
IL_0000: ldc.i4.1
IL_0001: newobj ""Fixable..ctor(int)""
IL_0006: stloc.2
IL_0007: ldloca.s V_2
IL_0009: call ""ref readonly int FixableExt.GetPinnableReference(in Fixable)""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: conv.u
IL_0011: ldc.i4.4
IL_0012: add
IL_0013: ldind.i4
IL_0014: call ""void System.Console.Write(int)""
IL_0019: ldc.i4.0
IL_001a: conv.u
IL_001b: stloc.1
IL_001c: ldloca.s V_0
IL_001e: ldc.i4.1
IL_001f: call ""Fixable..ctor(int)""
IL_0024: ldloca.s V_0
IL_0026: call ""ref readonly int FixableExt.GetPinnableReference(in Fixable)""
IL_002b: stloc.1
IL_002c: ldloc.1
IL_002d: conv.u
IL_002e: ldc.i4.2
IL_002f: conv.i
IL_0030: ldc.i4.4
IL_0031: mul
IL_0032: add
IL_0033: ldind.i4
IL_0034: call ""void System.Console.Write(int)""
IL_0039: ldc.i4.0
IL_003a: conv.u
IL_003b: stloc.1
IL_003c: ret
}
");
}
[Fact]
public void CustomFixedStructRefExtension()
{
var text = @"
unsafe class C
{
public static void Main()
{
var f = new Fixable(1);
fixed (int* p = f)
{
System.Console.Write(p[2]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
public static ref int GetPinnableReference(ref this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"3", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 33 (0x21)
.maxstack 3
.locals init (Fixable V_0, //f
pinned int& V_1)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: call ""Fixable..ctor(int)""
IL_0008: ldloca.s V_0
IL_000a: call ""ref int FixableExt.GetPinnableReference(ref Fixable)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: conv.u
IL_0012: ldc.i4.2
IL_0013: conv.i
IL_0014: ldc.i4.4
IL_0015: mul
IL_0016: add
IL_0017: ldind.i4
IL_0018: call ""void System.Console.Write(int)""
IL_001d: ldc.i4.0
IL_001e: conv.u
IL_001f: stloc.1
IL_0020: ret
}
");
}
[Fact]
public void CustomFixedStructRefExtensionErr()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
public static ref int GetPinnableReference(ref this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS1510: A ref or out value must be an assignable variable
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "new Fixable(1)").WithLocation(6, 25),
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25)
);
}
[Fact]
public void CustomFixedStructVariousErr01()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
private static ref int GetPinnableReference(this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS8385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25)
);
}
[Fact]
public void CustomFixedStructVariousErr01_oldVersion()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
private static ref int GetPinnableReference(this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe, parseOptions: TestOptions.Regular7_2);
compVerifier.VerifyDiagnostics(
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25)
);
}
[Fact]
public void CustomFixedStructVariousErr02()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
public static ref int GetPinnableReference()
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25),
// (6,25): error CS0176: Member 'Fixable.GetPinnableReference()' cannot be accessed with an instance reference; qualify it with a type name instead
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ObjectProhibited, "new Fixable(1)").WithArguments("Fixable.GetPinnableReference()").WithLocation(6, 25)
);
}
[Fact]
public void CustomFixedStructVariousErr03()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
public ref int GetPinnableReference => ref (new int[]{1,2,3})[0];
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS1955: Non-invocable member 'Fixable.GetPinnableReference' cannot be used like a method.
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "new Fixable(1)").WithArguments("Fixable.GetPinnableReference").WithLocation(6, 25),
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25)
);
}
[Fact]
public void CustomFixedStructVariousErr04()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
public ref int GetPinnableReference<T>() => ref (new int[]{1,2,3})[0];
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS0411: The type arguments for method 'Fixable.GetPinnableReference<T>()' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "new Fixable(1)").WithArguments("Fixable.GetPinnableReference<T>()").WithLocation(6, 25),
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25)
);
}
[Fact]
public void CustomFixedStructVariousErr05_Obsolete()
{
var text = @"
using System;
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
[Obsolete(""hi"", true)]
public ref int GetPinnableReference() => ref (new int[]{1,2,3})[0];
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (8,25): error CS0619: 'Fixable.GetPinnableReference()' is obsolete: 'hi'
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "new Fixable(1)").WithArguments("Fixable.GetPinnableReference()", "hi").WithLocation(8, 25)
);
}
[Fact]
public void CustomFixedStructVariousErr06_UseSite()
{
var missing_cs = "public struct Missing { }";
var missing = CreateCompilationWithMscorlib45(missing_cs, options: TestOptions.DebugDll, assemblyName: "missing");
var lib_cs = @"
public struct Fixable
{
public Fixable(int arg){}
public ref Missing GetPinnableReference() => throw null;
}
";
var lib = CreateCompilationWithMscorlib45(lib_cs, references: new[] { missing.EmitToImageReference() }, options: TestOptions.DebugDll);
var source =
@"
unsafe class C
{
public static void Main()
{
fixed (void* p = new Fixable(1))
{
}
}
}
";
var comp = CreateCompilationWithMscorlib45(source, references: new[] { lib.EmitToImageReference() }, options: TestOptions.UnsafeDebugDll);
comp.VerifyDiagnostics(
// (6,26): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// fixed (void* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_NoTypeDef, "new Fixable(1)").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 26),
// (6,26): error CS9385: The given expression cannot be used in a fixed statement
// fixed (void* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 26)
);
}
[Fact]
public void CustomFixedStructVariousErr07_Optional()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
public ref int GetPinnableReference(int x = 0) => ref (new int[]{1,2,3})[0];
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): warning CS0280: 'Fixable' does not implement the 'fixed' pattern. 'Fixable.GetPinnableReference(int)' has the wrong signature.
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.WRN_PatternBadSignature, "new Fixable(1)").WithArguments("Fixable", "fixed", "Fixable.GetPinnableReference(int)").WithLocation(6, 25),
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25)
);
}
[Fact]
public void FixStringMissingAllHelpers()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (char* p = string.Empty)
{
}
}
}
";
var comp = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
comp.MakeMemberMissing(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__get_OffsetToStringData);
comp.VerifyEmitDiagnostics(
// (6,26): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.RuntimeHelpers.get_OffsetToStringData'
// fixed (char* p = string.Empty)
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "string.Empty").WithArguments("System.Runtime.CompilerServices.RuntimeHelpers", "get_OffsetToStringData").WithLocation(6, 26)
);
}
[Fact]
public void FixStringArrayExtensionHelpersIgnored()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (char* p = ""A"")
{
*p = default;
}
fixed (char* p = new char[1])
{
*p = default;
}
}
}
public static class FixableExt
{
public static ref char GetPinnableReference(this string self) => throw null;
public static ref char GetPinnableReference(this char[] self) => throw null;
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"");
compVerifier.VerifyIL("C.Main()", @"
{
// Code size 60 (0x3c)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1,
char* V_2, //p
pinned char[] V_3)
IL_0000: ldstr ""A""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldloc.0
IL_0015: ldc.i4.0
IL_0016: stind.i2
IL_0017: ldnull
IL_0018: stloc.1
IL_0019: ldc.i4.1
IL_001a: newarr ""char""
IL_001f: dup
IL_0020: stloc.3
IL_0021: brfalse.s IL_0028
IL_0023: ldloc.3
IL_0024: ldlen
IL_0025: conv.i4
IL_0026: brtrue.s IL_002d
IL_0028: ldc.i4.0
IL_0029: conv.u
IL_002a: stloc.2
IL_002b: br.s IL_0036
IL_002d: ldloc.3
IL_002e: ldc.i4.0
IL_002f: ldelema ""char""
IL_0034: conv.u
IL_0035: stloc.2
IL_0036: ldloc.2
IL_0037: ldc.i4.0
IL_0038: stind.i2
IL_0039: ldnull
IL_003a: stloc.3
IL_003b: ret
}
");
}
[Fact]
public void CustomFixedDelegateErr()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable())
{
System.Console.Write(p[1]);
}
}
}
public delegate ref int ReturnsRef();
public struct Fixable
{
public Fixable(int arg){}
public ReturnsRef GetPinnableReference => null;
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable())
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable()").WithLocation(6, 25)
);
}
#endregion Custom fixed statement tests
#region Pointer conversion tests
[Fact]
public void ConvertNullToPointer()
{
var template = @"
using System;
unsafe class C
{{
static void Main()
{{
{0}
{{
char ch = 'a';
char* p = &ch;
Console.WriteLine(p == null);
p = null;
Console.WriteLine(p == null);
}}
}}
}}
";
var expectedIL = @"
{
// Code size 31 (0x1f)
.maxstack 2
.locals init (char V_0, //ch
char* V_1) //p
IL_0000: ldc.i4.s 97
IL_0002: stloc.0
IL_0003: ldloca.s V_0
IL_0005: conv.u
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: ldc.i4.0
IL_0009: conv.u
IL_000a: ceq
IL_000c: call ""void System.Console.WriteLine(bool)""
IL_0011: ldc.i4.0
IL_0012: conv.u
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: ldc.i4.0
IL_0016: conv.u
IL_0017: ceq
IL_0019: call ""void System.Console.WriteLine(bool)""
IL_001e: ret
}
";
var expectedOutput = @"False
True";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL);
CompileAndVerify(string.Format(template, "checked"), options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL);
}
[Fact]
public void ConvertPointerToPointerOrVoid()
{
var template = @"
using System;
unsafe class C
{{
static void Main()
{{
{0}
{{
char ch = 'a';
char* c1 = &ch;
void* v1 = c1;
void* v2 = (void**)v1;
char* c2 = (char*)v2;
Console.WriteLine(*c2);
}}
}}
}}
";
var expectedIL = @"
{
// Code size 19 (0x13)
.maxstack 1
.locals init (char V_0, //ch
void* V_1, //v1
void* V_2, //v2
char* V_3) //c2
IL_0000: ldc.i4.s 97
IL_0002: stloc.0
IL_0003: ldloca.s V_0
IL_0005: conv.u
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: stloc.2
IL_0009: ldloc.2
IL_000a: stloc.3
IL_000b: ldloc.3
IL_000c: ldind.u2
IL_000d: call ""void System.Console.WriteLine(char)""
IL_0012: ret
}
";
var expectedOutput = @"a";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL);
CompileAndVerify(string.Format(template, "checked"), options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL);
}
[Fact]
public void ConvertPointerToNumericUnchecked()
{
var text = @"
using System;
unsafe class C
{
void M(int* pi, void* pv, sbyte sb, byte b, short s, ushort us, int i, uint ui, long l, ulong ul)
{
unchecked
{
sb = (sbyte)pi;
b = (byte)pi;
s = (short)pi;
us = (ushort)pi;
i = (int)pi;
ui = (uint)pi;
l = (long)pi;
ul = (ulong)pi;
sb = (sbyte)pv;
b = (byte)pv;
s = (short)pv;
us = (ushort)pv;
i = (int)pv;
ui = (uint)pv;
l = (long)pv;
ul = (ulong)pv;
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", @"
{
// Code size 65 (0x41)
.maxstack 1
IL_0000: ldarg.1
IL_0001: conv.i1
IL_0002: starg.s V_3
IL_0004: ldarg.1
IL_0005: conv.u1
IL_0006: starg.s V_4
IL_0008: ldarg.1
IL_0009: conv.i2
IL_000a: starg.s V_5
IL_000c: ldarg.1
IL_000d: conv.u2
IL_000e: starg.s V_6
IL_0010: ldarg.1
IL_0011: conv.i4
IL_0012: starg.s V_7
IL_0014: ldarg.1
IL_0015: conv.u4
IL_0016: starg.s V_8
IL_0018: ldarg.1
IL_0019: conv.u8
IL_001a: starg.s V_9
IL_001c: ldarg.1
IL_001d: conv.u8
IL_001e: starg.s V_10
IL_0020: ldarg.2
IL_0021: conv.i1
IL_0022: starg.s V_3
IL_0024: ldarg.2
IL_0025: conv.u1
IL_0026: starg.s V_4
IL_0028: ldarg.2
IL_0029: conv.i2
IL_002a: starg.s V_5
IL_002c: ldarg.2
IL_002d: conv.u2
IL_002e: starg.s V_6
IL_0030: ldarg.2
IL_0031: conv.i4
IL_0032: starg.s V_7
IL_0034: ldarg.2
IL_0035: conv.u4
IL_0036: starg.s V_8
IL_0038: ldarg.2
IL_0039: conv.u8
IL_003a: starg.s V_9
IL_003c: ldarg.2
IL_003d: conv.u8
IL_003e: starg.s V_10
IL_0040: ret
}
");
}
[Fact]
public void ConvertPointerToNumericChecked()
{
var text = @"
using System;
unsafe class C
{
void M(int* pi, void* pv, sbyte sb, byte b, short s, ushort us, int i, uint ui, long l, ulong ul)
{
checked
{
sb = (sbyte)pi;
b = (byte)pi;
s = (short)pi;
us = (ushort)pi;
i = (int)pi;
ui = (uint)pi;
l = (long)pi;
ul = (ulong)pi;
sb = (sbyte)pv;
b = (byte)pv;
s = (short)pv;
us = (ushort)pv;
i = (int)pv;
ui = (uint)pv;
l = (long)pv;
ul = (ulong)pv;
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", @"
{
// Code size 65 (0x41)
.maxstack 1
IL_0000: ldarg.1
IL_0001: conv.ovf.i1.un
IL_0002: starg.s V_3
IL_0004: ldarg.1
IL_0005: conv.ovf.u1.un
IL_0006: starg.s V_4
IL_0008: ldarg.1
IL_0009: conv.ovf.i2.un
IL_000a: starg.s V_5
IL_000c: ldarg.1
IL_000d: conv.ovf.u2.un
IL_000e: starg.s V_6
IL_0010: ldarg.1
IL_0011: conv.ovf.i4.un
IL_0012: starg.s V_7
IL_0014: ldarg.1
IL_0015: conv.ovf.u4.un
IL_0016: starg.s V_8
IL_0018: ldarg.1
IL_0019: conv.ovf.i8.un
IL_001a: starg.s V_9
IL_001c: ldarg.1
IL_001d: conv.u8
IL_001e: starg.s V_10
IL_0020: ldarg.2
IL_0021: conv.ovf.i1.un
IL_0022: starg.s V_3
IL_0024: ldarg.2
IL_0025: conv.ovf.u1.un
IL_0026: starg.s V_4
IL_0028: ldarg.2
IL_0029: conv.ovf.i2.un
IL_002a: starg.s V_5
IL_002c: ldarg.2
IL_002d: conv.ovf.u2.un
IL_002e: starg.s V_6
IL_0030: ldarg.2
IL_0031: conv.ovf.i4.un
IL_0032: starg.s V_7
IL_0034: ldarg.2
IL_0035: conv.ovf.u4.un
IL_0036: starg.s V_8
IL_0038: ldarg.2
IL_0039: conv.ovf.i8.un
IL_003a: starg.s V_9
IL_003c: ldarg.2
IL_003d: conv.u8
IL_003e: starg.s V_10
IL_0040: ret
}
");
}
[Fact]
public void ConvertNumericToPointerUnchecked()
{
var text = @"
using System;
unsafe class C
{
void M(int* pi, void* pv, sbyte sb, byte b, short s, ushort us, int i, uint ui, long l, ulong ul)
{
unchecked
{
pi = (int*)sb;
pi = (int*)b;
pi = (int*)s;
pi = (int*)us;
pi = (int*)i;
pi = (int*)ui;
pi = (int*)l;
pi = (int*)ul;
pv = (void*)sb;
pv = (void*)b;
pv = (void*)s;
pv = (void*)us;
pv = (void*)i;
pv = (void*)ui;
pv = (void*)l;
pv = (void*)ul;
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", @"
{
// Code size 79 (0x4f)
.maxstack 1
IL_0000: ldarg.3
IL_0001: conv.i
IL_0002: starg.s V_1
IL_0004: ldarg.s V_4
IL_0006: conv.u
IL_0007: starg.s V_1
IL_0009: ldarg.s V_5
IL_000b: conv.i
IL_000c: starg.s V_1
IL_000e: ldarg.s V_6
IL_0010: conv.u
IL_0011: starg.s V_1
IL_0013: ldarg.s V_7
IL_0015: conv.i
IL_0016: starg.s V_1
IL_0018: ldarg.s V_8
IL_001a: conv.u
IL_001b: starg.s V_1
IL_001d: ldarg.s V_9
IL_001f: conv.u
IL_0020: starg.s V_1
IL_0022: ldarg.s V_10
IL_0024: conv.u
IL_0025: starg.s V_1
IL_0027: ldarg.3
IL_0028: conv.i
IL_0029: starg.s V_2
IL_002b: ldarg.s V_4
IL_002d: conv.u
IL_002e: starg.s V_2
IL_0030: ldarg.s V_5
IL_0032: conv.i
IL_0033: starg.s V_2
IL_0035: ldarg.s V_6
IL_0037: conv.u
IL_0038: starg.s V_2
IL_003a: ldarg.s V_7
IL_003c: conv.i
IL_003d: starg.s V_2
IL_003f: ldarg.s V_8
IL_0041: conv.u
IL_0042: starg.s V_2
IL_0044: ldarg.s V_9
IL_0046: conv.u
IL_0047: starg.s V_2
IL_0049: ldarg.s V_10
IL_004b: conv.u
IL_004c: starg.s V_2
IL_004e: ret
}
");
}
[Fact]
public void ConvertNumericToPointerChecked()
{
var text = @"
using System;
unsafe class C
{
void M(int* pi, void* pv, sbyte sb, byte b, short s, ushort us, int i, uint ui, long l, ulong ul)
{
checked
{
pi = (int*)sb;
pi = (int*)b;
pi = (int*)s;
pi = (int*)us;
pi = (int*)i;
pi = (int*)ui;
pi = (int*)l;
pi = (int*)ul;
pv = (void*)sb;
pv = (void*)b;
pv = (void*)s;
pv = (void*)us;
pv = (void*)i;
pv = (void*)ui;
pv = (void*)l;
pv = (void*)ul;
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", @"
{
// Code size 79 (0x4f)
.maxstack 1
IL_0000: ldarg.3
IL_0001: conv.ovf.u
IL_0002: starg.s V_1
IL_0004: ldarg.s V_4
IL_0006: conv.u
IL_0007: starg.s V_1
IL_0009: ldarg.s V_5
IL_000b: conv.ovf.u
IL_000c: starg.s V_1
IL_000e: ldarg.s V_6
IL_0010: conv.u
IL_0011: starg.s V_1
IL_0013: ldarg.s V_7
IL_0015: conv.ovf.u
IL_0016: starg.s V_1
IL_0018: ldarg.s V_8
IL_001a: conv.u
IL_001b: starg.s V_1
IL_001d: ldarg.s V_9
IL_001f: conv.ovf.u
IL_0020: starg.s V_1
IL_0022: ldarg.s V_10
IL_0024: conv.ovf.u.un
IL_0025: starg.s V_1
IL_0027: ldarg.3
IL_0028: conv.ovf.u
IL_0029: starg.s V_2
IL_002b: ldarg.s V_4
IL_002d: conv.u
IL_002e: starg.s V_2
IL_0030: ldarg.s V_5
IL_0032: conv.ovf.u
IL_0033: starg.s V_2
IL_0035: ldarg.s V_6
IL_0037: conv.u
IL_0038: starg.s V_2
IL_003a: ldarg.s V_7
IL_003c: conv.ovf.u
IL_003d: starg.s V_2
IL_003f: ldarg.s V_8
IL_0041: conv.u
IL_0042: starg.s V_2
IL_0044: ldarg.s V_9
IL_0046: conv.ovf.u
IL_0047: starg.s V_2
IL_0049: ldarg.s V_10
IL_004b: conv.ovf.u.un
IL_004c: starg.s V_2
IL_004e: ret
}
");
}
[Fact]
public void ConvertClassToPointerUDC()
{
var template = @"
using System;
unsafe class C
{{
void M(int* pi, void* pv, Explicit e, Implicit i)
{{
{0}
{{
e = (Explicit)pi;
e = (Explicit)pv;
i = pi;
i = pv;
pi = (int*)e;
pv = (int*)e;
pi = i;
pv = i;
}}
}}
}}
unsafe class Explicit
{{
public static explicit operator Explicit(void* p)
{{
return null;
}}
public static explicit operator int*(Explicit e)
{{
return null;
}}
}}
unsafe class Implicit
{{
public static implicit operator Implicit(void* p)
{{
return null;
}}
public static implicit operator int*(Implicit e)
{{
return null;
}}
}}
";
var expectedIL = @"
{
// Code size 67 (0x43)
.maxstack 1
IL_0000: ldarg.1
IL_0001: call ""Explicit Explicit.op_Explicit(void*)""
IL_0006: starg.s V_3
IL_0008: ldarg.2
IL_0009: call ""Explicit Explicit.op_Explicit(void*)""
IL_000e: starg.s V_3
IL_0010: ldarg.1
IL_0011: call ""Implicit Implicit.op_Implicit(void*)""
IL_0016: starg.s V_4
IL_0018: ldarg.2
IL_0019: call ""Implicit Implicit.op_Implicit(void*)""
IL_001e: starg.s V_4
IL_0020: ldarg.3
IL_0021: call ""int* Explicit.op_Explicit(Explicit)""
IL_0026: starg.s V_1
IL_0028: ldarg.3
IL_0029: call ""int* Explicit.op_Explicit(Explicit)""
IL_002e: starg.s V_2
IL_0030: ldarg.s V_4
IL_0032: call ""int* Implicit.op_Implicit(Implicit)""
IL_0037: starg.s V_1
IL_0039: ldarg.s V_4
IL_003b: call ""int* Implicit.op_Implicit(Implicit)""
IL_0040: starg.s V_2
IL_0042: ret
}
";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", expectedIL);
CompileAndVerify(string.Format(template, "checked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", expectedIL);
}
[Fact]
public void ConvertIntPtrToPointer()
{
var template = @"
using System;
unsafe class C
{{
void M(int* pi, void* pv, IntPtr i, UIntPtr u)
{{
{0}
{{
i = (IntPtr)pi;
i = (IntPtr)pv;
u = (UIntPtr)pi;
u = (UIntPtr)pv;
pi = (int*)i;
pv = (int*)i;
pi = (int*)u;
pv = (int*)u;
}}
}}
}}
";
// Nothing special here - just more UDCs.
var expectedIL = @"
{
// Code size 67 (0x43)
.maxstack 1
IL_0000: ldarg.1
IL_0001: call ""System.IntPtr System.IntPtr.op_Explicit(void*)""
IL_0006: starg.s V_3
IL_0008: ldarg.2
IL_0009: call ""System.IntPtr System.IntPtr.op_Explicit(void*)""
IL_000e: starg.s V_3
IL_0010: ldarg.1
IL_0011: call ""System.UIntPtr System.UIntPtr.op_Explicit(void*)""
IL_0016: starg.s V_4
IL_0018: ldarg.2
IL_0019: call ""System.UIntPtr System.UIntPtr.op_Explicit(void*)""
IL_001e: starg.s V_4
IL_0020: ldarg.3
IL_0021: call ""void* System.IntPtr.op_Explicit(System.IntPtr)""
IL_0026: starg.s V_1
IL_0028: ldarg.3
IL_0029: call ""void* System.IntPtr.op_Explicit(System.IntPtr)""
IL_002e: starg.s V_2
IL_0030: ldarg.s V_4
IL_0032: call ""void* System.UIntPtr.op_Explicit(System.UIntPtr)""
IL_0037: starg.s V_1
IL_0039: ldarg.s V_4
IL_003b: call ""void* System.UIntPtr.op_Explicit(System.UIntPtr)""
IL_0040: starg.s V_2
IL_0042: ret
}
";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", expectedIL);
CompileAndVerify(string.Format(template, "checked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", expectedIL);
}
[Fact]
public void FixedStatementConversion()
{
var template = @"
using System;
unsafe class C
{{
char c = 'a';
char[] a = new char[1];
static void Main()
{{
{0}
{{
C c = new C();
fixed (void* p = &c.c, q = c.a, r = ""hello"")
{{
Console.Write((int)*(char*)p);
Console.Write((int)*(char*)q);
Console.Write((int)*(char*)r);
}}
}}
}}
}}
";
// NB: "pinned System.IntPtr&" (which ildasm displays as "pinned native int&"), not void.
var expectedIL = @"
{
// Code size 112 (0x70)
.maxstack 2
.locals init (C V_0, //c
void* V_1, //p
void* V_2, //q
void* V_3, //r
pinned char& V_4,
pinned char[] V_5,
pinned string V_6)
-IL_0000: nop
-IL_0001: nop
-IL_0002: newobj ""C..ctor()""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldflda ""char C.c""
IL_000e: stloc.s V_4
-IL_0010: ldloc.s V_4
IL_0012: conv.u
IL_0013: stloc.1
-IL_0014: ldloc.0
IL_0015: ldfld ""char[] C.a""
IL_001a: dup
IL_001b: stloc.s V_5
IL_001d: brfalse.s IL_0025
IL_001f: ldloc.s V_5
IL_0021: ldlen
IL_0022: conv.i4
IL_0023: brtrue.s IL_002a
IL_0025: ldc.i4.0
IL_0026: conv.u
IL_0027: stloc.2
IL_0028: br.s IL_0034
IL_002a: ldloc.s V_5
IL_002c: ldc.i4.0
IL_002d: ldelema ""char""
IL_0032: conv.u
IL_0033: stloc.2
IL_0034: ldstr ""hello""
IL_0039: stloc.s V_6
-IL_003b: ldloc.s V_6
IL_003d: conv.u
IL_003e: stloc.3
IL_003f: ldloc.3
IL_0040: brfalse.s IL_004a
IL_0042: ldloc.3
IL_0043: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0048: add
IL_0049: stloc.3
-IL_004a: nop
-IL_004b: ldloc.1
IL_004c: ldind.u2
IL_004d: call ""void System.Console.Write(int)""
IL_0052: nop
-IL_0053: ldloc.2
IL_0054: ldind.u2
IL_0055: call ""void System.Console.Write(int)""
IL_005a: nop
-IL_005b: ldloc.3
IL_005c: ldind.u2
IL_005d: call ""void System.Console.Write(int)""
IL_0062: nop
-IL_0063: nop
~IL_0064: ldc.i4.0
IL_0065: conv.u
IL_0066: stloc.s V_4
IL_0068: ldnull
IL_0069: stloc.s V_5
IL_006b: ldnull
IL_006c: stloc.s V_6
-IL_006e: nop
-IL_006f: ret
}
";
var expectedOutput = @"970104";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeDebugExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL, sequencePoints: "C.Main");
CompileAndVerify(string.Format(template, "checked "), options: TestOptions.UnsafeDebugExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL, sequencePoints: "C.Main");
}
[Fact]
public void FixedStatementVoidPointerPointer()
{
var template = @"
using System;
unsafe class C
{{
void* v;
static void Main()
{{
{0}
{{
char ch = 'a';
C c = new C();
c.v = &ch;
fixed (void** p = &c.v)
{{
Console.Write(*(char*)*p);
}}
}}
}}
}}
";
// NB: "pinned void*&", as in Dev10.
var expectedIL = @"
{
// Code size 36 (0x24)
.maxstack 3
.locals init (char V_0, //ch
pinned void*& V_1)
IL_0000: ldc.i4.s 97
IL_0002: stloc.0
IL_0003: newobj ""C..ctor()""
IL_0008: dup
IL_0009: ldloca.s V_0
IL_000b: conv.u
IL_000c: stfld ""void* C.v""
IL_0011: ldflda ""void* C.v""
IL_0016: stloc.1
IL_0017: ldloc.1
IL_0018: conv.u
IL_0019: ldind.i
IL_001a: ldind.u2
IL_001b: call ""void System.Console.Write(char)""
IL_0020: ldc.i4.0
IL_0021: conv.u
IL_0022: stloc.1
IL_0023: ret
}
";
var expectedOutput = @"a";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL);
CompileAndVerify(string.Format(template, "checked"), options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL);
}
[ConditionalFact(typeof(DesktopOnly))]
public void PointerArrayConversion()
{
var template = @"
using System;
unsafe class C
{{
void M(int*[] api, void*[] apv, Array a)
{{
{0}
{{
a = api;
a = apv;
api = (int*[])a;
apv = (void*[])a;
}}
}}
}}
";
var expectedIL = @"
{
// Code size 23 (0x17)
.maxstack 1
IL_0000: ldarg.1
IL_0001: starg.s V_3
IL_0003: ldarg.2
IL_0004: starg.s V_3
IL_0006: ldarg.3
IL_0007: castclass ""int*[]""
IL_000c: starg.s V_1
IL_000e: ldarg.3
IL_000f: castclass ""void*[]""
IL_0014: starg.s V_2
IL_0016: ret
}
";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes).VerifyIL("C.M", expectedIL);
CompileAndVerify(string.Format(template, "checked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes).VerifyIL("C.M", expectedIL);
}
[ConditionalFact(typeof(DesktopOnly))]
public void PointerArrayConversionRuntimeError()
{
var text = @"
unsafe class C
{
static void Main()
{
System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture;
try
{
int*[] api = new int*[1];
System.Array a = api;
a.GetValue(0);
}
finally
{
System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture;
}
}
}
";
CompileAndVerifyException<NotSupportedException>(text, "Type is not supported.", allowUnsafe: true, verify: Verification.Fails);
}
[ConditionalFact(typeof(DesktopOnly))]
public void PointerArrayEnumerableConversion()
{
var template = @"
using System.Collections;
unsafe class C
{{
void M(int*[] api, void*[] apv, IEnumerable e)
{{
{0}
{{
e = api;
e = apv;
api = (int*[])e;
apv = (void*[])e;
}}
}}
}}
";
var expectedIL = @"
{
// Code size 23 (0x17)
.maxstack 1
IL_0000: ldarg.1
IL_0001: starg.s V_3
IL_0003: ldarg.2
IL_0004: starg.s V_3
IL_0006: ldarg.3
IL_0007: castclass ""int*[]""
IL_000c: starg.s V_1
IL_000e: ldarg.3
IL_000f: castclass ""void*[]""
IL_0014: starg.s V_2
IL_0016: ret
}
";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes).VerifyIL("C.M", expectedIL);
CompileAndVerify(string.Format(template, "checked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes).VerifyIL("C.M", expectedIL);
}
[ConditionalFact(typeof(DesktopOnly))]
public void PointerArrayEnumerableConversionRuntimeError()
{
var text = @"
unsafe class C
{
static void Main()
{
System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture;
try
{
int*[] api = new int*[1];
System.Collections.IEnumerable e = api;
var enumerator = e.GetEnumerator();
enumerator.MoveNext();
var current = enumerator.Current;
}
finally
{
System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture;
}
}
}
";
CompileAndVerifyException<NotSupportedException>(text, "Type is not supported.", allowUnsafe: true, verify: Verification.Fails);
}
[Fact]
public void PointerArrayForeachSingle()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
int*[] array = new []
{
(int*)1,
(int*)2,
};
foreach (var element in array)
{
Console.Write((int)element);
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "12", verify: Verification.Fails).VerifyIL("C.Main", @"
{
// Code size 41 (0x29)
.maxstack 4
.locals init (int*[] V_0,
int V_1)
IL_0000: ldc.i4.2
IL_0001: newarr ""int*""
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldc.i4.1
IL_0009: conv.i
IL_000a: stelem.i
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: conv.i
IL_000f: stelem.i
IL_0010: stloc.0
IL_0011: ldc.i4.0
IL_0012: stloc.1
IL_0013: br.s IL_0022
IL_0015: ldloc.0
IL_0016: ldloc.1
IL_0017: ldelem.i
IL_0018: conv.i4
IL_0019: call ""void System.Console.Write(int)""
IL_001e: ldloc.1
IL_001f: ldc.i4.1
IL_0020: add
IL_0021: stloc.1
IL_0022: ldloc.1
IL_0023: ldloc.0
IL_0024: ldlen
IL_0025: conv.i4
IL_0026: blt.s IL_0015
IL_0028: ret
}
");
}
[Fact]
public void PointerArrayForeachMultiple()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
int*[,] array = new [,]
{
{ (int*)1, (int*)2, },
{ (int*)3, (int*)4, },
};
foreach (var element in array)
{
Console.Write((int)element);
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "1234", verify: Verification.Fails).VerifyIL("C.Main", @"
{
// Code size 120 (0x78)
.maxstack 5
.locals init (int*[,] V_0,
int V_1,
int V_2,
int V_3,
int V_4)
IL_0000: ldc.i4.2
IL_0001: ldc.i4.2
IL_0002: newobj ""int*[*,*]..ctor""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.0
IL_000a: ldc.i4.1
IL_000b: conv.i
IL_000c: call ""int*[*,*].Set""
IL_0011: dup
IL_0012: ldc.i4.0
IL_0013: ldc.i4.1
IL_0014: ldc.i4.2
IL_0015: conv.i
IL_0016: call ""int*[*,*].Set""
IL_001b: dup
IL_001c: ldc.i4.1
IL_001d: ldc.i4.0
IL_001e: ldc.i4.3
IL_001f: conv.i
IL_0020: call ""int*[*,*].Set""
IL_0025: dup
IL_0026: ldc.i4.1
IL_0027: ldc.i4.1
IL_0028: ldc.i4.4
IL_0029: conv.i
IL_002a: call ""int*[*,*].Set""
IL_002f: stloc.0
IL_0030: ldloc.0
IL_0031: ldc.i4.0
IL_0032: callvirt ""int System.Array.GetUpperBound(int)""
IL_0037: stloc.1
IL_0038: ldloc.0
IL_0039: ldc.i4.1
IL_003a: callvirt ""int System.Array.GetUpperBound(int)""
IL_003f: stloc.2
IL_0040: ldloc.0
IL_0041: ldc.i4.0
IL_0042: callvirt ""int System.Array.GetLowerBound(int)""
IL_0047: stloc.3
IL_0048: br.s IL_0073
IL_004a: ldloc.0
IL_004b: ldc.i4.1
IL_004c: callvirt ""int System.Array.GetLowerBound(int)""
IL_0051: stloc.s V_4
IL_0053: br.s IL_006a
IL_0055: ldloc.0
IL_0056: ldloc.3
IL_0057: ldloc.s V_4
IL_0059: call ""int*[*,*].Get""
IL_005e: conv.i4
IL_005f: call ""void System.Console.Write(int)""
IL_0064: ldloc.s V_4
IL_0066: ldc.i4.1
IL_0067: add
IL_0068: stloc.s V_4
IL_006a: ldloc.s V_4
IL_006c: ldloc.2
IL_006d: ble.s IL_0055
IL_006f: ldloc.3
IL_0070: ldc.i4.1
IL_0071: add
IL_0072: stloc.3
IL_0073: ldloc.3
IL_0074: ldloc.1
IL_0075: ble.s IL_004a
IL_0077: ret
}
");
}
[ConditionalFact(typeof(DesktopOnly))]
public void PointerArrayForeachEnumerable()
{
var text = @"
using System;
using System.Collections;
unsafe class C
{
static void Main()
{
System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture;
try
{
int*[] array = new []
{
(int*)1,
(int*)2,
};
foreach (var element in (IEnumerable)array)
{
Console.Write((int)element);
}
}
finally
{
System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture;
}
}
}
";
CompileAndVerifyException<NotSupportedException>(text, "Type is not supported.", allowUnsafe: true, verify: Verification.Fails);
}
#endregion Pointer conversion tests
#region sizeof tests
[Fact]
public void SizeOfConstant()
{
var text = @"
using System;
class C
{
static void Main()
{
Console.WriteLine(sizeof(sbyte));
Console.WriteLine(sizeof(byte));
Console.WriteLine(sizeof(short));
Console.WriteLine(sizeof(ushort));
Console.WriteLine(sizeof(int));
Console.WriteLine(sizeof(uint));
Console.WriteLine(sizeof(long));
Console.WriteLine(sizeof(ulong));
Console.WriteLine(sizeof(char));
Console.WriteLine(sizeof(float));
Console.WriteLine(sizeof(double));
Console.WriteLine(sizeof(bool));
Console.WriteLine(sizeof(decimal)); //Supported by dev10, but not spec.
}
}
";
var expectedOutput = @"
1
1
2
2
4
4
8
8
2
4
8
1
16
".Trim();
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Passes).VerifyIL("C.Main", @"
{
// Code size 80 (0x50)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: call ""void System.Console.WriteLine(int)""
IL_0006: ldc.i4.1
IL_0007: call ""void System.Console.WriteLine(int)""
IL_000c: ldc.i4.2
IL_000d: call ""void System.Console.WriteLine(int)""
IL_0012: ldc.i4.2
IL_0013: call ""void System.Console.WriteLine(int)""
IL_0018: ldc.i4.4
IL_0019: call ""void System.Console.WriteLine(int)""
IL_001e: ldc.i4.4
IL_001f: call ""void System.Console.WriteLine(int)""
IL_0024: ldc.i4.8
IL_0025: call ""void System.Console.WriteLine(int)""
IL_002a: ldc.i4.8
IL_002b: call ""void System.Console.WriteLine(int)""
IL_0030: ldc.i4.2
IL_0031: call ""void System.Console.WriteLine(int)""
IL_0036: ldc.i4.4
IL_0037: call ""void System.Console.WriteLine(int)""
IL_003c: ldc.i4.8
IL_003d: call ""void System.Console.WriteLine(int)""
IL_0042: ldc.i4.1
IL_0043: call ""void System.Console.WriteLine(int)""
IL_0048: ldc.i4.s 16
IL_004a: call ""void System.Console.WriteLine(int)""
IL_004f: ret
}
");
}
[Fact]
public void SizeOfNonConstant()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
Console.WriteLine(sizeof(S));
Console.WriteLine(sizeof(Outer.Inner));
Console.WriteLine(sizeof(int*));
Console.WriteLine(sizeof(void*));
}
}
struct S
{
public byte b;
}
class Outer
{
public struct Inner
{
public char c;
}
}
";
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
1
2
4
4
".Trim();
}
else
{
expectedOutput = @"
1
2
8
8
".Trim();
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Passes).VerifyIL("C.Main", @"
{
// Code size 45 (0x2d)
.maxstack 1
IL_0000: sizeof ""S""
IL_0006: call ""void System.Console.WriteLine(int)""
IL_000b: sizeof ""Outer.Inner""
IL_0011: call ""void System.Console.WriteLine(int)""
IL_0016: sizeof ""int*""
IL_001c: call ""void System.Console.WriteLine(int)""
IL_0021: sizeof ""void*""
IL_0027: call ""void System.Console.WriteLine(int)""
IL_002c: ret
}
");
}
[Fact]
public void SizeOfEnum()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
Console.WriteLine(sizeof(E1));
Console.WriteLine(sizeof(E2));
Console.WriteLine(sizeof(E3));
}
}
enum E1 { A }
enum E2 : byte { A }
enum E3 : long { A }
";
var expectedOutput = @"
4
1
8
".Trim();
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Passes).VerifyIL("C.Main", @"
{
// Code size 19 (0x13)
.maxstack 1
IL_0000: ldc.i4.4
IL_0001: call ""void System.Console.WriteLine(int)""
IL_0006: ldc.i4.1
IL_0007: call ""void System.Console.WriteLine(int)""
IL_000c: ldc.i4.8
IL_000d: call ""void System.Console.WriteLine(int)""
IL_0012: ret
}
");
}
#endregion sizeof tests
#region Pointer arithmetic tests
[Fact]
public void NumericAdditionChecked()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
checked
{
S s = new S();
S* p = &s;
p = p + 2;
p = p + 3u;
p = p + 4l;
p = p + 5ul;
}
}
}
";
// Dev10 has conv.u after IL_000d and conv.i8 in place of conv.u8 at IL_0017.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 59 (0x3b)
.maxstack 3
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldc.i4.2
IL_000c: conv.i
IL_000d: sizeof ""S""
IL_0013: mul.ovf
IL_0014: add.ovf.un
IL_0015: ldc.i4.3
IL_0016: conv.u8
IL_0017: sizeof ""S""
IL_001d: conv.i8
IL_001e: mul.ovf
IL_001f: conv.i
IL_0020: add.ovf.un
IL_0021: ldc.i4.4
IL_0022: conv.i8
IL_0023: sizeof ""S""
IL_0029: conv.i8
IL_002a: mul.ovf
IL_002b: conv.i
IL_002c: add.ovf.un
IL_002d: ldc.i4.5
IL_002e: conv.i8
IL_002f: sizeof ""S""
IL_0035: conv.ovf.u8
IL_0036: mul.ovf.un
IL_0037: conv.u
IL_0038: add.ovf.un
IL_0039: pop
IL_003a: ret
}
");
}
[Fact]
public void NumericAdditionUnchecked()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
unchecked
{
S s = new S();
S* p = &s;
p = p + 2;
p = p + 3u;
p = p + 4l;
p = p + 5ul;
}
}
}
";
// Dev10 has conv.u after IL_000d and conv.i8 in place of conv.u8 at IL_0017.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 59 (0x3b)
.maxstack 3
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldc.i4.2
IL_000c: conv.i
IL_000d: sizeof ""S""
IL_0013: mul
IL_0014: add
IL_0015: ldc.i4.3
IL_0016: conv.u8
IL_0017: sizeof ""S""
IL_001d: conv.i8
IL_001e: mul
IL_001f: conv.i
IL_0020: add
IL_0021: ldc.i4.4
IL_0022: conv.i8
IL_0023: sizeof ""S""
IL_0029: conv.i8
IL_002a: mul
IL_002b: conv.i
IL_002c: add
IL_002d: pop
IL_002e: ldc.i4.5
IL_002f: conv.i8
IL_0030: sizeof ""S""
IL_0036: conv.i8
IL_0037: mul
IL_0038: conv.u
IL_0039: pop
IL_003a: ret
}
");
}
[Fact]
public void NumericSubtractionChecked()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
checked
{
S s = new S();
S* p = &s;
p = p - 2;
p = p - 3u;
p = p - 4l;
p = p - 5ul;
}
}
}
";
// Dev10 has conv.u after IL_000d and conv.i8 in place of conv.u8 at IL_0017.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 59 (0x3b)
.maxstack 3
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldc.i4.2
IL_000c: conv.i
IL_000d: sizeof ""S""
IL_0013: mul.ovf
IL_0014: sub.ovf.un
IL_0015: ldc.i4.3
IL_0016: conv.u8
IL_0017: sizeof ""S""
IL_001d: conv.i8
IL_001e: mul.ovf
IL_001f: conv.i
IL_0020: sub.ovf.un
IL_0021: ldc.i4.4
IL_0022: conv.i8
IL_0023: sizeof ""S""
IL_0029: conv.i8
IL_002a: mul.ovf
IL_002b: conv.i
IL_002c: sub.ovf.un
IL_002d: ldc.i4.5
IL_002e: conv.i8
IL_002f: sizeof ""S""
IL_0035: conv.ovf.u8
IL_0036: mul.ovf.un
IL_0037: conv.u
IL_0038: sub.ovf.un
IL_0039: pop
IL_003a: ret
}
");
}
[Fact]
public void NumericSubtractionUnchecked()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
unchecked
{
S s = new S();
S* p = &s;
p = p - 2;
p = p - 3u;
p = p - 4l;
p = p - 5ul;
}
}
}
";
// Dev10 has conv.u after IL_000d and conv.i8 in place of conv.u8 at IL_0017.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 59 (0x3b)
.maxstack 3
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldc.i4.2
IL_000c: conv.i
IL_000d: sizeof ""S""
IL_0013: mul
IL_0014: sub
IL_0015: ldc.i4.3
IL_0016: conv.u8
IL_0017: sizeof ""S""
IL_001d: conv.i8
IL_001e: mul
IL_001f: conv.i
IL_0020: sub
IL_0021: ldc.i4.4
IL_0022: conv.i8
IL_0023: sizeof ""S""
IL_0029: conv.i8
IL_002a: mul
IL_002b: conv.i
IL_002c: sub
IL_002d: pop
IL_002e: ldc.i4.5
IL_002f: conv.i8
IL_0030: sizeof ""S""
IL_0036: conv.i8
IL_0037: mul
IL_0038: conv.u
IL_0039: pop
IL_003a: ret
}
");
}
[WorkItem(546750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546750")]
[Fact]
public void NumericAdditionUnchecked_SizeOne()
{
var text = @"
using System;
unsafe class C
{
void Test(int i, uint u, long l, ulong ul)
{
unchecked
{
byte b = 3;
byte* p = &b;
p = p + 2;
p = p + 3u;
p = p + 4l;
p = p + 5ul;
p = p + i;
p = p + u;
p = p + l;
p = p + ul;
}
}
}
";
// NOTE: even when not optimized.
// NOTE: additional conversions applied to constants of type int and uint.
CompileAndVerify(text, options: TestOptions.UnsafeDebugDll, verify: Verification.Fails).VerifyIL("C.Test", @"
{
// Code size 50 (0x32)
.maxstack 2
.locals init (byte V_0, //b
byte* V_1) //p
IL_0000: nop
IL_0001: nop
IL_0002: ldc.i4.3
IL_0003: stloc.0
IL_0004: ldloca.s V_0
IL_0006: conv.u
IL_0007: stloc.1
IL_0008: ldloc.1
IL_0009: ldc.i4.2
IL_000a: add
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: ldc.i4.3
IL_000e: add
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.4
IL_0012: conv.i8
IL_0013: conv.i
IL_0014: add
IL_0015: stloc.1
IL_0016: ldloc.1
IL_0017: ldc.i4.5
IL_0018: conv.i8
IL_0019: conv.u
IL_001a: add
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: ldarg.1
IL_001e: add
IL_001f: stloc.1
IL_0020: ldloc.1
IL_0021: ldarg.2
IL_0022: conv.u
IL_0023: add
IL_0024: stloc.1
IL_0025: ldloc.1
IL_0026: ldarg.3
IL_0027: conv.i
IL_0028: add
IL_0029: stloc.1
IL_002a: ldloc.1
IL_002b: ldarg.s V_4
IL_002d: conv.u
IL_002e: add
IL_002f: stloc.1
IL_0030: nop
IL_0031: ret
}
");
}
[WorkItem(18871, "https://github.com/dotnet/roslyn/issues/18871")]
[WorkItem(546750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546750")]
[Fact]
public void NumericAdditionChecked_SizeOne()
{
var text = @"
using System;
unsafe class C
{
void Test(int i, uint u, long l, ulong ul)
{
checked
{
byte b = 3;
byte* p = &b;
p = p + 2;
p = p + 3u;
p = p + 4l;
p = p + 5ul;
p = p + i;
p = p + u;
p = p + l;
p = p + ul;
p = p + (-2);
}
}
void Test1(int i, uint u, long l, ulong ul)
{
checked
{
byte b = 3;
byte* p = &b;
p = p - 2;
p = p - 3u;
p = p - 4l;
p = p - 5ul;
p = p - i;
p = p - u;
p = p - l;
p = p - ul;
p = p - (-1);
}
}
}
";
// NOTE: even when not optimized.
// NOTE: additional conversions applied to constants of type int and uint.
// NOTE: identical to unchecked except "add" becomes "add.ovf.un".
var comp = CompileAndVerify(text, options: TestOptions.UnsafeDebugDll, verify: Verification.Fails);
comp.VerifyIL("C.Test", @"
{
// Code size 57 (0x39)
.maxstack 2
.locals init (byte V_0, //b
byte* V_1) //p
IL_0000: nop
IL_0001: nop
IL_0002: ldc.i4.3
IL_0003: stloc.0
IL_0004: ldloca.s V_0
IL_0006: conv.u
IL_0007: stloc.1
IL_0008: ldloc.1
IL_0009: ldc.i4.2
IL_000a: add.ovf.un
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: ldc.i4.3
IL_000e: add.ovf.un
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.4
IL_0012: conv.i8
IL_0013: conv.i
IL_0014: add.ovf.un
IL_0015: stloc.1
IL_0016: ldloc.1
IL_0017: ldc.i4.5
IL_0018: conv.i8
IL_0019: conv.u
IL_001a: add.ovf.un
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: ldarg.1
IL_001e: conv.i
IL_001f: add.ovf.un
IL_0020: stloc.1
IL_0021: ldloc.1
IL_0022: ldarg.2
IL_0023: conv.u
IL_0024: add.ovf.un
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: ldarg.3
IL_0028: conv.i
IL_0029: add.ovf.un
IL_002a: stloc.1
IL_002b: ldloc.1
IL_002c: ldarg.s V_4
IL_002e: conv.u
IL_002f: add.ovf.un
IL_0030: stloc.1
IL_0031: ldloc.1
IL_0032: ldc.i4.s -2
IL_0034: conv.i
IL_0035: add.ovf.un
IL_0036: stloc.1
IL_0037: nop
IL_0038: ret
}");
comp.VerifyIL("C.Test1", @"
{
// Code size 56 (0x38)
.maxstack 2
.locals init (byte V_0, //b
byte* V_1) //p
IL_0000: nop
IL_0001: nop
IL_0002: ldc.i4.3
IL_0003: stloc.0
IL_0004: ldloca.s V_0
IL_0006: conv.u
IL_0007: stloc.1
IL_0008: ldloc.1
IL_0009: ldc.i4.2
IL_000a: sub.ovf.un
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: ldc.i4.3
IL_000e: sub.ovf.un
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.4
IL_0012: conv.i8
IL_0013: conv.i
IL_0014: sub.ovf.un
IL_0015: stloc.1
IL_0016: ldloc.1
IL_0017: ldc.i4.5
IL_0018: conv.i8
IL_0019: conv.u
IL_001a: sub.ovf.un
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: ldarg.1
IL_001e: conv.i
IL_001f: sub.ovf.un
IL_0020: stloc.1
IL_0021: ldloc.1
IL_0022: ldarg.2
IL_0023: conv.u
IL_0024: sub.ovf.un
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: ldarg.3
IL_0028: conv.i
IL_0029: sub.ovf.un
IL_002a: stloc.1
IL_002b: ldloc.1
IL_002c: ldarg.s V_4
IL_002e: conv.u
IL_002f: sub.ovf.un
IL_0030: stloc.1
IL_0031: ldloc.1
IL_0032: ldc.i4.m1
IL_0033: conv.i
IL_0034: sub.ovf.un
IL_0035: stloc.1
IL_0036: nop
IL_0037: ret
}");
}
[Fact]
public void CheckedSignExtend()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
byte* ptr1 = default(byte*);
ptr1 = (byte*)2;
checked
{
// should not overflow regardless of 32/64 bit
ptr1 = ptr1 + 2147483649;
}
Console.WriteLine((long)ptr1);
byte* ptr = (byte*)2;
try
{
checked
{
int i = -1;
// should overflow regardless of 32/64 bit
ptr = ptr + i;
}
Console.WriteLine((long)ptr);
}
catch (OverflowException)
{
Console.WriteLine(""overflow"");
Console.WriteLine((long)ptr);
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"2147483651
overflow
2", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 67 (0x43)
.maxstack 2
.locals init (byte* V_0, //ptr1
byte* V_1, //ptr
int V_2) //i
IL_0000: ldloca.s V_0
IL_0002: initobj ""byte*""
IL_0008: ldc.i4.2
IL_0009: conv.i
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: ldc.i4 0x80000001
IL_0011: conv.u
IL_0012: add.ovf.un
IL_0013: stloc.0
IL_0014: ldloc.0
IL_0015: conv.u8
IL_0016: call ""void System.Console.WriteLine(long)""
IL_001b: ldc.i4.2
IL_001c: conv.i
IL_001d: stloc.1
.try
{
IL_001e: ldc.i4.m1
IL_001f: stloc.2
IL_0020: ldloc.1
IL_0021: ldloc.2
IL_0022: conv.i
IL_0023: add.ovf.un
IL_0024: stloc.1
IL_0025: ldloc.1
IL_0026: conv.u8
IL_0027: call ""void System.Console.WriteLine(long)""
IL_002c: leave.s IL_0042
}
catch System.OverflowException
{
IL_002e: pop
IL_002f: ldstr ""overflow""
IL_0034: call ""void System.Console.WriteLine(string)""
IL_0039: ldloc.1
IL_003a: conv.u8
IL_003b: call ""void System.Console.WriteLine(long)""
IL_0040: leave.s IL_0042
}
IL_0042: ret
}
");
}
[Fact]
public void Increment()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S* p = (S*)0;
checked
{
p++;
}
checked
{
++p;
}
unchecked
{
p++;
}
unchecked
{
++p;
}
Console.WriteLine((int)p);
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "4", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 47 (0x2f)
.maxstack 2
.locals init (S* V_0) //p
IL_0000: ldc.i4.0
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: sizeof ""S""
IL_000a: add.ovf.un
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: sizeof ""S""
IL_0013: add.ovf.un
IL_0014: stloc.0
IL_0015: ldloc.0
IL_0016: sizeof ""S""
IL_001c: add
IL_001d: stloc.0
IL_001e: ldloc.0
IL_001f: sizeof ""S""
IL_0025: add
IL_0026: stloc.0
IL_0027: ldloc.0
IL_0028: conv.i4
IL_0029: call ""void System.Console.WriteLine(int)""
IL_002e: ret
}
");
}
[Fact]
public void Decrement()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S* p = (S*)8;
checked
{
p--;
}
checked
{
--p;
}
unchecked
{
p--;
}
unchecked
{
--p;
}
Console.WriteLine((int)p);
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "4", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 47 (0x2f)
.maxstack 2
.locals init (S* V_0) //p
IL_0000: ldc.i4.8
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: sizeof ""S""
IL_000a: sub.ovf.un
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: sizeof ""S""
IL_0013: sub.ovf.un
IL_0014: stloc.0
IL_0015: ldloc.0
IL_0016: sizeof ""S""
IL_001c: sub
IL_001d: stloc.0
IL_001e: ldloc.0
IL_001f: sizeof ""S""
IL_0025: sub
IL_0026: stloc.0
IL_0027: ldloc.0
IL_0028: conv.i4
IL_0029: call ""void System.Console.WriteLine(int)""
IL_002e: ret
}
");
}
[Fact]
public void IncrementProperty()
{
var text = @"
using System;
unsafe struct S
{
S* P { get; set; }
S* this[int x] { get { return P; } set { P = value; } }
static void Main()
{
S s = new S();
s.P++;
--s[GetIndex()];
Console.Write((int)s.P);
}
static int GetIndex()
{
Console.Write(""I"");
return 1;
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "I0", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 74 (0x4a)
.maxstack 3
.locals init (S V_0, //s
S* V_1,
int V_2)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: dup
IL_000b: call ""readonly S* S.P.get""
IL_0010: stloc.1
IL_0011: ldloc.1
IL_0012: sizeof ""S""
IL_0018: add
IL_0019: call ""void S.P.set""
IL_001e: ldloca.s V_0
IL_0020: call ""int S.GetIndex()""
IL_0025: stloc.2
IL_0026: dup
IL_0027: ldloc.2
IL_0028: call ""S* S.this[int].get""
IL_002d: sizeof ""S""
IL_0033: sub
IL_0034: stloc.1
IL_0035: ldloc.2
IL_0036: ldloc.1
IL_0037: call ""void S.this[int].set""
IL_003c: ldloca.s V_0
IL_003e: call ""readonly S* S.P.get""
IL_0043: conv.i4
IL_0044: call ""void System.Console.Write(int)""
IL_0049: ret
}
");
}
[Fact]
public void CompoundAssignment()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S* p = (S*)8;
checked
{
p += 1;
p += 2U;
p -= 1L;
p -= 2UL;
}
unchecked
{
p += 1;
p += 2U;
p -= 1L;
p -= 2UL;
}
Console.WriteLine((int)p);
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "8", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 103 (0x67)
.maxstack 3
.locals init (S* V_0) //p
IL_0000: ldc.i4.8
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: sizeof ""S""
IL_000a: add.ovf.un
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: ldc.i4.2
IL_000e: conv.u8
IL_000f: sizeof ""S""
IL_0015: conv.i8
IL_0016: mul.ovf
IL_0017: conv.i
IL_0018: add.ovf.un
IL_0019: stloc.0
IL_001a: ldloc.0
IL_001b: sizeof ""S""
IL_0021: sub.ovf.un
IL_0022: stloc.0
IL_0023: ldloc.0
IL_0024: ldc.i4.2
IL_0025: conv.i8
IL_0026: sizeof ""S""
IL_002c: conv.ovf.u8
IL_002d: mul.ovf.un
IL_002e: conv.u
IL_002f: sub.ovf.un
IL_0030: stloc.0
IL_0031: ldloc.0
IL_0032: sizeof ""S""
IL_0038: add
IL_0039: stloc.0
IL_003a: ldloc.0
IL_003b: ldc.i4.2
IL_003c: conv.u8
IL_003d: sizeof ""S""
IL_0043: conv.i8
IL_0044: mul
IL_0045: conv.i
IL_0046: add
IL_0047: stloc.0
IL_0048: ldloc.0
IL_0049: sizeof ""S""
IL_004f: sub
IL_0050: stloc.0
IL_0051: ldloc.0
IL_0052: ldc.i4.2
IL_0053: conv.i8
IL_0054: sizeof ""S""
IL_005a: conv.i8
IL_005b: mul
IL_005c: conv.u
IL_005d: sub
IL_005e: stloc.0
IL_005f: ldloc.0
IL_0060: conv.i4
IL_0061: call ""void System.Console.WriteLine(int)""
IL_0066: ret
}
");
}
[Fact]
public void CompoundAssignProperty()
{
var text = @"
using System;
unsafe struct S
{
S* P { get; set; }
S* this[int x] { get { return P; } set { P = value; } }
static void Main()
{
S s = new S();
s.P += 3;
s[GetIndex()] -= 2;
Console.Write((int)s.P);
}
static int GetIndex()
{
Console.Write(""I"");
return 1;
}
}
";
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"I4";
}
else
{
expectedOutput = @"I8";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 78 (0x4e)
.maxstack 5
.locals init (S V_0, //s
S& V_1,
int V_2)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: dup
IL_000b: call ""readonly S* S.P.get""
IL_0010: ldc.i4.3
IL_0011: conv.i
IL_0012: sizeof ""S""
IL_0018: mul
IL_0019: add
IL_001a: call ""void S.P.set""
IL_001f: ldloca.s V_0
IL_0021: stloc.1
IL_0022: call ""int S.GetIndex()""
IL_0027: stloc.2
IL_0028: ldloc.1
IL_0029: ldloc.2
IL_002a: ldloc.1
IL_002b: ldloc.2
IL_002c: call ""S* S.this[int].get""
IL_0031: ldc.i4.2
IL_0032: conv.i
IL_0033: sizeof ""S""
IL_0039: mul
IL_003a: sub
IL_003b: call ""void S.this[int].set""
IL_0040: ldloca.s V_0
IL_0042: call ""readonly S* S.P.get""
IL_0047: conv.i4
IL_0048: call ""void System.Console.Write(int)""
IL_004d: ret
}
");
}
[Fact]
public void PointerSubtraction_EmptyStruct()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S* p = (S*)8;
S* q = (S*)4;
checked
{
Console.Write(p - q);
}
unchecked
{
Console.Write(p - q);
}
}
}
";
// NOTE: don't use checked subtraction or division in either case (matches dev10).
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "44", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 39 (0x27)
.maxstack 2
.locals init (S* V_0, //p
S* V_1) //q
IL_0000: ldc.i4.8
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldc.i4.4
IL_0004: conv.i
IL_0005: stloc.1
IL_0006: ldloc.0
IL_0007: ldloc.1
IL_0008: sub
IL_0009: sizeof ""S""
IL_000f: div
IL_0010: conv.i8
IL_0011: call ""void System.Console.Write(long)""
IL_0016: ldloc.0
IL_0017: ldloc.1
IL_0018: sub
IL_0019: sizeof ""S""
IL_001f: div
IL_0020: conv.i8
IL_0021: call ""void System.Console.Write(long)""
IL_0026: ret
}
");
}
[Fact]
public void PointerSubtraction_NonEmptyStruct()
{
var text = @"
using System;
unsafe struct S
{
int x; //non-empty struct
static void Main()
{
S* p = (S*)8;
S* q = (S*)4;
checked
{
Console.Write(p - q);
}
unchecked
{
Console.Write(p - q);
}
}
}
";
// NOTE: don't use checked subtraction or division in either case (matches dev10).
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "11", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 39 (0x27)
.maxstack 2
.locals init (S* V_0, //p
S* V_1) //q
IL_0000: ldc.i4.8
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldc.i4.4
IL_0004: conv.i
IL_0005: stloc.1
IL_0006: ldloc.0
IL_0007: ldloc.1
IL_0008: sub
IL_0009: sizeof ""S""
IL_000f: div
IL_0010: conv.i8
IL_0011: call ""void System.Console.Write(long)""
IL_0016: ldloc.0
IL_0017: ldloc.1
IL_0018: sub
IL_0019: sizeof ""S""
IL_001f: div
IL_0020: conv.i8
IL_0021: call ""void System.Console.Write(long)""
IL_0026: ret
}
");
}
[Fact]
public void PointerSubtraction_ConstantSize()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
int* p = (int*)8; //size is known at compile-time
int* q = (int*)4;
checked
{
Console.Write(p - q);
}
unchecked
{
Console.Write(p - q);
}
}
}
";
// NOTE: don't use checked subtraction or division in either case (matches dev10).
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "11", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 29 (0x1d)
.maxstack 2
.locals init (int* V_0, //p
int* V_1) //q
IL_0000: ldc.i4.8
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldc.i4.4
IL_0004: conv.i
IL_0005: stloc.1
IL_0006: ldloc.0
IL_0007: ldloc.1
IL_0008: sub
IL_0009: ldc.i4.4
IL_000a: div
IL_000b: conv.i8
IL_000c: call ""void System.Console.Write(long)""
IL_0011: ldloc.0
IL_0012: ldloc.1
IL_0013: sub
IL_0014: ldc.i4.4
IL_0015: div
IL_0016: conv.i8
IL_0017: call ""void System.Console.Write(long)""
IL_001c: ret
}
");
}
[Fact]
public void PointerSubtraction_IntegerDivision()
{
var text = @"
using System;
unsafe struct S
{
int x; //size = 4
static void Main()
{
S* p1 = (S*)7; //size is known at compile-time
S* p2 = (S*)9; //size is known at compile-time
S* q = (S*)4;
checked
{
Console.Write(p1 - q);
}
unchecked
{
Console.Write(p2 - q);
}
}
}
";
// NOTE: don't use checked subtraction or division in either case (matches dev10).
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "01", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 43 (0x2b)
.maxstack 2
.locals init (S* V_0, //p1
S* V_1, //p2
S* V_2) //q
IL_0000: ldc.i4.7
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldc.i4.s 9
IL_0005: conv.i
IL_0006: stloc.1
IL_0007: ldc.i4.4
IL_0008: conv.i
IL_0009: stloc.2
IL_000a: ldloc.0
IL_000b: ldloc.2
IL_000c: sub
IL_000d: sizeof ""S""
IL_0013: div
IL_0014: conv.i8
IL_0015: call ""void System.Console.Write(long)""
IL_001a: ldloc.1
IL_001b: ldloc.2
IL_001c: sub
IL_001d: sizeof ""S""
IL_0023: div
IL_0024: conv.i8
IL_0025: call ""void System.Console.Write(long)""
IL_002a: ret
}
");
}
[WorkItem(544155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544155")]
[Fact]
public void SubtractPointerTypes()
{
var text = @"
using System;
class PointerArithmetic
{
static unsafe void Main()
{
short ia1 = 10;
short* ptr = &ia1;
short* newPtr;
newPtr = ptr - 2;
Console.WriteLine((int)(ptr - newPtr));
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "2", verify: Verification.Fails);
}
#endregion Pointer arithmetic tests
#region Checked pointer arithmetic overflow tests
// 0 - operation name (e.g. "Add")
// 1 - pointed at type name (e.g. "S")
// 2 - operator (e.g. "+")
// 3 - checked/unchecked
private const string CheckedNumericHelperTemplate = @"
unsafe static class Helper
{{
public static void {0}Int({1}* p, int num, string description)
{{
{3}
{{
try
{{
p = p {2} num;
Console.WriteLine(""{0}Int: No exception at {{0}} (value = {{1}})"",
description, (ulong)p);
}}
catch (OverflowException)
{{
Console.WriteLine(""{0}Int: Exception at {{0}}"", description);
}}
}}
}}
public static void {0}UInt({1}* p, uint num, string description)
{{
{3}
{{
try
{{
p = p {2} num;
Console.WriteLine(""{0}UInt: No exception at {{0}} (value = {{1}})"",
description, (ulong)p);
}}
catch (OverflowException)
{{
Console.WriteLine(""{0}UInt: Exception at {{0}}"", description);
}}
}}
}}
public static void {0}Long({1}* p, long num, string description)
{{
{3}
{{
try
{{
p = p {2} num;
Console.WriteLine(""{0}Long: No exception at {{0}} (value = {{1}})"",
description, (ulong)p);
}}
catch (OverflowException)
{{
Console.WriteLine(""{0}Long: Exception at {{0}}"", description);
}}
}}
}}
public static void {0}ULong({1}* p, ulong num, string description)
{{
{3}
{{
try
{{
p = p {2} num;
Console.WriteLine(""{0}ULong: No exception at {{0}} (value = {{1}})"",
description, (ulong)p);
}}
catch (OverflowException)
{{
Console.WriteLine(""{0}ULong: Exception at {{0}}"", description);
}}
}}
}}
}}
";
private const string SizedStructs = @"
//sizeof SXX is 2 ^ XX
struct S00 { }
struct S01 { S00 a, b; }
struct S02 { S01 a, b; }
struct S03 { S02 a, b; }
struct S04 { S03 a, b; }
struct S05 { S04 a, b; }
struct S06 { S05 a, b; }
struct S07 { S06 a, b; }
struct S08 { S07 a, b; }
struct S09 { S08 a, b; }
struct S10 { S09 a, b; }
struct S11 { S10 a, b; }
struct S12 { S11 a, b; }
struct S13 { S12 a, b; }
struct S14 { S13 a, b; }
struct S15 { S14 a, b; }
struct S16 { S15 a, b; }
struct S17 { S16 a, b; }
struct S18 { S17 a, b; }
struct S19 { S18 a, b; }
struct S20 { S19 a, b; }
struct S21 { S20 a, b; }
struct S22 { S21 a, b; }
struct S23 { S22 a, b; }
struct S24 { S23 a, b; }
struct S25 { S24 a, b; }
struct S26 { S25 a, b; }
struct S27 { S26 a, b; }
//struct S28 { S27 a, b; } //Can't load type
//struct S29 { S28 a, b; } //Can't load type
//struct S30 { S29 a, b; } //Can't load type
//struct S31 { S30 a, b; } //Can't load type
";
// 0 - pointed-at type
private const string PositiveNumericAdditionCasesTemplate = @"
Helper.AddInt(({0}*)0, int.MaxValue, ""0 + int.MaxValue"");
Helper.AddInt(({0}*)1, int.MaxValue, ""1 + int.MaxValue"");
Helper.AddInt(({0}*)int.MaxValue, 0, ""int.MaxValue + 0"");
Helper.AddInt(({0}*)int.MaxValue, 1, ""int.MaxValue + 1"");
//Helper.AddInt(({0}*)0, uint.MaxValue, ""0 + uint.MaxValue"");
//Helper.AddInt(({0}*)1, uint.MaxValue, ""1 + uint.MaxValue"");
Helper.AddInt(({0}*)uint.MaxValue, 0, ""uint.MaxValue + 0"");
Helper.AddInt(({0}*)uint.MaxValue, 1, ""uint.MaxValue + 1"");
//Helper.AddInt(({0}*)0, long.MaxValue, ""0 + long.MaxValue"");
//Helper.AddInt(({0}*)1, long.MaxValue, ""1 + long.MaxValue"");
//Helper.AddInt(({0}*)long.MaxValue, 0, ""long.MaxValue + 0"");
//Helper.AddInt(({0}*)long.MaxValue, 1, ""long.MaxValue + 1"");
//Helper.AddInt(({0}*)0, ulong.MaxValue, ""0 + ulong.MaxValue"");
//Helper.AddInt(({0}*)1, ulong.MaxValue, ""1 + ulong.MaxValue"");
//Helper.AddInt(({0}*)ulong.MaxValue, 0, ""ulong.MaxValue + 0"");
//Helper.AddInt(({0}*)ulong.MaxValue, 1, ""ulong.MaxValue + 1"");
Console.WriteLine();
Helper.AddUInt(({0}*)0, int.MaxValue, ""0 + int.MaxValue"");
Helper.AddUInt(({0}*)1, int.MaxValue, ""1 + int.MaxValue"");
Helper.AddUInt(({0}*)int.MaxValue, 0, ""int.MaxValue + 0"");
Helper.AddUInt(({0}*)int.MaxValue, 1, ""int.MaxValue + 1"");
Helper.AddUInt(({0}*)0, uint.MaxValue, ""0 + uint.MaxValue"");
Helper.AddUInt(({0}*)1, uint.MaxValue, ""1 + uint.MaxValue"");
Helper.AddUInt(({0}*)uint.MaxValue, 0, ""uint.MaxValue + 0"");
Helper.AddUInt(({0}*)uint.MaxValue, 1, ""uint.MaxValue + 1"");
//Helper.AddUInt(({0}*)0, long.MaxValue, ""0 + long.MaxValue"");
//Helper.AddUInt(({0}*)1, long.MaxValue, ""1 + long.MaxValue"");
//Helper.AddUInt(({0}*)long.MaxValue, 0, ""long.MaxValue + 0"");
//Helper.AddUInt(({0}*)long.MaxValue, 1, ""long.MaxValue + 1"");
//Helper.AddUInt(({0}*)0, ulong.MaxValue, ""0 + ulong.MaxValue"");
//Helper.AddUInt(({0}*)1, ulong.MaxValue, ""1 + ulong.MaxValue"");
//Helper.AddUInt(({0}*)ulong.MaxValue, 0, ""ulong.MaxValue + 0"");
//Helper.AddUInt(({0}*)ulong.MaxValue, 1, ""ulong.MaxValue + 1"");
Console.WriteLine();
Helper.AddLong(({0}*)0, int.MaxValue, ""0 + int.MaxValue"");
Helper.AddLong(({0}*)1, int.MaxValue, ""1 + int.MaxValue"");
Helper.AddLong(({0}*)int.MaxValue, 0, ""int.MaxValue + 0"");
Helper.AddLong(({0}*)int.MaxValue, 1, ""int.MaxValue + 1"");
Helper.AddLong(({0}*)0, uint.MaxValue, ""0 + uint.MaxValue"");
Helper.AddLong(({0}*)1, uint.MaxValue, ""1 + uint.MaxValue"");
Helper.AddLong(({0}*)uint.MaxValue, 0, ""uint.MaxValue + 0"");
Helper.AddLong(({0}*)uint.MaxValue, 1, ""uint.MaxValue + 1"");
Helper.AddLong(({0}*)0, long.MaxValue, ""0 + long.MaxValue"");
Helper.AddLong(({0}*)1, long.MaxValue, ""1 + long.MaxValue"");
//Helper.AddLong(({0}*)long.MaxValue, 0, ""long.MaxValue + 0"");
//Helper.AddLong(({0}*)long.MaxValue, 1, ""long.MaxValue + 1"");
//Helper.AddLong(({0}*)0, ulong.MaxValue, ""0 + ulong.MaxValue"");
//Helper.AddLong(({0}*)1, ulong.MaxValue, ""1 + ulong.MaxValue"");
//Helper.AddLong(({0}*)ulong.MaxValue, 0, ""ulong.MaxValue + 0"");
//Helper.AddLong(({0}*)ulong.MaxValue, 1, ""ulong.MaxValue + 1"");
Console.WriteLine();
Helper.AddULong(({0}*)0, int.MaxValue, ""0 + int.MaxValue"");
Helper.AddULong(({0}*)1, int.MaxValue, ""1 + int.MaxValue"");
Helper.AddULong(({0}*)int.MaxValue, 0, ""int.MaxValue + 0"");
Helper.AddULong(({0}*)int.MaxValue, 1, ""int.MaxValue + 1"");
Helper.AddULong(({0}*)0, uint.MaxValue, ""0 + uint.MaxValue"");
Helper.AddULong(({0}*)1, uint.MaxValue, ""1 + uint.MaxValue"");
Helper.AddULong(({0}*)uint.MaxValue, 0, ""uint.MaxValue + 0"");
Helper.AddULong(({0}*)uint.MaxValue, 1, ""uint.MaxValue + 1"");
Helper.AddULong(({0}*)0, long.MaxValue, ""0 + long.MaxValue"");
Helper.AddULong(({0}*)1, long.MaxValue, ""1 + long.MaxValue"");
//Helper.AddULong(({0}*)long.MaxValue, 0, ""long.MaxValue + 0"");
//Helper.AddULong(({0}*)long.MaxValue, 1, ""long.MaxValue + 1"");
Helper.AddULong(({0}*)0, ulong.MaxValue, ""0 + ulong.MaxValue"");
Helper.AddULong(({0}*)1, ulong.MaxValue, ""1 + ulong.MaxValue"");
//Helper.AddULong(({0}*)ulong.MaxValue, 0, ""ulong.MaxValue + 0"");
//Helper.AddULong(({0}*)ulong.MaxValue, 1, ""ulong.MaxValue + 1"");
";
// 0 - pointed-at type
private const string NegativeNumericAdditionCasesTemplate = @"
Helper.AddInt(({0}*)0, -1, ""0 + (-1)"");
Helper.AddInt(({0}*)0, int.MinValue, ""0 + int.MinValue"");
//Helper.AddInt(({0}*)0, long.MinValue, ""0 + long.MinValue"");
Console.WriteLine();
Helper.AddLong(({0}*)0, -1, ""0 + (-1)"");
Helper.AddLong(({0}*)0, int.MinValue, ""0 + int.MinValue"");
Helper.AddLong(({0}*)0, long.MinValue, ""0 + long.MinValue"");
";
// 0 - pointed-at type
private const string PositiveNumericSubtractionCasesTemplate = @"
Helper.SubInt(({0}*)0, 1, ""0 - 1"");
Helper.SubInt(({0}*)0, int.MaxValue, ""0 - int.MaxValue"");
//Helper.SubInt(({0}*)0, uint.MaxValue, ""0 - uint.MaxValue"");
//Helper.SubInt(({0}*)0, long.MaxValue, ""0 - long.MaxValue"");
//Helper.SubInt(({0}*)0, ulong.MaxValue, ""0 - ulong.MaxValue"");
Console.WriteLine();
Helper.SubUInt(({0}*)0, 1, ""0 - 1"");
Helper.SubUInt(({0}*)0, int.MaxValue, ""0 - int.MaxValue"");
Helper.SubUInt(({0}*)0, uint.MaxValue, ""0 - uint.MaxValue"");
//Helper.SubUInt(({0}*)0, long.MaxValue, ""0 - long.MaxValue"");
//Helper.SubUInt(({0}*)0, ulong.MaxValue, ""0 - ulong.MaxValue"");
Console.WriteLine();
Helper.SubLong(({0}*)0, 1, ""0 - 1"");
Helper.SubLong(({0}*)0, int.MaxValue, ""0 - int.MaxValue"");
Helper.SubLong(({0}*)0, uint.MaxValue, ""0 - uint.MaxValue"");
Helper.SubLong(({0}*)0, long.MaxValue, ""0 - long.MaxValue"");
//Helper.SubLong(({0}*)0, ulong.MaxValue, ""0 - ulong.MaxValue"");
Console.WriteLine();
Helper.SubULong(({0}*)0, 1, ""0 - 1"");
Helper.SubULong(({0}*)0, int.MaxValue, ""0 - int.MaxValue"");
Helper.SubULong(({0}*)0, uint.MaxValue, ""0 - uint.MaxValue"");
Helper.SubULong(({0}*)0, long.MaxValue, ""0 - long.MaxValue"");
Helper.SubULong(({0}*)0, ulong.MaxValue, ""0 - ulong.MaxValue"");
";
// 0 - pointed-at type
private const string NegativeNumericSubtractionCasesTemplate = @"
Helper.SubInt(({0}*)0, -1, ""0 - -1"");
Helper.SubInt(({0}*)0, int.MinValue, ""0 - int.MinValue"");
Helper.SubInt(({0}*)0, -1 * int.MaxValue, ""0 - -int.MaxValue"");
Console.WriteLine();
Helper.SubLong(({0}*)0, -1L, ""0 - -1"");
Helper.SubLong(({0}*)0, int.MinValue, ""0 - int.MinValue"");
Helper.SubLong(({0}*)0, long.MinValue, ""0 - long.MinValue"");
Helper.SubLong(({0}*)0, -1L * int.MaxValue, ""0 - -int.MaxValue"");
Helper.SubLong(({0}*)0, -1L * uint.MaxValue, ""0 - -uint.MaxValue"");
Helper.SubLong(({0}*)0, -1L * long.MaxValue, ""0 - -long.MaxValue"");
Helper.SubLong(({0}*)0, -1L * long.MaxValue, ""0 - -ulong.MaxValue"");
Helper.SubLong(({0}*)0, -1L * int.MinValue, ""0 - -int.MinValue"");
//Helper.SubLong(({0}*)0, -1L * long.MinValue, ""0 - -long.MinValue"");
";
private static string MakeNumericOverflowTest(string casesTemplate, string pointedAtType, string operationName, string @operator, string checkedness)
{
const string mainClassTemplate = @"
using System;
unsafe class C
{{
static void Main()
{{
{0}
{{
{1}
}}
}}
}}
{2}
{3}
";
return string.Format(mainClassTemplate,
checkedness,
string.Format(casesTemplate, pointedAtType),
string.Format(CheckedNumericHelperTemplate, operationName, pointedAtType, @operator, checkedness),
SizedStructs);
}
// Positive numbers, size = 1
[Fact]
public void CheckedNumericAdditionOverflow1()
{
var text = MakeNumericOverflowTest(PositiveNumericAdditionCasesTemplate, "S00", "Add", "+", "checked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: Exception at uint.MaxValue + 1
AddUInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddUInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddUInt: No exception at 0 + uint.MaxValue (value = 4294967295)
AddUInt: Exception at 1 + uint.MaxValue
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: Exception at uint.MaxValue + 1
AddLong: No exception at 0 + int.MaxValue (value = 2147483647)
AddLong: No exception at 1 + int.MaxValue (value = 2147483648)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483648)
AddLong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddLong: Exception at 1 + uint.MaxValue
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: Exception at uint.MaxValue + 1
AddLong: No exception at 0 + long.MaxValue (value = 4294967295)
AddLong: Exception at 1 + long.MaxValue
AddULong: No exception at 0 + int.MaxValue (value = 2147483647)
AddULong: No exception at 1 + int.MaxValue (value = 2147483648)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483648)
AddULong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddULong: Exception at 1 + uint.MaxValue
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: Exception at uint.MaxValue + 1
AddULong: No exception at 0 + long.MaxValue (value = 4294967295)
AddULong: Exception at 1 + long.MaxValue
AddULong: No exception at 0 + ulong.MaxValue (value = 4294967295)
AddULong: Exception at 1 + ulong.MaxValue
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: No exception at uint.MaxValue + 1 (value = 4294967296)
AddUInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddUInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddUInt: No exception at 0 + uint.MaxValue (value = 4294967295)
AddUInt: No exception at 1 + uint.MaxValue (value = 4294967296)
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: No exception at uint.MaxValue + 1 (value = 4294967296)
AddLong: No exception at 0 + int.MaxValue (value = 2147483647)
AddLong: No exception at 1 + int.MaxValue (value = 2147483648)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483648)
AddLong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddLong: No exception at 1 + uint.MaxValue (value = 4294967296)
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: No exception at uint.MaxValue + 1 (value = 4294967296)
AddLong: No exception at 0 + long.MaxValue (value = 9223372036854775807)
AddLong: No exception at 1 + long.MaxValue (value = 9223372036854775808)
AddULong: No exception at 0 + int.MaxValue (value = 2147483647)
AddULong: No exception at 1 + int.MaxValue (value = 2147483648)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483648)
AddULong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddULong: No exception at 1 + uint.MaxValue (value = 4294967296)
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: No exception at uint.MaxValue + 1 (value = 4294967296)
AddULong: No exception at 0 + long.MaxValue (value = 9223372036854775807)
AddULong: No exception at 1 + long.MaxValue (value = 9223372036854775808)
AddULong: No exception at 0 + ulong.MaxValue (value = 18446744073709551615)
AddULong: Exception at 1 + ulong.MaxValue
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Positive numbers, size = 4
[Fact]
public void CheckedNumericAdditionOverflow2()
{
var text = MakeNumericOverflowTest(PositiveNumericAdditionCasesTemplate, "S02", "Add", "+", "checked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: Exception at 0 + int.MaxValue
AddInt: Exception at 1 + int.MaxValue
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: Exception at uint.MaxValue + 1
AddUInt: No exception at 0 + int.MaxValue (value = 4294967292)
AddUInt: No exception at 1 + int.MaxValue (value = 4294967293)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddUInt: No exception at 0 + uint.MaxValue (value = 4294967292)
AddUInt: No exception at 1 + uint.MaxValue (value = 4294967293)
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: Exception at uint.MaxValue + 1
AddLong: No exception at 0 + int.MaxValue (value = 4294967292)
AddLong: No exception at 1 + int.MaxValue (value = 4294967293)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483651)
AddLong: No exception at 0 + uint.MaxValue (value = 4294967292)
AddLong: No exception at 1 + uint.MaxValue (value = 4294967293)
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: Exception at uint.MaxValue + 1
AddLong: Exception at 0 + long.MaxValue
AddLong: Exception at 1 + long.MaxValue
AddULong: No exception at 0 + int.MaxValue (value = 4294967292)
AddULong: No exception at 1 + int.MaxValue (value = 4294967293)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483651)
AddULong: No exception at 0 + uint.MaxValue (value = 4294967292)
AddULong: No exception at 1 + uint.MaxValue (value = 4294967293)
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: Exception at uint.MaxValue + 1
AddULong: Exception at 0 + long.MaxValue
AddULong: Exception at 1 + long.MaxValue
AddULong: Exception at 0 + ulong.MaxValue
AddULong: Exception at 1 + ulong.MaxValue
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + int.MaxValue (value = 8589934588)
AddInt: No exception at 1 + int.MaxValue (value = 8589934589)
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: No exception at uint.MaxValue + 1 (value = 4294967299)
AddUInt: No exception at 0 + int.MaxValue (value = 8589934588)
AddUInt: No exception at 1 + int.MaxValue (value = 8589934589)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddUInt: No exception at 0 + uint.MaxValue (value = 17179869180)
AddUInt: No exception at 1 + uint.MaxValue (value = 17179869181)
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: No exception at uint.MaxValue + 1 (value = 4294967299)
AddLong: No exception at 0 + int.MaxValue (value = 8589934588)
AddLong: No exception at 1 + int.MaxValue (value = 8589934589)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483651)
AddLong: No exception at 0 + uint.MaxValue (value = 17179869180)
AddLong: No exception at 1 + uint.MaxValue (value = 17179869181)
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: No exception at uint.MaxValue + 1 (value = 4294967299)
AddLong: Exception at 0 + long.MaxValue
AddLong: Exception at 1 + long.MaxValue
AddULong: No exception at 0 + int.MaxValue (value = 8589934588)
AddULong: No exception at 1 + int.MaxValue (value = 8589934589)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483651)
AddULong: No exception at 0 + uint.MaxValue (value = 17179869180)
AddULong: No exception at 1 + uint.MaxValue (value = 17179869181)
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: No exception at uint.MaxValue + 1 (value = 4294967299)
AddULong: Exception at 0 + long.MaxValue
AddULong: Exception at 1 + long.MaxValue
AddULong: Exception at 0 + ulong.MaxValue
AddULong: Exception at 1 + ulong.MaxValue
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Negative numbers, size = 1
[Fact]
public void CheckedNumericAdditionOverflow3()
{
var text = MakeNumericOverflowTest(NegativeNumericAdditionCasesTemplate, "S00", "Add", "+", "checked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 4294967295)
AddInt: No exception at 0 + int.MinValue (value = 2147483648)
AddLong: No exception at 0 + (-1) (value = 4294967295)
AddLong: No exception at 0 + int.MinValue (value = 2147483648)
AddLong: No exception at 0 + long.MinValue (value = 0)
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 18446744073709551615)
AddInt: No exception at 0 + int.MinValue (value = 18446744071562067968)
AddLong: No exception at 0 + (-1) (value = 18446744073709551615)
AddLong: No exception at 0 + int.MinValue (value = 18446744071562067968)
AddLong: No exception at 0 + long.MinValue (value = 9223372036854775808)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: expectedOutput);
}
// Negative numbers, size = 4
[Fact]
public void CheckedNumericAdditionOverflow4()
{
var text = MakeNumericOverflowTest(NegativeNumericAdditionCasesTemplate, "S02", "Add", "+", "checked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 4294967292)
AddInt: Exception at 0 + int.MinValue
AddLong: No exception at 0 + (-1) (value = 4294967292)
AddLong: No exception at 0 + int.MinValue (value = 0)
AddLong: Exception at 0 + long.MinValue
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 18446744073709551612)
AddInt: No exception at 0 + int.MinValue (value = 18446744065119617024)
AddLong: No exception at 0 + (-1) (value = 18446744073709551612)
AddLong: No exception at 0 + int.MinValue (value = 18446744065119617024)
AddLong: Exception at 0 + long.MinValue
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Positive numbers, size = 1
[Fact]
public void CheckedNumericSubtractionOverflow1()
{
var text = MakeNumericOverflowTest(PositiveNumericSubtractionCasesTemplate, "S00", "Sub", "-", "checked");
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"
SubInt: Exception at 0 - 1
SubInt: Exception at 0 - int.MaxValue
SubUInt: Exception at 0 - 1
SubUInt: Exception at 0 - int.MaxValue
SubUInt: Exception at 0 - uint.MaxValue
SubLong: Exception at 0 - 1
SubLong: Exception at 0 - int.MaxValue
SubLong: Exception at 0 - uint.MaxValue
SubLong: Exception at 0 - long.MaxValue
SubULong: Exception at 0 - 1
SubULong: Exception at 0 - int.MaxValue
SubULong: Exception at 0 - uint.MaxValue
SubULong: Exception at 0 - long.MaxValue
SubULong: Exception at 0 - ulong.MaxValue
");
}
// Positive numbers, size = 4
[Fact]
public void CheckedNumericSubtractionOverflow2()
{
var text = MakeNumericOverflowTest(PositiveNumericSubtractionCasesTemplate, "S02", "Sub", "-", "checked");
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"
SubInt: Exception at 0 - 1
SubInt: Exception at 0 - int.MaxValue
SubUInt: Exception at 0 - 1
SubUInt: Exception at 0 - int.MaxValue
SubUInt: Exception at 0 - uint.MaxValue
SubLong: Exception at 0 - 1
SubLong: Exception at 0 - int.MaxValue
SubLong: Exception at 0 - uint.MaxValue
SubLong: Exception at 0 - long.MaxValue
SubULong: Exception at 0 - 1
SubULong: Exception at 0 - int.MaxValue
SubULong: Exception at 0 - uint.MaxValue
SubULong: Exception at 0 - long.MaxValue
SubULong: Exception at 0 - ulong.MaxValue
");
}
// Negative numbers, size = 1
[Fact]
public void CheckedNumericSubtractionOverflow3()
{
var text = MakeNumericOverflowTest(NegativeNumericSubtractionCasesTemplate, "S00", "Sub", "-", "checked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
SubInt: Exception at 0 - -1
SubInt: Exception at 0 - int.MinValue
SubInt: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -1
SubLong: Exception at 0 - int.MinValue
SubLong: No exception at 0 - long.MinValue (value = 0)
SubLong: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -uint.MaxValue
SubLong: Exception at 0 - -long.MaxValue
SubLong: Exception at 0 - -ulong.MaxValue
SubLong: Exception at 0 - -int.MinValue
";
}
else
{
expectedOutput = @"
SubInt: Exception at 0 - -1
SubInt: Exception at 0 - int.MinValue
SubInt: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -1
SubLong: Exception at 0 - int.MinValue
SubLong: Exception at 0 - long.MinValue
SubLong: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -uint.MaxValue
SubLong: Exception at 0 - -long.MaxValue
SubLong: Exception at 0 - -ulong.MaxValue
SubLong: Exception at 0 - -int.MinValue
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Negative numbers, size = 4
[Fact]
public void CheckedNumericSubtractionOverflow4()
{
var text = MakeNumericOverflowTest(NegativeNumericSubtractionCasesTemplate, "S02", "Sub", "-", "checked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
SubInt: Exception at 0 - -1
SubInt: Exception at 0 - int.MinValue
SubInt: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -1
SubLong: No exception at 0 - int.MinValue (value = 0)
SubLong: Exception at 0 - long.MinValue
SubLong: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -uint.MaxValue
SubLong: Exception at 0 - -long.MaxValue
SubLong: Exception at 0 - -ulong.MaxValue
SubLong: No exception at 0 - -int.MinValue (value = 0)
";
}
else
{
expectedOutput = @"
SubInt: Exception at 0 - -1
SubInt: Exception at 0 - int.MinValue
SubInt: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -1
SubLong: Exception at 0 - int.MinValue
SubLong: Exception at 0 - long.MinValue
SubLong: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -uint.MaxValue
SubLong: Exception at 0 - -long.MaxValue
SubLong: Exception at 0 - -ulong.MaxValue
SubLong: Exception at 0 - -int.MinValue
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
[Fact]
public void CheckedNumericSubtractionQuirk()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
checked
{
S* p;
p = (S*)0 + (-1);
System.Console.WriteLine(""No exception from addition"");
try
{
p = (S*)0 - 1;
}
catch (OverflowException)
{
System.Console.WriteLine(""Exception from subtraction"");
}
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Passes, expectedOutput: @"
No exception from addition
Exception from subtraction
");
}
[Fact]
public void CheckedNumericAdditionQuirk()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
checked
{
S* p;
p = (S*)1 + int.MaxValue;
System.Console.WriteLine(""No exception for pointer + int"");
try
{
p = int.MaxValue + (S*)1;
}
catch (OverflowException)
{
System.Console.WriteLine(""Exception for int + pointer"");
}
}
}
}
";
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
No exception for pointer + int
Exception for int + pointer
";
}
else
{
expectedOutput = @"
No exception for pointer + int
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Passes);
}
[Fact]
public void CheckedPointerSubtractionQuirk()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S* p = (S*)uint.MinValue;
S* q = (S*)uint.MaxValue;
checked
{
Console.Write(p - q);
}
unchecked
{
Console.Write(p - q);
}
}
}
";
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"11";
}
else
{
expectedOutput = @"-4294967295-4294967295";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
[Fact]
public void CheckedPointerElementAccessQuirk()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
fixed (byte* p = new byte[2])
{
p[0] = 12;
// Take a pointer to the second element of the array.
byte* q = p + 1;
// Compute the offset that will wrap around all the way to the preceding byte of memory.
// We do this so that we can overflow, but still end up in valid memory.
ulong offset = sizeof(IntPtr) == sizeof(int) ? uint.MaxValue : ulong.MaxValue;
checked
{
Console.WriteLine(q[offset]);
System.Console.WriteLine(""No exception for element access"");
try
{
Console.WriteLine(*(q + offset));
}
catch (OverflowException)
{
System.Console.WriteLine(""Exception for add-then-dereference"");
}
}
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"
12
No exception for element access
Exception for add-then-dereference
");
}
#endregion Checked pointer arithmetic overflow tests
#region Unchecked pointer arithmetic overflow tests
// Positive numbers, size = 1
[Fact]
public void UncheckedNumericAdditionOverflow1()
{
var text = MakeNumericOverflowTest(PositiveNumericAdditionCasesTemplate, "S00", "Add", "+", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: No exception at uint.MaxValue + 1 (value = 0)
AddUInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddUInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddUInt: No exception at 0 + uint.MaxValue (value = 4294967295)
AddUInt: No exception at 1 + uint.MaxValue (value = 0)
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: No exception at uint.MaxValue + 1 (value = 0)
AddLong: No exception at 0 + int.MaxValue (value = 2147483647)
AddLong: No exception at 1 + int.MaxValue (value = 2147483648)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483648)
AddLong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddLong: No exception at 1 + uint.MaxValue (value = 0)
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: No exception at uint.MaxValue + 1 (value = 0)
AddLong: No exception at 0 + long.MaxValue (value = 4294967295)
AddLong: No exception at 1 + long.MaxValue (value = 0)
AddULong: No exception at 0 + int.MaxValue (value = 2147483647)
AddULong: No exception at 1 + int.MaxValue (value = 2147483648)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483648)
AddULong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddULong: No exception at 1 + uint.MaxValue (value = 0)
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: No exception at uint.MaxValue + 1 (value = 0)
AddULong: No exception at 0 + long.MaxValue (value = 4294967295)
AddULong: No exception at 1 + long.MaxValue (value = 0)
AddULong: No exception at 0 + ulong.MaxValue (value = 4294967295)
AddULong: No exception at 1 + ulong.MaxValue (value = 0)
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: No exception at uint.MaxValue + 1 (value = 4294967296)
AddUInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddUInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddUInt: No exception at 0 + uint.MaxValue (value = 4294967295)
AddUInt: No exception at 1 + uint.MaxValue (value = 4294967296)
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: No exception at uint.MaxValue + 1 (value = 4294967296)
AddLong: No exception at 0 + int.MaxValue (value = 2147483647)
AddLong: No exception at 1 + int.MaxValue (value = 2147483648)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483648)
AddLong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddLong: No exception at 1 + uint.MaxValue (value = 4294967296)
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: No exception at uint.MaxValue + 1 (value = 4294967296)
AddLong: No exception at 0 + long.MaxValue (value = 9223372036854775807)
AddLong: No exception at 1 + long.MaxValue (value = 9223372036854775808)
AddULong: No exception at 0 + int.MaxValue (value = 2147483647)
AddULong: No exception at 1 + int.MaxValue (value = 2147483648)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483648)
AddULong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddULong: No exception at 1 + uint.MaxValue (value = 4294967296)
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: No exception at uint.MaxValue + 1 (value = 4294967296)
AddULong: No exception at 0 + long.MaxValue (value = 9223372036854775807)
AddULong: No exception at 1 + long.MaxValue (value = 9223372036854775808)
AddULong: No exception at 0 + ulong.MaxValue (value = 18446744073709551615)
AddULong: No exception at 1 + ulong.MaxValue (value = 0)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Positive numbers, size = 4
[Fact]
public void UncheckedNumericAdditionOverflow2()
{
var text = MakeNumericOverflowTest(PositiveNumericAdditionCasesTemplate, "S02", "Add", "+", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: No exception at 0 + int.MaxValue (value = 4294967292)
AddInt: No exception at 1 + int.MaxValue (value = 4294967293)
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: No exception at uint.MaxValue + 1 (value = 3)
AddUInt: No exception at 0 + int.MaxValue (value = 4294967292)
AddUInt: No exception at 1 + int.MaxValue (value = 4294967293)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddUInt: No exception at 0 + uint.MaxValue (value = 4294967292)
AddUInt: No exception at 1 + uint.MaxValue (value = 4294967293)
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: No exception at uint.MaxValue + 1 (value = 3)
AddLong: No exception at 0 + int.MaxValue (value = 4294967292)
AddLong: No exception at 1 + int.MaxValue (value = 4294967293)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483651)
AddLong: No exception at 0 + uint.MaxValue (value = 4294967292)
AddLong: No exception at 1 + uint.MaxValue (value = 4294967293)
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: No exception at uint.MaxValue + 1 (value = 3)
AddLong: No exception at 0 + long.MaxValue (value = 4294967292)
AddLong: No exception at 1 + long.MaxValue (value = 4294967293)
AddULong: No exception at 0 + int.MaxValue (value = 4294967292)
AddULong: No exception at 1 + int.MaxValue (value = 4294967293)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483651)
AddULong: No exception at 0 + uint.MaxValue (value = 4294967292)
AddULong: No exception at 1 + uint.MaxValue (value = 4294967293)
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: No exception at uint.MaxValue + 1 (value = 3)
AddULong: No exception at 0 + long.MaxValue (value = 4294967292)
AddULong: No exception at 1 + long.MaxValue (value = 4294967293)
AddULong: No exception at 0 + ulong.MaxValue (value = 4294967292)
AddULong: No exception at 1 + ulong.MaxValue (value = 4294967293)
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + int.MaxValue (value = 8589934588)
AddInt: No exception at 1 + int.MaxValue (value = 8589934589)
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: No exception at uint.MaxValue + 1 (value = 4294967299)
AddUInt: No exception at 0 + int.MaxValue (value = 8589934588)
AddUInt: No exception at 1 + int.MaxValue (value = 8589934589)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddUInt: No exception at 0 + uint.MaxValue (value = 17179869180)
AddUInt: No exception at 1 + uint.MaxValue (value = 17179869181)
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: No exception at uint.MaxValue + 1 (value = 4294967299)
AddLong: No exception at 0 + int.MaxValue (value = 8589934588)
AddLong: No exception at 1 + int.MaxValue (value = 8589934589)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483651)
AddLong: No exception at 0 + uint.MaxValue (value = 17179869180)
AddLong: No exception at 1 + uint.MaxValue (value = 17179869181)
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: No exception at uint.MaxValue + 1 (value = 4294967299)
AddLong: No exception at 0 + long.MaxValue (value = 18446744073709551612)
AddLong: No exception at 1 + long.MaxValue (value = 18446744073709551613)
AddULong: No exception at 0 + int.MaxValue (value = 8589934588)
AddULong: No exception at 1 + int.MaxValue (value = 8589934589)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483651)
AddULong: No exception at 0 + uint.MaxValue (value = 17179869180)
AddULong: No exception at 1 + uint.MaxValue (value = 17179869181)
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: No exception at uint.MaxValue + 1 (value = 4294967299)
AddULong: No exception at 0 + long.MaxValue (value = 18446744073709551612)
AddULong: No exception at 1 + long.MaxValue (value = 18446744073709551613)
AddULong: No exception at 0 + ulong.MaxValue (value = 18446744073709551612)
AddULong: No exception at 1 + ulong.MaxValue (value = 18446744073709551613)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Negative numbers, size = 1
[Fact]
public void UncheckedNumericAdditionOverflow3()
{
var text = MakeNumericOverflowTest(NegativeNumericAdditionCasesTemplate, "S00", "Add", "+", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 4294967295)
AddInt: No exception at 0 + int.MinValue (value = 2147483648)
AddLong: No exception at 0 + (-1) (value = 4294967295)
AddLong: No exception at 0 + int.MinValue (value = 2147483648)
AddLong: No exception at 0 + long.MinValue (value = 0)
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 18446744073709551615)
AddInt: No exception at 0 + int.MinValue (value = 18446744071562067968)
AddLong: No exception at 0 + (-1) (value = 18446744073709551615)
AddLong: No exception at 0 + int.MinValue (value = 18446744071562067968)
AddLong: No exception at 0 + long.MinValue (value = 9223372036854775808)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Negative numbers, size = 4
[Fact]
public void UncheckedNumericAdditionOverflow4()
{
var text = MakeNumericOverflowTest(NegativeNumericAdditionCasesTemplate, "S02", "Add", "+", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 4294967292)
AddInt: No exception at 0 + int.MinValue (value = 0)
AddLong: No exception at 0 + (-1) (value = 4294967292)
AddLong: No exception at 0 + int.MinValue (value = 0)
AddLong: No exception at 0 + long.MinValue (value = 0)
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 18446744073709551612)
AddInt: No exception at 0 + int.MinValue (value = 18446744065119617024)
AddLong: No exception at 0 + (-1) (value = 18446744073709551612)
AddLong: No exception at 0 + int.MinValue (value = 18446744065119617024)
AddLong: No exception at 0 + long.MinValue (value = 0)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Positive numbers, size = 1
[Fact]
public void UncheckedNumericSubtractionOverflow1()
{
var text = MakeNumericOverflowTest(PositiveNumericSubtractionCasesTemplate, "S00", "Sub", "-", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
SubInt: No exception at 0 - 1 (value = 4294967295)
SubInt: No exception at 0 - int.MaxValue (value = 2147483649)
SubUInt: No exception at 0 - 1 (value = 4294967295)
SubUInt: No exception at 0 - int.MaxValue (value = 2147483649)
SubUInt: No exception at 0 - uint.MaxValue (value = 1)
SubLong: No exception at 0 - 1 (value = 4294967295)
SubLong: No exception at 0 - int.MaxValue (value = 2147483649)
SubLong: No exception at 0 - uint.MaxValue (value = 1)
SubLong: No exception at 0 - long.MaxValue (value = 1)
SubULong: No exception at 0 - 1 (value = 4294967295)
SubULong: No exception at 0 - int.MaxValue (value = 2147483649)
SubULong: No exception at 0 - uint.MaxValue (value = 1)
SubULong: No exception at 0 - long.MaxValue (value = 1)
SubULong: No exception at 0 - ulong.MaxValue (value = 1)
";
}
else
{
expectedOutput = @"
SubInt: No exception at 0 - 1 (value = 18446744073709551615)
SubInt: No exception at 0 - int.MaxValue (value = 18446744071562067969)
SubUInt: No exception at 0 - 1 (value = 18446744073709551615)
SubUInt: No exception at 0 - int.MaxValue (value = 18446744071562067969)
SubUInt: No exception at 0 - uint.MaxValue (value = 18446744069414584321)
SubLong: No exception at 0 - 1 (value = 18446744073709551615)
SubLong: No exception at 0 - int.MaxValue (value = 18446744071562067969)
SubLong: No exception at 0 - uint.MaxValue (value = 18446744069414584321)
SubLong: No exception at 0 - long.MaxValue (value = 9223372036854775809)
SubULong: No exception at 0 - 1 (value = 18446744073709551615)
SubULong: No exception at 0 - int.MaxValue (value = 18446744071562067969)
SubULong: No exception at 0 - uint.MaxValue (value = 18446744069414584321)
SubULong: No exception at 0 - long.MaxValue (value = 9223372036854775809)
SubULong: No exception at 0 - ulong.MaxValue (value = 1)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Positive numbers, size = 4
[Fact]
public void UncheckedNumericSubtractionOverflow2()
{
var text = MakeNumericOverflowTest(PositiveNumericSubtractionCasesTemplate, "S02", "Sub", "-", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
SubInt: No exception at 0 - 1 (value = 4294967292)
SubInt: No exception at 0 - int.MaxValue (value = 4)
SubUInt: No exception at 0 - 1 (value = 4294967292)
SubUInt: No exception at 0 - int.MaxValue (value = 4)
SubUInt: No exception at 0 - uint.MaxValue (value = 4)
SubLong: No exception at 0 - 1 (value = 4294967292)
SubLong: No exception at 0 - int.MaxValue (value = 4)
SubLong: No exception at 0 - uint.MaxValue (value = 4)
SubLong: No exception at 0 - long.MaxValue (value = 4)
SubULong: No exception at 0 - 1 (value = 4294967292)
SubULong: No exception at 0 - int.MaxValue (value = 4)
SubULong: No exception at 0 - uint.MaxValue (value = 4)
SubULong: No exception at 0 - long.MaxValue (value = 4)
SubULong: No exception at 0 - ulong.MaxValue (value = 4)
";
}
else
{
expectedOutput = @"
SubInt: No exception at 0 - 1 (value = 18446744073709551612)
SubInt: No exception at 0 - int.MaxValue (value = 18446744065119617028)
SubUInt: No exception at 0 - 1 (value = 18446744073709551612)
SubUInt: No exception at 0 - int.MaxValue (value = 18446744065119617028)
SubUInt: No exception at 0 - uint.MaxValue (value = 18446744056529682436)
SubLong: No exception at 0 - 1 (value = 18446744073709551612)
SubLong: No exception at 0 - int.MaxValue (value = 18446744065119617028)
SubLong: No exception at 0 - uint.MaxValue (value = 18446744056529682436)
SubLong: No exception at 0 - long.MaxValue (value = 4)
SubULong: No exception at 0 - 1 (value = 18446744073709551612)
SubULong: No exception at 0 - int.MaxValue (value = 18446744065119617028)
SubULong: No exception at 0 - uint.MaxValue (value = 18446744056529682436)
SubULong: No exception at 0 - long.MaxValue (value = 4)
SubULong: No exception at 0 - ulong.MaxValue (value = 4)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Negative numbers, size = 1
[Fact]
public void UncheckedNumericSubtractionOverflow3()
{
var text = MakeNumericOverflowTest(NegativeNumericSubtractionCasesTemplate, "S00", "Sub", "-", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
SubInt: No exception at 0 - -1 (value = 1)
SubInt: No exception at 0 - int.MinValue (value = 2147483648)
SubInt: No exception at 0 - -int.MaxValue (value = 2147483647)
SubLong: No exception at 0 - -1 (value = 1)
SubLong: No exception at 0 - int.MinValue (value = 2147483648)
SubLong: No exception at 0 - long.MinValue (value = 0)
SubLong: No exception at 0 - -int.MaxValue (value = 2147483647)
SubLong: No exception at 0 - -uint.MaxValue (value = 4294967295)
SubLong: No exception at 0 - -long.MaxValue (value = 4294967295)
SubLong: No exception at 0 - -ulong.MaxValue (value = 4294967295)
SubLong: No exception at 0 - -int.MinValue (value = 2147483648)
";
}
else
{
expectedOutput = @"
SubInt: No exception at 0 - -1 (value = 1)
SubInt: No exception at 0 - int.MinValue (value = 2147483648)
SubInt: No exception at 0 - -int.MaxValue (value = 2147483647)
SubLong: No exception at 0 - -1 (value = 1)
SubLong: No exception at 0 - int.MinValue (value = 2147483648)
SubLong: No exception at 0 - long.MinValue (value = 9223372036854775808)
SubLong: No exception at 0 - -int.MaxValue (value = 2147483647)
SubLong: No exception at 0 - -uint.MaxValue (value = 4294967295)
SubLong: No exception at 0 - -long.MaxValue (value = 9223372036854775807)
SubLong: No exception at 0 - -ulong.MaxValue (value = 9223372036854775807)
SubLong: No exception at 0 - -int.MinValue (value = 18446744071562067968)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Negative numbers, size = 4
[Fact]
public void UncheckedNumericSubtractionOverflow4()
{
var text = MakeNumericOverflowTest(NegativeNumericSubtractionCasesTemplate, "S02", "Sub", "-", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
SubInt: No exception at 0 - -1 (value = 4)
SubInt: No exception at 0 - int.MinValue (value = 0)
SubInt: No exception at 0 - -int.MaxValue (value = 4294967292)
SubLong: No exception at 0 - -1 (value = 4)
SubLong: No exception at 0 - int.MinValue (value = 0)
SubLong: No exception at 0 - long.MinValue (value = 0)
SubLong: No exception at 0 - -int.MaxValue (value = 4294967292)
SubLong: No exception at 0 - -uint.MaxValue (value = 4294967292)
SubLong: No exception at 0 - -long.MaxValue (value = 4294967292)
SubLong: No exception at 0 - -ulong.MaxValue (value = 4294967292)
SubLong: No exception at 0 - -int.MinValue (value = 0)";
}
else
{
expectedOutput = @"
SubInt: No exception at 0 - -1 (value = 4)
SubInt: No exception at 0 - int.MinValue (value = 8589934592)
SubInt: No exception at 0 - -int.MaxValue (value = 8589934588)
SubLong: No exception at 0 - -1 (value = 4)
SubLong: No exception at 0 - int.MinValue (value = 8589934592)
SubLong: No exception at 0 - long.MinValue (value = 0)
SubLong: No exception at 0 - -int.MaxValue (value = 8589934588)
SubLong: No exception at 0 - -uint.MaxValue (value = 17179869180)
SubLong: No exception at 0 - -long.MaxValue (value = 18446744073709551612)
SubLong: No exception at 0 - -ulong.MaxValue (value = 18446744073709551612)
SubLong: No exception at 0 - -int.MinValue (value = 18446744065119617024)";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
#endregion Unchecked pointer arithmetic overflow tests
#region Pointer comparison tests
[Fact]
public void PointerComparisonSameType()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S* p = (S*)0;
S* q = (S*)1;
unchecked
{
Write(p == q);
Write(p != q);
Write(p <= q);
Write(p >= q);
Write(p < q);
Write(p > q);
}
checked
{
Write(p == q);
Write(p != q);
Write(p <= q);
Write(p >= q);
Write(p < q);
Write(p > q);
}
}
static void Write(bool b)
{
Console.Write(b ? 1 : 0);
}
}
";
// NOTE: all comparisons unsigned.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "011010011010", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 133 (0x85)
.maxstack 2
.locals init (S* V_0, //p
S* V_1) //q
IL_0000: ldc.i4.0
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldc.i4.1
IL_0004: conv.i
IL_0005: stloc.1
IL_0006: ldloc.0
IL_0007: ldloc.1
IL_0008: ceq
IL_000a: call ""void S.Write(bool)""
IL_000f: ldloc.0
IL_0010: ldloc.1
IL_0011: ceq
IL_0013: ldc.i4.0
IL_0014: ceq
IL_0016: call ""void S.Write(bool)""
IL_001b: ldloc.0
IL_001c: ldloc.1
IL_001d: cgt.un
IL_001f: ldc.i4.0
IL_0020: ceq
IL_0022: call ""void S.Write(bool)""
IL_0027: ldloc.0
IL_0028: ldloc.1
IL_0029: clt.un
IL_002b: ldc.i4.0
IL_002c: ceq
IL_002e: call ""void S.Write(bool)""
IL_0033: ldloc.0
IL_0034: ldloc.1
IL_0035: clt.un
IL_0037: call ""void S.Write(bool)""
IL_003c: ldloc.0
IL_003d: ldloc.1
IL_003e: cgt.un
IL_0040: call ""void S.Write(bool)""
IL_0045: ldloc.0
IL_0046: ldloc.1
IL_0047: ceq
IL_0049: call ""void S.Write(bool)""
IL_004e: ldloc.0
IL_004f: ldloc.1
IL_0050: ceq
IL_0052: ldc.i4.0
IL_0053: ceq
IL_0055: call ""void S.Write(bool)""
IL_005a: ldloc.0
IL_005b: ldloc.1
IL_005c: cgt.un
IL_005e: ldc.i4.0
IL_005f: ceq
IL_0061: call ""void S.Write(bool)""
IL_0066: ldloc.0
IL_0067: ldloc.1
IL_0068: clt.un
IL_006a: ldc.i4.0
IL_006b: ceq
IL_006d: call ""void S.Write(bool)""
IL_0072: ldloc.0
IL_0073: ldloc.1
IL_0074: clt.un
IL_0076: call ""void S.Write(bool)""
IL_007b: ldloc.0
IL_007c: ldloc.1
IL_007d: cgt.un
IL_007f: call ""void S.Write(bool)""
IL_0084: ret
}
");
}
[Fact, WorkItem(49639, "https://github.com/dotnet/roslyn/issues/49639")]
public void CompareToNullWithNestedUnconstrainedTypeParameter()
{
var verifier = CompileAndVerify(@"
using System;
unsafe
{
test<int>(null);
S<int> s = default;
test<int>(&s);
static void test<T>(S<T>* s)
{
Console.WriteLine(s == null);
Console.WriteLine(s is null);
}
}
struct S<T> {}
", options: TestOptions.UnsafeReleaseExe, expectedOutput: @"
True
True
False
False", verify: Verification.Skipped);
verifier.VerifyIL("Program.<<Main>$>g__test|0_0<T>(S<T>*)", @"
{
// Code size 21 (0x15)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: conv.u
IL_0003: ceq
IL_0005: call ""void System.Console.WriteLine(bool)""
IL_000a: ldarg.0
IL_000b: ldc.i4.0
IL_000c: conv.u
IL_000d: ceq
IL_000f: call ""void System.Console.WriteLine(bool)""
IL_0014: ret
}
");
}
[Fact, WorkItem(49639, "https://github.com/dotnet/roslyn/issues/49639")]
public void CompareToNullWithPointerToUnmanagedTypeParameter()
{
var verifier = CompileAndVerify(@"
using System;
unsafe
{
test<int>(null);
int i = 0;
test<int>(&i);
static void test<T>(T* t) where T : unmanaged
{
Console.WriteLine(t == null);
Console.WriteLine(t is null);
}
}
", options: TestOptions.UnsafeReleaseExe, expectedOutput: @"
True
True
False
False", verify: Verification.Skipped);
verifier.VerifyIL("Program.<<Main>$>g__test|0_0<T>(T*)", @"
{
// Code size 21 (0x15)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: conv.u
IL_0003: ceq
IL_0005: call ""void System.Console.WriteLine(bool)""
IL_000a: ldarg.0
IL_000b: ldc.i4.0
IL_000c: conv.u
IL_000d: ceq
IL_000f: call ""void System.Console.WriteLine(bool)""
IL_0014: ret
}
");
}
[Theory]
[InlineData("int*")]
[InlineData("delegate*<void>")]
[InlineData("T*")]
[InlineData("delegate*<T>")]
public void CompareToNullInPatternOutsideUnsafe(string pointerType)
{
var comp = CreateCompilation($@"
var c = default(S<int>);
_ = c.Field is null;
unsafe struct S<T> where T : unmanaged
{{
#pragma warning disable CS0649 // Field is unassigned
public {pointerType} Field;
}}
", options: TestOptions.UnsafeReleaseExe);
comp.VerifyDiagnostics(
// (3,5): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// _ = c.Field is null;
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "c.Field").WithLocation(3, 5)
);
}
#endregion Pointer comparison tests
#region stackalloc tests
[Fact]
public void SimpleStackAlloc()
{
var text = @"
unsafe class C
{
void M()
{
int count = 1;
checked
{
int* p = stackalloc int[2];
char* q = stackalloc char[count];
Use(p);
Use(q);
}
unchecked
{
int* p = stackalloc int[2];
char* q = stackalloc char[count];
Use(p);
Use(q);
}
}
static void Use(int * ptr)
{
}
static void Use(char * ptr)
{
}
}
";
// NOTE: conversion is always unchecked, multiplication is always checked.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", @"
{
// Code size 47 (0x2f)
.maxstack 2
.locals init (int V_0, //count
int* V_1, //p
int* V_2) //p
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.8
IL_0003: conv.u
IL_0004: localloc
IL_0006: stloc.1
IL_0007: ldloc.0
IL_0008: conv.u
IL_0009: ldc.i4.2
IL_000a: mul.ovf.un
IL_000b: localloc
IL_000d: ldloc.1
IL_000e: call ""void C.Use(int*)""
IL_0013: call ""void C.Use(char*)""
IL_0018: ldc.i4.8
IL_0019: conv.u
IL_001a: localloc
IL_001c: stloc.2
IL_001d: ldloc.0
IL_001e: conv.u
IL_001f: ldc.i4.2
IL_0020: mul.ovf.un
IL_0021: localloc
IL_0023: ldloc.2
IL_0024: call ""void C.Use(int*)""
IL_0029: call ""void C.Use(char*)""
IL_002e: ret
}
");
}
[Fact]
public void StackAllocConversion()
{
var text = @"
unsafe class C
{
void M()
{
void* p = stackalloc int[2];
C q = stackalloc int[2];
}
public static implicit operator C(int* p)
{
return null;
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", @"
{
// Code size 16 (0x10)
.maxstack 1
.locals init (void* V_0) //p
IL_0000: ldc.i4.8
IL_0001: conv.u
IL_0002: localloc
IL_0004: stloc.0
IL_0005: ldc.i4.8
IL_0006: conv.u
IL_0007: localloc
IL_0009: call ""C C.op_Implicit(int*)""
IL_000e: pop
IL_000f: ret
}
");
}
[Fact]
public void StackAllocConversionZero()
{
var text = @"
unsafe class C
{
void M()
{
void* p = stackalloc int[0];
C q = stackalloc int[0];
}
public static implicit operator C(int* p)
{
return null;
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", @"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (void* V_0) //p
IL_0000: ldc.i4.0
IL_0001: conv.u
IL_0002: stloc.0
IL_0003: ldc.i4.0
IL_0004: conv.u
IL_0005: call ""C C.op_Implicit(int*)""
IL_000a: pop
IL_000b: ret
}
");
}
[Fact]
public void StackAllocSpecExample() //Section 18.8
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
Console.WriteLine(IntToString(123));
Console.WriteLine(IntToString(-456));
}
static string IntToString(int value) {
int n = value >= 0? value: -value;
unsafe {
char* buffer = stackalloc char[16];
char* p = buffer + 16;
do {
*--p = (char)(n % 10 + '0');
n /= 10;
} while (n != 0);
if (value < 0) *--p = '-';
return new string(p, 0, (int)(buffer + 16 - p));
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"123
-456
");
}
// See MethodToClassRewriter.VisitAssignmentOperator for an explanation.
[Fact]
public void StackAllocIntoHoistedLocal1()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
var p = stackalloc int[2];
var q = stackalloc int[2];
Action a = () =>
{
var r = stackalloc int[2];
var s = stackalloc int[2];
Action b = () =>
{
p = null; //capture p
r = null; //capture r
};
Use(s);
};
Use(q);
}
static void Use(int * ptr)
{
}
}
";
var verifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails);
// Note that the stackalloc for p is written into a temp *before* the receiver (i.e. "this")
// for C.<>c__DisplayClass0.p is pushed onto the stack.
verifier.VerifyIL("C.Main", @"
{
// Code size 28 (0x1c)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
int* V_1)
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: ldc.i4.8
IL_0007: conv.u
IL_0008: localloc
IL_000a: stloc.1
IL_000b: ldloc.0
IL_000c: ldloc.1
IL_000d: stfld ""int* C.<>c__DisplayClass0_0.p""
IL_0012: ldc.i4.8
IL_0013: conv.u
IL_0014: localloc
IL_0016: call ""void C.Use(int*)""
IL_001b: ret
}
");
// Check that the same thing works inside a lambda.
verifier.VerifyIL("C.<>c__DisplayClass0_0.<Main>b__0", @"
{
// Code size 35 (0x23)
.maxstack 2
.locals init (C.<>c__DisplayClass0_1 V_0, //CS$<>8__locals0
int* V_1)
IL_0000: newobj ""C.<>c__DisplayClass0_1..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldarg.0
IL_0008: stfld ""C.<>c__DisplayClass0_0 C.<>c__DisplayClass0_1.CS$<>8__locals1""
IL_000d: ldc.i4.8
IL_000e: conv.u
IL_000f: localloc
IL_0011: stloc.1
IL_0012: ldloc.0
IL_0013: ldloc.1
IL_0014: stfld ""int* C.<>c__DisplayClass0_1.r""
IL_0019: ldc.i4.8
IL_001a: conv.u
IL_001b: localloc
IL_001d: call ""void C.Use(int*)""
IL_0022: ret
}
");
}
// See MethodToClassRewriter.VisitAssignmentOperator for an explanation.
[Fact]
public void StackAllocIntoHoistedLocal2()
{
// From native bug #59454 (in DevDiv collection)
var text = @"
unsafe class T
{
delegate int D();
static void Main()
{
int* v = stackalloc int[1];
D d = delegate { return *v; };
System.Console.WriteLine(d());
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "0", verify: Verification.Fails).VerifyIL("T.Main", @"
{
// Code size 41 (0x29)
.maxstack 2
.locals init (T.<>c__DisplayClass1_0 V_0, //CS$<>8__locals0
int* V_1)
IL_0000: newobj ""T.<>c__DisplayClass1_0..ctor()""
IL_0005: stloc.0
IL_0006: ldc.i4.4
IL_0007: conv.u
IL_0008: localloc
IL_000a: stloc.1
IL_000b: ldloc.0
IL_000c: ldloc.1
IL_000d: stfld ""int* T.<>c__DisplayClass1_0.v""
IL_0012: ldloc.0
IL_0013: ldftn ""int T.<>c__DisplayClass1_0.<Main>b__0()""
IL_0019: newobj ""T.D..ctor(object, System.IntPtr)""
IL_001e: callvirt ""int T.D.Invoke()""
IL_0023: call ""void System.Console.WriteLine(int)""
IL_0028: ret
}
");
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "0", verify: Verification.Fails).VerifyIL("T.Main", @"
{
// Code size 41 (0x29)
.maxstack 2
.locals init (T.<>c__DisplayClass1_0 V_0, //CS$<>8__locals0
int* V_1)
IL_0000: newobj ""T.<>c__DisplayClass1_0..ctor()""
IL_0005: stloc.0
IL_0006: ldc.i4.4
IL_0007: conv.u
IL_0008: localloc
IL_000a: stloc.1
IL_000b: ldloc.0
IL_000c: ldloc.1
IL_000d: stfld ""int* T.<>c__DisplayClass1_0.v""
IL_0012: ldloc.0
IL_0013: ldftn ""int T.<>c__DisplayClass1_0.<Main>b__0()""
IL_0019: newobj ""T.D..ctor(object, System.IntPtr)""
IL_001e: callvirt ""int T.D.Invoke()""
IL_0023: call ""void System.Console.WriteLine(int)""
IL_0028: ret
}
");
}
[Fact]
public void CSLegacyStackallocUse32bitChecked()
{
// This is from C# Legacy test where it uses Perl script to call ildasm and check 'mul.ovf' emitted
// $Roslyn\Main\LegacyTest\CSharp\Source\csharp\Source\Conformance\unsafecode\stackalloc\regr001.cs
var text = @"// <Title>Should checked affect stackalloc?</Title>
// <Description>
// The lower level localloc MSIL instruction takes an unsigned native int as input; however the higher level
// stackalloc uses only 32-bits. The example shows the operation overflowing the 32-bit multiply which leads to
// a curious edge condition.
// If compile with /checked we insert a mul.ovf instruction, and this causes a system overflow exception at runtime.
// </Description>
// <RelatedBugs>VSW:489857</RelatedBugs>
using System;
public class C
{
private static unsafe int Main()
{
Int64* intArray = stackalloc Int64[0x7fffffff];
return (int)intArray[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 13 (0xd)
.maxstack 2
IL_0000: ldc.i4 0x7fffffff
IL_0005: conv.u
IL_0006: ldc.i4.8
IL_0007: mul.ovf.un
IL_0008: localloc
IL_000a: ldind.i8
IL_000b: conv.i4
IL_000c: ret
}
");
}
#endregion stackalloc tests
#region Functional tests
[Fact]
public void BubbleSort()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
BubbleSort();
BubbleSort(1);
BubbleSort(2, 1);
BubbleSort(3, 1, 2);
BubbleSort(3, 1, 4, 2);
}
static void BubbleSort(params int[] array)
{
if (array == null)
{
return;
}
fixed (int* begin = array)
{
BubbleSort(begin, end: begin + array.Length);
}
Console.WriteLine(string.Join("", "", array));
}
private static void BubbleSort(int* begin, int* end)
{
for (int* firstUnsorted = begin; firstUnsorted < end; firstUnsorted++)
{
for (int* current = firstUnsorted; current + 1 < end; current++)
{
if (current[0] > current[1])
{
SwapWithNext(current);
}
}
}
}
static void SwapWithNext(int* p)
{
int temp = *p;
p[0] = p[1];
p[1] = temp;
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"
1
1, 2
1, 2, 3
1, 2, 3, 4");
}
[Fact]
public void BigStructs()
{
var text = @"
unsafe class C
{
static void Main()
{
void* v;
CheckOverflow(""(S15*)0 + sizeof(S15)"", () => v = checked((S15*)0 + sizeof(S15)));
CheckOverflow(""(S15*)0 + sizeof(S16)"", () => v = checked((S15*)0 + sizeof(S16)));
CheckOverflow(""(S16*)0 + sizeof(S15)"", () => v = checked((S16*)0 + sizeof(S15)));
}
static void CheckOverflow(string description, System.Action operation)
{
try
{
operation();
System.Console.WriteLine(""No overflow from {0}"", description);
}
catch (System.OverflowException)
{
System.Console.WriteLine(""Overflow from {0}"", description);
}
}
}
" + SizedStructs;
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
No overflow from (S15*)0 + sizeof(S15)
Overflow from (S15*)0 + sizeof(S16)
Overflow from (S16*)0 + sizeof(S15)";
}
else
{
expectedOutput = @"
No overflow from (S15*)0 + sizeof(S15)
No overflow from (S15*)0 + sizeof(S16)
No overflow from (S16*)0 + sizeof(S15)";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
[Fact]
public void LambdaConversion()
{
var text = @"
using System;
class Program
{
static void Main()
{
Goo(x => { });
}
static void Goo(F1 f) { Console.WriteLine(1); }
static void Goo(F2 f) { Console.WriteLine(2); }
}
unsafe delegate void F1(int* x);
delegate void F2(int x);
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"2", verify: Verification.Passes);
}
[Fact]
public void LocalVariableReuse()
{
var text = @"
unsafe class C
{
int this[string s] { get { return 0; } set { } }
void Test()
{
{
this[""not pinned"".ToString()] += 2; //creates an unpinned string local (for the argument)
}
fixed (char* p = ""pinned"") //creates a pinned string local
{
}
{
this[""not pinned"".ToString()] += 2; //reuses the unpinned string local
}
fixed (char* p = ""pinned"") //reuses the pinned string local
{
}
}
}
";
// NOTE: one pinned string temp and one unpinned string temp.
// That is, pinned temps are reused in by other pinned temps
// but not by unpinned temps and vice versa.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.Test", @"
{
// Code size 99 (0x63)
.maxstack 4
.locals init (string V_0,
char* V_1, //p
pinned string V_2,
char* V_3) //p
IL_0000: ldstr ""not pinned""
IL_0005: callvirt ""string object.ToString()""
IL_000a: stloc.0
IL_000b: ldarg.0
IL_000c: ldloc.0
IL_000d: ldarg.0
IL_000e: ldloc.0
IL_000f: call ""int C.this[string].get""
IL_0014: ldc.i4.2
IL_0015: add
IL_0016: call ""void C.this[string].set""
IL_001b: ldstr ""pinned""
IL_0020: stloc.2
IL_0021: ldloc.2
IL_0022: conv.u
IL_0023: stloc.1
IL_0024: ldloc.1
IL_0025: brfalse.s IL_002f
IL_0027: ldloc.1
IL_0028: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_002d: add
IL_002e: stloc.1
IL_002f: ldnull
IL_0030: stloc.2
IL_0031: ldstr ""not pinned""
IL_0036: callvirt ""string object.ToString()""
IL_003b: stloc.0
IL_003c: ldarg.0
IL_003d: ldloc.0
IL_003e: ldarg.0
IL_003f: ldloc.0
IL_0040: call ""int C.this[string].get""
IL_0045: ldc.i4.2
IL_0046: add
IL_0047: call ""void C.this[string].set""
IL_004c: ldstr ""pinned""
IL_0051: stloc.2
IL_0052: ldloc.2
IL_0053: conv.u
IL_0054: stloc.3
IL_0055: ldloc.3
IL_0056: brfalse.s IL_0060
IL_0058: ldloc.3
IL_0059: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_005e: add
IL_005f: stloc.3
IL_0060: ldnull
IL_0061: stloc.2
IL_0062: ret
}");
}
[WorkItem(544229, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544229")]
[Fact]
public void UnsafeTypeAsAttributeArgument()
{
var template = @"
using System;
namespace System
{{
class Int32 {{ }}
}}
[A(Type = typeof({0}))]
class A : Attribute
{{
public Type Type;
static void Main()
{{
var a = (A)typeof(A).GetCustomAttributes(false)[0];
Console.WriteLine(a.Type == typeof({0}));
}}
}}
";
CompileAndVerify(string.Format(template, "int"), options: TestOptions.UnsafeReleaseExe, expectedOutput: @"True", verify: Verification.Passes);
CompileAndVerify(string.Format(template, "int*"), options: TestOptions.UnsafeReleaseExe, expectedOutput: @"True", verify: Verification.Passes);
CompileAndVerify(string.Format(template, "int**"), options: TestOptions.UnsafeReleaseExe, expectedOutput: @"True", verify: Verification.Passes);
CompileAndVerify(string.Format(template, "int[]"), options: TestOptions.UnsafeReleaseExe, expectedOutput: @"True", verify: Verification.Passes);
CompileAndVerify(string.Format(template, "int[][]"), options: TestOptions.UnsafeReleaseExe, expectedOutput: @"True", verify: Verification.Passes);
CompileAndVerify(string.Format(template, "int*[]"), options: TestOptions.UnsafeReleaseExe, expectedOutput: @"True", verify: Verification.Passes);
}
#endregion Functional tests
#region Regression tests
[WorkItem(545026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545026")]
[Fact]
public void MixedSafeAndUnsafeFields()
{
var text =
@"struct Perf_Contexts
{
int data;
private int SuppressUnused(int x) { data = x; return data; }
}
public sealed class ChannelServices
{
static unsafe Perf_Contexts* GetPrivateContextsPerfCounters() { return null; }
private static int I1 = 12;
unsafe private static Perf_Contexts* perf_Contexts = GetPrivateContextsPerfCounters();
private static int I2 = 13;
private static int SuppressUnused(int x) { return I1 + I2; }
}
public class Test
{
public static void Main()
{
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails).VerifyDiagnostics();
}
[WorkItem(545026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545026")]
[Fact]
public void SafeFieldBeforeUnsafeField()
{
var text = @"
class C
{
int x = 1;
unsafe int* p = (int*)2;
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyDiagnostics(
// (4,9): warning CS0414: The field 'C.x' is assigned but its value is never used
// int x = 1;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x").WithArguments("C.x"));
}
[WorkItem(545026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545026")]
[Fact]
public void SafeFieldAfterUnsafeField()
{
var text = @"
class C
{
unsafe int* p = (int*)2;
int x = 1;
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyDiagnostics(
// (5,9): warning CS0414: The field 'C.x' is assigned but its value is never used
// int x = 1;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x").WithArguments("C.x"));
}
[WorkItem(545026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545026"), WorkItem(598170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598170")]
[Fact]
public void FixedPassByRef()
{
var text = @"
class Test
{
unsafe static int printAddress(out int* pI)
{
pI = null;
System.Console.WriteLine((ulong)pI);
return 1;
}
unsafe static int printAddress1(ref int* pI)
{
pI = null;
System.Console.WriteLine((ulong)pI);
return 1;
}
static int Main()
{
int retval = 0;
S s = new S();
unsafe
{
retval = Test.printAddress(out s.i);
retval = Test.printAddress1(ref s.i);
}
if (retval == 0)
System.Console.WriteLine(""Failed."");
return retval;
}
}
unsafe struct S
{
public fixed int i[1];
}
";
var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (24,44): error CS1510: A ref or out argument must be an assignable variable
// retval = Test.printAddress(out s.i);
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "s.i"),
// (25,45): error CS1510: A ref or out argument must be an assignable variable
// retval = Test.printAddress1(ref s.i);
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "s.i"));
}
[Fact, WorkItem(545293, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545293"), WorkItem(881188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/881188")]
public void EmptyAndFixedBufferStructIsInitialized()
{
var text = @"
public struct EmptyStruct { }
unsafe public struct FixedStruct { fixed char c[10]; }
public struct OuterStruct
{
EmptyStruct ES;
FixedStruct FS;
override public string ToString() { return (ES.ToString() + FS.ToString()); }
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes).VerifyDiagnostics(
// (8,17): warning CS0649: Field 'OuterStruct.FS' is never assigned to, and will always have its default value
// FixedStruct FS;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "FS").WithArguments("OuterStruct.FS", "").WithLocation(8, 17),
// (7,17): warning CS0649: Field 'OuterStruct.ES' is never assigned to, and will always have its default value
// EmptyStruct ES;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "ES").WithArguments("OuterStruct.ES", "").WithLocation(7, 17)
);
}
[Fact, WorkItem(545296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545296"), WorkItem(545999, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545999")]
public void FixedBufferAndStatementWithFixedArrayElementAsInitializer()
{
var text = @"
unsafe public struct FixedStruct
{
fixed int i[1];
fixed char c[10];
override public string ToString() {
fixed (char* pc = this.c) { return pc[0].ToString(); }
}
}
";
var comp = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyDiagnostics();
comp.VerifyIL("FixedStruct.ToString", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (pinned char& V_0)
IL_0000: ldarg.0
IL_0001: ldflda ""char* FixedStruct.c""
IL_0006: ldflda ""char FixedStruct.<c>e__FixedBuffer.FixedElementField""
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: conv.u
IL_000e: call ""string char.ToString()""
IL_0013: ret
}
");
}
[Fact]
public void FixedBufferAndStatementWithFixedArrayElementAsInitializerExe()
{
var text = @"
class Program
{
unsafe static void Main(string[] args)
{
FixedStruct s = new FixedStruct();
s.c[0] = 'A';
s.c[1] = 'B';
s.c[2] = 'C';
FixedStruct[] arr = { s };
System.Console.Write(arr[0].ToString());
}
}
unsafe public struct FixedStruct
{
public fixed char c[10];
override public string ToString()
{
fixed (char* pc = this.c)
{
System.Console.Write(pc[0]);
System.Console.Write(pc[1].ToString());
return pc[2].ToString();
}
}
}";
var comp = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "ABC", verify: Verification.Fails).VerifyDiagnostics();
comp.VerifyIL("FixedStruct.ToString", @"
{
// Code size 45 (0x2d)
.maxstack 3
.locals init (pinned char& V_0)
IL_0000: ldarg.0
IL_0001: ldflda ""char* FixedStruct.c""
IL_0006: ldflda ""char FixedStruct.<c>e__FixedBuffer.FixedElementField""
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: conv.u
IL_000e: dup
IL_000f: ldind.u2
IL_0010: call ""void System.Console.Write(char)""
IL_0015: dup
IL_0016: ldc.i4.2
IL_0017: add
IL_0018: call ""string char.ToString()""
IL_001d: call ""void System.Console.Write(string)""
IL_0022: ldc.i4.2
IL_0023: conv.i
IL_0024: ldc.i4.2
IL_0025: mul
IL_0026: add
IL_0027: call ""string char.ToString()""
IL_002c: ret
}
");
}
[Fact, WorkItem(545299, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545299")]
public void FixedStatementInlambda()
{
var text = @"
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
unsafe class C<T> where T : struct
{
public void Goo()
{
Func<T, char> d = delegate
{
fixed (char* p = ""blah"")
{
for (char* pp = p; pp != null; pp++)
return *pp;
}
return 'c';
};
Console.WriteLine(d(default(T)));
}
}
class A
{
static void Main()
{
new C<int>().Goo();
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "b", verify: Verification.Fails);
}
[Fact, WorkItem(546865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546865")]
public void DontStackScheduleLocalPerformingPointerConversion()
{
var text = @"
using System;
unsafe struct S1
{
public char* charPointer;
}
unsafe class Test
{
static void Main()
{
S1 s1 = new S1();
fixed (char* p = ""hello"")
{
s1.charPointer = p;
ulong UserData = (ulong)&s1;
Test1(UserData);
}
}
static void Test1(ulong number)
{
S1* structPointer = (S1*)number;
Console.WriteLine(new string(structPointer->charPointer));
}
static ulong Test2()
{
S1* structPointer = (S1*)null; // null to pointer
int* intPointer = (int*)structPointer; // pointer to pointer
void* voidPointer = (void*)intPointer; // pointer to void
ulong number = (ulong)voidPointer; // pointer to integer
return number;
}
}
";
var verifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "hello", verify: Verification.Fails);
// Note that the pointer local is not scheduled on the stack.
verifier.VerifyIL("Test.Test1", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (S1* V_0) //structPointer
IL_0000: ldarg.0
IL_0001: conv.u
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldfld ""char* S1.charPointer""
IL_0009: newobj ""string..ctor(char*)""
IL_000e: call ""void System.Console.WriteLine(string)""
IL_0013: ret
}");
// All locals retained.
verifier.VerifyIL("Test.Test2", @"
{
// Code size 10 (0xa)
.maxstack 1
.locals init (S1* V_0, //structPointer
int* V_1, //intPointer
void* V_2) //voidPointer
IL_0000: ldc.i4.0
IL_0001: conv.u
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: stloc.1
IL_0005: ldloc.1
IL_0006: stloc.2
IL_0007: ldloc.2
IL_0008: conv.u8
IL_0009: ret
}");
}
[Fact, WorkItem(546807, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546807")]
public void PointerMemberAccessReadonlyField()
{
var text = @"
using System;
unsafe class C
{
public S1* S1;
}
unsafe struct S1
{
public readonly int* X;
public int* Y;
}
unsafe class Test
{
static void Main()
{
S1 s1 = new S1();
C c = new C();
c.S1 = &s1;
Console.WriteLine(null == c.S1->X);
Console.WriteLine(null == c.S1->Y);
}
}
";
var verifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"
True
True");
// NOTE: ldobj before ldfld S1.X, but not before ldfld S1.Y.
verifier.VerifyIL("Test.Main", @"
{
// Code size 64 (0x40)
.maxstack 2
.locals init (S1 V_0, //s1
C V_1) //c
IL_0000: ldloca.s V_0
IL_0002: initobj ""S1""
IL_0008: newobj ""C..ctor()""
IL_000d: stloc.1
IL_000e: ldloc.1
IL_000f: ldloca.s V_0
IL_0011: conv.u
IL_0012: stfld ""S1* C.S1""
IL_0017: ldc.i4.0
IL_0018: conv.u
IL_0019: ldloc.1
IL_001a: ldfld ""S1* C.S1""
IL_001f: ldfld ""int* S1.X""
IL_0024: ceq
IL_0026: call ""void System.Console.WriteLine(bool)""
IL_002b: ldc.i4.0
IL_002c: conv.u
IL_002d: ldloc.1
IL_002e: ldfld ""S1* C.S1""
IL_0033: ldfld ""int* S1.Y""
IL_0038: ceq
IL_003a: call ""void System.Console.WriteLine(bool)""
IL_003f: ret
}
");
}
[Fact, WorkItem(546807, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546807")]
public void PointerMemberAccessCall()
{
var text = @"
using System;
unsafe class C
{
public S1* S1;
}
unsafe struct S1
{
public int X;
public void Instance()
{
Console.WriteLine(this.X);
}
}
static class Extensions
{
public static void Extension(this S1 s1)
{
Console.WriteLine(s1.X);
}
}
unsafe class Test
{
static void Main()
{
S1 s1 = new S1 { X = 2 };
C c = new C();
c.S1 = &s1;
c.S1->Instance();
c.S1->Extension();
}
}
";
var verifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"
2
2");
// NOTE: ldobj before extension call, but not before instance call.
verifier.VerifyIL("Test.Main", @"
{
// Code size 59 (0x3b)
.maxstack 3
.locals init (S1 V_0, //s1
S1 V_1)
IL_0000: ldloca.s V_1
IL_0002: initobj ""S1""
IL_0008: ldloca.s V_1
IL_000a: ldc.i4.2
IL_000b: stfld ""int S1.X""
IL_0010: ldloc.1
IL_0011: stloc.0
IL_0012: newobj ""C..ctor()""
IL_0017: dup
IL_0018: ldloca.s V_0
IL_001a: conv.u
IL_001b: stfld ""S1* C.S1""
IL_0020: dup
IL_0021: ldfld ""S1* C.S1""
IL_0026: call ""void S1.Instance()""
IL_002b: ldfld ""S1* C.S1""
IL_0030: ldobj ""S1""
IL_0035: call ""void Extensions.Extension(S1)""
IL_003a: ret
}");
}
[Fact, WorkItem(531327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531327")]
public void PointerParameter()
{
var text = @"
using System;
unsafe struct S1
{
static void M(N.S2* ps2){}
}
namespace N
{
public struct S2
{
public int F;
}
}
";
var verifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll.WithConcurrentBuild(false), verify: Verification.Passes);
}
[Fact, WorkItem(531327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531327")]
public void PointerReturn()
{
var text = @"
using System;
namespace N
{
public struct S2
{
public int F;
}
}
unsafe struct S1
{
static N.S2* M(int ps2){return null;}
}
";
var verifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll.WithConcurrentBuild(false), verify: Verification.Fails);
}
[Fact, WorkItem(748530, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/748530")]
public void Repro748530()
{
var text = @"
unsafe class A
{
public unsafe struct ListNode
{
internal ListNode(int data, ListNode* pNext)
{
}
}
}
";
var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics();
}
[WorkItem(682584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682584")]
[Fact]
public void UnsafeMathConv()
{
var text = @"
using System;
unsafe class C
{
static void Main(string[] args)
{
byte* data = (byte*)0x76543210;
uint offset = 0x80000000;
byte* wrong = data + offset;
Console.WriteLine(""{0:X}"", (ulong)wrong);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "F6543210", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 36 (0x24)
.maxstack 2
.locals init (byte* V_0, //data
uint V_1, //offset
byte* V_2) //wrong
IL_0000: ldc.i4 0x76543210
IL_0005: conv.i
IL_0006: stloc.0
IL_0007: ldc.i4 0x80000000
IL_000c: stloc.1
IL_000d: ldloc.0
IL_000e: ldloc.1
IL_000f: conv.u
IL_0010: add
IL_0011: stloc.2
IL_0012: ldstr ""{0:X}""
IL_0017: ldloc.2
IL_0018: conv.u8
IL_0019: box ""ulong""
IL_001e: call ""void System.Console.WriteLine(string, object)""
IL_0023: ret
}
");
}
[WorkItem(682584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682584")]
[Fact]
public void UnsafeMathConv001()
{
var text = @"
using System;
unsafe class C
{
static void Main(string[] args)
{
short* data = (short*)0x76543210;
uint offset = 0x40000000;
short* wrong = data + offset;
Console.WriteLine(""{0:X}"", (ulong)wrong);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "F6543210", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 40 (0x28)
.maxstack 3
.locals init (short* V_0, //data
uint V_1, //offset
short* V_2) //wrong
IL_0000: ldc.i4 0x76543210
IL_0005: conv.i
IL_0006: stloc.0
IL_0007: ldc.i4 0x40000000
IL_000c: stloc.1
IL_000d: ldloc.0
IL_000e: ldloc.1
IL_000f: conv.u8
IL_0010: ldc.i4.2
IL_0011: conv.i8
IL_0012: mul
IL_0013: conv.i
IL_0014: add
IL_0015: stloc.2
IL_0016: ldstr ""{0:X}""
IL_001b: ldloc.2
IL_001c: conv.u8
IL_001d: box ""ulong""
IL_0022: call ""void System.Console.WriteLine(string, object)""
IL_0027: ret
}
");
}
[WorkItem(682584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682584")]
[Fact]
public void UnsafeMathConv002()
{
var text = @"
using System;
unsafe class C
{
static void Main(string[] args)
{
byte* data = (byte*)0x76543210;
byte* wrong = data + 0x80000000u;
Console.WriteLine(""{0:X}"", (ulong)wrong);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "F6543210", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 34 (0x22)
.maxstack 2
.locals init (byte* V_0, //data
byte* V_1) //wrong
IL_0000: ldc.i4 0x76543210
IL_0005: conv.i
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4 0x80000000
IL_000d: conv.u
IL_000e: add
IL_000f: stloc.1
IL_0010: ldstr ""{0:X}""
IL_0015: ldloc.1
IL_0016: conv.u8
IL_0017: box ""ulong""
IL_001c: call ""void System.Console.WriteLine(string, object)""
IL_0021: ret
}
");
}
[WorkItem(682584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682584")]
[Fact]
public void UnsafeMathConv002a()
{
var text = @"
using System;
unsafe class C
{
static void Main(string[] args)
{
byte* data = (byte*)0x76543210;
byte* wrong = data + 0x7FFFFFFFu;
Console.WriteLine(""{0:X}"", (ulong)wrong);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "F654320F", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (byte* V_0, //data
byte* V_1) //wrong
IL_0000: ldc.i4 0x76543210
IL_0005: conv.i
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4 0x7fffffff
IL_000d: add
IL_000e: stloc.1
IL_000f: ldstr ""{0:X}""
IL_0014: ldloc.1
IL_0015: conv.u8
IL_0016: box ""ulong""
IL_001b: call ""void System.Console.WriteLine(string, object)""
IL_0020: ret
}
");
}
[WorkItem(857598, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/857598")]
[Fact]
public void VoidToNullable()
{
var text = @"
unsafe class C
{
public int? x = (int?)(void*)0;
}
class c1
{
public static void Main()
{
var x = new C();
System.Console.WriteLine(x.x);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "0", verify: Verification.Passes);
compVerifier.VerifyIL("C..ctor", @"
{
// Code size 21 (0x15)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: conv.i
IL_0003: conv.i4
IL_0004: newobj ""int?..ctor(int)""
IL_0009: stfld ""int? C.x""
IL_000e: ldarg.0
IL_000f: call ""object..ctor()""
IL_0014: ret
}
");
}
[WorkItem(907771, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/907771")]
[Fact]
public void UnsafeBeforeReturn001()
{
var text = @"
using System;
public unsafe class C
{
private static readonly byte[] _emptyArray = new byte[0];
public static void Main()
{
System.Console.WriteLine(ToManagedByteArray(2));
}
public static byte[] ToManagedByteArray(uint byteCount)
{
if (byteCount == 0)
{
return _emptyArray; // degenerate case
}
else
{
byte[] bytes = new byte[byteCount];
fixed (byte* pBytes = bytes)
{
}
return bytes;
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "System.Byte[]", verify: Verification.Fails);
compVerifier.VerifyIL("C.ToManagedByteArray", @"
{
// Code size 42 (0x2a)
.maxstack 3
.locals init (byte* V_0, //pBytes
pinned byte[] V_1)
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0009
IL_0003: ldsfld ""byte[] C._emptyArray""
IL_0008: ret
IL_0009: ldarg.0
IL_000a: newarr ""byte""
IL_000f: dup
IL_0010: dup
IL_0011: stloc.1
IL_0012: brfalse.s IL_0019
IL_0014: ldloc.1
IL_0015: ldlen
IL_0016: conv.i4
IL_0017: brtrue.s IL_001e
IL_0019: ldc.i4.0
IL_001a: conv.u
IL_001b: stloc.0
IL_001c: br.s IL_0027
IL_001e: ldloc.1
IL_001f: ldc.i4.0
IL_0020: ldelema ""byte""
IL_0025: conv.u
IL_0026: stloc.0
IL_0027: ldnull
IL_0028: stloc.1
IL_0029: ret
}
");
}
[WorkItem(907771, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/907771")]
[Fact]
public void UnsafeBeforeReturn002()
{
var text = @"
using System;
public unsafe class C
{
private static readonly byte[] _emptyArray = new byte[0];
public static void Main()
{
System.Console.WriteLine(ToManagedByteArray(2));
}
public static byte[] ToManagedByteArray(uint byteCount)
{
if (byteCount == 0)
{
return _emptyArray; // degenerate case
}
else
{
byte[] bytes = new byte[byteCount];
fixed (byte* pBytes = bytes)
{
}
return bytes;
}
}
}
";
var v = CompileAndVerify(text, options: TestOptions.UnsafeDebugExe, expectedOutput: "System.Byte[]", verify: Verification.Fails);
v.VerifyIL("C.ToManagedByteArray", @"
{
// Code size 64 (0x40)
.maxstack 2
.locals init (bool V_0,
byte[] V_1,
byte[] V_2, //bytes
byte* V_3, //pBytes
pinned byte[] V_4)
-IL_0000: nop
-IL_0001: ldarg.0
IL_0002: ldc.i4.0
IL_0003: ceq
IL_0005: stloc.0
~IL_0006: ldloc.0
IL_0007: brfalse.s IL_0012
-IL_0009: nop
-IL_000a: ldsfld ""byte[] C._emptyArray""
IL_000f: stloc.1
IL_0010: br.s IL_003e
-IL_0012: nop
-IL_0013: ldarg.0
IL_0014: newarr ""byte""
IL_0019: stloc.2
-IL_001a: ldloc.2
IL_001b: dup
IL_001c: stloc.s V_4
IL_001e: brfalse.s IL_0026
IL_0020: ldloc.s V_4
IL_0022: ldlen
IL_0023: conv.i4
IL_0024: brtrue.s IL_002b
IL_0026: ldc.i4.0
IL_0027: conv.u
IL_0028: stloc.3
IL_0029: br.s IL_0035
IL_002b: ldloc.s V_4
IL_002d: ldc.i4.0
IL_002e: ldelema ""byte""
IL_0033: conv.u
IL_0034: stloc.3
-IL_0035: nop
-IL_0036: nop
~IL_0037: ldnull
IL_0038: stloc.s V_4
-IL_003a: ldloc.2
IL_003b: stloc.1
IL_003c: br.s IL_003e
-IL_003e: ldloc.1
IL_003f: ret
}
", sequencePoints: "C.ToManagedByteArray");
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void SystemIntPtrInSignature_BreakingChange()
{
// NOTE: the IL is intentionally not compliant with ECMA spec
// in particular Metadata spec II.23.2.16 (Short form signatures) says that
// [mscorlib]System.IntPtr is not supposed to be used in metadata
// and short-version 'native int' is supposed to be used instead.
var ilSource =
@"
.class public AddressHelper{
.method public hidebysig static valuetype [mscorlib]System.IntPtr AddressOf<T>(!!0& t){
ldarg 0
ldind.i
ret
}
}
";
var csharpSource =
@"
class Program
{
static void Main(string[] args)
{
var s = string.Empty;
var i = AddressHelper.AddressOf(ref s);
System.Console.WriteLine(i);
}
}
";
var cscomp = CreateCompilationWithILAndMscorlib40(csharpSource, ilSource);
var expected = new[] {
// (7,35): error CS0570: 'AddressHelper.AddressOf<T>(?)' is not supported by the language
// var i = AddressHelper.AddressOf(ref s);
Diagnostic(ErrorCode.ERR_BindToBogus, "AddressOf").WithArguments("AddressHelper.AddressOf<T>(?)").WithLocation(7, 35)
};
cscomp.VerifyDiagnostics(expected);
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void SystemIntPtrInSignature_BreakingChange_001()
{
var ilSource =
@"
.class public AddressHelper{
.method public hidebysig static native int AddressOf<T>(!!0& t){
ldc.i4.5
conv.u
ret
}
}
";
var csharpSource =
@"
class Program
{
static void Main(string[] args)
{
var s = string.Empty;
var i = AddressHelper.AddressOf(ref s);
System.Console.WriteLine(i);
}
}
";
var compilation = CreateCompilationWithILAndMscorlib40(csharpSource, ilSource, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
var result = CompileAndVerify(compilation, expectedOutput: "5");
}
[Fact, WorkItem(7550, "https://github.com/dotnet/roslyn/issues/7550")]
public void EnsureNullPointerIsPoppedIfUnused()
{
string source = @"
public class A
{
public unsafe byte* Ptr;
static void Main()
{
unsafe
{
var x = new A();
byte* ptr = (x == null) ? null : x.Ptr;
}
System.Console.WriteLine(""OK"");
}
}
";
CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, expectedOutput: "OK", verify: Verification.Passes);
}
[Fact, WorkItem(40768, "https://github.com/dotnet/roslyn/issues/40768")]
public void DoesNotEmitArrayDotEmptyForEmptyPointerArrayParams()
{
var source = @"
using System;
public static class Program
{
public static unsafe void Main()
{
Console.WriteLine(Test());
}
public static unsafe int Test(params int*[] types)
{
return types.Length;
}
}";
var comp = CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, expectedOutput: "0", verify: Verification.Fails);
comp.VerifyIL("Program.Main", @"
{
// Code size 17 (0x11)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: newarr ""int*""
IL_0006: call ""int Program.Test(params int*[])""
IL_000b: call ""void System.Console.WriteLine(int)""
IL_0010: ret
}");
}
[Fact]
public void DoesEmitArrayDotEmptyForEmptyPointerArrayArrayParams()
{
var source = @"
using System;
public static class Program
{
public static unsafe void Main()
{
Console.WriteLine(Test());
}
public static unsafe int Test(params int*[][] types)
{
return types.Length;
}
}";
var comp = CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, expectedOutput: "0");
comp.VerifyIL("Program.Main", @"
{
// Code size 16 (0x10)
.maxstack 1
IL_0000: call ""int*[][] System.Array.Empty<int*[]>()""
IL_0005: call ""int Program.Test(params int*[][])""
IL_000a: call ""void System.Console.WriteLine(int)""
IL_000f: ret
}");
}
#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 Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class UnsafeTests : EmitMetadataTestBase
{
#region AddressOf tests
[Fact]
public void AddressOfLocal_Unused()
{
var text = @"
unsafe class C
{
void M()
{
int x;
int* p = &x;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes);
compVerifier.VerifyIL("C.M", @"
{
// Code size 4 (0x4)
.maxstack 1
.locals init (int V_0) //x
IL_0000: ldloca.s V_0
IL_0002: pop
IL_0003: ret
}
");
}
[Fact]
public void AddressOfLocal_Used()
{
var text = @"
unsafe class C
{
void M(int* param)
{
int x;
int* p = &x;
M(p);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails);
compVerifier.VerifyIL("C.M", @"
{
// Code size 12 (0xc)
.maxstack 2
.locals init (int V_0, //x
int* V_1) //p
IL_0000: ldloca.s V_0
IL_0002: conv.u
IL_0003: stloc.1
IL_0004: ldarg.0
IL_0005: ldloc.1
IL_0006: call ""void C.M(int*)""
IL_000b: ret
}
");
}
[Fact]
public void AddressOfParameter_Unused()
{
var text = @"
unsafe class C
{
void M(int x)
{
int* p = &x;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes);
compVerifier.VerifyIL("C.M", @"
{
// Code size 4 (0x4)
.maxstack 1
IL_0000: ldarga.s V_1
IL_0002: pop
IL_0003: ret
}
");
}
[Fact]
public void AddressOfParameter_Used()
{
var text = @"
unsafe class C
{
void M(int x, int* param)
{
int* p = &x;
M(x, p);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails);
compVerifier.VerifyIL("C.M", @"
{
// Code size 13 (0xd)
.maxstack 3
.locals init (int* V_0) //p
IL_0000: ldarga.s V_1
IL_0002: conv.u
IL_0003: stloc.0
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: ldloc.0
IL_0007: call ""void C.M(int, int*)""
IL_000c: ret
}
");
}
[Fact]
public void AddressOfStructField()
{
var text = @"
unsafe class C
{
void M()
{
S1 s;
S1* p1 = &s;
S2* p2 = &s.s;
int* p3 = &s.s.x;
Goo(s, p1, p2, p3);
}
void Goo(S1 s, S1* p1, S2* p2, int* p3) { }
}
struct S1
{
public S2 s;
}
struct S2
{
public int x;
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails);
compVerifier.VerifyIL("C.M", @"
{
// Code size 38 (0x26)
.maxstack 5
.locals init (S1 V_0, //s
S1* V_1, //p1
S2* V_2, //p2
int* V_3) //p3
IL_0000: ldloca.s V_0
IL_0002: conv.u
IL_0003: stloc.1
IL_0004: ldloca.s V_0
IL_0006: ldflda ""S2 S1.s""
IL_000b: conv.u
IL_000c: stloc.2
IL_000d: ldloca.s V_0
IL_000f: ldflda ""S2 S1.s""
IL_0014: ldflda ""int S2.x""
IL_0019: conv.u
IL_001a: stloc.3
IL_001b: ldarg.0
IL_001c: ldloc.0
IL_001d: ldloc.1
IL_001e: ldloc.2
IL_001f: ldloc.3
IL_0020: call ""void C.Goo(S1, S1*, S2*, int*)""
IL_0025: ret
}
");
}
[Fact]
public void AddressOfSuppressOptimization()
{
var text = @"
unsafe class C
{
static void M()
{
int x = 123;
Goo(&x); // should not optimize into 'Goo(&123)'
}
static void Goo(int* p) { }
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails);
compVerifier.VerifyIL("C.M", @"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (int V_0) //x
IL_0000: ldc.i4.s 123
IL_0002: stloc.0
IL_0003: ldloca.s V_0
IL_0005: conv.u
IL_0006: call ""void C.Goo(int*)""
IL_000b: ret
}
");
}
#endregion AddressOf tests
#region Dereference tests
[Fact]
public void DereferenceLocal()
{
var text = @"
unsafe class C
{
static void Main()
{
int x = 123;
int* p = &x;
System.Console.WriteLine(*p);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "123", verify: Verification.Fails);
// NOTE: p is optimized away, but & and * aren't.
compVerifier.VerifyIL("C.Main", @"
{
// Code size 13 (0xd)
.maxstack 1
.locals init (int V_0) //x
IL_0000: ldc.i4.s 123
IL_0002: stloc.0
IL_0003: ldloca.s V_0
IL_0005: conv.u
IL_0006: ldind.i4
IL_0007: call ""void System.Console.WriteLine(int)""
IL_000c: ret
}
");
}
[Fact]
public void DereferenceParameter()
{
var text = @"
unsafe class C
{
static void Main()
{
long x = 456;
System.Console.WriteLine(Dereference(&x));
}
static long Dereference(long* p)
{
return *p;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "456", verify: Verification.Fails);
compVerifier.VerifyIL("C.Dereference", @"
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldind.i8
IL_0002: ret
}
");
}
[Fact]
public void DereferenceWrite()
{
var text = @"
unsafe class C
{
static void Main()
{
int x = 1;
int* p = &x;
*p = 2;
System.Console.WriteLine(x);
}
}
";
var compVerifierOptimized = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "2", verify: Verification.Fails);
// NOTE: p is optimized away, but & and * aren't.
compVerifierOptimized.VerifyIL("C.Main", @"
{
// Code size 14 (0xe)
.maxstack 2
.locals init (int V_0) //x
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: conv.u
IL_0005: ldc.i4.2
IL_0006: stind.i4
IL_0007: ldloc.0
IL_0008: call ""void System.Console.WriteLine(int)""
IL_000d: ret
}
");
var compVerifierUnoptimized = CompileAndVerify(text, options: TestOptions.UnsafeDebugExe, expectedOutput: "2", verify: Verification.Fails);
compVerifierUnoptimized.VerifyIL("C.Main", @"
{
// Code size 18 (0x12)
.maxstack 2
.locals init (int V_0, //x
int* V_1) //p
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldloca.s V_0
IL_0005: conv.u
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: ldc.i4.2
IL_0009: stind.i4
IL_000a: ldloc.0
IL_000b: call ""void System.Console.WriteLine(int)""
IL_0010: nop
IL_0011: ret
}
");
}
[Fact]
public void DereferenceStruct()
{
var text = @"
unsafe struct S
{
S* p;
byte x;
static void Main()
{
S s;
S* sp = &s;
(*sp).p = sp;
(*sp).x = 1;
System.Console.WriteLine((*(s.p)).x);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "1", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 35 (0x23)
.maxstack 2
.locals init (S V_0, //s
S* V_1) //sp
IL_0000: ldloca.s V_0
IL_0002: conv.u
IL_0003: stloc.1
IL_0004: ldloc.1
IL_0005: ldloc.1
IL_0006: stfld ""S* S.p""
IL_000b: ldloc.1
IL_000c: ldc.i4.1
IL_000d: stfld ""byte S.x""
IL_0012: ldloc.0
IL_0013: ldfld ""S* S.p""
IL_0018: ldfld ""byte S.x""
IL_001d: call ""void System.Console.WriteLine(int)""
IL_0022: ret
}
");
}
[Fact]
public void DereferenceSwap()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
byte b1 = 2;
byte b2 = 7;
Console.WriteLine(""Before: {0} {1}"", b1, b2);
Swap(&b1, &b2);
Console.WriteLine(""After: {0} {1}"", b1, b2);
}
static void Swap(byte* p1, byte* p2)
{
byte tmp = *p1;
*p1 = *p2;
*p2 = tmp;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"Before: 2 7
After: 7 2", verify: Verification.Fails);
compVerifier.VerifyIL("C.Swap", @"
{
// Code size 11 (0xb)
.maxstack 2
.locals init (byte V_0) //tmp
IL_0000: ldarg.0
IL_0001: ldind.u1
IL_0002: stloc.0
IL_0003: ldarg.0
IL_0004: ldarg.1
IL_0005: ldind.u1
IL_0006: stind.i1
IL_0007: ldarg.1
IL_0008: ldloc.0
IL_0009: stind.i1
IL_000a: ret
}
");
}
[Fact]
public void DereferenceIsLValue1()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
char c = 'a';
char* p = &c;
Console.Write(c);
Incr(ref *p);
Console.Write(c);
}
static void Incr(ref char c)
{
c++;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"ab", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 24 (0x18)
.maxstack 2
.locals init (char V_0) //c
IL_0000: ldc.i4.s 97
IL_0002: stloc.0
IL_0003: ldloca.s V_0
IL_0005: conv.u
IL_0006: ldloc.0
IL_0007: call ""void System.Console.Write(char)""
IL_000c: call ""void C.Incr(ref char)""
IL_0011: ldloc.0
IL_0012: call ""void System.Console.Write(char)""
IL_0017: ret
}
");
}
[Fact]
public void DereferenceIsLValue2()
{
var text = @"
using System;
unsafe struct S
{
int x;
static void Main()
{
S s;
s.x = 1;
S* p = &s;
Console.Write(s.x);
(*p).Mutate();
Console.Write(s.x);
}
void Mutate()
{
x++;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"12", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 39 (0x27)
.maxstack 2
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: stfld ""int S.x""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldloc.0
IL_000c: ldfld ""int S.x""
IL_0011: call ""void System.Console.Write(int)""
IL_0016: call ""void S.Mutate()""
IL_001b: ldloc.0
IL_001c: ldfld ""int S.x""
IL_0021: call ""void System.Console.Write(int)""
IL_0026: ret
}
");
}
#endregion Dereference tests
#region Pointer member access tests
[Fact]
public void PointerMemberAccessRead()
{
var text = @"
using System;
unsafe struct S
{
int x;
static void Main()
{
S s;
s.x = 3;
S* p = &s;
Console.Write(p->x);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"3", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.3
IL_0003: stfld ""int S.x""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldfld ""int S.x""
IL_0010: call ""void System.Console.Write(int)""
IL_0015: ret
}
");
compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"3", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.3
IL_0003: stfld ""int S.x""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldfld ""int S.x""
IL_0010: call ""void System.Console.Write(int)""
IL_0015: ret
}
");
}
[Fact]
public void PointerMemberAccessWrite()
{
var text = @"
using System;
unsafe struct S
{
int x;
static void Main()
{
S s;
s.x = 3;
S* p = &s;
Console.Write(s.x);
p->x = 4;
Console.Write(s.x);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"34", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 40 (0x28)
.maxstack 2
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.3
IL_0003: stfld ""int S.x""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldloc.0
IL_000c: ldfld ""int S.x""
IL_0011: call ""void System.Console.Write(int)""
IL_0016: ldc.i4.4
IL_0017: stfld ""int S.x""
IL_001c: ldloc.0
IL_001d: ldfld ""int S.x""
IL_0022: call ""void System.Console.Write(int)""
IL_0027: ret
}
");
compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"34", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 40 (0x28)
.maxstack 2
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.3
IL_0003: stfld ""int S.x""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldloc.0
IL_000c: ldfld ""int S.x""
IL_0011: call ""void System.Console.Write(int)""
IL_0016: ldc.i4.4
IL_0017: stfld ""int S.x""
IL_001c: ldloc.0
IL_001d: ldfld ""int S.x""
IL_0022: call ""void System.Console.Write(int)""
IL_0027: ret
}
");
}
[Fact]
public void PointerMemberAccessInvoke()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S s;
S* p = &s;
p->M();
p->M(1);
p->M(1, 2);
}
void M() { Console.Write(1); }
void M(int x) { Console.Write(2); }
}
static class Extensions
{
public static void M(this S s, int x, int y) { Console.Write(3); }
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"123", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 29 (0x1d)
.maxstack 3
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: conv.u
IL_0003: dup
IL_0004: call ""void S.M()""
IL_0009: dup
IL_000a: ldc.i4.1
IL_000b: call ""void S.M(int)""
IL_0010: ldobj ""S""
IL_0015: ldc.i4.1
IL_0016: ldc.i4.2
IL_0017: call ""void Extensions.M(S, int, int)""
IL_001c: ret
}
");
compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"123", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 29 (0x1d)
.maxstack 3
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: conv.u
IL_0003: dup
IL_0004: call ""void S.M()""
IL_0009: dup
IL_000a: ldc.i4.1
IL_000b: call ""void S.M(int)""
IL_0010: ldobj ""S""
IL_0015: ldc.i4.1
IL_0016: ldc.i4.2
IL_0017: call ""void Extensions.M(S, int, int)""
IL_001c: ret
}
");
}
[Fact]
public void PointerMemberAccessInvoke001()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S s;
S* p = &s;
Test(ref p);
}
static void Test(ref S* p)
{
p->M();
p->M(1);
p->M(1, 2);
}
void M() { Console.Write(1); }
void M(int x) { Console.Write(2); }
}
static class Extensions
{
public static void M(this S s, int x, int y) { Console.Write(3); }
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"123", verify: Verification.Fails);
compVerifier.VerifyIL("S.Test(ref S*)", @"
{
// Code size 30 (0x1e)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldind.i
IL_0002: call ""void S.M()""
IL_0007: ldarg.0
IL_0008: ldind.i
IL_0009: ldc.i4.1
IL_000a: call ""void S.M(int)""
IL_000f: ldarg.0
IL_0010: ldind.i
IL_0011: ldobj ""S""
IL_0016: ldc.i4.1
IL_0017: ldc.i4.2
IL_0018: call ""void Extensions.M(S, int, int)""
IL_001d: ret
}
");
compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"123", verify: Verification.Fails);
compVerifier.VerifyIL("S.Test(ref S*)", @"
{
// Code size 30 (0x1e)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldind.i
IL_0002: call ""void S.M()""
IL_0007: ldarg.0
IL_0008: ldind.i
IL_0009: ldc.i4.1
IL_000a: call ""void S.M(int)""
IL_000f: ldarg.0
IL_0010: ldind.i
IL_0011: ldobj ""S""
IL_0016: ldc.i4.1
IL_0017: ldc.i4.2
IL_0018: call ""void Extensions.M(S, int, int)""
IL_001d: ret
}
");
}
[Fact]
public void PointerMemberAccessMutate()
{
var text = @"
using System;
unsafe struct S
{
int x;
static void Main()
{
S s;
s.x = 3;
S* p = &s;
Console.Write((p->x)++);
Console.Write((p->x)++);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"34", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 49 (0x31)
.maxstack 4
.locals init (S V_0, //s
int V_1)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.3
IL_0003: stfld ""int S.x""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: dup
IL_000c: ldflda ""int S.x""
IL_0011: dup
IL_0012: ldind.i4
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: ldc.i4.1
IL_0016: add
IL_0017: stind.i4
IL_0018: ldloc.1
IL_0019: call ""void System.Console.Write(int)""
IL_001e: ldflda ""int S.x""
IL_0023: dup
IL_0024: ldind.i4
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: ldc.i4.1
IL_0028: add
IL_0029: stind.i4
IL_002a: ldloc.1
IL_002b: call ""void System.Console.Write(int)""
IL_0030: ret
}
");
compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"34", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 49 (0x31)
.maxstack 4
.locals init (S V_0, //s
int V_1)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.3
IL_0003: stfld ""int S.x""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: dup
IL_000c: ldflda ""int S.x""
IL_0011: dup
IL_0012: ldind.i4
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: ldc.i4.1
IL_0016: add
IL_0017: stind.i4
IL_0018: ldloc.1
IL_0019: call ""void System.Console.Write(int)""
IL_001e: ldflda ""int S.x""
IL_0023: dup
IL_0024: ldind.i4
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: ldc.i4.1
IL_0028: add
IL_0029: stind.i4
IL_002a: ldloc.1
IL_002b: call ""void System.Console.Write(int)""
IL_0030: ret
}
");
}
#endregion Pointer member access tests
#region Pointer element access tests
[Fact]
public void PointerElementAccessCheckedAndUnchecked()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S s = new S();
S* p = &s;
int i = (int)p;
uint ui = (uint)p;
long l = (long)p;
ulong ul = (ulong)p;
checked
{
s = p[i];
s = p[ui];
s = p[l];
s = p[ul];
}
unchecked
{
s = p[i];
s = p[ui];
s = p[l];
s = p[ul];
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails);
// The conversions differ from dev10 in the same way as for numeric addition.
// Note that, unlike for numeric addition, the add operation is never checked.
compVerifier.VerifyIL("S.Main", @"
{
// Code size 170 (0xaa)
.maxstack 4
.locals init (S V_0, //s
int V_1, //i
uint V_2, //ui
long V_3, //l
ulong V_4) //ul
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: dup
IL_000c: conv.i4
IL_000d: stloc.1
IL_000e: dup
IL_000f: conv.u4
IL_0010: stloc.2
IL_0011: dup
IL_0012: conv.u8
IL_0013: stloc.3
IL_0014: dup
IL_0015: conv.u8
IL_0016: stloc.s V_4
IL_0018: dup
IL_0019: ldloc.1
IL_001a: conv.i
IL_001b: sizeof ""S""
IL_0021: mul.ovf
IL_0022: add
IL_0023: ldobj ""S""
IL_0028: stloc.0
IL_0029: dup
IL_002a: ldloc.2
IL_002b: conv.u8
IL_002c: sizeof ""S""
IL_0032: conv.i8
IL_0033: mul.ovf
IL_0034: conv.i
IL_0035: add
IL_0036: ldobj ""S""
IL_003b: stloc.0
IL_003c: dup
IL_003d: ldloc.3
IL_003e: sizeof ""S""
IL_0044: conv.i8
IL_0045: mul.ovf
IL_0046: conv.i
IL_0047: add
IL_0048: ldobj ""S""
IL_004d: stloc.0
IL_004e: dup
IL_004f: ldloc.s V_4
IL_0051: sizeof ""S""
IL_0057: conv.ovf.u8
IL_0058: mul.ovf.un
IL_0059: conv.u
IL_005a: add
IL_005b: ldobj ""S""
IL_0060: stloc.0
IL_0061: dup
IL_0062: ldloc.1
IL_0063: conv.i
IL_0064: sizeof ""S""
IL_006a: mul
IL_006b: add
IL_006c: ldobj ""S""
IL_0071: stloc.0
IL_0072: dup
IL_0073: ldloc.2
IL_0074: conv.u8
IL_0075: sizeof ""S""
IL_007b: conv.i8
IL_007c: mul
IL_007d: conv.i
IL_007e: add
IL_007f: ldobj ""S""
IL_0084: stloc.0
IL_0085: dup
IL_0086: ldloc.3
IL_0087: sizeof ""S""
IL_008d: conv.i8
IL_008e: mul
IL_008f: conv.i
IL_0090: add
IL_0091: ldobj ""S""
IL_0096: stloc.0
IL_0097: ldloc.s V_4
IL_0099: sizeof ""S""
IL_009f: conv.i8
IL_00a0: mul
IL_00a1: conv.u
IL_00a2: add
IL_00a3: ldobj ""S""
IL_00a8: stloc.0
IL_00a9: ret
}
");
}
[Fact]
public void PointerElementAccessWrite()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
int* p = null;
p[1] = 2;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 9 (0x9)
.maxstack 2
.locals init (int* V_0) //p
IL_0000: ldc.i4.0
IL_0001: conv.u
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldc.i4.4
IL_0005: add
IL_0006: ldc.i4.2
IL_0007: stind.i4
IL_0008: ret
}
");
}
[Fact]
public void PointerElementAccessMutate()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
int[] array = new int[3];
fixed (int* p = array)
{
p[1] += ++p[0];
p[2] -= p[1]--;
}
foreach (int element in array)
{
Console.WriteLine(element);
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"
1
0
-1", verify: Verification.Fails);
}
[Fact]
public void PointerElementAccessNested()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
fixed (int* q = new int[3])
{
q[0] = 2;
q[1] = 0;
q[2] = 1;
Console.Write(q[q[q[q[q[q[*q]]]]]]);
Console.Write(q[q[q[q[q[q[q[*q]]]]]]]);
Console.Write(q[q[q[q[q[q[q[q[*q]]]]]]]]);
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "210", verify: Verification.Fails);
}
[Fact]
public void PointerElementAccessZero()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
int x = 1;
int* p = &x;
Console.WriteLine(p[0]);
}
}
";
// NOTE: no pointer arithmetic - just dereference p.
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "1", verify: Verification.Fails).VerifyIL("C.Main", @"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (int V_0) //x
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: conv.u
IL_0005: ldind.i4
IL_0006: call ""void System.Console.WriteLine(int)""
IL_000b: ret
}
");
}
#endregion Pointer element access tests
#region Fixed statement tests
[Fact]
public void FixedStatementField()
{
var text = @"
using System;
unsafe class C
{
int x;
static void Main()
{
C c = new C();
fixed (int* p = &c.x)
{
*p = 1;
}
Console.WriteLine(c.x);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"1", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 30 (0x1e)
.maxstack 3
.locals init (pinned int& V_0)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: ldflda ""int C.x""
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: conv.u
IL_000e: ldc.i4.1
IL_000f: stind.i4
IL_0010: ldc.i4.0
IL_0011: conv.u
IL_0012: stloc.0
IL_0013: ldfld ""int C.x""
IL_0018: call ""void System.Console.WriteLine(int)""
IL_001d: ret
}
");
}
[Fact]
public void FixedStatementThis()
{
var text = @"
public class Program
{
public static void Main()
{
S1 s = default;
s.Test();
}
unsafe readonly struct S1
{
readonly int x;
public void Test()
{
fixed(void* p = &this)
{
*(int*)p = 123;
}
ref readonly S1 r = ref this;
fixed (S1* p = &r)
{
System.Console.WriteLine(p->x);
}
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"123", verify: Verification.Fails);
compVerifier.VerifyIL("Program.S1.Test()", @"
{
// Code size 30 (0x1e)
.maxstack 2
.locals init (void* V_0, //p
pinned Program.S1& V_1)
IL_0000: ldarg.0
IL_0001: stloc.1
IL_0002: ldloc.1
IL_0003: conv.u
IL_0004: stloc.0
IL_0005: ldloc.0
IL_0006: ldc.i4.s 123
IL_0008: stind.i4
IL_0009: ldc.i4.0
IL_000a: conv.u
IL_000b: stloc.1
IL_000c: ldarg.0
IL_000d: stloc.1
IL_000e: ldloc.1
IL_000f: conv.u
IL_0010: ldfld ""int Program.S1.x""
IL_0015: call ""void System.Console.WriteLine(int)""
IL_001a: ldc.i4.0
IL_001b: conv.u
IL_001c: stloc.1
IL_001d: ret
}
");
}
[WorkItem(22306, "https://github.com/dotnet/roslyn/issues/22306")]
[Fact]
public void FixedStatementMultipleFields()
{
var text = @"
using System;
unsafe class C
{
int x;
readonly int y;
static void Main()
{
C c = new C();
fixed (int* p = &c.x, q = &c.y)
{
*p = 1;
*q = 2;
}
Console.Write(c.x);
Console.Write(c.y);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"12", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 57 (0x39)
.maxstack 4
.locals init (int* V_0, //p
pinned int& V_1,
pinned int& V_2)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: ldflda ""int C.x""
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: conv.u
IL_000e: stloc.0
IL_000f: dup
IL_0010: ldflda ""int C.y""
IL_0015: stloc.2
IL_0016: ldloc.2
IL_0017: conv.u
IL_0018: ldloc.0
IL_0019: ldc.i4.1
IL_001a: stind.i4
IL_001b: ldc.i4.2
IL_001c: stind.i4
IL_001d: ldc.i4.0
IL_001e: conv.u
IL_001f: stloc.1
IL_0020: ldc.i4.0
IL_0021: conv.u
IL_0022: stloc.2
IL_0023: dup
IL_0024: ldfld ""int C.x""
IL_0029: call ""void System.Console.Write(int)""
IL_002e: ldfld ""int C.y""
IL_0033: call ""void System.Console.Write(int)""
IL_0038: ret
}
");
}
[WorkItem(22306, "https://github.com/dotnet/roslyn/issues/22306")]
[Fact]
public void FixedStatementMultipleMethods()
{
var text = @"
using System;
unsafe class C
{
int x;
readonly int y;
ref int X()=>ref x;
ref readonly int this[int i]=>ref y;
static void Main()
{
C c = new C();
fixed (int* p = &c.X(), q = &c[3])
{
*p = 1;
*q = 2;
}
Console.Write(c.x);
Console.Write(c.y);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"12", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 58 (0x3a)
.maxstack 4
.locals init (int* V_0, //p
pinned int& V_1,
pinned int& V_2)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: callvirt ""ref int C.X()""
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: conv.u
IL_000e: stloc.0
IL_000f: dup
IL_0010: ldc.i4.3
IL_0011: callvirt ""ref readonly int C.this[int].get""
IL_0016: stloc.2
IL_0017: ldloc.2
IL_0018: conv.u
IL_0019: ldloc.0
IL_001a: ldc.i4.1
IL_001b: stind.i4
IL_001c: ldc.i4.2
IL_001d: stind.i4
IL_001e: ldc.i4.0
IL_001f: conv.u
IL_0020: stloc.1
IL_0021: ldc.i4.0
IL_0022: conv.u
IL_0023: stloc.2
IL_0024: dup
IL_0025: ldfld ""int C.x""
IL_002a: call ""void System.Console.Write(int)""
IL_002f: ldfld ""int C.y""
IL_0034: call ""void System.Console.Write(int)""
IL_0039: ret
}
");
}
[WorkItem(546866, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546866")]
[Fact]
public void FixedStatementProperty()
{
var text =
@"class C
{
string P { get { return null; } }
char[] Q { get { return null; } }
unsafe static void M(C c)
{
fixed (char* o = c.P)
{
}
fixed (char* o = c.Q)
{
}
}
}";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails);
compVerifier.VerifyIL("C.M(C)",
@"
{
// Code size 55 (0x37)
.maxstack 2
.locals init (char* V_0, //o
pinned string V_1,
char* V_2, //o
pinned char[] V_3)
IL_0000: ldarg.0
IL_0001: callvirt ""string C.P.get""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_0015
IL_000d: ldloc.0
IL_000e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0013: add
IL_0014: stloc.0
IL_0015: ldnull
IL_0016: stloc.1
IL_0017: ldarg.0
IL_0018: callvirt ""char[] C.Q.get""
IL_001d: dup
IL_001e: stloc.3
IL_001f: brfalse.s IL_0026
IL_0021: ldloc.3
IL_0022: ldlen
IL_0023: conv.i4
IL_0024: brtrue.s IL_002b
IL_0026: ldc.i4.0
IL_0027: conv.u
IL_0028: stloc.2
IL_0029: br.s IL_0034
IL_002b: ldloc.3
IL_002c: ldc.i4.0
IL_002d: ldelema ""char""
IL_0032: conv.u
IL_0033: stloc.2
IL_0034: ldnull
IL_0035: stloc.3
IL_0036: ret
}
");
}
[Fact]
public void FixedStatementMultipleOptimized()
{
var text = @"
using System;
unsafe class C
{
int x;
int y;
static void Main()
{
C c = new C();
fixed (int* p = &c.x, q = &c.y)
{
*p = 1;
*q = 2;
}
Console.Write(c.x);
Console.Write(c.y);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"12", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 57 (0x39)
.maxstack 4
.locals init (int* V_0, //p
pinned int& V_1,
pinned int& V_2)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: ldflda ""int C.x""
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: conv.u
IL_000e: stloc.0
IL_000f: dup
IL_0010: ldflda ""int C.y""
IL_0015: stloc.2
IL_0016: ldloc.2
IL_0017: conv.u
IL_0018: ldloc.0
IL_0019: ldc.i4.1
IL_001a: stind.i4
IL_001b: ldc.i4.2
IL_001c: stind.i4
IL_001d: ldc.i4.0
IL_001e: conv.u
IL_001f: stloc.1
IL_0020: ldc.i4.0
IL_0021: conv.u
IL_0022: stloc.2
IL_0023: dup
IL_0024: ldfld ""int C.x""
IL_0029: call ""void System.Console.Write(int)""
IL_002e: ldfld ""int C.y""
IL_0033: call ""void System.Console.Write(int)""
IL_0038: ret
}
");
}
[Fact]
public void FixedStatementReferenceParameter()
{
var text = @"
using System;
class C
{
static void Main()
{
char ch;
M(out ch);
Console.WriteLine(ch);
}
unsafe static void M(out char ch)
{
fixed (char* p = &ch)
{
*p = 'a';
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"a", verify: Verification.Fails);
compVerifier.VerifyIL("C.M", @"
{
// Code size 11 (0xb)
.maxstack 2
.locals init (pinned char& V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: conv.u
IL_0004: ldc.i4.s 97
IL_0006: stind.i2
IL_0007: ldc.i4.0
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ret
}
");
}
[Fact]
public void FixedStatementReferenceParameterDebug()
{
var text = @"
using System;
class C
{
static void Main()
{
char ch;
M(out ch);
Console.WriteLine(ch);
}
unsafe static void M(out char ch)
{
fixed (char* p = &ch)
{
*p = 'a';
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeDebugExe, expectedOutput: @"a", verify: Verification.Fails);
compVerifier.VerifyIL("C.M", @"
{
// Code size 16 (0x10)
.maxstack 2
.locals init (char* V_0, //p
pinned char& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.1
IL_0003: ldloc.1
IL_0004: conv.u
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldc.i4.s 97
IL_000a: stind.i2
IL_000b: nop
IL_000c: ldc.i4.0
IL_000d: conv.u
IL_000e: stloc.1
IL_000f: ret
}
");
}
[Fact]
public void FixedStatementStringLiteral()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
fixed (char* p = ""hello"")
{
Console.WriteLine(*p);
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeDebugExe, expectedOutput: @"h", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 34 (0x22)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
-IL_0000: nop
IL_0001: ldstr ""hello""
IL_0006: stloc.1
-IL_0007: ldloc.1
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_0015
IL_000d: ldloc.0
IL_000e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0013: add
IL_0014: stloc.0
-IL_0015: nop
-IL_0016: ldloc.0
IL_0017: ldind.u2
IL_0018: call ""void System.Console.WriteLine(char)""
IL_001d: nop
-IL_001e: nop
~IL_001f: ldnull
IL_0020: stloc.1
-IL_0021: ret
}
", sequencePoints: "C.Main");
}
[Fact]
public void FixedStatementStringVariable()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
string s = ""hello"";
fixed (char* p = s)
{
Console.Write(*p);
}
s = null;
fixed (char* p = s)
{
Console.Write(p == null);
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeDebugExe, expectedOutput: @"hTrue", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 72 (0x48)
.maxstack 2
.locals init (string V_0, //s
char* V_1, //p
pinned string V_2,
char* V_3, //p
pinned string V_4)
-IL_0000: nop
-IL_0001: ldstr ""hello""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: stloc.2
-IL_0009: ldloc.2
IL_000a: conv.u
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: brfalse.s IL_0017
IL_000f: ldloc.1
IL_0010: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0015: add
IL_0016: stloc.1
-IL_0017: nop
-IL_0018: ldloc.1
IL_0019: ldind.u2
IL_001a: call ""void System.Console.Write(char)""
IL_001f: nop
-IL_0020: nop
~IL_0021: ldnull
IL_0022: stloc.2
-IL_0023: ldnull
IL_0024: stloc.0
IL_0025: ldloc.0
IL_0026: stloc.s V_4
-IL_0028: ldloc.s V_4
IL_002a: conv.u
IL_002b: stloc.3
IL_002c: ldloc.3
IL_002d: brfalse.s IL_0037
IL_002f: ldloc.3
IL_0030: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0035: add
IL_0036: stloc.3
-IL_0037: nop
-IL_0038: ldloc.3
IL_0039: ldc.i4.0
IL_003a: conv.u
IL_003b: ceq
IL_003d: call ""void System.Console.Write(bool)""
IL_0042: nop
-IL_0043: nop
~IL_0044: ldnull
IL_0045: stloc.s V_4
-IL_0047: ret
}
", sequencePoints: "C.Main");
}
[Fact]
public void FixedStatementStringVariableOptimized()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
string s = ""hello"";
fixed (char* p = s)
{
Console.Write(*p);
}
s = null;
fixed (char* p = s)
{
Console.Write(p == null);
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"hTrue", verify: Verification.Fails);
// Null checks and branches are much simpler, but string temps are NOT optimized away.
compVerifier.VerifyIL("C.Main", @"
{
// Code size 58 (0x3a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1,
char* V_2) //p
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldloc.0
IL_0015: ldind.u2
IL_0016: call ""void System.Console.Write(char)""
IL_001b: ldnull
IL_001c: stloc.1
IL_001d: ldnull
IL_001e: stloc.1
IL_001f: ldloc.1
IL_0020: conv.u
IL_0021: stloc.2
IL_0022: ldloc.2
IL_0023: brfalse.s IL_002d
IL_0025: ldloc.2
IL_0026: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_002b: add
IL_002c: stloc.2
IL_002d: ldloc.2
IL_002e: ldc.i4.0
IL_002f: conv.u
IL_0030: ceq
IL_0032: call ""void System.Console.Write(bool)""
IL_0037: ldnull
IL_0038: stloc.1
IL_0039: ret
}
");
}
[Fact]
public void FixedStatementOneDimensionalArray()
{
var text = @"
using System;
unsafe class C
{
int[] a = new int[1];
static void Main()
{
C c = new C();
Console.Write(c.a[0]);
fixed (int* p = c.a)
{
*p = 1;
}
Console.Write(c.a[0]);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"01", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 65 (0x41)
.maxstack 3
.locals init (int* V_0, //p
pinned int[] V_1)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: ldfld ""int[] C.a""
IL_000b: ldc.i4.0
IL_000c: ldelem.i4
IL_000d: call ""void System.Console.Write(int)""
IL_0012: dup
IL_0013: ldfld ""int[] C.a""
IL_0018: dup
IL_0019: stloc.1
IL_001a: brfalse.s IL_0021
IL_001c: ldloc.1
IL_001d: ldlen
IL_001e: conv.i4
IL_001f: brtrue.s IL_0026
IL_0021: ldc.i4.0
IL_0022: conv.u
IL_0023: stloc.0
IL_0024: br.s IL_002f
IL_0026: ldloc.1
IL_0027: ldc.i4.0
IL_0028: ldelema ""int""
IL_002d: conv.u
IL_002e: stloc.0
IL_002f: ldloc.0
IL_0030: ldc.i4.1
IL_0031: stind.i4
IL_0032: ldnull
IL_0033: stloc.1
IL_0034: ldfld ""int[] C.a""
IL_0039: ldc.i4.0
IL_003a: ldelem.i4
IL_003b: call ""void System.Console.Write(int)""
IL_0040: ret
}
");
}
[Fact]
public void FixedStatementOneDimensionalArrayOptimized()
{
var text = @"
using System;
unsafe class C
{
int[] a = new int[1];
static void Main()
{
C c = new C();
Console.Write(c.a[0]);
fixed (int* p = c.a)
{
*p = 1;
}
Console.Write(c.a[0]);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"01", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 65 (0x41)
.maxstack 3
.locals init (int* V_0, //p
pinned int[] V_1)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: ldfld ""int[] C.a""
IL_000b: ldc.i4.0
IL_000c: ldelem.i4
IL_000d: call ""void System.Console.Write(int)""
IL_0012: dup
IL_0013: ldfld ""int[] C.a""
IL_0018: dup
IL_0019: stloc.1
IL_001a: brfalse.s IL_0021
IL_001c: ldloc.1
IL_001d: ldlen
IL_001e: conv.i4
IL_001f: brtrue.s IL_0026
IL_0021: ldc.i4.0
IL_0022: conv.u
IL_0023: stloc.0
IL_0024: br.s IL_002f
IL_0026: ldloc.1
IL_0027: ldc.i4.0
IL_0028: ldelema ""int""
IL_002d: conv.u
IL_002e: stloc.0
IL_002f: ldloc.0
IL_0030: ldc.i4.1
IL_0031: stind.i4
IL_0032: ldnull
IL_0033: stloc.1
IL_0034: ldfld ""int[] C.a""
IL_0039: ldc.i4.0
IL_003a: ldelem.i4
IL_003b: call ""void System.Console.Write(int)""
IL_0040: ret
}
");
}
[Fact]
public void FixedStatementMultiDimensionalArrayOptimized()
{
var text = @"
using System;
unsafe class C
{
int[,] a = new int[1,1];
static void Main()
{
C c = new C();
Console.Write(c.a[0, 0]);
fixed (int* p = c.a)
{
*p = 1;
}
Console.Write(c.a[0, 0]);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"01", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 79 (0x4f)
.maxstack 4
.locals init (int* V_0, //p
pinned int[,] V_1)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: ldfld ""int[,] C.a""
IL_000b: ldc.i4.0
IL_000c: ldc.i4.0
IL_000d: call ""int[*,*].Get""
IL_0012: call ""void System.Console.Write(int)""
IL_0017: dup
IL_0018: ldfld ""int[,] C.a""
IL_001d: dup
IL_001e: stloc.1
IL_001f: brfalse.s IL_0029
IL_0021: ldloc.1
IL_0022: callvirt ""int System.Array.Length.get""
IL_0027: brtrue.s IL_002e
IL_0029: ldc.i4.0
IL_002a: conv.u
IL_002b: stloc.0
IL_002c: br.s IL_0038
IL_002e: ldloc.1
IL_002f: ldc.i4.0
IL_0030: ldc.i4.0
IL_0031: call ""int[*,*].Address""
IL_0036: conv.u
IL_0037: stloc.0
IL_0038: ldloc.0
IL_0039: ldc.i4.1
IL_003a: stind.i4
IL_003b: ldnull
IL_003c: stloc.1
IL_003d: ldfld ""int[,] C.a""
IL_0042: ldc.i4.0
IL_0043: ldc.i4.0
IL_0044: call ""int[*,*].Get""
IL_0049: call ""void System.Console.Write(int)""
IL_004e: ret
}
");
}
[Fact]
public void FixedStatementMixed()
{
var text = @"
using System;
unsafe class C
{
char c = 'a';
char[] a = new char[1];
static void Main()
{
C c = new C();
fixed (char* p = &c.c, q = c.a, r = ""hello"")
{
Console.Write((int)*p);
Console.Write((int)*q);
Console.Write((int)*r);
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"970104", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 99 (0x63)
.maxstack 2
.locals init (char* V_0, //p
char* V_1, //q
char* V_2, //r
pinned char& V_3,
pinned char[] V_4,
pinned string V_5)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: ldflda ""char C.c""
IL_000b: stloc.3
IL_000c: ldloc.3
IL_000d: conv.u
IL_000e: stloc.0
IL_000f: ldfld ""char[] C.a""
IL_0014: dup
IL_0015: stloc.s V_4
IL_0017: brfalse.s IL_001f
IL_0019: ldloc.s V_4
IL_001b: ldlen
IL_001c: conv.i4
IL_001d: brtrue.s IL_0024
IL_001f: ldc.i4.0
IL_0020: conv.u
IL_0021: stloc.1
IL_0022: br.s IL_002e
IL_0024: ldloc.s V_4
IL_0026: ldc.i4.0
IL_0027: ldelema ""char""
IL_002c: conv.u
IL_002d: stloc.1
IL_002e: ldstr ""hello""
IL_0033: stloc.s V_5
IL_0035: ldloc.s V_5
IL_0037: conv.u
IL_0038: stloc.2
IL_0039: ldloc.2
IL_003a: brfalse.s IL_0044
IL_003c: ldloc.2
IL_003d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0042: add
IL_0043: stloc.2
IL_0044: ldloc.0
IL_0045: ldind.u2
IL_0046: call ""void System.Console.Write(int)""
IL_004b: ldloc.1
IL_004c: ldind.u2
IL_004d: call ""void System.Console.Write(int)""
IL_0052: ldloc.2
IL_0053: ldind.u2
IL_0054: call ""void System.Console.Write(int)""
IL_0059: ldc.i4.0
IL_005a: conv.u
IL_005b: stloc.3
IL_005c: ldnull
IL_005d: stloc.s V_4
IL_005f: ldnull
IL_0060: stloc.s V_5
IL_0062: ret
}
");
}
[Fact]
public void FixedStatementInTryOfTryFinally()
{
var text = @"
unsafe class C
{
static void nop() { }
void Test()
{
try
{
fixed (char* p = ""hello"")
{
}
}
finally
{
nop();
}
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 32 (0x20)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_001f
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
}
finally
{
IL_0019: call ""void C.nop()""
IL_001e: endfinally
}
IL_001f: ret
}
");
}
[Fact]
public void FixedStatementInTryOfTryCatch()
{
var text = @"
unsafe class C
{
void Test()
{
try
{
fixed (char* p = ""hello"")
{
}
}
catch
{
}
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 31 (0x1f)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_0019
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: leave.s IL_001e
}
catch object
{
IL_001b: pop
IL_001c: leave.s IL_001e
}
IL_001e: ret
}
");
}
[Fact]
public void FixedStatementInFinally()
{
var text = @"
unsafe class C
{
void Test()
{
try
{
}
finally
{
fixed (char* p = ""hello"")
{
}
}
}
}
";
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: leave.s IL_0019
}
finally
{
IL_0002: ldstr ""hello""
IL_0007: stloc.1
IL_0008: ldloc.1
IL_0009: conv.u
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0016
IL_000e: ldloc.0
IL_000f: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0014: add
IL_0015: stloc.0
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: ret
}
");
}
[Fact]
public void FixedStatementInCatchOfTryCatch()
{
var text = @"
unsafe class C
{
void nop() { }
void Test()
{
try
{
nop();
}
catch
{
fixed (char* p = ""hello"")
{
}
}
}
}
";
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test",
@"{
// Code size 34 (0x22)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: ldarg.0
IL_0001: call ""void C.nop()""
IL_0006: leave.s IL_0021
}
catch object
{
IL_0008: pop
IL_0009: ldstr ""hello""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: conv.u
IL_0011: stloc.0
IL_0012: ldloc.0
IL_0013: brfalse.s IL_001d
IL_0015: ldloc.0
IL_0016: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_001b: add
IL_001c: stloc.0
IL_001d: ldnull
IL_001e: stloc.1
IL_001f: leave.s IL_0021
}
IL_0021: ret
}");
}
[Fact]
public void FixedStatementInCatchOfTryCatchFinally()
{
var text = @"
unsafe class C
{
static void nop() { }
void Test()
{
try
{
nop();
}
catch
{
fixed (char* p = ""hello"")
{
}
}
finally
{
}
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 36 (0x24)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: call ""void C.nop()""
IL_0005: leave.s IL_0023
}
catch object
{
IL_0007: pop
.try
{
IL_0008: ldstr ""hello""
IL_000d: stloc.1
IL_000e: ldloc.1
IL_000f: conv.u
IL_0010: stloc.0
IL_0011: ldloc.0
IL_0012: brfalse.s IL_001c
IL_0014: ldloc.0
IL_0015: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_001a: add
IL_001b: stloc.0
IL_001c: leave.s IL_0021
}
finally
{
IL_001e: ldnull
IL_001f: stloc.1
IL_0020: endfinally
}
IL_0021: leave.s IL_0023
}
IL_0023: ret
}
");
}
[Fact]
public void FixedStatementInFixed_NoBranch()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* q = ""goodbye"")
{
fixed (char* p = ""hello"")
{
}
}
}
}
";
// Neither inner nor outer has finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 45 (0x2d)
.maxstack 2
.locals init (char* V_0, //q
pinned string V_1,
char* V_2, //p
pinned string V_3)
IL_0000: ldstr ""goodbye""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldstr ""hello""
IL_0019: stloc.3
IL_001a: ldloc.3
IL_001b: conv.u
IL_001c: stloc.2
IL_001d: ldloc.2
IL_001e: brfalse.s IL_0028
IL_0020: ldloc.2
IL_0021: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0026: add
IL_0027: stloc.2
IL_0028: ldnull
IL_0029: stloc.3
IL_002a: ldnull
IL_002b: stloc.1
IL_002c: ret
}
");
}
[Fact]
public void FixedStatementInFixed_InnerBranch()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* q = ""goodbye"")
{
fixed (char* p = ""hello"")
{
goto label;
}
}
label: ;
}
}
";
// Inner and outer both have finally blocks.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 50 (0x32)
.maxstack 2
.locals init (char* V_0, //q
pinned string V_1,
char* V_2, //p
pinned string V_3)
.try
{
IL_0000: ldstr ""goodbye""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: nop
.try
{
IL_0015: ldstr ""hello""
IL_001a: stloc.3
IL_001b: ldloc.3
IL_001c: conv.u
IL_001d: stloc.2
IL_001e: ldloc.2
IL_001f: brfalse.s IL_0029
IL_0021: ldloc.2
IL_0022: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0027: add
IL_0028: stloc.2
IL_0029: leave.s IL_0031
}
finally
{
IL_002b: ldnull
IL_002c: stloc.3
IL_002d: endfinally
}
}
finally
{
IL_002e: ldnull
IL_002f: stloc.1
IL_0030: endfinally
}
IL_0031: ret
}
");
}
[Fact]
public void FixedStatementInFixed_OuterBranch()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* q = ""goodbye"")
{
fixed (char* p = ""hello"")
{
}
goto label;
}
label: ;
}
}
";
// Outer has finally, inner does not.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 48 (0x30)
.maxstack 2
.locals init (char* V_0, //q
pinned string V_1,
char* V_2, //p
pinned string V_3)
.try
{
IL_0000: ldstr ""goodbye""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldstr ""hello""
IL_0019: stloc.3
IL_001a: ldloc.3
IL_001b: conv.u
IL_001c: stloc.2
IL_001d: ldloc.2
IL_001e: brfalse.s IL_0028
IL_0020: ldloc.2
IL_0021: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0026: add
IL_0027: stloc.2
IL_0028: ldnull
IL_0029: stloc.3
IL_002a: leave.s IL_002f
}
finally
{
IL_002c: ldnull
IL_002d: stloc.1
IL_002e: endfinally
}
IL_002f: ret
}
");
}
[Fact]
public void FixedStatementInFixed_Nesting()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p1 = ""A"")
{
fixed (char* p2 = ""B"")
{
fixed (char* p3 = ""C"")
{
}
fixed (char* p4 = ""D"")
{
}
}
fixed (char* p5 = ""E"")
{
fixed (char* p6 = ""F"")
{
}
fixed (char* p7 = ""G"")
{
}
}
}
}
}
";
// This test checks two things:
// 1) nothing blows up with triple-nesting, and
// 2) none of the fixed statements has a try-finally.
// CONSIDER: Shorter test that performs the same checks.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 187 (0xbb)
.maxstack 2
.locals init (char* V_0, //p1
pinned string V_1,
char* V_2, //p2
pinned string V_3,
char* V_4, //p3
pinned string V_5,
char* V_6, //p4
char* V_7, //p5
char* V_8, //p6
char* V_9) //p7
IL_0000: ldstr ""A""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldstr ""B""
IL_0019: stloc.3
IL_001a: ldloc.3
IL_001b: conv.u
IL_001c: stloc.2
IL_001d: ldloc.2
IL_001e: brfalse.s IL_0028
IL_0020: ldloc.2
IL_0021: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0026: add
IL_0027: stloc.2
IL_0028: ldstr ""C""
IL_002d: stloc.s V_5
IL_002f: ldloc.s V_5
IL_0031: conv.u
IL_0032: stloc.s V_4
IL_0034: ldloc.s V_4
IL_0036: brfalse.s IL_0042
IL_0038: ldloc.s V_4
IL_003a: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_003f: add
IL_0040: stloc.s V_4
IL_0042: ldnull
IL_0043: stloc.s V_5
IL_0045: ldstr ""D""
IL_004a: stloc.s V_5
IL_004c: ldloc.s V_5
IL_004e: conv.u
IL_004f: stloc.s V_6
IL_0051: ldloc.s V_6
IL_0053: brfalse.s IL_005f
IL_0055: ldloc.s V_6
IL_0057: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_005c: add
IL_005d: stloc.s V_6
IL_005f: ldnull
IL_0060: stloc.s V_5
IL_0062: ldnull
IL_0063: stloc.3
IL_0064: ldstr ""E""
IL_0069: stloc.3
IL_006a: ldloc.3
IL_006b: conv.u
IL_006c: stloc.s V_7
IL_006e: ldloc.s V_7
IL_0070: brfalse.s IL_007c
IL_0072: ldloc.s V_7
IL_0074: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0079: add
IL_007a: stloc.s V_7
IL_007c: ldstr ""F""
IL_0081: stloc.s V_5
IL_0083: ldloc.s V_5
IL_0085: conv.u
IL_0086: stloc.s V_8
IL_0088: ldloc.s V_8
IL_008a: brfalse.s IL_0096
IL_008c: ldloc.s V_8
IL_008e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0093: add
IL_0094: stloc.s V_8
IL_0096: ldnull
IL_0097: stloc.s V_5
IL_0099: ldstr ""G""
IL_009e: stloc.s V_5
IL_00a0: ldloc.s V_5
IL_00a2: conv.u
IL_00a3: stloc.s V_9
IL_00a5: ldloc.s V_9
IL_00a7: brfalse.s IL_00b3
IL_00a9: ldloc.s V_9
IL_00ab: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_00b0: add
IL_00b1: stloc.s V_9
IL_00b3: ldnull
IL_00b4: stloc.s V_5
IL_00b6: ldnull
IL_00b7: stloc.3
IL_00b8: ldnull
IL_00b9: stloc.1
IL_00ba: ret
}
");
}
[Fact]
public void FixedStatementInUsing()
{
var text = @"
unsafe class C
{
void Test()
{
using (System.IDisposable d = null)
{
fixed (char* p = ""hello"")
{
}
}
}
}
";
// CONSIDER: This is sort of silly since the using is optimized away.
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_0019
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: ret
}
");
}
[Fact]
public void FixedStatementInLock()
{
var text = @"
unsafe class C
{
void Test()
{
lock (this)
{
fixed (char* p = ""hello"")
{
}
}
}
}
";
// Cleanup not in finally (matches dev11, but not clear why).
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 47 (0x2f)
.maxstack 2
.locals init (C V_0,
bool V_1,
char* V_2, //p
pinned string V_3)
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 ""void System.Threading.Monitor.Enter(object, ref bool)""
IL_000c: ldstr ""hello""
IL_0011: stloc.3
IL_0012: ldloc.3
IL_0013: conv.u
IL_0014: stloc.2
IL_0015: ldloc.2
IL_0016: brfalse.s IL_0020
IL_0018: ldloc.2
IL_0019: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_001e: add
IL_001f: stloc.2
IL_0020: ldnull
IL_0021: stloc.3
IL_0022: leave.s IL_002e
}
finally
{
IL_0024: ldloc.1
IL_0025: brfalse.s IL_002d
IL_0027: ldloc.0
IL_0028: call ""void System.Threading.Monitor.Exit(object)""
IL_002d: endfinally
}
IL_002e: ret
}
");
}
[Fact]
public void FixedStatementInForEach_NoDispose()
{
var text = @"
unsafe class C
{
void Test(int[] array)
{
foreach (int i in array)
{
fixed (char* p = ""hello"")
{
}
}
}
}
";
// Cleanup in finally.
// CONSIDER: dev11 is smarter and skips the try-finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 46 (0x2e)
.maxstack 2
.locals init (int[] V_0,
int V_1,
char* V_2, //p
pinned string V_3)
IL_0000: ldarg.1
IL_0001: stloc.0
IL_0002: ldc.i4.0
IL_0003: stloc.1
IL_0004: br.s IL_0027
IL_0006: ldloc.0
IL_0007: ldloc.1
IL_0008: ldelem.i4
IL_0009: pop
.try
{
IL_000a: ldstr ""hello""
IL_000f: stloc.3
IL_0010: ldloc.3
IL_0011: conv.u
IL_0012: stloc.2
IL_0013: ldloc.2
IL_0014: brfalse.s IL_001e
IL_0016: ldloc.2
IL_0017: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_001c: add
IL_001d: stloc.2
IL_001e: leave.s IL_0023
}
finally
{
IL_0020: ldnull
IL_0021: stloc.3
IL_0022: endfinally
}
IL_0023: ldloc.1
IL_0024: ldc.i4.1
IL_0025: add
IL_0026: stloc.1
IL_0027: ldloc.1
IL_0028: ldloc.0
IL_0029: ldlen
IL_002a: conv.i4
IL_002b: blt.s IL_0006
IL_002d: ret
}
");
}
[Fact]
public void FixedStatementInForEach_Dispose()
{
var text = @"
unsafe class C
{
void Test(Enumerable e)
{
foreach (var x in e)
{
fixed (char* p = ""hello"")
{
}
}
}
}
class Enumerable
{
public Enumerator GetEnumerator() { return new Enumerator(); }
}
class Enumerator : System.IDisposable
{
int x;
public int Current { get { return x; } }
public bool MoveNext() { return ++x < 4; }
void System.IDisposable.Dispose() { }
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 62 (0x3e)
.maxstack 2
.locals init (Enumerator V_0,
char* V_1, //p
pinned string V_2)
IL_0000: ldarg.1
IL_0001: callvirt ""Enumerator Enumerable.GetEnumerator()""
IL_0006: stloc.0
.try
{
IL_0007: br.s IL_0029
IL_0009: ldloc.0
IL_000a: callvirt ""int Enumerator.Current.get""
IL_000f: pop
.try
{
IL_0010: ldstr ""hello""
IL_0015: stloc.2
IL_0016: ldloc.2
IL_0017: conv.u
IL_0018: stloc.1
IL_0019: ldloc.1
IL_001a: brfalse.s IL_0024
IL_001c: ldloc.1
IL_001d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0022: add
IL_0023: stloc.1
IL_0024: leave.s IL_0029
}
finally
{
IL_0026: ldnull
IL_0027: stloc.2
IL_0028: endfinally
}
IL_0029: ldloc.0
IL_002a: callvirt ""bool Enumerator.MoveNext()""
IL_002f: brtrue.s IL_0009
IL_0031: leave.s IL_003d
}
finally
{
IL_0033: ldloc.0
IL_0034: brfalse.s IL_003c
IL_0036: ldloc.0
IL_0037: callvirt ""void System.IDisposable.Dispose()""
IL_003c: endfinally
}
IL_003d: ret
}
");
}
[Fact]
public void FixedStatementInLambda1()
{
var text = @"
unsafe class C
{
void Test()
{
System.Action a = () =>
{
try
{
fixed (char* p = ""hello"")
{
}
}
finally
{
}
};
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.<>c.<Test>b__0_0()", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_0019
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: ret
}");
}
[Fact]
public void FixedStatementInLambda2()
{
var text = @"
unsafe class C
{
void Test()
{
try
{
System.Action a = () =>
{
fixed (char* p = ""hello"")
{
}
};
}
finally
{
}
}
}
";
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.<>c.<Test>b__0_0()", @"
{
// Code size 23 (0x17)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldnull
IL_0015: stloc.1
IL_0016: ret
}
");
}
[Fact]
public void FixedStatementInLambda3()
{
var text = @"
unsafe class C
{
void Test()
{
System.Action a = () =>
{
fixed (char* p = ""hello"")
{
goto label;
}
label: ;
};
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.<>c.<Test>b__0_0()", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_0019
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: ret
}
");
}
[Fact]
public void FixedStatementInFieldInitializer1()
{
var text = @"
unsafe class C
{
System.Action a = () =>
{
try
{
fixed (char* p = ""hello"")
{
}
}
finally
{
}
};
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.<>c.<.ctor>b__1_0()", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_0019
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: ret
}
");
}
[Fact]
public void FixedStatementInFieldInitializer2()
{
var text = @"
unsafe class C
{
System.Action a = () =>
{
fixed (char* p = ""hello"")
{
goto label;
}
label: ;
};
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.<>c.<.ctor>b__1_0()", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_0019
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: ret
}
");
}
[Fact]
public void FixedStatementWithBranchOut_LoopBreak()
{
var text = @"
unsafe class C
{
void Test()
{
while(true)
{
fixed (char* p = ""hello"")
{
break;
}
}
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 27 (0x1b)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: nop
.try
{
IL_0001: ldstr ""hello""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_0015
IL_000d: ldloc.0
IL_000e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0013: add
IL_0014: stloc.0
IL_0015: leave.s IL_001a
}
finally
{
IL_0017: ldnull
IL_0018: stloc.1
IL_0019: endfinally
}
IL_001a: ret
}
");
}
[Fact]
public void FixedStatementWithBranchOut_LoopContinue()
{
var text = @"
unsafe class C
{
void Test()
{
while(true)
{
fixed (char* p = ""hello"")
{
continue;
}
}
}
}
";
// Cleanup in finally.
// CONSIDER: dev11 doesn't have a finally here, but that seems incorrect.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: nop
.try
{
IL_0001: ldstr ""hello""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_0015
IL_000d: ldloc.0
IL_000e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0013: add
IL_0014: stloc.0
IL_0015: leave.s IL_0000
}
finally
{
IL_0017: ldnull
IL_0018: stloc.1
IL_0019: endfinally
}
}
");
}
[Fact]
public void FixedStatementWithBranchOut_SwitchBreak()
{
var text = @"
unsafe class C
{
void Test()
{
switch (1)
{
case 1:
fixed (char* p = ""hello"")
{
break;
}
}
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 27 (0x1b)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: nop
.try
{
IL_0001: ldstr ""hello""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_0015
IL_000d: ldloc.0
IL_000e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0013: add
IL_0014: stloc.0
IL_0015: leave.s IL_001a
}
finally
{
IL_0017: ldnull
IL_0018: stloc.1
IL_0019: endfinally
}
IL_001a: ret
}
");
}
[Fact]
public void FixedStatementWithBranchOut_SwitchGoto()
{
var text = @"
unsafe class C
{
void Test()
{
switch (1)
{
case 1:
fixed (char* p = ""hello"")
{
goto case 1;
}
}
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: nop
.try
{
IL_0001: ldstr ""hello""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_0015
IL_000d: ldloc.0
IL_000e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0013: add
IL_0014: stloc.0
IL_0015: leave.s IL_0000
}
finally
{
IL_0017: ldnull
IL_0018: stloc.1
IL_0019: endfinally
}
}
");
}
[Fact]
public void FixedStatementWithBranchOut_BackwardGoto()
{
var text = @"
unsafe class C
{
void Test()
{
label:
fixed (char* p = ""hello"")
{
goto label;
}
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: nop
.try
{
IL_0001: ldstr ""hello""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_0015
IL_000d: ldloc.0
IL_000e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0013: add
IL_0014: stloc.0
IL_0015: leave.s IL_0000
}
finally
{
IL_0017: ldnull
IL_0018: stloc.1
IL_0019: endfinally
}
}
");
}
[Fact]
public void FixedStatementWithBranchOut_ForwardGoto()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p = ""hello"")
{
goto label;
}
label: ;
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_0019
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: ret
}
");
}
[Fact]
public void FixedStatementWithBranchOut_Throw()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p = ""hello"")
{
throw null;
}
}
}
";
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldnull
IL_0015: throw
}
");
}
[Fact]
public void FixedStatementWithBranchOut_Return()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p = ""hello"")
{
return;
}
}
}
";
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 21 (0x15)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ret
}
");
}
[Fact]
public void FixedStatementWithNoBranchOut_Loop()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p = ""hello"")
{
for (int i = 0; i < 10; i++)
{
}
}
}
}
";
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 36 (0x24)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1,
int V_2) //i
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldc.i4.0
IL_0015: stloc.2
IL_0016: br.s IL_001c
IL_0018: ldloc.2
IL_0019: ldc.i4.1
IL_001a: add
IL_001b: stloc.2
IL_001c: ldloc.2
IL_001d: ldc.i4.s 10
IL_001f: blt.s IL_0018
IL_0021: ldnull
IL_0022: stloc.1
IL_0023: ret
}
");
}
[Fact]
public void FixedStatementWithNoBranchOut_InternalGoto()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p = ""hello"")
{
goto label;
label: ;
}
}
}
";
// NOTE: Dev11 uses a finally here, but it's unnecessary.
// From GotoChecker::VisitGOTO:
// We have an unrealized goto, so we do not know whether it
// branches out or not. We should be conservative and assume that
// it does.
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 23 (0x17)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldnull
IL_0015: stloc.1
IL_0016: ret
}
");
}
[Fact]
public void FixedStatementWithNoBranchOut_Switch()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p = ""hello"")
{
switch(*p)
{
case 'a':
Test();
goto case 'b';
case 'b':
Test();
goto case 'c';
case 'c':
Test();
goto case 'd';
case 'd':
Test();
goto case 'e';
case 'e':
Test();
goto case 'f';
case 'f':
Test();
goto default;
default:
Test();
break;
}
}
}
}
";
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 103 (0x67)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1,
char V_2)
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldloc.0
IL_0015: ldind.u2
IL_0016: stloc.2
IL_0017: ldloc.2
IL_0018: ldc.i4.s 97
IL_001a: sub
IL_001b: switch (
IL_003a,
IL_0040,
IL_0046,
IL_004c,
IL_0052,
IL_0058)
IL_0038: br.s IL_005e
IL_003a: ldarg.0
IL_003b: call ""void C.Test()""
IL_0040: ldarg.0
IL_0041: call ""void C.Test()""
IL_0046: ldarg.0
IL_0047: call ""void C.Test()""
IL_004c: ldarg.0
IL_004d: call ""void C.Test()""
IL_0052: ldarg.0
IL_0053: call ""void C.Test()""
IL_0058: ldarg.0
IL_0059: call ""void C.Test()""
IL_005e: ldarg.0
IL_005f: call ""void C.Test()""
IL_0064: ldnull
IL_0065: stloc.1
IL_0066: ret
}
");
}
[Fact]
public void FixedStatementWithParenthesizedStringExpression()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p = ((""hello"")))
{
}
}
}";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 23 (0x17)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldnull
IL_0015: stloc.1
IL_0016: ret
}
");
}
#endregion Fixed statement tests
#region Custom fixed statement tests
[Fact]
public void SimpleCaseOfCustomFixed()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable())
{
System.Console.WriteLine(p[1]);
}
}
}
class Fixable
{
public ref int GetPinnableReference()
{
return ref (new int[]{1,2,3})[0];
}
}
static class FixableExt
{
public static ref int GetPinnableReference(this Fixable self)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"2", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (pinned int& V_0)
IL_0000: newobj ""Fixable..ctor()""
IL_0005: dup
IL_0006: brtrue.s IL_000d
IL_0008: pop
IL_0009: ldc.i4.0
IL_000a: conv.u
IL_000b: br.s IL_0015
IL_000d: call ""ref int Fixable.GetPinnableReference()""
IL_0012: stloc.0
IL_0013: ldloc.0
IL_0014: conv.u
IL_0015: ldc.i4.4
IL_0016: add
IL_0017: ldind.i4
IL_0018: call ""void System.Console.WriteLine(int)""
IL_001d: ldc.i4.0
IL_001e: conv.u
IL_001f: stloc.0
IL_0020: ret
}
");
}
[Fact]
public void SimpleCaseOfCustomFixedExt()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable())
{
System.Console.WriteLine(p[1]);
}
}
}
class Fixable
{
public ref int GetPinnableReference<T>() => throw null;
}
static class FixableExt
{
public static ref int GetPinnableReference<T>(this T self)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"2", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (pinned int& V_0)
IL_0000: newobj ""Fixable..ctor()""
IL_0005: dup
IL_0006: brtrue.s IL_000d
IL_0008: pop
IL_0009: ldc.i4.0
IL_000a: conv.u
IL_000b: br.s IL_0015
IL_000d: call ""ref int FixableExt.GetPinnableReference<Fixable>(Fixable)""
IL_0012: stloc.0
IL_0013: ldloc.0
IL_0014: conv.u
IL_0015: ldc.i4.4
IL_0016: add
IL_0017: ldind.i4
IL_0018: call ""void System.Console.WriteLine(int)""
IL_001d: ldc.i4.0
IL_001e: conv.u
IL_001f: stloc.0
IL_0020: ret
}
");
}
[Fact]
public void SimpleCaseOfCustomFixed_oldVersion()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable())
{
System.Console.WriteLine(p[1]);
}
}
class Fixable
{
public ref int GetPinnableReference()
{
return ref (new int[]{1,2,3})[0];
}
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe, parseOptions: TestOptions.Regular7_2);
compVerifier.VerifyDiagnostics(
// (6,25): error CS8320: Feature 'extensible fixed statement' is not available in C# 7.2. Please use language version 7.3 or greater.
// fixed (int* p = new Fixable())
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "new Fixable()").WithArguments("extensible fixed statement", "7.3").WithLocation(6, 25)
);
}
[Fact]
public void SimpleCaseOfCustomFixedNull()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = (Fixable)null)
{
System.Console.WriteLine((int)p);
}
}
class Fixable
{
public ref int GetPinnableReference()
{
return ref (new int[]{1,2,3})[0];
}
}
}";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"0", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 26 (0x1a)
.maxstack 1
.locals init (pinned int& V_0)
IL_0000: ldnull
IL_0001: brtrue.s IL_0007
IL_0003: ldc.i4.0
IL_0004: conv.u
IL_0005: br.s IL_0010
IL_0007: ldnull
IL_0008: call ""ref int C.Fixable.GetPinnableReference()""
IL_000d: stloc.0
IL_000e: ldloc.0
IL_000f: conv.u
IL_0010: conv.i4
IL_0011: call ""void System.Console.WriteLine(int)""
IL_0016: ldc.i4.0
IL_0017: conv.u
IL_0018: stloc.0
IL_0019: ret
}
");
}
[Fact]
public void SimpleCaseOfCustomFixedStruct()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable())
{
System.Console.WriteLine(p[1]);
}
}
struct Fixable
{
public ref int GetPinnableReference()
{
return ref (new int[]{1,2,3})[0];
}
}
}";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"2", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 29 (0x1d)
.maxstack 2
.locals init (pinned int& V_0,
C.Fixable V_1)
IL_0000: ldloca.s V_1
IL_0002: dup
IL_0003: initobj ""C.Fixable""
IL_0009: call ""ref int C.Fixable.GetPinnableReference()""
IL_000e: stloc.0
IL_000f: ldloc.0
IL_0010: conv.u
IL_0011: ldc.i4.4
IL_0012: add
IL_0013: ldind.i4
IL_0014: call ""void System.Console.WriteLine(int)""
IL_0019: ldc.i4.0
IL_001a: conv.u
IL_001b: stloc.0
IL_001c: ret
}
");
}
[Fact]
public void CustomFixedStructNullable()
{
var text = @"
unsafe class C
{
public static void Main()
{
Fixable? f = new Fixable();
fixed (int* p = f)
{
System.Console.WriteLine(p[1]);
}
}
}
public struct Fixable
{
public ref int GetPinnableReference()
{
return ref (new int[]{1,2,3})[0];
}
}
public static class FixableExt
{
public static ref int GetPinnableReference(this Fixable? f)
{
return ref f.Value.GetPinnableReference();
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"2", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 34 (0x22)
.maxstack 2
.locals init (Fixable V_0,
pinned int& V_1)
IL_0000: ldloca.s V_0
IL_0002: initobj ""Fixable""
IL_0008: ldloc.0
IL_0009: newobj ""Fixable?..ctor(Fixable)""
IL_000e: call ""ref int FixableExt.GetPinnableReference(Fixable?)""
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: conv.u
IL_0016: ldc.i4.4
IL_0017: add
IL_0018: ldind.i4
IL_0019: call ""void System.Console.WriteLine(int)""
IL_001e: ldc.i4.0
IL_001f: conv.u
IL_0020: stloc.1
IL_0021: ret
}
");
}
[Fact]
public void CustomFixedStructNullableErr()
{
var text = @"
unsafe class C
{
public static void Main()
{
Fixable? f = new Fixable();
fixed (int* p = f)
{
System.Console.WriteLine(p[1]);
}
}
}
public struct Fixable
{
public ref int GetPinnableReference()
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (8,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = f)
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "f").WithLocation(8, 25)
);
}
[Fact]
public void CustomFixedErrAmbiguous()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
var f = new Fixable(1);
fixed (int* p = f)
{
System.Console.Write(p[2]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
public static ref readonly int GetPinnableReference(in this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
public static class FixableExt1
{
public static ref readonly int GetPinnableReference(in this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS0121: The call is ambiguous between the following methods or properties: 'FixableExt.GetPinnableReference(in Fixable)' and 'FixableExt1.GetPinnableReference(in Fixable)'
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_AmbigCall, "new Fixable(1)").WithArguments("FixableExt.GetPinnableReference(in Fixable)", "FixableExt1.GetPinnableReference(in Fixable)").WithLocation(6, 25),
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25),
// (12,25): error CS0121: The call is ambiguous between the following methods or properties: 'FixableExt.GetPinnableReference(in Fixable)' and 'FixableExt1.GetPinnableReference(in Fixable)'
// fixed (int* p = f)
Diagnostic(ErrorCode.ERR_AmbigCall, "f").WithArguments("FixableExt.GetPinnableReference(in Fixable)", "FixableExt1.GetPinnableReference(in Fixable)").WithLocation(12, 25),
// (12,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = f)
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "f").WithLocation(12, 25)
);
}
[Fact]
public void CustomFixedErrDynamic()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = (dynamic)(new Fixable(1)))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
public static ref readonly int GetPinnableReference(in this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = (dynamic)(new Fixable(1)))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "(dynamic)(new Fixable(1))").WithLocation(6, 25)
);
}
[Fact]
public void CustomFixedErrBad()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = (HocusPocus)(new Fixable(1)))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
public static ref readonly int GetPinnableReference(in this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,26): error CS0246: The type or namespace name 'HocusPocus' could not be found (are you missing a using directive or an assembly reference?)
// fixed (int* p = (HocusPocus)(new Fixable(1)))
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "HocusPocus").WithArguments("HocusPocus").WithLocation(6, 26)
);
}
[Fact]
public void SimpleCaseOfCustomFixedGeneric()
{
var text = @"
unsafe class C
{
public static void Main()
{
Test(42);
Test((object)null);
}
public static void Test<T>(T arg)
{
fixed (int* p = arg)
{
System.Console.Write(p == null? 0: p[1]);
}
}
}
static class FixAllExt
{
public static ref int GetPinnableReference<T>(this T dummy)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"20", verify: Verification.Fails);
compVerifier.VerifyIL("C.Test<T>(T)", @"
{
// Code size 49 (0x31)
.maxstack 2
.locals init (int* V_0, //p
pinned int& V_1)
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: brtrue.s IL_000c
IL_0008: ldc.i4.0
IL_0009: conv.u
IL_000a: br.s IL_001b
IL_000c: ldarga.s V_0
IL_000e: ldobj ""T""
IL_0013: call ""ref int FixAllExt.GetPinnableReference<T>(T)""
IL_0018: stloc.1
IL_0019: ldloc.1
IL_001a: conv.u
IL_001b: stloc.0
IL_001c: ldloc.0
IL_001d: ldc.i4.0
IL_001e: conv.u
IL_001f: beq.s IL_0027
IL_0021: ldloc.0
IL_0022: ldc.i4.4
IL_0023: add
IL_0024: ldind.i4
IL_0025: br.s IL_0028
IL_0027: ldc.i4.0
IL_0028: call ""void System.Console.Write(int)""
IL_002d: ldc.i4.0
IL_002e: conv.u
IL_002f: stloc.1
IL_0030: ret
}
");
}
[Fact]
public void CustomFixedStructSideeffects()
{
var text = @"
unsafe class C
{
public static void Main()
{
var b = new FixableStruct();
Test(ref b);
System.Console.WriteLine(b.x);
}
public static void Test(ref FixableStruct arg)
{
fixed (int* p = arg)
{
System.Console.Write(p[1]);
}
}
}
struct FixableStruct
{
public int x;
public ref int GetPinnableReference()
{
x = 456;
return ref (new int[] { 4, 5, 6 })[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"5456");
compVerifier.VerifyIL("C.Test(ref FixableStruct)", @"
{
// Code size 21 (0x15)
.maxstack 2
.locals init (pinned int& V_0)
IL_0000: ldarg.0
IL_0001: call ""ref int FixableStruct.GetPinnableReference()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: conv.u
IL_0009: ldc.i4.4
IL_000a: add
IL_000b: ldind.i4
IL_000c: call ""void System.Console.Write(int)""
IL_0011: ldc.i4.0
IL_0012: conv.u
IL_0013: stloc.0
IL_0014: ret
}
");
}
[Fact]
public void CustomFixedClassSideeffects()
{
var text = @"
using System;
unsafe class C
{
public static void Main()
{
var b = new FixableClass();
Test(ref b);
System.Console.WriteLine(b.x);
}
public static void Test(ref FixableClass arg)
{
fixed (int* p = arg)
{
System.Console.Write(p[1]);
}
}
}
class FixableClass
{
public int x;
[Obsolete]
public ref int GetPinnableReference()
{
x = 456;
return ref (new int[] { 4, 5, 6 })[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"5456");
compVerifier.VerifyDiagnostics(
// (14,29): warning CS0612: 'FixableClass.GetPinnableReference()' is obsolete
// fixed (int* p = arg)
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "arg").WithArguments("FixableClass.GetPinnableReference()").WithLocation(14, 29)
);
// note that defensive copy is created
compVerifier.VerifyIL("C.Test(ref FixableClass)", @"
{
// Code size 30 (0x1e)
.maxstack 2
.locals init (pinned int& V_0)
IL_0000: ldarg.0
IL_0001: ldind.ref
IL_0002: dup
IL_0003: brtrue.s IL_000a
IL_0005: pop
IL_0006: ldc.i4.0
IL_0007: conv.u
IL_0008: br.s IL_0012
IL_000a: call ""ref int FixableClass.GetPinnableReference()""
IL_000f: stloc.0
IL_0010: ldloc.0
IL_0011: conv.u
IL_0012: ldc.i4.4
IL_0013: add
IL_0014: ldind.i4
IL_0015: call ""void System.Console.Write(int)""
IL_001a: ldc.i4.0
IL_001b: conv.u
IL_001c: stloc.0
IL_001d: ret
}
");
}
[Fact]
public void CustomFixedGenericSideeffects()
{
var text = @"
unsafe class C
{
public static void Main()
{
var a = new FixableClass();
Test(ref a);
System.Console.WriteLine(a.x);
var b = new FixableStruct();
Test(ref b);
System.Console.WriteLine(b.x);
}
public static void Test<T>(ref T arg) where T: IFixable
{
fixed (int* p = arg)
{
System.Console.Write(p[1]);
}
}
}
interface IFixable
{
ref int GetPinnableReference();
}
class FixableClass : IFixable
{
public int x;
public ref int GetPinnableReference()
{
x = 123;
return ref (new int[] { 1, 2, 3 })[0];
}
}
struct FixableStruct : IFixable
{
public int x;
public ref int GetPinnableReference()
{
x = 456;
return ref (new int[] { 4, 5, 6 })[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"2123
5456");
compVerifier.VerifyIL("C.Test<T>(ref T)", @"
{
// Code size 64 (0x40)
.maxstack 2
.locals init (pinned int& V_0,
T V_1)
IL_0000: ldarg.0
IL_0001: ldloca.s V_1
IL_0003: initobj ""T""
IL_0009: ldloc.1
IL_000a: box ""T""
IL_000f: brtrue.s IL_0026
IL_0011: ldobj ""T""
IL_0016: stloc.1
IL_0017: ldloca.s V_1
IL_0019: ldloc.1
IL_001a: box ""T""
IL_001f: brtrue.s IL_0026
IL_0021: pop
IL_0022: ldc.i4.0
IL_0023: conv.u
IL_0024: br.s IL_0034
IL_0026: constrained. ""T""
IL_002c: callvirt ""ref int IFixable.GetPinnableReference()""
IL_0031: stloc.0
IL_0032: ldloc.0
IL_0033: conv.u
IL_0034: ldc.i4.4
IL_0035: add
IL_0036: ldind.i4
IL_0037: call ""void System.Console.Write(int)""
IL_003c: ldc.i4.0
IL_003d: conv.u
IL_003e: stloc.0
IL_003f: ret
}
");
}
[Fact]
public void CustomFixedGenericRefExtension()
{
var text = @"
unsafe class C
{
public static void Main()
{
var b = new FixableStruct();
Test(ref b);
System.Console.WriteLine(b.x);
}
public static void Test<T>(ref T arg) where T: struct, IFixable
{
fixed (int* p = arg)
{
System.Console.Write(p[1]);
}
}
}
public interface IFixable
{
ref int GetPinnableReferenceImpl();
}
public struct FixableStruct : IFixable
{
public int x;
public ref int GetPinnableReferenceImpl()
{
x = 456;
return ref (new int[] { 4, 5, 6 })[0];
}
}
public static class FixableExt
{
public static ref int GetPinnableReference<T>(ref this T f) where T: struct, IFixable
{
return ref f.GetPinnableReferenceImpl();
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"5456");
compVerifier.VerifyIL("C.Test<T>(ref T)", @"
{
// Code size 21 (0x15)
.maxstack 2
.locals init (pinned int& V_0)
IL_0000: ldarg.0
IL_0001: call ""ref int FixableExt.GetPinnableReference<T>(ref T)""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: conv.u
IL_0009: ldc.i4.4
IL_000a: add
IL_000b: ldind.i4
IL_000c: call ""void System.Console.Write(int)""
IL_0011: ldc.i4.0
IL_0012: conv.u
IL_0013: stloc.0
IL_0014: ret
}
");
}
[Fact]
public void CustomFixedStructInExtension()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
var f = new Fixable(1);
fixed (int* p = f)
{
System.Console.Write(p[2]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
public static ref readonly int GetPinnableReference(in this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"23", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 61 (0x3d)
.maxstack 3
.locals init (Fixable V_0, //f
pinned int& V_1,
Fixable V_2)
IL_0000: ldc.i4.1
IL_0001: newobj ""Fixable..ctor(int)""
IL_0006: stloc.2
IL_0007: ldloca.s V_2
IL_0009: call ""ref readonly int FixableExt.GetPinnableReference(in Fixable)""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: conv.u
IL_0011: ldc.i4.4
IL_0012: add
IL_0013: ldind.i4
IL_0014: call ""void System.Console.Write(int)""
IL_0019: ldc.i4.0
IL_001a: conv.u
IL_001b: stloc.1
IL_001c: ldloca.s V_0
IL_001e: ldc.i4.1
IL_001f: call ""Fixable..ctor(int)""
IL_0024: ldloca.s V_0
IL_0026: call ""ref readonly int FixableExt.GetPinnableReference(in Fixable)""
IL_002b: stloc.1
IL_002c: ldloc.1
IL_002d: conv.u
IL_002e: ldc.i4.2
IL_002f: conv.i
IL_0030: ldc.i4.4
IL_0031: mul
IL_0032: add
IL_0033: ldind.i4
IL_0034: call ""void System.Console.Write(int)""
IL_0039: ldc.i4.0
IL_003a: conv.u
IL_003b: stloc.1
IL_003c: ret
}
");
}
[Fact]
public void CustomFixedStructRefExtension()
{
var text = @"
unsafe class C
{
public static void Main()
{
var f = new Fixable(1);
fixed (int* p = f)
{
System.Console.Write(p[2]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
public static ref int GetPinnableReference(ref this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"3", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 33 (0x21)
.maxstack 3
.locals init (Fixable V_0, //f
pinned int& V_1)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: call ""Fixable..ctor(int)""
IL_0008: ldloca.s V_0
IL_000a: call ""ref int FixableExt.GetPinnableReference(ref Fixable)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: conv.u
IL_0012: ldc.i4.2
IL_0013: conv.i
IL_0014: ldc.i4.4
IL_0015: mul
IL_0016: add
IL_0017: ldind.i4
IL_0018: call ""void System.Console.Write(int)""
IL_001d: ldc.i4.0
IL_001e: conv.u
IL_001f: stloc.1
IL_0020: ret
}
");
}
[Fact]
public void CustomFixedStructRefExtensionErr()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
public static ref int GetPinnableReference(ref this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS1510: A ref or out value must be an assignable variable
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "new Fixable(1)").WithLocation(6, 25),
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25)
);
}
[Fact]
public void CustomFixedStructVariousErr01()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
private static ref int GetPinnableReference(this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS8385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25)
);
}
[Fact]
public void CustomFixedStructVariousErr01_oldVersion()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
private static ref int GetPinnableReference(this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe, parseOptions: TestOptions.Regular7_2);
compVerifier.VerifyDiagnostics(
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25)
);
}
[Fact]
public void CustomFixedStructVariousErr02()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
public static ref int GetPinnableReference()
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25),
// (6,25): error CS0176: Member 'Fixable.GetPinnableReference()' cannot be accessed with an instance reference; qualify it with a type name instead
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ObjectProhibited, "new Fixable(1)").WithArguments("Fixable.GetPinnableReference()").WithLocation(6, 25)
);
}
[Fact]
public void CustomFixedStructVariousErr03()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
public ref int GetPinnableReference => ref (new int[]{1,2,3})[0];
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS1955: Non-invocable member 'Fixable.GetPinnableReference' cannot be used like a method.
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "new Fixable(1)").WithArguments("Fixable.GetPinnableReference").WithLocation(6, 25),
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25)
);
}
[Fact]
public void CustomFixedStructVariousErr04()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
public ref int GetPinnableReference<T>() => ref (new int[]{1,2,3})[0];
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS0411: The type arguments for method 'Fixable.GetPinnableReference<T>()' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "new Fixable(1)").WithArguments("Fixable.GetPinnableReference<T>()").WithLocation(6, 25),
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25)
);
}
[Fact]
public void CustomFixedStructVariousErr05_Obsolete()
{
var text = @"
using System;
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
[Obsolete(""hi"", true)]
public ref int GetPinnableReference() => ref (new int[]{1,2,3})[0];
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (8,25): error CS0619: 'Fixable.GetPinnableReference()' is obsolete: 'hi'
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "new Fixable(1)").WithArguments("Fixable.GetPinnableReference()", "hi").WithLocation(8, 25)
);
}
[Fact]
public void CustomFixedStructVariousErr06_UseSite()
{
var missing_cs = "public struct Missing { }";
var missing = CreateCompilationWithMscorlib45(missing_cs, options: TestOptions.DebugDll, assemblyName: "missing");
var lib_cs = @"
public struct Fixable
{
public Fixable(int arg){}
public ref Missing GetPinnableReference() => throw null;
}
";
var lib = CreateCompilationWithMscorlib45(lib_cs, references: new[] { missing.EmitToImageReference() }, options: TestOptions.DebugDll);
var source =
@"
unsafe class C
{
public static void Main()
{
fixed (void* p = new Fixable(1))
{
}
}
}
";
var comp = CreateCompilationWithMscorlib45(source, references: new[] { lib.EmitToImageReference() }, options: TestOptions.UnsafeDebugDll);
comp.VerifyDiagnostics(
// (6,26): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// fixed (void* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_NoTypeDef, "new Fixable(1)").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 26),
// (6,26): error CS9385: The given expression cannot be used in a fixed statement
// fixed (void* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 26)
);
}
[Fact]
public void CustomFixedStructVariousErr07_Optional()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
public ref int GetPinnableReference(int x = 0) => ref (new int[]{1,2,3})[0];
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): warning CS0280: 'Fixable' does not implement the 'fixed' pattern. 'Fixable.GetPinnableReference(int)' has the wrong signature.
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.WRN_PatternBadSignature, "new Fixable(1)").WithArguments("Fixable", "fixed", "Fixable.GetPinnableReference(int)").WithLocation(6, 25),
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25)
);
}
[Fact]
public void FixStringMissingAllHelpers()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (char* p = string.Empty)
{
}
}
}
";
var comp = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
comp.MakeMemberMissing(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__get_OffsetToStringData);
comp.VerifyEmitDiagnostics(
// (6,26): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.RuntimeHelpers.get_OffsetToStringData'
// fixed (char* p = string.Empty)
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "string.Empty").WithArguments("System.Runtime.CompilerServices.RuntimeHelpers", "get_OffsetToStringData").WithLocation(6, 26)
);
}
[Fact]
public void FixStringArrayExtensionHelpersIgnored()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (char* p = ""A"")
{
*p = default;
}
fixed (char* p = new char[1])
{
*p = default;
}
}
}
public static class FixableExt
{
public static ref char GetPinnableReference(this string self) => throw null;
public static ref char GetPinnableReference(this char[] self) => throw null;
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"");
compVerifier.VerifyIL("C.Main()", @"
{
// Code size 60 (0x3c)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1,
char* V_2, //p
pinned char[] V_3)
IL_0000: ldstr ""A""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldloc.0
IL_0015: ldc.i4.0
IL_0016: stind.i2
IL_0017: ldnull
IL_0018: stloc.1
IL_0019: ldc.i4.1
IL_001a: newarr ""char""
IL_001f: dup
IL_0020: stloc.3
IL_0021: brfalse.s IL_0028
IL_0023: ldloc.3
IL_0024: ldlen
IL_0025: conv.i4
IL_0026: brtrue.s IL_002d
IL_0028: ldc.i4.0
IL_0029: conv.u
IL_002a: stloc.2
IL_002b: br.s IL_0036
IL_002d: ldloc.3
IL_002e: ldc.i4.0
IL_002f: ldelema ""char""
IL_0034: conv.u
IL_0035: stloc.2
IL_0036: ldloc.2
IL_0037: ldc.i4.0
IL_0038: stind.i2
IL_0039: ldnull
IL_003a: stloc.3
IL_003b: ret
}
");
}
[Fact]
public void CustomFixedDelegateErr()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable())
{
System.Console.Write(p[1]);
}
}
}
public delegate ref int ReturnsRef();
public struct Fixable
{
public Fixable(int arg){}
public ReturnsRef GetPinnableReference => null;
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable())
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable()").WithLocation(6, 25)
);
}
#endregion Custom fixed statement tests
#region Pointer conversion tests
[Fact]
public void ConvertNullToPointer()
{
var template = @"
using System;
unsafe class C
{{
static void Main()
{{
{0}
{{
char ch = 'a';
char* p = &ch;
Console.WriteLine(p == null);
p = null;
Console.WriteLine(p == null);
}}
}}
}}
";
var expectedIL = @"
{
// Code size 31 (0x1f)
.maxstack 2
.locals init (char V_0, //ch
char* V_1) //p
IL_0000: ldc.i4.s 97
IL_0002: stloc.0
IL_0003: ldloca.s V_0
IL_0005: conv.u
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: ldc.i4.0
IL_0009: conv.u
IL_000a: ceq
IL_000c: call ""void System.Console.WriteLine(bool)""
IL_0011: ldc.i4.0
IL_0012: conv.u
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: ldc.i4.0
IL_0016: conv.u
IL_0017: ceq
IL_0019: call ""void System.Console.WriteLine(bool)""
IL_001e: ret
}
";
var expectedOutput = @"False
True";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL);
CompileAndVerify(string.Format(template, "checked"), options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL);
}
[Fact]
public void ConvertPointerToPointerOrVoid()
{
var template = @"
using System;
unsafe class C
{{
static void Main()
{{
{0}
{{
char ch = 'a';
char* c1 = &ch;
void* v1 = c1;
void* v2 = (void**)v1;
char* c2 = (char*)v2;
Console.WriteLine(*c2);
}}
}}
}}
";
var expectedIL = @"
{
// Code size 19 (0x13)
.maxstack 1
.locals init (char V_0, //ch
void* V_1, //v1
void* V_2, //v2
char* V_3) //c2
IL_0000: ldc.i4.s 97
IL_0002: stloc.0
IL_0003: ldloca.s V_0
IL_0005: conv.u
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: stloc.2
IL_0009: ldloc.2
IL_000a: stloc.3
IL_000b: ldloc.3
IL_000c: ldind.u2
IL_000d: call ""void System.Console.WriteLine(char)""
IL_0012: ret
}
";
var expectedOutput = @"a";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL);
CompileAndVerify(string.Format(template, "checked"), options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL);
}
[Fact]
public void ConvertPointerToNumericUnchecked()
{
var text = @"
using System;
unsafe class C
{
void M(int* pi, void* pv, sbyte sb, byte b, short s, ushort us, int i, uint ui, long l, ulong ul)
{
unchecked
{
sb = (sbyte)pi;
b = (byte)pi;
s = (short)pi;
us = (ushort)pi;
i = (int)pi;
ui = (uint)pi;
l = (long)pi;
ul = (ulong)pi;
sb = (sbyte)pv;
b = (byte)pv;
s = (short)pv;
us = (ushort)pv;
i = (int)pv;
ui = (uint)pv;
l = (long)pv;
ul = (ulong)pv;
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", @"
{
// Code size 65 (0x41)
.maxstack 1
IL_0000: ldarg.1
IL_0001: conv.i1
IL_0002: starg.s V_3
IL_0004: ldarg.1
IL_0005: conv.u1
IL_0006: starg.s V_4
IL_0008: ldarg.1
IL_0009: conv.i2
IL_000a: starg.s V_5
IL_000c: ldarg.1
IL_000d: conv.u2
IL_000e: starg.s V_6
IL_0010: ldarg.1
IL_0011: conv.i4
IL_0012: starg.s V_7
IL_0014: ldarg.1
IL_0015: conv.u4
IL_0016: starg.s V_8
IL_0018: ldarg.1
IL_0019: conv.u8
IL_001a: starg.s V_9
IL_001c: ldarg.1
IL_001d: conv.u8
IL_001e: starg.s V_10
IL_0020: ldarg.2
IL_0021: conv.i1
IL_0022: starg.s V_3
IL_0024: ldarg.2
IL_0025: conv.u1
IL_0026: starg.s V_4
IL_0028: ldarg.2
IL_0029: conv.i2
IL_002a: starg.s V_5
IL_002c: ldarg.2
IL_002d: conv.u2
IL_002e: starg.s V_6
IL_0030: ldarg.2
IL_0031: conv.i4
IL_0032: starg.s V_7
IL_0034: ldarg.2
IL_0035: conv.u4
IL_0036: starg.s V_8
IL_0038: ldarg.2
IL_0039: conv.u8
IL_003a: starg.s V_9
IL_003c: ldarg.2
IL_003d: conv.u8
IL_003e: starg.s V_10
IL_0040: ret
}
");
}
[Fact]
public void ConvertPointerToNumericChecked()
{
var text = @"
using System;
unsafe class C
{
void M(int* pi, void* pv, sbyte sb, byte b, short s, ushort us, int i, uint ui, long l, ulong ul)
{
checked
{
sb = (sbyte)pi;
b = (byte)pi;
s = (short)pi;
us = (ushort)pi;
i = (int)pi;
ui = (uint)pi;
l = (long)pi;
ul = (ulong)pi;
sb = (sbyte)pv;
b = (byte)pv;
s = (short)pv;
us = (ushort)pv;
i = (int)pv;
ui = (uint)pv;
l = (long)pv;
ul = (ulong)pv;
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", @"
{
// Code size 65 (0x41)
.maxstack 1
IL_0000: ldarg.1
IL_0001: conv.ovf.i1.un
IL_0002: starg.s V_3
IL_0004: ldarg.1
IL_0005: conv.ovf.u1.un
IL_0006: starg.s V_4
IL_0008: ldarg.1
IL_0009: conv.ovf.i2.un
IL_000a: starg.s V_5
IL_000c: ldarg.1
IL_000d: conv.ovf.u2.un
IL_000e: starg.s V_6
IL_0010: ldarg.1
IL_0011: conv.ovf.i4.un
IL_0012: starg.s V_7
IL_0014: ldarg.1
IL_0015: conv.ovf.u4.un
IL_0016: starg.s V_8
IL_0018: ldarg.1
IL_0019: conv.ovf.i8.un
IL_001a: starg.s V_9
IL_001c: ldarg.1
IL_001d: conv.u8
IL_001e: starg.s V_10
IL_0020: ldarg.2
IL_0021: conv.ovf.i1.un
IL_0022: starg.s V_3
IL_0024: ldarg.2
IL_0025: conv.ovf.u1.un
IL_0026: starg.s V_4
IL_0028: ldarg.2
IL_0029: conv.ovf.i2.un
IL_002a: starg.s V_5
IL_002c: ldarg.2
IL_002d: conv.ovf.u2.un
IL_002e: starg.s V_6
IL_0030: ldarg.2
IL_0031: conv.ovf.i4.un
IL_0032: starg.s V_7
IL_0034: ldarg.2
IL_0035: conv.ovf.u4.un
IL_0036: starg.s V_8
IL_0038: ldarg.2
IL_0039: conv.ovf.i8.un
IL_003a: starg.s V_9
IL_003c: ldarg.2
IL_003d: conv.u8
IL_003e: starg.s V_10
IL_0040: ret
}
");
}
[Fact]
public void ConvertNumericToPointerUnchecked()
{
var text = @"
using System;
unsafe class C
{
void M(int* pi, void* pv, sbyte sb, byte b, short s, ushort us, int i, uint ui, long l, ulong ul)
{
unchecked
{
pi = (int*)sb;
pi = (int*)b;
pi = (int*)s;
pi = (int*)us;
pi = (int*)i;
pi = (int*)ui;
pi = (int*)l;
pi = (int*)ul;
pv = (void*)sb;
pv = (void*)b;
pv = (void*)s;
pv = (void*)us;
pv = (void*)i;
pv = (void*)ui;
pv = (void*)l;
pv = (void*)ul;
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", @"
{
// Code size 79 (0x4f)
.maxstack 1
IL_0000: ldarg.3
IL_0001: conv.i
IL_0002: starg.s V_1
IL_0004: ldarg.s V_4
IL_0006: conv.u
IL_0007: starg.s V_1
IL_0009: ldarg.s V_5
IL_000b: conv.i
IL_000c: starg.s V_1
IL_000e: ldarg.s V_6
IL_0010: conv.u
IL_0011: starg.s V_1
IL_0013: ldarg.s V_7
IL_0015: conv.i
IL_0016: starg.s V_1
IL_0018: ldarg.s V_8
IL_001a: conv.u
IL_001b: starg.s V_1
IL_001d: ldarg.s V_9
IL_001f: conv.u
IL_0020: starg.s V_1
IL_0022: ldarg.s V_10
IL_0024: conv.u
IL_0025: starg.s V_1
IL_0027: ldarg.3
IL_0028: conv.i
IL_0029: starg.s V_2
IL_002b: ldarg.s V_4
IL_002d: conv.u
IL_002e: starg.s V_2
IL_0030: ldarg.s V_5
IL_0032: conv.i
IL_0033: starg.s V_2
IL_0035: ldarg.s V_6
IL_0037: conv.u
IL_0038: starg.s V_2
IL_003a: ldarg.s V_7
IL_003c: conv.i
IL_003d: starg.s V_2
IL_003f: ldarg.s V_8
IL_0041: conv.u
IL_0042: starg.s V_2
IL_0044: ldarg.s V_9
IL_0046: conv.u
IL_0047: starg.s V_2
IL_0049: ldarg.s V_10
IL_004b: conv.u
IL_004c: starg.s V_2
IL_004e: ret
}
");
}
[Fact]
public void ConvertNumericToPointerChecked()
{
var text = @"
using System;
unsafe class C
{
void M(int* pi, void* pv, sbyte sb, byte b, short s, ushort us, int i, uint ui, long l, ulong ul)
{
checked
{
pi = (int*)sb;
pi = (int*)b;
pi = (int*)s;
pi = (int*)us;
pi = (int*)i;
pi = (int*)ui;
pi = (int*)l;
pi = (int*)ul;
pv = (void*)sb;
pv = (void*)b;
pv = (void*)s;
pv = (void*)us;
pv = (void*)i;
pv = (void*)ui;
pv = (void*)l;
pv = (void*)ul;
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", @"
{
// Code size 79 (0x4f)
.maxstack 1
IL_0000: ldarg.3
IL_0001: conv.ovf.u
IL_0002: starg.s V_1
IL_0004: ldarg.s V_4
IL_0006: conv.u
IL_0007: starg.s V_1
IL_0009: ldarg.s V_5
IL_000b: conv.ovf.u
IL_000c: starg.s V_1
IL_000e: ldarg.s V_6
IL_0010: conv.u
IL_0011: starg.s V_1
IL_0013: ldarg.s V_7
IL_0015: conv.ovf.u
IL_0016: starg.s V_1
IL_0018: ldarg.s V_8
IL_001a: conv.u
IL_001b: starg.s V_1
IL_001d: ldarg.s V_9
IL_001f: conv.ovf.u
IL_0020: starg.s V_1
IL_0022: ldarg.s V_10
IL_0024: conv.ovf.u.un
IL_0025: starg.s V_1
IL_0027: ldarg.3
IL_0028: conv.ovf.u
IL_0029: starg.s V_2
IL_002b: ldarg.s V_4
IL_002d: conv.u
IL_002e: starg.s V_2
IL_0030: ldarg.s V_5
IL_0032: conv.ovf.u
IL_0033: starg.s V_2
IL_0035: ldarg.s V_6
IL_0037: conv.u
IL_0038: starg.s V_2
IL_003a: ldarg.s V_7
IL_003c: conv.ovf.u
IL_003d: starg.s V_2
IL_003f: ldarg.s V_8
IL_0041: conv.u
IL_0042: starg.s V_2
IL_0044: ldarg.s V_9
IL_0046: conv.ovf.u
IL_0047: starg.s V_2
IL_0049: ldarg.s V_10
IL_004b: conv.ovf.u.un
IL_004c: starg.s V_2
IL_004e: ret
}
");
}
[Fact]
public void ConvertClassToPointerUDC()
{
var template = @"
using System;
unsafe class C
{{
void M(int* pi, void* pv, Explicit e, Implicit i)
{{
{0}
{{
e = (Explicit)pi;
e = (Explicit)pv;
i = pi;
i = pv;
pi = (int*)e;
pv = (int*)e;
pi = i;
pv = i;
}}
}}
}}
unsafe class Explicit
{{
public static explicit operator Explicit(void* p)
{{
return null;
}}
public static explicit operator int*(Explicit e)
{{
return null;
}}
}}
unsafe class Implicit
{{
public static implicit operator Implicit(void* p)
{{
return null;
}}
public static implicit operator int*(Implicit e)
{{
return null;
}}
}}
";
var expectedIL = @"
{
// Code size 67 (0x43)
.maxstack 1
IL_0000: ldarg.1
IL_0001: call ""Explicit Explicit.op_Explicit(void*)""
IL_0006: starg.s V_3
IL_0008: ldarg.2
IL_0009: call ""Explicit Explicit.op_Explicit(void*)""
IL_000e: starg.s V_3
IL_0010: ldarg.1
IL_0011: call ""Implicit Implicit.op_Implicit(void*)""
IL_0016: starg.s V_4
IL_0018: ldarg.2
IL_0019: call ""Implicit Implicit.op_Implicit(void*)""
IL_001e: starg.s V_4
IL_0020: ldarg.3
IL_0021: call ""int* Explicit.op_Explicit(Explicit)""
IL_0026: starg.s V_1
IL_0028: ldarg.3
IL_0029: call ""int* Explicit.op_Explicit(Explicit)""
IL_002e: starg.s V_2
IL_0030: ldarg.s V_4
IL_0032: call ""int* Implicit.op_Implicit(Implicit)""
IL_0037: starg.s V_1
IL_0039: ldarg.s V_4
IL_003b: call ""int* Implicit.op_Implicit(Implicit)""
IL_0040: starg.s V_2
IL_0042: ret
}
";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", expectedIL);
CompileAndVerify(string.Format(template, "checked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", expectedIL);
}
[Fact]
public void ConvertIntPtrToPointer()
{
var template = @"
using System;
unsafe class C
{{
void M(int* pi, void* pv, IntPtr i, UIntPtr u)
{{
{0}
{{
i = (IntPtr)pi;
i = (IntPtr)pv;
u = (UIntPtr)pi;
u = (UIntPtr)pv;
pi = (int*)i;
pv = (int*)i;
pi = (int*)u;
pv = (int*)u;
}}
}}
}}
";
// Nothing special here - just more UDCs.
var expectedIL = @"
{
// Code size 67 (0x43)
.maxstack 1
IL_0000: ldarg.1
IL_0001: call ""System.IntPtr System.IntPtr.op_Explicit(void*)""
IL_0006: starg.s V_3
IL_0008: ldarg.2
IL_0009: call ""System.IntPtr System.IntPtr.op_Explicit(void*)""
IL_000e: starg.s V_3
IL_0010: ldarg.1
IL_0011: call ""System.UIntPtr System.UIntPtr.op_Explicit(void*)""
IL_0016: starg.s V_4
IL_0018: ldarg.2
IL_0019: call ""System.UIntPtr System.UIntPtr.op_Explicit(void*)""
IL_001e: starg.s V_4
IL_0020: ldarg.3
IL_0021: call ""void* System.IntPtr.op_Explicit(System.IntPtr)""
IL_0026: starg.s V_1
IL_0028: ldarg.3
IL_0029: call ""void* System.IntPtr.op_Explicit(System.IntPtr)""
IL_002e: starg.s V_2
IL_0030: ldarg.s V_4
IL_0032: call ""void* System.UIntPtr.op_Explicit(System.UIntPtr)""
IL_0037: starg.s V_1
IL_0039: ldarg.s V_4
IL_003b: call ""void* System.UIntPtr.op_Explicit(System.UIntPtr)""
IL_0040: starg.s V_2
IL_0042: ret
}
";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", expectedIL);
CompileAndVerify(string.Format(template, "checked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", expectedIL);
}
[Fact]
public void FixedStatementConversion()
{
var template = @"
using System;
unsafe class C
{{
char c = 'a';
char[] a = new char[1];
static void Main()
{{
{0}
{{
C c = new C();
fixed (void* p = &c.c, q = c.a, r = ""hello"")
{{
Console.Write((int)*(char*)p);
Console.Write((int)*(char*)q);
Console.Write((int)*(char*)r);
}}
}}
}}
}}
";
// NB: "pinned System.IntPtr&" (which ildasm displays as "pinned native int&"), not void.
var expectedIL = @"
{
// Code size 112 (0x70)
.maxstack 2
.locals init (C V_0, //c
void* V_1, //p
void* V_2, //q
void* V_3, //r
pinned char& V_4,
pinned char[] V_5,
pinned string V_6)
-IL_0000: nop
-IL_0001: nop
-IL_0002: newobj ""C..ctor()""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldflda ""char C.c""
IL_000e: stloc.s V_4
-IL_0010: ldloc.s V_4
IL_0012: conv.u
IL_0013: stloc.1
-IL_0014: ldloc.0
IL_0015: ldfld ""char[] C.a""
IL_001a: dup
IL_001b: stloc.s V_5
IL_001d: brfalse.s IL_0025
IL_001f: ldloc.s V_5
IL_0021: ldlen
IL_0022: conv.i4
IL_0023: brtrue.s IL_002a
IL_0025: ldc.i4.0
IL_0026: conv.u
IL_0027: stloc.2
IL_0028: br.s IL_0034
IL_002a: ldloc.s V_5
IL_002c: ldc.i4.0
IL_002d: ldelema ""char""
IL_0032: conv.u
IL_0033: stloc.2
IL_0034: ldstr ""hello""
IL_0039: stloc.s V_6
-IL_003b: ldloc.s V_6
IL_003d: conv.u
IL_003e: stloc.3
IL_003f: ldloc.3
IL_0040: brfalse.s IL_004a
IL_0042: ldloc.3
IL_0043: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0048: add
IL_0049: stloc.3
-IL_004a: nop
-IL_004b: ldloc.1
IL_004c: ldind.u2
IL_004d: call ""void System.Console.Write(int)""
IL_0052: nop
-IL_0053: ldloc.2
IL_0054: ldind.u2
IL_0055: call ""void System.Console.Write(int)""
IL_005a: nop
-IL_005b: ldloc.3
IL_005c: ldind.u2
IL_005d: call ""void System.Console.Write(int)""
IL_0062: nop
-IL_0063: nop
~IL_0064: ldc.i4.0
IL_0065: conv.u
IL_0066: stloc.s V_4
IL_0068: ldnull
IL_0069: stloc.s V_5
IL_006b: ldnull
IL_006c: stloc.s V_6
-IL_006e: nop
-IL_006f: ret
}
";
var expectedOutput = @"970104";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeDebugExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL, sequencePoints: "C.Main");
CompileAndVerify(string.Format(template, "checked "), options: TestOptions.UnsafeDebugExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL, sequencePoints: "C.Main");
}
[Fact]
public void FixedStatementVoidPointerPointer()
{
var template = @"
using System;
unsafe class C
{{
void* v;
static void Main()
{{
{0}
{{
char ch = 'a';
C c = new C();
c.v = &ch;
fixed (void** p = &c.v)
{{
Console.Write(*(char*)*p);
}}
}}
}}
}}
";
// NB: "pinned void*&", as in Dev10.
var expectedIL = @"
{
// Code size 36 (0x24)
.maxstack 3
.locals init (char V_0, //ch
pinned void*& V_1)
IL_0000: ldc.i4.s 97
IL_0002: stloc.0
IL_0003: newobj ""C..ctor()""
IL_0008: dup
IL_0009: ldloca.s V_0
IL_000b: conv.u
IL_000c: stfld ""void* C.v""
IL_0011: ldflda ""void* C.v""
IL_0016: stloc.1
IL_0017: ldloc.1
IL_0018: conv.u
IL_0019: ldind.i
IL_001a: ldind.u2
IL_001b: call ""void System.Console.Write(char)""
IL_0020: ldc.i4.0
IL_0021: conv.u
IL_0022: stloc.1
IL_0023: ret
}
";
var expectedOutput = @"a";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL);
CompileAndVerify(string.Format(template, "checked"), options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL);
}
[ConditionalFact(typeof(DesktopOnly))]
public void PointerArrayConversion()
{
var template = @"
using System;
unsafe class C
{{
void M(int*[] api, void*[] apv, Array a)
{{
{0}
{{
a = api;
a = apv;
api = (int*[])a;
apv = (void*[])a;
}}
}}
}}
";
var expectedIL = @"
{
// Code size 23 (0x17)
.maxstack 1
IL_0000: ldarg.1
IL_0001: starg.s V_3
IL_0003: ldarg.2
IL_0004: starg.s V_3
IL_0006: ldarg.3
IL_0007: castclass ""int*[]""
IL_000c: starg.s V_1
IL_000e: ldarg.3
IL_000f: castclass ""void*[]""
IL_0014: starg.s V_2
IL_0016: ret
}
";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes).VerifyIL("C.M", expectedIL);
CompileAndVerify(string.Format(template, "checked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes).VerifyIL("C.M", expectedIL);
}
[ConditionalFact(typeof(DesktopOnly))]
public void PointerArrayConversionRuntimeError()
{
var text = @"
unsafe class C
{
static void Main()
{
System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture;
try
{
int*[] api = new int*[1];
System.Array a = api;
a.GetValue(0);
}
finally
{
System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture;
}
}
}
";
CompileAndVerifyException<NotSupportedException>(text, "Type is not supported.", allowUnsafe: true, verify: Verification.Fails);
}
[ConditionalFact(typeof(DesktopOnly))]
public void PointerArrayEnumerableConversion()
{
var template = @"
using System.Collections;
unsafe class C
{{
void M(int*[] api, void*[] apv, IEnumerable e)
{{
{0}
{{
e = api;
e = apv;
api = (int*[])e;
apv = (void*[])e;
}}
}}
}}
";
var expectedIL = @"
{
// Code size 23 (0x17)
.maxstack 1
IL_0000: ldarg.1
IL_0001: starg.s V_3
IL_0003: ldarg.2
IL_0004: starg.s V_3
IL_0006: ldarg.3
IL_0007: castclass ""int*[]""
IL_000c: starg.s V_1
IL_000e: ldarg.3
IL_000f: castclass ""void*[]""
IL_0014: starg.s V_2
IL_0016: ret
}
";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes).VerifyIL("C.M", expectedIL);
CompileAndVerify(string.Format(template, "checked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes).VerifyIL("C.M", expectedIL);
}
[ConditionalFact(typeof(DesktopOnly))]
public void PointerArrayEnumerableConversionRuntimeError()
{
var text = @"
unsafe class C
{
static void Main()
{
System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture;
try
{
int*[] api = new int*[1];
System.Collections.IEnumerable e = api;
var enumerator = e.GetEnumerator();
enumerator.MoveNext();
var current = enumerator.Current;
}
finally
{
System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture;
}
}
}
";
CompileAndVerifyException<NotSupportedException>(text, "Type is not supported.", allowUnsafe: true, verify: Verification.Fails);
}
[Fact]
public void PointerArrayForeachSingle()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
int*[] array = new []
{
(int*)1,
(int*)2,
};
foreach (var element in array)
{
Console.Write((int)element);
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "12", verify: Verification.Fails).VerifyIL("C.Main", @"
{
// Code size 41 (0x29)
.maxstack 4
.locals init (int*[] V_0,
int V_1)
IL_0000: ldc.i4.2
IL_0001: newarr ""int*""
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldc.i4.1
IL_0009: conv.i
IL_000a: stelem.i
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: conv.i
IL_000f: stelem.i
IL_0010: stloc.0
IL_0011: ldc.i4.0
IL_0012: stloc.1
IL_0013: br.s IL_0022
IL_0015: ldloc.0
IL_0016: ldloc.1
IL_0017: ldelem.i
IL_0018: conv.i4
IL_0019: call ""void System.Console.Write(int)""
IL_001e: ldloc.1
IL_001f: ldc.i4.1
IL_0020: add
IL_0021: stloc.1
IL_0022: ldloc.1
IL_0023: ldloc.0
IL_0024: ldlen
IL_0025: conv.i4
IL_0026: blt.s IL_0015
IL_0028: ret
}
");
}
[Fact]
public void PointerArrayForeachMultiple()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
int*[,] array = new [,]
{
{ (int*)1, (int*)2, },
{ (int*)3, (int*)4, },
};
foreach (var element in array)
{
Console.Write((int)element);
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "1234", verify: Verification.Fails).VerifyIL("C.Main", @"
{
// Code size 120 (0x78)
.maxstack 5
.locals init (int*[,] V_0,
int V_1,
int V_2,
int V_3,
int V_4)
IL_0000: ldc.i4.2
IL_0001: ldc.i4.2
IL_0002: newobj ""int*[*,*]..ctor""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.0
IL_000a: ldc.i4.1
IL_000b: conv.i
IL_000c: call ""int*[*,*].Set""
IL_0011: dup
IL_0012: ldc.i4.0
IL_0013: ldc.i4.1
IL_0014: ldc.i4.2
IL_0015: conv.i
IL_0016: call ""int*[*,*].Set""
IL_001b: dup
IL_001c: ldc.i4.1
IL_001d: ldc.i4.0
IL_001e: ldc.i4.3
IL_001f: conv.i
IL_0020: call ""int*[*,*].Set""
IL_0025: dup
IL_0026: ldc.i4.1
IL_0027: ldc.i4.1
IL_0028: ldc.i4.4
IL_0029: conv.i
IL_002a: call ""int*[*,*].Set""
IL_002f: stloc.0
IL_0030: ldloc.0
IL_0031: ldc.i4.0
IL_0032: callvirt ""int System.Array.GetUpperBound(int)""
IL_0037: stloc.1
IL_0038: ldloc.0
IL_0039: ldc.i4.1
IL_003a: callvirt ""int System.Array.GetUpperBound(int)""
IL_003f: stloc.2
IL_0040: ldloc.0
IL_0041: ldc.i4.0
IL_0042: callvirt ""int System.Array.GetLowerBound(int)""
IL_0047: stloc.3
IL_0048: br.s IL_0073
IL_004a: ldloc.0
IL_004b: ldc.i4.1
IL_004c: callvirt ""int System.Array.GetLowerBound(int)""
IL_0051: stloc.s V_4
IL_0053: br.s IL_006a
IL_0055: ldloc.0
IL_0056: ldloc.3
IL_0057: ldloc.s V_4
IL_0059: call ""int*[*,*].Get""
IL_005e: conv.i4
IL_005f: call ""void System.Console.Write(int)""
IL_0064: ldloc.s V_4
IL_0066: ldc.i4.1
IL_0067: add
IL_0068: stloc.s V_4
IL_006a: ldloc.s V_4
IL_006c: ldloc.2
IL_006d: ble.s IL_0055
IL_006f: ldloc.3
IL_0070: ldc.i4.1
IL_0071: add
IL_0072: stloc.3
IL_0073: ldloc.3
IL_0074: ldloc.1
IL_0075: ble.s IL_004a
IL_0077: ret
}
");
}
[ConditionalFact(typeof(DesktopOnly))]
public void PointerArrayForeachEnumerable()
{
var text = @"
using System;
using System.Collections;
unsafe class C
{
static void Main()
{
System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture;
try
{
int*[] array = new []
{
(int*)1,
(int*)2,
};
foreach (var element in (IEnumerable)array)
{
Console.Write((int)element);
}
}
finally
{
System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture;
}
}
}
";
CompileAndVerifyException<NotSupportedException>(text, "Type is not supported.", allowUnsafe: true, verify: Verification.Fails);
}
#endregion Pointer conversion tests
#region sizeof tests
[Fact]
public void SizeOfConstant()
{
var text = @"
using System;
class C
{
static void Main()
{
Console.WriteLine(sizeof(sbyte));
Console.WriteLine(sizeof(byte));
Console.WriteLine(sizeof(short));
Console.WriteLine(sizeof(ushort));
Console.WriteLine(sizeof(int));
Console.WriteLine(sizeof(uint));
Console.WriteLine(sizeof(long));
Console.WriteLine(sizeof(ulong));
Console.WriteLine(sizeof(char));
Console.WriteLine(sizeof(float));
Console.WriteLine(sizeof(double));
Console.WriteLine(sizeof(bool));
Console.WriteLine(sizeof(decimal)); //Supported by dev10, but not spec.
}
}
";
var expectedOutput = @"
1
1
2
2
4
4
8
8
2
4
8
1
16
".Trim();
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Passes).VerifyIL("C.Main", @"
{
// Code size 80 (0x50)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: call ""void System.Console.WriteLine(int)""
IL_0006: ldc.i4.1
IL_0007: call ""void System.Console.WriteLine(int)""
IL_000c: ldc.i4.2
IL_000d: call ""void System.Console.WriteLine(int)""
IL_0012: ldc.i4.2
IL_0013: call ""void System.Console.WriteLine(int)""
IL_0018: ldc.i4.4
IL_0019: call ""void System.Console.WriteLine(int)""
IL_001e: ldc.i4.4
IL_001f: call ""void System.Console.WriteLine(int)""
IL_0024: ldc.i4.8
IL_0025: call ""void System.Console.WriteLine(int)""
IL_002a: ldc.i4.8
IL_002b: call ""void System.Console.WriteLine(int)""
IL_0030: ldc.i4.2
IL_0031: call ""void System.Console.WriteLine(int)""
IL_0036: ldc.i4.4
IL_0037: call ""void System.Console.WriteLine(int)""
IL_003c: ldc.i4.8
IL_003d: call ""void System.Console.WriteLine(int)""
IL_0042: ldc.i4.1
IL_0043: call ""void System.Console.WriteLine(int)""
IL_0048: ldc.i4.s 16
IL_004a: call ""void System.Console.WriteLine(int)""
IL_004f: ret
}
");
}
[Fact]
public void SizeOfNonConstant()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
Console.WriteLine(sizeof(S));
Console.WriteLine(sizeof(Outer.Inner));
Console.WriteLine(sizeof(int*));
Console.WriteLine(sizeof(void*));
}
}
struct S
{
public byte b;
}
class Outer
{
public struct Inner
{
public char c;
}
}
";
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
1
2
4
4
".Trim();
}
else
{
expectedOutput = @"
1
2
8
8
".Trim();
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Passes).VerifyIL("C.Main", @"
{
// Code size 45 (0x2d)
.maxstack 1
IL_0000: sizeof ""S""
IL_0006: call ""void System.Console.WriteLine(int)""
IL_000b: sizeof ""Outer.Inner""
IL_0011: call ""void System.Console.WriteLine(int)""
IL_0016: sizeof ""int*""
IL_001c: call ""void System.Console.WriteLine(int)""
IL_0021: sizeof ""void*""
IL_0027: call ""void System.Console.WriteLine(int)""
IL_002c: ret
}
");
}
[Fact]
public void SizeOfEnum()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
Console.WriteLine(sizeof(E1));
Console.WriteLine(sizeof(E2));
Console.WriteLine(sizeof(E3));
}
}
enum E1 { A }
enum E2 : byte { A }
enum E3 : long { A }
";
var expectedOutput = @"
4
1
8
".Trim();
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Passes).VerifyIL("C.Main", @"
{
// Code size 19 (0x13)
.maxstack 1
IL_0000: ldc.i4.4
IL_0001: call ""void System.Console.WriteLine(int)""
IL_0006: ldc.i4.1
IL_0007: call ""void System.Console.WriteLine(int)""
IL_000c: ldc.i4.8
IL_000d: call ""void System.Console.WriteLine(int)""
IL_0012: ret
}
");
}
#endregion sizeof tests
#region Pointer arithmetic tests
[Fact]
public void NumericAdditionChecked()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
checked
{
S s = new S();
S* p = &s;
p = p + 2;
p = p + 3u;
p = p + 4l;
p = p + 5ul;
}
}
}
";
// Dev10 has conv.u after IL_000d and conv.i8 in place of conv.u8 at IL_0017.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 59 (0x3b)
.maxstack 3
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldc.i4.2
IL_000c: conv.i
IL_000d: sizeof ""S""
IL_0013: mul.ovf
IL_0014: add.ovf.un
IL_0015: ldc.i4.3
IL_0016: conv.u8
IL_0017: sizeof ""S""
IL_001d: conv.i8
IL_001e: mul.ovf
IL_001f: conv.i
IL_0020: add.ovf.un
IL_0021: ldc.i4.4
IL_0022: conv.i8
IL_0023: sizeof ""S""
IL_0029: conv.i8
IL_002a: mul.ovf
IL_002b: conv.i
IL_002c: add.ovf.un
IL_002d: ldc.i4.5
IL_002e: conv.i8
IL_002f: sizeof ""S""
IL_0035: conv.ovf.u8
IL_0036: mul.ovf.un
IL_0037: conv.u
IL_0038: add.ovf.un
IL_0039: pop
IL_003a: ret
}
");
}
[Fact]
public void NumericAdditionUnchecked()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
unchecked
{
S s = new S();
S* p = &s;
p = p + 2;
p = p + 3u;
p = p + 4l;
p = p + 5ul;
}
}
}
";
// Dev10 has conv.u after IL_000d and conv.i8 in place of conv.u8 at IL_0017.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 59 (0x3b)
.maxstack 3
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldc.i4.2
IL_000c: conv.i
IL_000d: sizeof ""S""
IL_0013: mul
IL_0014: add
IL_0015: ldc.i4.3
IL_0016: conv.u8
IL_0017: sizeof ""S""
IL_001d: conv.i8
IL_001e: mul
IL_001f: conv.i
IL_0020: add
IL_0021: ldc.i4.4
IL_0022: conv.i8
IL_0023: sizeof ""S""
IL_0029: conv.i8
IL_002a: mul
IL_002b: conv.i
IL_002c: add
IL_002d: pop
IL_002e: ldc.i4.5
IL_002f: conv.i8
IL_0030: sizeof ""S""
IL_0036: conv.i8
IL_0037: mul
IL_0038: conv.u
IL_0039: pop
IL_003a: ret
}
");
}
[Fact]
public void NumericSubtractionChecked()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
checked
{
S s = new S();
S* p = &s;
p = p - 2;
p = p - 3u;
p = p - 4l;
p = p - 5ul;
}
}
}
";
// Dev10 has conv.u after IL_000d and conv.i8 in place of conv.u8 at IL_0017.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 59 (0x3b)
.maxstack 3
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldc.i4.2
IL_000c: conv.i
IL_000d: sizeof ""S""
IL_0013: mul.ovf
IL_0014: sub.ovf.un
IL_0015: ldc.i4.3
IL_0016: conv.u8
IL_0017: sizeof ""S""
IL_001d: conv.i8
IL_001e: mul.ovf
IL_001f: conv.i
IL_0020: sub.ovf.un
IL_0021: ldc.i4.4
IL_0022: conv.i8
IL_0023: sizeof ""S""
IL_0029: conv.i8
IL_002a: mul.ovf
IL_002b: conv.i
IL_002c: sub.ovf.un
IL_002d: ldc.i4.5
IL_002e: conv.i8
IL_002f: sizeof ""S""
IL_0035: conv.ovf.u8
IL_0036: mul.ovf.un
IL_0037: conv.u
IL_0038: sub.ovf.un
IL_0039: pop
IL_003a: ret
}
");
}
[Fact]
public void NumericSubtractionUnchecked()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
unchecked
{
S s = new S();
S* p = &s;
p = p - 2;
p = p - 3u;
p = p - 4l;
p = p - 5ul;
}
}
}
";
// Dev10 has conv.u after IL_000d and conv.i8 in place of conv.u8 at IL_0017.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 59 (0x3b)
.maxstack 3
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldc.i4.2
IL_000c: conv.i
IL_000d: sizeof ""S""
IL_0013: mul
IL_0014: sub
IL_0015: ldc.i4.3
IL_0016: conv.u8
IL_0017: sizeof ""S""
IL_001d: conv.i8
IL_001e: mul
IL_001f: conv.i
IL_0020: sub
IL_0021: ldc.i4.4
IL_0022: conv.i8
IL_0023: sizeof ""S""
IL_0029: conv.i8
IL_002a: mul
IL_002b: conv.i
IL_002c: sub
IL_002d: pop
IL_002e: ldc.i4.5
IL_002f: conv.i8
IL_0030: sizeof ""S""
IL_0036: conv.i8
IL_0037: mul
IL_0038: conv.u
IL_0039: pop
IL_003a: ret
}
");
}
[WorkItem(546750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546750")]
[Fact]
public void NumericAdditionUnchecked_SizeOne()
{
var text = @"
using System;
unsafe class C
{
void Test(int i, uint u, long l, ulong ul)
{
unchecked
{
byte b = 3;
byte* p = &b;
p = p + 2;
p = p + 3u;
p = p + 4l;
p = p + 5ul;
p = p + i;
p = p + u;
p = p + l;
p = p + ul;
}
}
}
";
// NOTE: even when not optimized.
// NOTE: additional conversions applied to constants of type int and uint.
CompileAndVerify(text, options: TestOptions.UnsafeDebugDll, verify: Verification.Fails).VerifyIL("C.Test", @"
{
// Code size 50 (0x32)
.maxstack 2
.locals init (byte V_0, //b
byte* V_1) //p
IL_0000: nop
IL_0001: nop
IL_0002: ldc.i4.3
IL_0003: stloc.0
IL_0004: ldloca.s V_0
IL_0006: conv.u
IL_0007: stloc.1
IL_0008: ldloc.1
IL_0009: ldc.i4.2
IL_000a: add
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: ldc.i4.3
IL_000e: add
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.4
IL_0012: conv.i8
IL_0013: conv.i
IL_0014: add
IL_0015: stloc.1
IL_0016: ldloc.1
IL_0017: ldc.i4.5
IL_0018: conv.i8
IL_0019: conv.u
IL_001a: add
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: ldarg.1
IL_001e: add
IL_001f: stloc.1
IL_0020: ldloc.1
IL_0021: ldarg.2
IL_0022: conv.u
IL_0023: add
IL_0024: stloc.1
IL_0025: ldloc.1
IL_0026: ldarg.3
IL_0027: conv.i
IL_0028: add
IL_0029: stloc.1
IL_002a: ldloc.1
IL_002b: ldarg.s V_4
IL_002d: conv.u
IL_002e: add
IL_002f: stloc.1
IL_0030: nop
IL_0031: ret
}
");
}
[WorkItem(18871, "https://github.com/dotnet/roslyn/issues/18871")]
[WorkItem(546750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546750")]
[Fact]
public void NumericAdditionChecked_SizeOne()
{
var text = @"
using System;
unsafe class C
{
void Test(int i, uint u, long l, ulong ul)
{
checked
{
byte b = 3;
byte* p = &b;
p = p + 2;
p = p + 3u;
p = p + 4l;
p = p + 5ul;
p = p + i;
p = p + u;
p = p + l;
p = p + ul;
p = p + (-2);
}
}
void Test1(int i, uint u, long l, ulong ul)
{
checked
{
byte b = 3;
byte* p = &b;
p = p - 2;
p = p - 3u;
p = p - 4l;
p = p - 5ul;
p = p - i;
p = p - u;
p = p - l;
p = p - ul;
p = p - (-1);
}
}
}
";
// NOTE: even when not optimized.
// NOTE: additional conversions applied to constants of type int and uint.
// NOTE: identical to unchecked except "add" becomes "add.ovf.un".
var comp = CompileAndVerify(text, options: TestOptions.UnsafeDebugDll, verify: Verification.Fails);
comp.VerifyIL("C.Test", @"
{
// Code size 57 (0x39)
.maxstack 2
.locals init (byte V_0, //b
byte* V_1) //p
IL_0000: nop
IL_0001: nop
IL_0002: ldc.i4.3
IL_0003: stloc.0
IL_0004: ldloca.s V_0
IL_0006: conv.u
IL_0007: stloc.1
IL_0008: ldloc.1
IL_0009: ldc.i4.2
IL_000a: add.ovf.un
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: ldc.i4.3
IL_000e: add.ovf.un
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.4
IL_0012: conv.i8
IL_0013: conv.i
IL_0014: add.ovf.un
IL_0015: stloc.1
IL_0016: ldloc.1
IL_0017: ldc.i4.5
IL_0018: conv.i8
IL_0019: conv.u
IL_001a: add.ovf.un
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: ldarg.1
IL_001e: conv.i
IL_001f: add.ovf.un
IL_0020: stloc.1
IL_0021: ldloc.1
IL_0022: ldarg.2
IL_0023: conv.u
IL_0024: add.ovf.un
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: ldarg.3
IL_0028: conv.i
IL_0029: add.ovf.un
IL_002a: stloc.1
IL_002b: ldloc.1
IL_002c: ldarg.s V_4
IL_002e: conv.u
IL_002f: add.ovf.un
IL_0030: stloc.1
IL_0031: ldloc.1
IL_0032: ldc.i4.s -2
IL_0034: conv.i
IL_0035: add.ovf.un
IL_0036: stloc.1
IL_0037: nop
IL_0038: ret
}");
comp.VerifyIL("C.Test1", @"
{
// Code size 56 (0x38)
.maxstack 2
.locals init (byte V_0, //b
byte* V_1) //p
IL_0000: nop
IL_0001: nop
IL_0002: ldc.i4.3
IL_0003: stloc.0
IL_0004: ldloca.s V_0
IL_0006: conv.u
IL_0007: stloc.1
IL_0008: ldloc.1
IL_0009: ldc.i4.2
IL_000a: sub.ovf.un
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: ldc.i4.3
IL_000e: sub.ovf.un
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.4
IL_0012: conv.i8
IL_0013: conv.i
IL_0014: sub.ovf.un
IL_0015: stloc.1
IL_0016: ldloc.1
IL_0017: ldc.i4.5
IL_0018: conv.i8
IL_0019: conv.u
IL_001a: sub.ovf.un
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: ldarg.1
IL_001e: conv.i
IL_001f: sub.ovf.un
IL_0020: stloc.1
IL_0021: ldloc.1
IL_0022: ldarg.2
IL_0023: conv.u
IL_0024: sub.ovf.un
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: ldarg.3
IL_0028: conv.i
IL_0029: sub.ovf.un
IL_002a: stloc.1
IL_002b: ldloc.1
IL_002c: ldarg.s V_4
IL_002e: conv.u
IL_002f: sub.ovf.un
IL_0030: stloc.1
IL_0031: ldloc.1
IL_0032: ldc.i4.m1
IL_0033: conv.i
IL_0034: sub.ovf.un
IL_0035: stloc.1
IL_0036: nop
IL_0037: ret
}");
}
[Fact]
public void CheckedSignExtend()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
byte* ptr1 = default(byte*);
ptr1 = (byte*)2;
checked
{
// should not overflow regardless of 32/64 bit
ptr1 = ptr1 + 2147483649;
}
Console.WriteLine((long)ptr1);
byte* ptr = (byte*)2;
try
{
checked
{
int i = -1;
// should overflow regardless of 32/64 bit
ptr = ptr + i;
}
Console.WriteLine((long)ptr);
}
catch (OverflowException)
{
Console.WriteLine(""overflow"");
Console.WriteLine((long)ptr);
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"2147483651
overflow
2", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 67 (0x43)
.maxstack 2
.locals init (byte* V_0, //ptr1
byte* V_1, //ptr
int V_2) //i
IL_0000: ldloca.s V_0
IL_0002: initobj ""byte*""
IL_0008: ldc.i4.2
IL_0009: conv.i
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: ldc.i4 0x80000001
IL_0011: conv.u
IL_0012: add.ovf.un
IL_0013: stloc.0
IL_0014: ldloc.0
IL_0015: conv.u8
IL_0016: call ""void System.Console.WriteLine(long)""
IL_001b: ldc.i4.2
IL_001c: conv.i
IL_001d: stloc.1
.try
{
IL_001e: ldc.i4.m1
IL_001f: stloc.2
IL_0020: ldloc.1
IL_0021: ldloc.2
IL_0022: conv.i
IL_0023: add.ovf.un
IL_0024: stloc.1
IL_0025: ldloc.1
IL_0026: conv.u8
IL_0027: call ""void System.Console.WriteLine(long)""
IL_002c: leave.s IL_0042
}
catch System.OverflowException
{
IL_002e: pop
IL_002f: ldstr ""overflow""
IL_0034: call ""void System.Console.WriteLine(string)""
IL_0039: ldloc.1
IL_003a: conv.u8
IL_003b: call ""void System.Console.WriteLine(long)""
IL_0040: leave.s IL_0042
}
IL_0042: ret
}
");
}
[Fact]
public void Increment()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S* p = (S*)0;
checked
{
p++;
}
checked
{
++p;
}
unchecked
{
p++;
}
unchecked
{
++p;
}
Console.WriteLine((int)p);
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "4", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 47 (0x2f)
.maxstack 2
.locals init (S* V_0) //p
IL_0000: ldc.i4.0
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: sizeof ""S""
IL_000a: add.ovf.un
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: sizeof ""S""
IL_0013: add.ovf.un
IL_0014: stloc.0
IL_0015: ldloc.0
IL_0016: sizeof ""S""
IL_001c: add
IL_001d: stloc.0
IL_001e: ldloc.0
IL_001f: sizeof ""S""
IL_0025: add
IL_0026: stloc.0
IL_0027: ldloc.0
IL_0028: conv.i4
IL_0029: call ""void System.Console.WriteLine(int)""
IL_002e: ret
}
");
}
[Fact]
public void Decrement()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S* p = (S*)8;
checked
{
p--;
}
checked
{
--p;
}
unchecked
{
p--;
}
unchecked
{
--p;
}
Console.WriteLine((int)p);
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "4", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 47 (0x2f)
.maxstack 2
.locals init (S* V_0) //p
IL_0000: ldc.i4.8
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: sizeof ""S""
IL_000a: sub.ovf.un
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: sizeof ""S""
IL_0013: sub.ovf.un
IL_0014: stloc.0
IL_0015: ldloc.0
IL_0016: sizeof ""S""
IL_001c: sub
IL_001d: stloc.0
IL_001e: ldloc.0
IL_001f: sizeof ""S""
IL_0025: sub
IL_0026: stloc.0
IL_0027: ldloc.0
IL_0028: conv.i4
IL_0029: call ""void System.Console.WriteLine(int)""
IL_002e: ret
}
");
}
[Fact]
public void IncrementProperty()
{
var text = @"
using System;
unsafe struct S
{
S* P { get; set; }
S* this[int x] { get { return P; } set { P = value; } }
static void Main()
{
S s = new S();
s.P++;
--s[GetIndex()];
Console.Write((int)s.P);
}
static int GetIndex()
{
Console.Write(""I"");
return 1;
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "I0", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 74 (0x4a)
.maxstack 3
.locals init (S V_0, //s
S* V_1,
int V_2)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: dup
IL_000b: call ""readonly S* S.P.get""
IL_0010: stloc.1
IL_0011: ldloc.1
IL_0012: sizeof ""S""
IL_0018: add
IL_0019: call ""void S.P.set""
IL_001e: ldloca.s V_0
IL_0020: call ""int S.GetIndex()""
IL_0025: stloc.2
IL_0026: dup
IL_0027: ldloc.2
IL_0028: call ""S* S.this[int].get""
IL_002d: sizeof ""S""
IL_0033: sub
IL_0034: stloc.1
IL_0035: ldloc.2
IL_0036: ldloc.1
IL_0037: call ""void S.this[int].set""
IL_003c: ldloca.s V_0
IL_003e: call ""readonly S* S.P.get""
IL_0043: conv.i4
IL_0044: call ""void System.Console.Write(int)""
IL_0049: ret
}
");
}
[Fact]
public void CompoundAssignment()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S* p = (S*)8;
checked
{
p += 1;
p += 2U;
p -= 1L;
p -= 2UL;
}
unchecked
{
p += 1;
p += 2U;
p -= 1L;
p -= 2UL;
}
Console.WriteLine((int)p);
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "8", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 103 (0x67)
.maxstack 3
.locals init (S* V_0) //p
IL_0000: ldc.i4.8
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: sizeof ""S""
IL_000a: add.ovf.un
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: ldc.i4.2
IL_000e: conv.u8
IL_000f: sizeof ""S""
IL_0015: conv.i8
IL_0016: mul.ovf
IL_0017: conv.i
IL_0018: add.ovf.un
IL_0019: stloc.0
IL_001a: ldloc.0
IL_001b: sizeof ""S""
IL_0021: sub.ovf.un
IL_0022: stloc.0
IL_0023: ldloc.0
IL_0024: ldc.i4.2
IL_0025: conv.i8
IL_0026: sizeof ""S""
IL_002c: conv.ovf.u8
IL_002d: mul.ovf.un
IL_002e: conv.u
IL_002f: sub.ovf.un
IL_0030: stloc.0
IL_0031: ldloc.0
IL_0032: sizeof ""S""
IL_0038: add
IL_0039: stloc.0
IL_003a: ldloc.0
IL_003b: ldc.i4.2
IL_003c: conv.u8
IL_003d: sizeof ""S""
IL_0043: conv.i8
IL_0044: mul
IL_0045: conv.i
IL_0046: add
IL_0047: stloc.0
IL_0048: ldloc.0
IL_0049: sizeof ""S""
IL_004f: sub
IL_0050: stloc.0
IL_0051: ldloc.0
IL_0052: ldc.i4.2
IL_0053: conv.i8
IL_0054: sizeof ""S""
IL_005a: conv.i8
IL_005b: mul
IL_005c: conv.u
IL_005d: sub
IL_005e: stloc.0
IL_005f: ldloc.0
IL_0060: conv.i4
IL_0061: call ""void System.Console.WriteLine(int)""
IL_0066: ret
}
");
}
[Fact]
public void CompoundAssignProperty()
{
var text = @"
using System;
unsafe struct S
{
S* P { get; set; }
S* this[int x] { get { return P; } set { P = value; } }
static void Main()
{
S s = new S();
s.P += 3;
s[GetIndex()] -= 2;
Console.Write((int)s.P);
}
static int GetIndex()
{
Console.Write(""I"");
return 1;
}
}
";
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"I4";
}
else
{
expectedOutput = @"I8";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 78 (0x4e)
.maxstack 5
.locals init (S V_0, //s
S& V_1,
int V_2)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: dup
IL_000b: call ""readonly S* S.P.get""
IL_0010: ldc.i4.3
IL_0011: conv.i
IL_0012: sizeof ""S""
IL_0018: mul
IL_0019: add
IL_001a: call ""void S.P.set""
IL_001f: ldloca.s V_0
IL_0021: stloc.1
IL_0022: call ""int S.GetIndex()""
IL_0027: stloc.2
IL_0028: ldloc.1
IL_0029: ldloc.2
IL_002a: ldloc.1
IL_002b: ldloc.2
IL_002c: call ""S* S.this[int].get""
IL_0031: ldc.i4.2
IL_0032: conv.i
IL_0033: sizeof ""S""
IL_0039: mul
IL_003a: sub
IL_003b: call ""void S.this[int].set""
IL_0040: ldloca.s V_0
IL_0042: call ""readonly S* S.P.get""
IL_0047: conv.i4
IL_0048: call ""void System.Console.Write(int)""
IL_004d: ret
}
");
}
[Fact]
public void PointerSubtraction_EmptyStruct()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S* p = (S*)8;
S* q = (S*)4;
checked
{
Console.Write(p - q);
}
unchecked
{
Console.Write(p - q);
}
}
}
";
// NOTE: don't use checked subtraction or division in either case (matches dev10).
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "44", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 39 (0x27)
.maxstack 2
.locals init (S* V_0, //p
S* V_1) //q
IL_0000: ldc.i4.8
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldc.i4.4
IL_0004: conv.i
IL_0005: stloc.1
IL_0006: ldloc.0
IL_0007: ldloc.1
IL_0008: sub
IL_0009: sizeof ""S""
IL_000f: div
IL_0010: conv.i8
IL_0011: call ""void System.Console.Write(long)""
IL_0016: ldloc.0
IL_0017: ldloc.1
IL_0018: sub
IL_0019: sizeof ""S""
IL_001f: div
IL_0020: conv.i8
IL_0021: call ""void System.Console.Write(long)""
IL_0026: ret
}
");
}
[Fact]
public void PointerSubtraction_NonEmptyStruct()
{
var text = @"
using System;
unsafe struct S
{
int x; //non-empty struct
static void Main()
{
S* p = (S*)8;
S* q = (S*)4;
checked
{
Console.Write(p - q);
}
unchecked
{
Console.Write(p - q);
}
}
}
";
// NOTE: don't use checked subtraction or division in either case (matches dev10).
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "11", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 39 (0x27)
.maxstack 2
.locals init (S* V_0, //p
S* V_1) //q
IL_0000: ldc.i4.8
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldc.i4.4
IL_0004: conv.i
IL_0005: stloc.1
IL_0006: ldloc.0
IL_0007: ldloc.1
IL_0008: sub
IL_0009: sizeof ""S""
IL_000f: div
IL_0010: conv.i8
IL_0011: call ""void System.Console.Write(long)""
IL_0016: ldloc.0
IL_0017: ldloc.1
IL_0018: sub
IL_0019: sizeof ""S""
IL_001f: div
IL_0020: conv.i8
IL_0021: call ""void System.Console.Write(long)""
IL_0026: ret
}
");
}
[Fact]
public void PointerSubtraction_ConstantSize()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
int* p = (int*)8; //size is known at compile-time
int* q = (int*)4;
checked
{
Console.Write(p - q);
}
unchecked
{
Console.Write(p - q);
}
}
}
";
// NOTE: don't use checked subtraction or division in either case (matches dev10).
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "11", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 29 (0x1d)
.maxstack 2
.locals init (int* V_0, //p
int* V_1) //q
IL_0000: ldc.i4.8
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldc.i4.4
IL_0004: conv.i
IL_0005: stloc.1
IL_0006: ldloc.0
IL_0007: ldloc.1
IL_0008: sub
IL_0009: ldc.i4.4
IL_000a: div
IL_000b: conv.i8
IL_000c: call ""void System.Console.Write(long)""
IL_0011: ldloc.0
IL_0012: ldloc.1
IL_0013: sub
IL_0014: ldc.i4.4
IL_0015: div
IL_0016: conv.i8
IL_0017: call ""void System.Console.Write(long)""
IL_001c: ret
}
");
}
[Fact]
public void PointerSubtraction_IntegerDivision()
{
var text = @"
using System;
unsafe struct S
{
int x; //size = 4
static void Main()
{
S* p1 = (S*)7; //size is known at compile-time
S* p2 = (S*)9; //size is known at compile-time
S* q = (S*)4;
checked
{
Console.Write(p1 - q);
}
unchecked
{
Console.Write(p2 - q);
}
}
}
";
// NOTE: don't use checked subtraction or division in either case (matches dev10).
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "01", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 43 (0x2b)
.maxstack 2
.locals init (S* V_0, //p1
S* V_1, //p2
S* V_2) //q
IL_0000: ldc.i4.7
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldc.i4.s 9
IL_0005: conv.i
IL_0006: stloc.1
IL_0007: ldc.i4.4
IL_0008: conv.i
IL_0009: stloc.2
IL_000a: ldloc.0
IL_000b: ldloc.2
IL_000c: sub
IL_000d: sizeof ""S""
IL_0013: div
IL_0014: conv.i8
IL_0015: call ""void System.Console.Write(long)""
IL_001a: ldloc.1
IL_001b: ldloc.2
IL_001c: sub
IL_001d: sizeof ""S""
IL_0023: div
IL_0024: conv.i8
IL_0025: call ""void System.Console.Write(long)""
IL_002a: ret
}
");
}
[WorkItem(544155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544155")]
[Fact]
public void SubtractPointerTypes()
{
var text = @"
using System;
class PointerArithmetic
{
static unsafe void Main()
{
short ia1 = 10;
short* ptr = &ia1;
short* newPtr;
newPtr = ptr - 2;
Console.WriteLine((int)(ptr - newPtr));
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "2", verify: Verification.Fails);
}
#endregion Pointer arithmetic tests
#region Checked pointer arithmetic overflow tests
// 0 - operation name (e.g. "Add")
// 1 - pointed at type name (e.g. "S")
// 2 - operator (e.g. "+")
// 3 - checked/unchecked
private const string CheckedNumericHelperTemplate = @"
unsafe static class Helper
{{
public static void {0}Int({1}* p, int num, string description)
{{
{3}
{{
try
{{
p = p {2} num;
Console.WriteLine(""{0}Int: No exception at {{0}} (value = {{1}})"",
description, (ulong)p);
}}
catch (OverflowException)
{{
Console.WriteLine(""{0}Int: Exception at {{0}}"", description);
}}
}}
}}
public static void {0}UInt({1}* p, uint num, string description)
{{
{3}
{{
try
{{
p = p {2} num;
Console.WriteLine(""{0}UInt: No exception at {{0}} (value = {{1}})"",
description, (ulong)p);
}}
catch (OverflowException)
{{
Console.WriteLine(""{0}UInt: Exception at {{0}}"", description);
}}
}}
}}
public static void {0}Long({1}* p, long num, string description)
{{
{3}
{{
try
{{
p = p {2} num;
Console.WriteLine(""{0}Long: No exception at {{0}} (value = {{1}})"",
description, (ulong)p);
}}
catch (OverflowException)
{{
Console.WriteLine(""{0}Long: Exception at {{0}}"", description);
}}
}}
}}
public static void {0}ULong({1}* p, ulong num, string description)
{{
{3}
{{
try
{{
p = p {2} num;
Console.WriteLine(""{0}ULong: No exception at {{0}} (value = {{1}})"",
description, (ulong)p);
}}
catch (OverflowException)
{{
Console.WriteLine(""{0}ULong: Exception at {{0}}"", description);
}}
}}
}}
}}
";
private const string SizedStructs = @"
//sizeof SXX is 2 ^ XX
struct S00 { }
struct S01 { S00 a, b; }
struct S02 { S01 a, b; }
struct S03 { S02 a, b; }
struct S04 { S03 a, b; }
struct S05 { S04 a, b; }
struct S06 { S05 a, b; }
struct S07 { S06 a, b; }
struct S08 { S07 a, b; }
struct S09 { S08 a, b; }
struct S10 { S09 a, b; }
struct S11 { S10 a, b; }
struct S12 { S11 a, b; }
struct S13 { S12 a, b; }
struct S14 { S13 a, b; }
struct S15 { S14 a, b; }
struct S16 { S15 a, b; }
struct S17 { S16 a, b; }
struct S18 { S17 a, b; }
struct S19 { S18 a, b; }
struct S20 { S19 a, b; }
struct S21 { S20 a, b; }
struct S22 { S21 a, b; }
struct S23 { S22 a, b; }
struct S24 { S23 a, b; }
struct S25 { S24 a, b; }
struct S26 { S25 a, b; }
struct S27 { S26 a, b; }
//struct S28 { S27 a, b; } //Can't load type
//struct S29 { S28 a, b; } //Can't load type
//struct S30 { S29 a, b; } //Can't load type
//struct S31 { S30 a, b; } //Can't load type
";
// 0 - pointed-at type
private const string PositiveNumericAdditionCasesTemplate = @"
Helper.AddInt(({0}*)0, int.MaxValue, ""0 + int.MaxValue"");
Helper.AddInt(({0}*)1, int.MaxValue, ""1 + int.MaxValue"");
Helper.AddInt(({0}*)int.MaxValue, 0, ""int.MaxValue + 0"");
Helper.AddInt(({0}*)int.MaxValue, 1, ""int.MaxValue + 1"");
//Helper.AddInt(({0}*)0, uint.MaxValue, ""0 + uint.MaxValue"");
//Helper.AddInt(({0}*)1, uint.MaxValue, ""1 + uint.MaxValue"");
Helper.AddInt(({0}*)uint.MaxValue, 0, ""uint.MaxValue + 0"");
Helper.AddInt(({0}*)uint.MaxValue, 1, ""uint.MaxValue + 1"");
//Helper.AddInt(({0}*)0, long.MaxValue, ""0 + long.MaxValue"");
//Helper.AddInt(({0}*)1, long.MaxValue, ""1 + long.MaxValue"");
//Helper.AddInt(({0}*)long.MaxValue, 0, ""long.MaxValue + 0"");
//Helper.AddInt(({0}*)long.MaxValue, 1, ""long.MaxValue + 1"");
//Helper.AddInt(({0}*)0, ulong.MaxValue, ""0 + ulong.MaxValue"");
//Helper.AddInt(({0}*)1, ulong.MaxValue, ""1 + ulong.MaxValue"");
//Helper.AddInt(({0}*)ulong.MaxValue, 0, ""ulong.MaxValue + 0"");
//Helper.AddInt(({0}*)ulong.MaxValue, 1, ""ulong.MaxValue + 1"");
Console.WriteLine();
Helper.AddUInt(({0}*)0, int.MaxValue, ""0 + int.MaxValue"");
Helper.AddUInt(({0}*)1, int.MaxValue, ""1 + int.MaxValue"");
Helper.AddUInt(({0}*)int.MaxValue, 0, ""int.MaxValue + 0"");
Helper.AddUInt(({0}*)int.MaxValue, 1, ""int.MaxValue + 1"");
Helper.AddUInt(({0}*)0, uint.MaxValue, ""0 + uint.MaxValue"");
Helper.AddUInt(({0}*)1, uint.MaxValue, ""1 + uint.MaxValue"");
Helper.AddUInt(({0}*)uint.MaxValue, 0, ""uint.MaxValue + 0"");
Helper.AddUInt(({0}*)uint.MaxValue, 1, ""uint.MaxValue + 1"");
//Helper.AddUInt(({0}*)0, long.MaxValue, ""0 + long.MaxValue"");
//Helper.AddUInt(({0}*)1, long.MaxValue, ""1 + long.MaxValue"");
//Helper.AddUInt(({0}*)long.MaxValue, 0, ""long.MaxValue + 0"");
//Helper.AddUInt(({0}*)long.MaxValue, 1, ""long.MaxValue + 1"");
//Helper.AddUInt(({0}*)0, ulong.MaxValue, ""0 + ulong.MaxValue"");
//Helper.AddUInt(({0}*)1, ulong.MaxValue, ""1 + ulong.MaxValue"");
//Helper.AddUInt(({0}*)ulong.MaxValue, 0, ""ulong.MaxValue + 0"");
//Helper.AddUInt(({0}*)ulong.MaxValue, 1, ""ulong.MaxValue + 1"");
Console.WriteLine();
Helper.AddLong(({0}*)0, int.MaxValue, ""0 + int.MaxValue"");
Helper.AddLong(({0}*)1, int.MaxValue, ""1 + int.MaxValue"");
Helper.AddLong(({0}*)int.MaxValue, 0, ""int.MaxValue + 0"");
Helper.AddLong(({0}*)int.MaxValue, 1, ""int.MaxValue + 1"");
Helper.AddLong(({0}*)0, uint.MaxValue, ""0 + uint.MaxValue"");
Helper.AddLong(({0}*)1, uint.MaxValue, ""1 + uint.MaxValue"");
Helper.AddLong(({0}*)uint.MaxValue, 0, ""uint.MaxValue + 0"");
Helper.AddLong(({0}*)uint.MaxValue, 1, ""uint.MaxValue + 1"");
Helper.AddLong(({0}*)0, long.MaxValue, ""0 + long.MaxValue"");
Helper.AddLong(({0}*)1, long.MaxValue, ""1 + long.MaxValue"");
//Helper.AddLong(({0}*)long.MaxValue, 0, ""long.MaxValue + 0"");
//Helper.AddLong(({0}*)long.MaxValue, 1, ""long.MaxValue + 1"");
//Helper.AddLong(({0}*)0, ulong.MaxValue, ""0 + ulong.MaxValue"");
//Helper.AddLong(({0}*)1, ulong.MaxValue, ""1 + ulong.MaxValue"");
//Helper.AddLong(({0}*)ulong.MaxValue, 0, ""ulong.MaxValue + 0"");
//Helper.AddLong(({0}*)ulong.MaxValue, 1, ""ulong.MaxValue + 1"");
Console.WriteLine();
Helper.AddULong(({0}*)0, int.MaxValue, ""0 + int.MaxValue"");
Helper.AddULong(({0}*)1, int.MaxValue, ""1 + int.MaxValue"");
Helper.AddULong(({0}*)int.MaxValue, 0, ""int.MaxValue + 0"");
Helper.AddULong(({0}*)int.MaxValue, 1, ""int.MaxValue + 1"");
Helper.AddULong(({0}*)0, uint.MaxValue, ""0 + uint.MaxValue"");
Helper.AddULong(({0}*)1, uint.MaxValue, ""1 + uint.MaxValue"");
Helper.AddULong(({0}*)uint.MaxValue, 0, ""uint.MaxValue + 0"");
Helper.AddULong(({0}*)uint.MaxValue, 1, ""uint.MaxValue + 1"");
Helper.AddULong(({0}*)0, long.MaxValue, ""0 + long.MaxValue"");
Helper.AddULong(({0}*)1, long.MaxValue, ""1 + long.MaxValue"");
//Helper.AddULong(({0}*)long.MaxValue, 0, ""long.MaxValue + 0"");
//Helper.AddULong(({0}*)long.MaxValue, 1, ""long.MaxValue + 1"");
Helper.AddULong(({0}*)0, ulong.MaxValue, ""0 + ulong.MaxValue"");
Helper.AddULong(({0}*)1, ulong.MaxValue, ""1 + ulong.MaxValue"");
//Helper.AddULong(({0}*)ulong.MaxValue, 0, ""ulong.MaxValue + 0"");
//Helper.AddULong(({0}*)ulong.MaxValue, 1, ""ulong.MaxValue + 1"");
";
// 0 - pointed-at type
private const string NegativeNumericAdditionCasesTemplate = @"
Helper.AddInt(({0}*)0, -1, ""0 + (-1)"");
Helper.AddInt(({0}*)0, int.MinValue, ""0 + int.MinValue"");
//Helper.AddInt(({0}*)0, long.MinValue, ""0 + long.MinValue"");
Console.WriteLine();
Helper.AddLong(({0}*)0, -1, ""0 + (-1)"");
Helper.AddLong(({0}*)0, int.MinValue, ""0 + int.MinValue"");
Helper.AddLong(({0}*)0, long.MinValue, ""0 + long.MinValue"");
";
// 0 - pointed-at type
private const string PositiveNumericSubtractionCasesTemplate = @"
Helper.SubInt(({0}*)0, 1, ""0 - 1"");
Helper.SubInt(({0}*)0, int.MaxValue, ""0 - int.MaxValue"");
//Helper.SubInt(({0}*)0, uint.MaxValue, ""0 - uint.MaxValue"");
//Helper.SubInt(({0}*)0, long.MaxValue, ""0 - long.MaxValue"");
//Helper.SubInt(({0}*)0, ulong.MaxValue, ""0 - ulong.MaxValue"");
Console.WriteLine();
Helper.SubUInt(({0}*)0, 1, ""0 - 1"");
Helper.SubUInt(({0}*)0, int.MaxValue, ""0 - int.MaxValue"");
Helper.SubUInt(({0}*)0, uint.MaxValue, ""0 - uint.MaxValue"");
//Helper.SubUInt(({0}*)0, long.MaxValue, ""0 - long.MaxValue"");
//Helper.SubUInt(({0}*)0, ulong.MaxValue, ""0 - ulong.MaxValue"");
Console.WriteLine();
Helper.SubLong(({0}*)0, 1, ""0 - 1"");
Helper.SubLong(({0}*)0, int.MaxValue, ""0 - int.MaxValue"");
Helper.SubLong(({0}*)0, uint.MaxValue, ""0 - uint.MaxValue"");
Helper.SubLong(({0}*)0, long.MaxValue, ""0 - long.MaxValue"");
//Helper.SubLong(({0}*)0, ulong.MaxValue, ""0 - ulong.MaxValue"");
Console.WriteLine();
Helper.SubULong(({0}*)0, 1, ""0 - 1"");
Helper.SubULong(({0}*)0, int.MaxValue, ""0 - int.MaxValue"");
Helper.SubULong(({0}*)0, uint.MaxValue, ""0 - uint.MaxValue"");
Helper.SubULong(({0}*)0, long.MaxValue, ""0 - long.MaxValue"");
Helper.SubULong(({0}*)0, ulong.MaxValue, ""0 - ulong.MaxValue"");
";
// 0 - pointed-at type
private const string NegativeNumericSubtractionCasesTemplate = @"
Helper.SubInt(({0}*)0, -1, ""0 - -1"");
Helper.SubInt(({0}*)0, int.MinValue, ""0 - int.MinValue"");
Helper.SubInt(({0}*)0, -1 * int.MaxValue, ""0 - -int.MaxValue"");
Console.WriteLine();
Helper.SubLong(({0}*)0, -1L, ""0 - -1"");
Helper.SubLong(({0}*)0, int.MinValue, ""0 - int.MinValue"");
Helper.SubLong(({0}*)0, long.MinValue, ""0 - long.MinValue"");
Helper.SubLong(({0}*)0, -1L * int.MaxValue, ""0 - -int.MaxValue"");
Helper.SubLong(({0}*)0, -1L * uint.MaxValue, ""0 - -uint.MaxValue"");
Helper.SubLong(({0}*)0, -1L * long.MaxValue, ""0 - -long.MaxValue"");
Helper.SubLong(({0}*)0, -1L * long.MaxValue, ""0 - -ulong.MaxValue"");
Helper.SubLong(({0}*)0, -1L * int.MinValue, ""0 - -int.MinValue"");
//Helper.SubLong(({0}*)0, -1L * long.MinValue, ""0 - -long.MinValue"");
";
private static string MakeNumericOverflowTest(string casesTemplate, string pointedAtType, string operationName, string @operator, string checkedness)
{
const string mainClassTemplate = @"
using System;
unsafe class C
{{
static void Main()
{{
{0}
{{
{1}
}}
}}
}}
{2}
{3}
";
return string.Format(mainClassTemplate,
checkedness,
string.Format(casesTemplate, pointedAtType),
string.Format(CheckedNumericHelperTemplate, operationName, pointedAtType, @operator, checkedness),
SizedStructs);
}
// Positive numbers, size = 1
[Fact]
public void CheckedNumericAdditionOverflow1()
{
var text = MakeNumericOverflowTest(PositiveNumericAdditionCasesTemplate, "S00", "Add", "+", "checked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: Exception at uint.MaxValue + 1
AddUInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddUInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddUInt: No exception at 0 + uint.MaxValue (value = 4294967295)
AddUInt: Exception at 1 + uint.MaxValue
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: Exception at uint.MaxValue + 1
AddLong: No exception at 0 + int.MaxValue (value = 2147483647)
AddLong: No exception at 1 + int.MaxValue (value = 2147483648)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483648)
AddLong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddLong: Exception at 1 + uint.MaxValue
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: Exception at uint.MaxValue + 1
AddLong: No exception at 0 + long.MaxValue (value = 4294967295)
AddLong: Exception at 1 + long.MaxValue
AddULong: No exception at 0 + int.MaxValue (value = 2147483647)
AddULong: No exception at 1 + int.MaxValue (value = 2147483648)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483648)
AddULong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddULong: Exception at 1 + uint.MaxValue
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: Exception at uint.MaxValue + 1
AddULong: No exception at 0 + long.MaxValue (value = 4294967295)
AddULong: Exception at 1 + long.MaxValue
AddULong: No exception at 0 + ulong.MaxValue (value = 4294967295)
AddULong: Exception at 1 + ulong.MaxValue
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: No exception at uint.MaxValue + 1 (value = 4294967296)
AddUInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddUInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddUInt: No exception at 0 + uint.MaxValue (value = 4294967295)
AddUInt: No exception at 1 + uint.MaxValue (value = 4294967296)
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: No exception at uint.MaxValue + 1 (value = 4294967296)
AddLong: No exception at 0 + int.MaxValue (value = 2147483647)
AddLong: No exception at 1 + int.MaxValue (value = 2147483648)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483648)
AddLong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddLong: No exception at 1 + uint.MaxValue (value = 4294967296)
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: No exception at uint.MaxValue + 1 (value = 4294967296)
AddLong: No exception at 0 + long.MaxValue (value = 9223372036854775807)
AddLong: No exception at 1 + long.MaxValue (value = 9223372036854775808)
AddULong: No exception at 0 + int.MaxValue (value = 2147483647)
AddULong: No exception at 1 + int.MaxValue (value = 2147483648)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483648)
AddULong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddULong: No exception at 1 + uint.MaxValue (value = 4294967296)
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: No exception at uint.MaxValue + 1 (value = 4294967296)
AddULong: No exception at 0 + long.MaxValue (value = 9223372036854775807)
AddULong: No exception at 1 + long.MaxValue (value = 9223372036854775808)
AddULong: No exception at 0 + ulong.MaxValue (value = 18446744073709551615)
AddULong: Exception at 1 + ulong.MaxValue
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Positive numbers, size = 4
[Fact]
public void CheckedNumericAdditionOverflow2()
{
var text = MakeNumericOverflowTest(PositiveNumericAdditionCasesTemplate, "S02", "Add", "+", "checked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: Exception at 0 + int.MaxValue
AddInt: Exception at 1 + int.MaxValue
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: Exception at uint.MaxValue + 1
AddUInt: No exception at 0 + int.MaxValue (value = 4294967292)
AddUInt: No exception at 1 + int.MaxValue (value = 4294967293)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddUInt: No exception at 0 + uint.MaxValue (value = 4294967292)
AddUInt: No exception at 1 + uint.MaxValue (value = 4294967293)
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: Exception at uint.MaxValue + 1
AddLong: No exception at 0 + int.MaxValue (value = 4294967292)
AddLong: No exception at 1 + int.MaxValue (value = 4294967293)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483651)
AddLong: No exception at 0 + uint.MaxValue (value = 4294967292)
AddLong: No exception at 1 + uint.MaxValue (value = 4294967293)
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: Exception at uint.MaxValue + 1
AddLong: Exception at 0 + long.MaxValue
AddLong: Exception at 1 + long.MaxValue
AddULong: No exception at 0 + int.MaxValue (value = 4294967292)
AddULong: No exception at 1 + int.MaxValue (value = 4294967293)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483651)
AddULong: No exception at 0 + uint.MaxValue (value = 4294967292)
AddULong: No exception at 1 + uint.MaxValue (value = 4294967293)
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: Exception at uint.MaxValue + 1
AddULong: Exception at 0 + long.MaxValue
AddULong: Exception at 1 + long.MaxValue
AddULong: Exception at 0 + ulong.MaxValue
AddULong: Exception at 1 + ulong.MaxValue
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + int.MaxValue (value = 8589934588)
AddInt: No exception at 1 + int.MaxValue (value = 8589934589)
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: No exception at uint.MaxValue + 1 (value = 4294967299)
AddUInt: No exception at 0 + int.MaxValue (value = 8589934588)
AddUInt: No exception at 1 + int.MaxValue (value = 8589934589)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddUInt: No exception at 0 + uint.MaxValue (value = 17179869180)
AddUInt: No exception at 1 + uint.MaxValue (value = 17179869181)
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: No exception at uint.MaxValue + 1 (value = 4294967299)
AddLong: No exception at 0 + int.MaxValue (value = 8589934588)
AddLong: No exception at 1 + int.MaxValue (value = 8589934589)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483651)
AddLong: No exception at 0 + uint.MaxValue (value = 17179869180)
AddLong: No exception at 1 + uint.MaxValue (value = 17179869181)
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: No exception at uint.MaxValue + 1 (value = 4294967299)
AddLong: Exception at 0 + long.MaxValue
AddLong: Exception at 1 + long.MaxValue
AddULong: No exception at 0 + int.MaxValue (value = 8589934588)
AddULong: No exception at 1 + int.MaxValue (value = 8589934589)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483651)
AddULong: No exception at 0 + uint.MaxValue (value = 17179869180)
AddULong: No exception at 1 + uint.MaxValue (value = 17179869181)
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: No exception at uint.MaxValue + 1 (value = 4294967299)
AddULong: Exception at 0 + long.MaxValue
AddULong: Exception at 1 + long.MaxValue
AddULong: Exception at 0 + ulong.MaxValue
AddULong: Exception at 1 + ulong.MaxValue
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Negative numbers, size = 1
[Fact]
public void CheckedNumericAdditionOverflow3()
{
var text = MakeNumericOverflowTest(NegativeNumericAdditionCasesTemplate, "S00", "Add", "+", "checked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 4294967295)
AddInt: No exception at 0 + int.MinValue (value = 2147483648)
AddLong: No exception at 0 + (-1) (value = 4294967295)
AddLong: No exception at 0 + int.MinValue (value = 2147483648)
AddLong: No exception at 0 + long.MinValue (value = 0)
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 18446744073709551615)
AddInt: No exception at 0 + int.MinValue (value = 18446744071562067968)
AddLong: No exception at 0 + (-1) (value = 18446744073709551615)
AddLong: No exception at 0 + int.MinValue (value = 18446744071562067968)
AddLong: No exception at 0 + long.MinValue (value = 9223372036854775808)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: expectedOutput);
}
// Negative numbers, size = 4
[Fact]
public void CheckedNumericAdditionOverflow4()
{
var text = MakeNumericOverflowTest(NegativeNumericAdditionCasesTemplate, "S02", "Add", "+", "checked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 4294967292)
AddInt: Exception at 0 + int.MinValue
AddLong: No exception at 0 + (-1) (value = 4294967292)
AddLong: No exception at 0 + int.MinValue (value = 0)
AddLong: Exception at 0 + long.MinValue
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 18446744073709551612)
AddInt: No exception at 0 + int.MinValue (value = 18446744065119617024)
AddLong: No exception at 0 + (-1) (value = 18446744073709551612)
AddLong: No exception at 0 + int.MinValue (value = 18446744065119617024)
AddLong: Exception at 0 + long.MinValue
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Positive numbers, size = 1
[Fact]
public void CheckedNumericSubtractionOverflow1()
{
var text = MakeNumericOverflowTest(PositiveNumericSubtractionCasesTemplate, "S00", "Sub", "-", "checked");
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"
SubInt: Exception at 0 - 1
SubInt: Exception at 0 - int.MaxValue
SubUInt: Exception at 0 - 1
SubUInt: Exception at 0 - int.MaxValue
SubUInt: Exception at 0 - uint.MaxValue
SubLong: Exception at 0 - 1
SubLong: Exception at 0 - int.MaxValue
SubLong: Exception at 0 - uint.MaxValue
SubLong: Exception at 0 - long.MaxValue
SubULong: Exception at 0 - 1
SubULong: Exception at 0 - int.MaxValue
SubULong: Exception at 0 - uint.MaxValue
SubULong: Exception at 0 - long.MaxValue
SubULong: Exception at 0 - ulong.MaxValue
");
}
// Positive numbers, size = 4
[Fact]
public void CheckedNumericSubtractionOverflow2()
{
var text = MakeNumericOverflowTest(PositiveNumericSubtractionCasesTemplate, "S02", "Sub", "-", "checked");
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"
SubInt: Exception at 0 - 1
SubInt: Exception at 0 - int.MaxValue
SubUInt: Exception at 0 - 1
SubUInt: Exception at 0 - int.MaxValue
SubUInt: Exception at 0 - uint.MaxValue
SubLong: Exception at 0 - 1
SubLong: Exception at 0 - int.MaxValue
SubLong: Exception at 0 - uint.MaxValue
SubLong: Exception at 0 - long.MaxValue
SubULong: Exception at 0 - 1
SubULong: Exception at 0 - int.MaxValue
SubULong: Exception at 0 - uint.MaxValue
SubULong: Exception at 0 - long.MaxValue
SubULong: Exception at 0 - ulong.MaxValue
");
}
// Negative numbers, size = 1
[Fact]
public void CheckedNumericSubtractionOverflow3()
{
var text = MakeNumericOverflowTest(NegativeNumericSubtractionCasesTemplate, "S00", "Sub", "-", "checked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
SubInt: Exception at 0 - -1
SubInt: Exception at 0 - int.MinValue
SubInt: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -1
SubLong: Exception at 0 - int.MinValue
SubLong: No exception at 0 - long.MinValue (value = 0)
SubLong: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -uint.MaxValue
SubLong: Exception at 0 - -long.MaxValue
SubLong: Exception at 0 - -ulong.MaxValue
SubLong: Exception at 0 - -int.MinValue
";
}
else
{
expectedOutput = @"
SubInt: Exception at 0 - -1
SubInt: Exception at 0 - int.MinValue
SubInt: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -1
SubLong: Exception at 0 - int.MinValue
SubLong: Exception at 0 - long.MinValue
SubLong: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -uint.MaxValue
SubLong: Exception at 0 - -long.MaxValue
SubLong: Exception at 0 - -ulong.MaxValue
SubLong: Exception at 0 - -int.MinValue
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Negative numbers, size = 4
[Fact]
public void CheckedNumericSubtractionOverflow4()
{
var text = MakeNumericOverflowTest(NegativeNumericSubtractionCasesTemplate, "S02", "Sub", "-", "checked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
SubInt: Exception at 0 - -1
SubInt: Exception at 0 - int.MinValue
SubInt: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -1
SubLong: No exception at 0 - int.MinValue (value = 0)
SubLong: Exception at 0 - long.MinValue
SubLong: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -uint.MaxValue
SubLong: Exception at 0 - -long.MaxValue
SubLong: Exception at 0 - -ulong.MaxValue
SubLong: No exception at 0 - -int.MinValue (value = 0)
";
}
else
{
expectedOutput = @"
SubInt: Exception at 0 - -1
SubInt: Exception at 0 - int.MinValue
SubInt: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -1
SubLong: Exception at 0 - int.MinValue
SubLong: Exception at 0 - long.MinValue
SubLong: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -uint.MaxValue
SubLong: Exception at 0 - -long.MaxValue
SubLong: Exception at 0 - -ulong.MaxValue
SubLong: Exception at 0 - -int.MinValue
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
[Fact]
public void CheckedNumericSubtractionQuirk()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
checked
{
S* p;
p = (S*)0 + (-1);
System.Console.WriteLine(""No exception from addition"");
try
{
p = (S*)0 - 1;
}
catch (OverflowException)
{
System.Console.WriteLine(""Exception from subtraction"");
}
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Passes, expectedOutput: @"
No exception from addition
Exception from subtraction
");
}
[Fact]
public void CheckedNumericAdditionQuirk()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
checked
{
S* p;
p = (S*)1 + int.MaxValue;
System.Console.WriteLine(""No exception for pointer + int"");
try
{
p = int.MaxValue + (S*)1;
}
catch (OverflowException)
{
System.Console.WriteLine(""Exception for int + pointer"");
}
}
}
}
";
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
No exception for pointer + int
Exception for int + pointer
";
}
else
{
expectedOutput = @"
No exception for pointer + int
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Passes);
}
[Fact]
public void CheckedPointerSubtractionQuirk()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S* p = (S*)uint.MinValue;
S* q = (S*)uint.MaxValue;
checked
{
Console.Write(p - q);
}
unchecked
{
Console.Write(p - q);
}
}
}
";
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"11";
}
else
{
expectedOutput = @"-4294967295-4294967295";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
[Fact]
public void CheckedPointerElementAccessQuirk()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
fixed (byte* p = new byte[2])
{
p[0] = 12;
// Take a pointer to the second element of the array.
byte* q = p + 1;
// Compute the offset that will wrap around all the way to the preceding byte of memory.
// We do this so that we can overflow, but still end up in valid memory.
ulong offset = sizeof(IntPtr) == sizeof(int) ? uint.MaxValue : ulong.MaxValue;
checked
{
Console.WriteLine(q[offset]);
System.Console.WriteLine(""No exception for element access"");
try
{
Console.WriteLine(*(q + offset));
}
catch (OverflowException)
{
System.Console.WriteLine(""Exception for add-then-dereference"");
}
}
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"
12
No exception for element access
Exception for add-then-dereference
");
}
#endregion Checked pointer arithmetic overflow tests
#region Unchecked pointer arithmetic overflow tests
// Positive numbers, size = 1
[Fact]
public void UncheckedNumericAdditionOverflow1()
{
var text = MakeNumericOverflowTest(PositiveNumericAdditionCasesTemplate, "S00", "Add", "+", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: No exception at uint.MaxValue + 1 (value = 0)
AddUInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddUInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddUInt: No exception at 0 + uint.MaxValue (value = 4294967295)
AddUInt: No exception at 1 + uint.MaxValue (value = 0)
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: No exception at uint.MaxValue + 1 (value = 0)
AddLong: No exception at 0 + int.MaxValue (value = 2147483647)
AddLong: No exception at 1 + int.MaxValue (value = 2147483648)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483648)
AddLong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddLong: No exception at 1 + uint.MaxValue (value = 0)
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: No exception at uint.MaxValue + 1 (value = 0)
AddLong: No exception at 0 + long.MaxValue (value = 4294967295)
AddLong: No exception at 1 + long.MaxValue (value = 0)
AddULong: No exception at 0 + int.MaxValue (value = 2147483647)
AddULong: No exception at 1 + int.MaxValue (value = 2147483648)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483648)
AddULong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddULong: No exception at 1 + uint.MaxValue (value = 0)
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: No exception at uint.MaxValue + 1 (value = 0)
AddULong: No exception at 0 + long.MaxValue (value = 4294967295)
AddULong: No exception at 1 + long.MaxValue (value = 0)
AddULong: No exception at 0 + ulong.MaxValue (value = 4294967295)
AddULong: No exception at 1 + ulong.MaxValue (value = 0)
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: No exception at uint.MaxValue + 1 (value = 4294967296)
AddUInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddUInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddUInt: No exception at 0 + uint.MaxValue (value = 4294967295)
AddUInt: No exception at 1 + uint.MaxValue (value = 4294967296)
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: No exception at uint.MaxValue + 1 (value = 4294967296)
AddLong: No exception at 0 + int.MaxValue (value = 2147483647)
AddLong: No exception at 1 + int.MaxValue (value = 2147483648)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483648)
AddLong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddLong: No exception at 1 + uint.MaxValue (value = 4294967296)
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: No exception at uint.MaxValue + 1 (value = 4294967296)
AddLong: No exception at 0 + long.MaxValue (value = 9223372036854775807)
AddLong: No exception at 1 + long.MaxValue (value = 9223372036854775808)
AddULong: No exception at 0 + int.MaxValue (value = 2147483647)
AddULong: No exception at 1 + int.MaxValue (value = 2147483648)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483648)
AddULong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddULong: No exception at 1 + uint.MaxValue (value = 4294967296)
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: No exception at uint.MaxValue + 1 (value = 4294967296)
AddULong: No exception at 0 + long.MaxValue (value = 9223372036854775807)
AddULong: No exception at 1 + long.MaxValue (value = 9223372036854775808)
AddULong: No exception at 0 + ulong.MaxValue (value = 18446744073709551615)
AddULong: No exception at 1 + ulong.MaxValue (value = 0)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Positive numbers, size = 4
[Fact]
public void UncheckedNumericAdditionOverflow2()
{
var text = MakeNumericOverflowTest(PositiveNumericAdditionCasesTemplate, "S02", "Add", "+", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: No exception at 0 + int.MaxValue (value = 4294967292)
AddInt: No exception at 1 + int.MaxValue (value = 4294967293)
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: No exception at uint.MaxValue + 1 (value = 3)
AddUInt: No exception at 0 + int.MaxValue (value = 4294967292)
AddUInt: No exception at 1 + int.MaxValue (value = 4294967293)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddUInt: No exception at 0 + uint.MaxValue (value = 4294967292)
AddUInt: No exception at 1 + uint.MaxValue (value = 4294967293)
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: No exception at uint.MaxValue + 1 (value = 3)
AddLong: No exception at 0 + int.MaxValue (value = 4294967292)
AddLong: No exception at 1 + int.MaxValue (value = 4294967293)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483651)
AddLong: No exception at 0 + uint.MaxValue (value = 4294967292)
AddLong: No exception at 1 + uint.MaxValue (value = 4294967293)
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: No exception at uint.MaxValue + 1 (value = 3)
AddLong: No exception at 0 + long.MaxValue (value = 4294967292)
AddLong: No exception at 1 + long.MaxValue (value = 4294967293)
AddULong: No exception at 0 + int.MaxValue (value = 4294967292)
AddULong: No exception at 1 + int.MaxValue (value = 4294967293)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483651)
AddULong: No exception at 0 + uint.MaxValue (value = 4294967292)
AddULong: No exception at 1 + uint.MaxValue (value = 4294967293)
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: No exception at uint.MaxValue + 1 (value = 3)
AddULong: No exception at 0 + long.MaxValue (value = 4294967292)
AddULong: No exception at 1 + long.MaxValue (value = 4294967293)
AddULong: No exception at 0 + ulong.MaxValue (value = 4294967292)
AddULong: No exception at 1 + ulong.MaxValue (value = 4294967293)
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + int.MaxValue (value = 8589934588)
AddInt: No exception at 1 + int.MaxValue (value = 8589934589)
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: No exception at uint.MaxValue + 1 (value = 4294967299)
AddUInt: No exception at 0 + int.MaxValue (value = 8589934588)
AddUInt: No exception at 1 + int.MaxValue (value = 8589934589)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddUInt: No exception at 0 + uint.MaxValue (value = 17179869180)
AddUInt: No exception at 1 + uint.MaxValue (value = 17179869181)
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: No exception at uint.MaxValue + 1 (value = 4294967299)
AddLong: No exception at 0 + int.MaxValue (value = 8589934588)
AddLong: No exception at 1 + int.MaxValue (value = 8589934589)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483651)
AddLong: No exception at 0 + uint.MaxValue (value = 17179869180)
AddLong: No exception at 1 + uint.MaxValue (value = 17179869181)
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: No exception at uint.MaxValue + 1 (value = 4294967299)
AddLong: No exception at 0 + long.MaxValue (value = 18446744073709551612)
AddLong: No exception at 1 + long.MaxValue (value = 18446744073709551613)
AddULong: No exception at 0 + int.MaxValue (value = 8589934588)
AddULong: No exception at 1 + int.MaxValue (value = 8589934589)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483651)
AddULong: No exception at 0 + uint.MaxValue (value = 17179869180)
AddULong: No exception at 1 + uint.MaxValue (value = 17179869181)
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: No exception at uint.MaxValue + 1 (value = 4294967299)
AddULong: No exception at 0 + long.MaxValue (value = 18446744073709551612)
AddULong: No exception at 1 + long.MaxValue (value = 18446744073709551613)
AddULong: No exception at 0 + ulong.MaxValue (value = 18446744073709551612)
AddULong: No exception at 1 + ulong.MaxValue (value = 18446744073709551613)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Negative numbers, size = 1
[Fact]
public void UncheckedNumericAdditionOverflow3()
{
var text = MakeNumericOverflowTest(NegativeNumericAdditionCasesTemplate, "S00", "Add", "+", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 4294967295)
AddInt: No exception at 0 + int.MinValue (value = 2147483648)
AddLong: No exception at 0 + (-1) (value = 4294967295)
AddLong: No exception at 0 + int.MinValue (value = 2147483648)
AddLong: No exception at 0 + long.MinValue (value = 0)
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 18446744073709551615)
AddInt: No exception at 0 + int.MinValue (value = 18446744071562067968)
AddLong: No exception at 0 + (-1) (value = 18446744073709551615)
AddLong: No exception at 0 + int.MinValue (value = 18446744071562067968)
AddLong: No exception at 0 + long.MinValue (value = 9223372036854775808)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Negative numbers, size = 4
[Fact]
public void UncheckedNumericAdditionOverflow4()
{
var text = MakeNumericOverflowTest(NegativeNumericAdditionCasesTemplate, "S02", "Add", "+", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 4294967292)
AddInt: No exception at 0 + int.MinValue (value = 0)
AddLong: No exception at 0 + (-1) (value = 4294967292)
AddLong: No exception at 0 + int.MinValue (value = 0)
AddLong: No exception at 0 + long.MinValue (value = 0)
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 18446744073709551612)
AddInt: No exception at 0 + int.MinValue (value = 18446744065119617024)
AddLong: No exception at 0 + (-1) (value = 18446744073709551612)
AddLong: No exception at 0 + int.MinValue (value = 18446744065119617024)
AddLong: No exception at 0 + long.MinValue (value = 0)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Positive numbers, size = 1
[Fact]
public void UncheckedNumericSubtractionOverflow1()
{
var text = MakeNumericOverflowTest(PositiveNumericSubtractionCasesTemplate, "S00", "Sub", "-", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
SubInt: No exception at 0 - 1 (value = 4294967295)
SubInt: No exception at 0 - int.MaxValue (value = 2147483649)
SubUInt: No exception at 0 - 1 (value = 4294967295)
SubUInt: No exception at 0 - int.MaxValue (value = 2147483649)
SubUInt: No exception at 0 - uint.MaxValue (value = 1)
SubLong: No exception at 0 - 1 (value = 4294967295)
SubLong: No exception at 0 - int.MaxValue (value = 2147483649)
SubLong: No exception at 0 - uint.MaxValue (value = 1)
SubLong: No exception at 0 - long.MaxValue (value = 1)
SubULong: No exception at 0 - 1 (value = 4294967295)
SubULong: No exception at 0 - int.MaxValue (value = 2147483649)
SubULong: No exception at 0 - uint.MaxValue (value = 1)
SubULong: No exception at 0 - long.MaxValue (value = 1)
SubULong: No exception at 0 - ulong.MaxValue (value = 1)
";
}
else
{
expectedOutput = @"
SubInt: No exception at 0 - 1 (value = 18446744073709551615)
SubInt: No exception at 0 - int.MaxValue (value = 18446744071562067969)
SubUInt: No exception at 0 - 1 (value = 18446744073709551615)
SubUInt: No exception at 0 - int.MaxValue (value = 18446744071562067969)
SubUInt: No exception at 0 - uint.MaxValue (value = 18446744069414584321)
SubLong: No exception at 0 - 1 (value = 18446744073709551615)
SubLong: No exception at 0 - int.MaxValue (value = 18446744071562067969)
SubLong: No exception at 0 - uint.MaxValue (value = 18446744069414584321)
SubLong: No exception at 0 - long.MaxValue (value = 9223372036854775809)
SubULong: No exception at 0 - 1 (value = 18446744073709551615)
SubULong: No exception at 0 - int.MaxValue (value = 18446744071562067969)
SubULong: No exception at 0 - uint.MaxValue (value = 18446744069414584321)
SubULong: No exception at 0 - long.MaxValue (value = 9223372036854775809)
SubULong: No exception at 0 - ulong.MaxValue (value = 1)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Positive numbers, size = 4
[Fact]
public void UncheckedNumericSubtractionOverflow2()
{
var text = MakeNumericOverflowTest(PositiveNumericSubtractionCasesTemplate, "S02", "Sub", "-", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
SubInt: No exception at 0 - 1 (value = 4294967292)
SubInt: No exception at 0 - int.MaxValue (value = 4)
SubUInt: No exception at 0 - 1 (value = 4294967292)
SubUInt: No exception at 0 - int.MaxValue (value = 4)
SubUInt: No exception at 0 - uint.MaxValue (value = 4)
SubLong: No exception at 0 - 1 (value = 4294967292)
SubLong: No exception at 0 - int.MaxValue (value = 4)
SubLong: No exception at 0 - uint.MaxValue (value = 4)
SubLong: No exception at 0 - long.MaxValue (value = 4)
SubULong: No exception at 0 - 1 (value = 4294967292)
SubULong: No exception at 0 - int.MaxValue (value = 4)
SubULong: No exception at 0 - uint.MaxValue (value = 4)
SubULong: No exception at 0 - long.MaxValue (value = 4)
SubULong: No exception at 0 - ulong.MaxValue (value = 4)
";
}
else
{
expectedOutput = @"
SubInt: No exception at 0 - 1 (value = 18446744073709551612)
SubInt: No exception at 0 - int.MaxValue (value = 18446744065119617028)
SubUInt: No exception at 0 - 1 (value = 18446744073709551612)
SubUInt: No exception at 0 - int.MaxValue (value = 18446744065119617028)
SubUInt: No exception at 0 - uint.MaxValue (value = 18446744056529682436)
SubLong: No exception at 0 - 1 (value = 18446744073709551612)
SubLong: No exception at 0 - int.MaxValue (value = 18446744065119617028)
SubLong: No exception at 0 - uint.MaxValue (value = 18446744056529682436)
SubLong: No exception at 0 - long.MaxValue (value = 4)
SubULong: No exception at 0 - 1 (value = 18446744073709551612)
SubULong: No exception at 0 - int.MaxValue (value = 18446744065119617028)
SubULong: No exception at 0 - uint.MaxValue (value = 18446744056529682436)
SubULong: No exception at 0 - long.MaxValue (value = 4)
SubULong: No exception at 0 - ulong.MaxValue (value = 4)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Negative numbers, size = 1
[Fact]
public void UncheckedNumericSubtractionOverflow3()
{
var text = MakeNumericOverflowTest(NegativeNumericSubtractionCasesTemplate, "S00", "Sub", "-", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
SubInt: No exception at 0 - -1 (value = 1)
SubInt: No exception at 0 - int.MinValue (value = 2147483648)
SubInt: No exception at 0 - -int.MaxValue (value = 2147483647)
SubLong: No exception at 0 - -1 (value = 1)
SubLong: No exception at 0 - int.MinValue (value = 2147483648)
SubLong: No exception at 0 - long.MinValue (value = 0)
SubLong: No exception at 0 - -int.MaxValue (value = 2147483647)
SubLong: No exception at 0 - -uint.MaxValue (value = 4294967295)
SubLong: No exception at 0 - -long.MaxValue (value = 4294967295)
SubLong: No exception at 0 - -ulong.MaxValue (value = 4294967295)
SubLong: No exception at 0 - -int.MinValue (value = 2147483648)
";
}
else
{
expectedOutput = @"
SubInt: No exception at 0 - -1 (value = 1)
SubInt: No exception at 0 - int.MinValue (value = 2147483648)
SubInt: No exception at 0 - -int.MaxValue (value = 2147483647)
SubLong: No exception at 0 - -1 (value = 1)
SubLong: No exception at 0 - int.MinValue (value = 2147483648)
SubLong: No exception at 0 - long.MinValue (value = 9223372036854775808)
SubLong: No exception at 0 - -int.MaxValue (value = 2147483647)
SubLong: No exception at 0 - -uint.MaxValue (value = 4294967295)
SubLong: No exception at 0 - -long.MaxValue (value = 9223372036854775807)
SubLong: No exception at 0 - -ulong.MaxValue (value = 9223372036854775807)
SubLong: No exception at 0 - -int.MinValue (value = 18446744071562067968)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Negative numbers, size = 4
[Fact]
public void UncheckedNumericSubtractionOverflow4()
{
var text = MakeNumericOverflowTest(NegativeNumericSubtractionCasesTemplate, "S02", "Sub", "-", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
SubInt: No exception at 0 - -1 (value = 4)
SubInt: No exception at 0 - int.MinValue (value = 0)
SubInt: No exception at 0 - -int.MaxValue (value = 4294967292)
SubLong: No exception at 0 - -1 (value = 4)
SubLong: No exception at 0 - int.MinValue (value = 0)
SubLong: No exception at 0 - long.MinValue (value = 0)
SubLong: No exception at 0 - -int.MaxValue (value = 4294967292)
SubLong: No exception at 0 - -uint.MaxValue (value = 4294967292)
SubLong: No exception at 0 - -long.MaxValue (value = 4294967292)
SubLong: No exception at 0 - -ulong.MaxValue (value = 4294967292)
SubLong: No exception at 0 - -int.MinValue (value = 0)";
}
else
{
expectedOutput = @"
SubInt: No exception at 0 - -1 (value = 4)
SubInt: No exception at 0 - int.MinValue (value = 8589934592)
SubInt: No exception at 0 - -int.MaxValue (value = 8589934588)
SubLong: No exception at 0 - -1 (value = 4)
SubLong: No exception at 0 - int.MinValue (value = 8589934592)
SubLong: No exception at 0 - long.MinValue (value = 0)
SubLong: No exception at 0 - -int.MaxValue (value = 8589934588)
SubLong: No exception at 0 - -uint.MaxValue (value = 17179869180)
SubLong: No exception at 0 - -long.MaxValue (value = 18446744073709551612)
SubLong: No exception at 0 - -ulong.MaxValue (value = 18446744073709551612)
SubLong: No exception at 0 - -int.MinValue (value = 18446744065119617024)";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
#endregion Unchecked pointer arithmetic overflow tests
#region Pointer comparison tests
[Fact]
public void PointerComparisonSameType()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S* p = (S*)0;
S* q = (S*)1;
unchecked
{
Write(p == q);
Write(p != q);
Write(p <= q);
Write(p >= q);
Write(p < q);
Write(p > q);
}
checked
{
Write(p == q);
Write(p != q);
Write(p <= q);
Write(p >= q);
Write(p < q);
Write(p > q);
}
}
static void Write(bool b)
{
Console.Write(b ? 1 : 0);
}
}
";
// NOTE: all comparisons unsigned.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "011010011010", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 133 (0x85)
.maxstack 2
.locals init (S* V_0, //p
S* V_1) //q
IL_0000: ldc.i4.0
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldc.i4.1
IL_0004: conv.i
IL_0005: stloc.1
IL_0006: ldloc.0
IL_0007: ldloc.1
IL_0008: ceq
IL_000a: call ""void S.Write(bool)""
IL_000f: ldloc.0
IL_0010: ldloc.1
IL_0011: ceq
IL_0013: ldc.i4.0
IL_0014: ceq
IL_0016: call ""void S.Write(bool)""
IL_001b: ldloc.0
IL_001c: ldloc.1
IL_001d: cgt.un
IL_001f: ldc.i4.0
IL_0020: ceq
IL_0022: call ""void S.Write(bool)""
IL_0027: ldloc.0
IL_0028: ldloc.1
IL_0029: clt.un
IL_002b: ldc.i4.0
IL_002c: ceq
IL_002e: call ""void S.Write(bool)""
IL_0033: ldloc.0
IL_0034: ldloc.1
IL_0035: clt.un
IL_0037: call ""void S.Write(bool)""
IL_003c: ldloc.0
IL_003d: ldloc.1
IL_003e: cgt.un
IL_0040: call ""void S.Write(bool)""
IL_0045: ldloc.0
IL_0046: ldloc.1
IL_0047: ceq
IL_0049: call ""void S.Write(bool)""
IL_004e: ldloc.0
IL_004f: ldloc.1
IL_0050: ceq
IL_0052: ldc.i4.0
IL_0053: ceq
IL_0055: call ""void S.Write(bool)""
IL_005a: ldloc.0
IL_005b: ldloc.1
IL_005c: cgt.un
IL_005e: ldc.i4.0
IL_005f: ceq
IL_0061: call ""void S.Write(bool)""
IL_0066: ldloc.0
IL_0067: ldloc.1
IL_0068: clt.un
IL_006a: ldc.i4.0
IL_006b: ceq
IL_006d: call ""void S.Write(bool)""
IL_0072: ldloc.0
IL_0073: ldloc.1
IL_0074: clt.un
IL_0076: call ""void S.Write(bool)""
IL_007b: ldloc.0
IL_007c: ldloc.1
IL_007d: cgt.un
IL_007f: call ""void S.Write(bool)""
IL_0084: ret
}
");
}
[Fact, WorkItem(49639, "https://github.com/dotnet/roslyn/issues/49639")]
public void CompareToNullWithNestedUnconstrainedTypeParameter()
{
var verifier = CompileAndVerify(@"
using System;
unsafe
{
test<int>(null);
S<int> s = default;
test<int>(&s);
static void test<T>(S<T>* s)
{
Console.WriteLine(s == null);
Console.WriteLine(s is null);
}
}
struct S<T> {}
", options: TestOptions.UnsafeReleaseExe, expectedOutput: @"
True
True
False
False", verify: Verification.Skipped);
verifier.VerifyIL("Program.<<Main>$>g__test|0_0<T>(S<T>*)", @"
{
// Code size 21 (0x15)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: conv.u
IL_0003: ceq
IL_0005: call ""void System.Console.WriteLine(bool)""
IL_000a: ldarg.0
IL_000b: ldc.i4.0
IL_000c: conv.u
IL_000d: ceq
IL_000f: call ""void System.Console.WriteLine(bool)""
IL_0014: ret
}
");
}
[Fact, WorkItem(49639, "https://github.com/dotnet/roslyn/issues/49639")]
public void CompareToNullWithPointerToUnmanagedTypeParameter()
{
var verifier = CompileAndVerify(@"
using System;
unsafe
{
test<int>(null);
int i = 0;
test<int>(&i);
static void test<T>(T* t) where T : unmanaged
{
Console.WriteLine(t == null);
Console.WriteLine(t is null);
}
}
", options: TestOptions.UnsafeReleaseExe, expectedOutput: @"
True
True
False
False", verify: Verification.Skipped);
verifier.VerifyIL("Program.<<Main>$>g__test|0_0<T>(T*)", @"
{
// Code size 21 (0x15)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: conv.u
IL_0003: ceq
IL_0005: call ""void System.Console.WriteLine(bool)""
IL_000a: ldarg.0
IL_000b: ldc.i4.0
IL_000c: conv.u
IL_000d: ceq
IL_000f: call ""void System.Console.WriteLine(bool)""
IL_0014: ret
}
");
}
[Theory]
[InlineData("int*")]
[InlineData("delegate*<void>")]
[InlineData("T*")]
[InlineData("delegate*<T>")]
public void CompareToNullInPatternOutsideUnsafe(string pointerType)
{
var comp = CreateCompilation($@"
var c = default(S<int>);
_ = c.Field is null;
unsafe struct S<T> where T : unmanaged
{{
#pragma warning disable CS0649 // Field is unassigned
public {pointerType} Field;
}}
", options: TestOptions.UnsafeReleaseExe);
comp.VerifyDiagnostics(
// (3,5): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// _ = c.Field is null;
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "c.Field").WithLocation(3, 5)
);
}
#endregion Pointer comparison tests
#region stackalloc tests
[Fact]
public void SimpleStackAlloc()
{
var text = @"
unsafe class C
{
void M()
{
int count = 1;
checked
{
int* p = stackalloc int[2];
char* q = stackalloc char[count];
Use(p);
Use(q);
}
unchecked
{
int* p = stackalloc int[2];
char* q = stackalloc char[count];
Use(p);
Use(q);
}
}
static void Use(int * ptr)
{
}
static void Use(char * ptr)
{
}
}
";
// NOTE: conversion is always unchecked, multiplication is always checked.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", @"
{
// Code size 47 (0x2f)
.maxstack 2
.locals init (int V_0, //count
int* V_1, //p
int* V_2) //p
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.8
IL_0003: conv.u
IL_0004: localloc
IL_0006: stloc.1
IL_0007: ldloc.0
IL_0008: conv.u
IL_0009: ldc.i4.2
IL_000a: mul.ovf.un
IL_000b: localloc
IL_000d: ldloc.1
IL_000e: call ""void C.Use(int*)""
IL_0013: call ""void C.Use(char*)""
IL_0018: ldc.i4.8
IL_0019: conv.u
IL_001a: localloc
IL_001c: stloc.2
IL_001d: ldloc.0
IL_001e: conv.u
IL_001f: ldc.i4.2
IL_0020: mul.ovf.un
IL_0021: localloc
IL_0023: ldloc.2
IL_0024: call ""void C.Use(int*)""
IL_0029: call ""void C.Use(char*)""
IL_002e: ret
}
");
}
[Fact]
public void StackAllocConversion()
{
var text = @"
unsafe class C
{
void M()
{
void* p = stackalloc int[2];
C q = stackalloc int[2];
}
public static implicit operator C(int* p)
{
return null;
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", @"
{
// Code size 16 (0x10)
.maxstack 1
.locals init (void* V_0) //p
IL_0000: ldc.i4.8
IL_0001: conv.u
IL_0002: localloc
IL_0004: stloc.0
IL_0005: ldc.i4.8
IL_0006: conv.u
IL_0007: localloc
IL_0009: call ""C C.op_Implicit(int*)""
IL_000e: pop
IL_000f: ret
}
");
}
[Fact]
public void StackAllocConversionZero()
{
var text = @"
unsafe class C
{
void M()
{
void* p = stackalloc int[0];
C q = stackalloc int[0];
}
public static implicit operator C(int* p)
{
return null;
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", @"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (void* V_0) //p
IL_0000: ldc.i4.0
IL_0001: conv.u
IL_0002: stloc.0
IL_0003: ldc.i4.0
IL_0004: conv.u
IL_0005: call ""C C.op_Implicit(int*)""
IL_000a: pop
IL_000b: ret
}
");
}
[Fact]
public void StackAllocSpecExample() //Section 18.8
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
Console.WriteLine(IntToString(123));
Console.WriteLine(IntToString(-456));
}
static string IntToString(int value) {
int n = value >= 0? value: -value;
unsafe {
char* buffer = stackalloc char[16];
char* p = buffer + 16;
do {
*--p = (char)(n % 10 + '0');
n /= 10;
} while (n != 0);
if (value < 0) *--p = '-';
return new string(p, 0, (int)(buffer + 16 - p));
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"123
-456
");
}
// See MethodToClassRewriter.VisitAssignmentOperator for an explanation.
[Fact]
public void StackAllocIntoHoistedLocal1()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
var p = stackalloc int[2];
var q = stackalloc int[2];
Action a = () =>
{
var r = stackalloc int[2];
var s = stackalloc int[2];
Action b = () =>
{
p = null; //capture p
r = null; //capture r
};
Use(s);
};
Use(q);
}
static void Use(int * ptr)
{
}
}
";
var verifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails);
// Note that the stackalloc for p is written into a temp *before* the receiver (i.e. "this")
// for C.<>c__DisplayClass0.p is pushed onto the stack.
verifier.VerifyIL("C.Main", @"
{
// Code size 28 (0x1c)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
int* V_1)
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: ldc.i4.8
IL_0007: conv.u
IL_0008: localloc
IL_000a: stloc.1
IL_000b: ldloc.0
IL_000c: ldloc.1
IL_000d: stfld ""int* C.<>c__DisplayClass0_0.p""
IL_0012: ldc.i4.8
IL_0013: conv.u
IL_0014: localloc
IL_0016: call ""void C.Use(int*)""
IL_001b: ret
}
");
// Check that the same thing works inside a lambda.
verifier.VerifyIL("C.<>c__DisplayClass0_0.<Main>b__0", @"
{
// Code size 35 (0x23)
.maxstack 2
.locals init (C.<>c__DisplayClass0_1 V_0, //CS$<>8__locals0
int* V_1)
IL_0000: newobj ""C.<>c__DisplayClass0_1..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldarg.0
IL_0008: stfld ""C.<>c__DisplayClass0_0 C.<>c__DisplayClass0_1.CS$<>8__locals1""
IL_000d: ldc.i4.8
IL_000e: conv.u
IL_000f: localloc
IL_0011: stloc.1
IL_0012: ldloc.0
IL_0013: ldloc.1
IL_0014: stfld ""int* C.<>c__DisplayClass0_1.r""
IL_0019: ldc.i4.8
IL_001a: conv.u
IL_001b: localloc
IL_001d: call ""void C.Use(int*)""
IL_0022: ret
}
");
}
// See MethodToClassRewriter.VisitAssignmentOperator for an explanation.
[Fact]
public void StackAllocIntoHoistedLocal2()
{
// From native bug #59454 (in DevDiv collection)
var text = @"
unsafe class T
{
delegate int D();
static void Main()
{
int* v = stackalloc int[1];
D d = delegate { return *v; };
System.Console.WriteLine(d());
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "0", verify: Verification.Fails).VerifyIL("T.Main", @"
{
// Code size 41 (0x29)
.maxstack 2
.locals init (T.<>c__DisplayClass1_0 V_0, //CS$<>8__locals0
int* V_1)
IL_0000: newobj ""T.<>c__DisplayClass1_0..ctor()""
IL_0005: stloc.0
IL_0006: ldc.i4.4
IL_0007: conv.u
IL_0008: localloc
IL_000a: stloc.1
IL_000b: ldloc.0
IL_000c: ldloc.1
IL_000d: stfld ""int* T.<>c__DisplayClass1_0.v""
IL_0012: ldloc.0
IL_0013: ldftn ""int T.<>c__DisplayClass1_0.<Main>b__0()""
IL_0019: newobj ""T.D..ctor(object, System.IntPtr)""
IL_001e: callvirt ""int T.D.Invoke()""
IL_0023: call ""void System.Console.WriteLine(int)""
IL_0028: ret
}
");
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "0", verify: Verification.Fails).VerifyIL("T.Main", @"
{
// Code size 41 (0x29)
.maxstack 2
.locals init (T.<>c__DisplayClass1_0 V_0, //CS$<>8__locals0
int* V_1)
IL_0000: newobj ""T.<>c__DisplayClass1_0..ctor()""
IL_0005: stloc.0
IL_0006: ldc.i4.4
IL_0007: conv.u
IL_0008: localloc
IL_000a: stloc.1
IL_000b: ldloc.0
IL_000c: ldloc.1
IL_000d: stfld ""int* T.<>c__DisplayClass1_0.v""
IL_0012: ldloc.0
IL_0013: ldftn ""int T.<>c__DisplayClass1_0.<Main>b__0()""
IL_0019: newobj ""T.D..ctor(object, System.IntPtr)""
IL_001e: callvirt ""int T.D.Invoke()""
IL_0023: call ""void System.Console.WriteLine(int)""
IL_0028: ret
}
");
}
[Fact]
public void CSLegacyStackallocUse32bitChecked()
{
// This is from C# Legacy test where it uses Perl script to call ildasm and check 'mul.ovf' emitted
// $Roslyn\Main\LegacyTest\CSharp\Source\csharp\Source\Conformance\unsafecode\stackalloc\regr001.cs
var text = @"// <Title>Should checked affect stackalloc?</Title>
// <Description>
// The lower level localloc MSIL instruction takes an unsigned native int as input; however the higher level
// stackalloc uses only 32-bits. The example shows the operation overflowing the 32-bit multiply which leads to
// a curious edge condition.
// If compile with /checked we insert a mul.ovf instruction, and this causes a system overflow exception at runtime.
// </Description>
// <RelatedBugs>VSW:489857</RelatedBugs>
using System;
public class C
{
private static unsafe int Main()
{
Int64* intArray = stackalloc Int64[0x7fffffff];
return (int)intArray[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 13 (0xd)
.maxstack 2
IL_0000: ldc.i4 0x7fffffff
IL_0005: conv.u
IL_0006: ldc.i4.8
IL_0007: mul.ovf.un
IL_0008: localloc
IL_000a: ldind.i8
IL_000b: conv.i4
IL_000c: ret
}
");
}
#endregion stackalloc tests
#region Functional tests
[Fact]
public void BubbleSort()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
BubbleSort();
BubbleSort(1);
BubbleSort(2, 1);
BubbleSort(3, 1, 2);
BubbleSort(3, 1, 4, 2);
}
static void BubbleSort(params int[] array)
{
if (array == null)
{
return;
}
fixed (int* begin = array)
{
BubbleSort(begin, end: begin + array.Length);
}
Console.WriteLine(string.Join("", "", array));
}
private static void BubbleSort(int* begin, int* end)
{
for (int* firstUnsorted = begin; firstUnsorted < end; firstUnsorted++)
{
for (int* current = firstUnsorted; current + 1 < end; current++)
{
if (current[0] > current[1])
{
SwapWithNext(current);
}
}
}
}
static void SwapWithNext(int* p)
{
int temp = *p;
p[0] = p[1];
p[1] = temp;
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"
1
1, 2
1, 2, 3
1, 2, 3, 4");
}
[Fact]
public void BigStructs()
{
var text = @"
unsafe class C
{
static void Main()
{
void* v;
CheckOverflow(""(S15*)0 + sizeof(S15)"", () => v = checked((S15*)0 + sizeof(S15)));
CheckOverflow(""(S15*)0 + sizeof(S16)"", () => v = checked((S15*)0 + sizeof(S16)));
CheckOverflow(""(S16*)0 + sizeof(S15)"", () => v = checked((S16*)0 + sizeof(S15)));
}
static void CheckOverflow(string description, System.Action operation)
{
try
{
operation();
System.Console.WriteLine(""No overflow from {0}"", description);
}
catch (System.OverflowException)
{
System.Console.WriteLine(""Overflow from {0}"", description);
}
}
}
" + SizedStructs;
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
No overflow from (S15*)0 + sizeof(S15)
Overflow from (S15*)0 + sizeof(S16)
Overflow from (S16*)0 + sizeof(S15)";
}
else
{
expectedOutput = @"
No overflow from (S15*)0 + sizeof(S15)
No overflow from (S15*)0 + sizeof(S16)
No overflow from (S16*)0 + sizeof(S15)";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
[Fact]
public void LambdaConversion()
{
var text = @"
using System;
class Program
{
static void Main()
{
Goo(x => { });
}
static void Goo(F1 f) { Console.WriteLine(1); }
static void Goo(F2 f) { Console.WriteLine(2); }
}
unsafe delegate void F1(int* x);
delegate void F2(int x);
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"2", verify: Verification.Passes);
}
[Fact]
public void LocalVariableReuse()
{
var text = @"
unsafe class C
{
int this[string s] { get { return 0; } set { } }
void Test()
{
{
this[""not pinned"".ToString()] += 2; //creates an unpinned string local (for the argument)
}
fixed (char* p = ""pinned"") //creates a pinned string local
{
}
{
this[""not pinned"".ToString()] += 2; //reuses the unpinned string local
}
fixed (char* p = ""pinned"") //reuses the pinned string local
{
}
}
}
";
// NOTE: one pinned string temp and one unpinned string temp.
// That is, pinned temps are reused in by other pinned temps
// but not by unpinned temps and vice versa.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.Test", @"
{
// Code size 99 (0x63)
.maxstack 4
.locals init (string V_0,
char* V_1, //p
pinned string V_2,
char* V_3) //p
IL_0000: ldstr ""not pinned""
IL_0005: callvirt ""string object.ToString()""
IL_000a: stloc.0
IL_000b: ldarg.0
IL_000c: ldloc.0
IL_000d: ldarg.0
IL_000e: ldloc.0
IL_000f: call ""int C.this[string].get""
IL_0014: ldc.i4.2
IL_0015: add
IL_0016: call ""void C.this[string].set""
IL_001b: ldstr ""pinned""
IL_0020: stloc.2
IL_0021: ldloc.2
IL_0022: conv.u
IL_0023: stloc.1
IL_0024: ldloc.1
IL_0025: brfalse.s IL_002f
IL_0027: ldloc.1
IL_0028: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_002d: add
IL_002e: stloc.1
IL_002f: ldnull
IL_0030: stloc.2
IL_0031: ldstr ""not pinned""
IL_0036: callvirt ""string object.ToString()""
IL_003b: stloc.0
IL_003c: ldarg.0
IL_003d: ldloc.0
IL_003e: ldarg.0
IL_003f: ldloc.0
IL_0040: call ""int C.this[string].get""
IL_0045: ldc.i4.2
IL_0046: add
IL_0047: call ""void C.this[string].set""
IL_004c: ldstr ""pinned""
IL_0051: stloc.2
IL_0052: ldloc.2
IL_0053: conv.u
IL_0054: stloc.3
IL_0055: ldloc.3
IL_0056: brfalse.s IL_0060
IL_0058: ldloc.3
IL_0059: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_005e: add
IL_005f: stloc.3
IL_0060: ldnull
IL_0061: stloc.2
IL_0062: ret
}");
}
[WorkItem(544229, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544229")]
[Fact]
public void UnsafeTypeAsAttributeArgument()
{
var template = @"
using System;
namespace System
{{
class Int32 {{ }}
}}
[A(Type = typeof({0}))]
class A : Attribute
{{
public Type Type;
static void Main()
{{
var a = (A)typeof(A).GetCustomAttributes(false)[0];
Console.WriteLine(a.Type == typeof({0}));
}}
}}
";
CompileAndVerify(string.Format(template, "int"), options: TestOptions.UnsafeReleaseExe, expectedOutput: @"True", verify: Verification.Passes);
CompileAndVerify(string.Format(template, "int*"), options: TestOptions.UnsafeReleaseExe, expectedOutput: @"True", verify: Verification.Passes);
CompileAndVerify(string.Format(template, "int**"), options: TestOptions.UnsafeReleaseExe, expectedOutput: @"True", verify: Verification.Passes);
CompileAndVerify(string.Format(template, "int[]"), options: TestOptions.UnsafeReleaseExe, expectedOutput: @"True", verify: Verification.Passes);
CompileAndVerify(string.Format(template, "int[][]"), options: TestOptions.UnsafeReleaseExe, expectedOutput: @"True", verify: Verification.Passes);
CompileAndVerify(string.Format(template, "int*[]"), options: TestOptions.UnsafeReleaseExe, expectedOutput: @"True", verify: Verification.Passes);
}
#endregion Functional tests
#region Regression tests
[WorkItem(545026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545026")]
[Fact]
public void MixedSafeAndUnsafeFields()
{
var text =
@"struct Perf_Contexts
{
int data;
private int SuppressUnused(int x) { data = x; return data; }
}
public sealed class ChannelServices
{
static unsafe Perf_Contexts* GetPrivateContextsPerfCounters() { return null; }
private static int I1 = 12;
unsafe private static Perf_Contexts* perf_Contexts = GetPrivateContextsPerfCounters();
private static int I2 = 13;
private static int SuppressUnused(int x) { return I1 + I2; }
}
public class Test
{
public static void Main()
{
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails).VerifyDiagnostics();
}
[WorkItem(545026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545026")]
[Fact]
public void SafeFieldBeforeUnsafeField()
{
var text = @"
class C
{
int x = 1;
unsafe int* p = (int*)2;
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyDiagnostics(
// (4,9): warning CS0414: The field 'C.x' is assigned but its value is never used
// int x = 1;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x").WithArguments("C.x"));
}
[WorkItem(545026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545026")]
[Fact]
public void SafeFieldAfterUnsafeField()
{
var text = @"
class C
{
unsafe int* p = (int*)2;
int x = 1;
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyDiagnostics(
// (5,9): warning CS0414: The field 'C.x' is assigned but its value is never used
// int x = 1;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x").WithArguments("C.x"));
}
[WorkItem(545026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545026"), WorkItem(598170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598170")]
[Fact]
public void FixedPassByRef()
{
var text = @"
class Test
{
unsafe static int printAddress(out int* pI)
{
pI = null;
System.Console.WriteLine((ulong)pI);
return 1;
}
unsafe static int printAddress1(ref int* pI)
{
pI = null;
System.Console.WriteLine((ulong)pI);
return 1;
}
static int Main()
{
int retval = 0;
S s = new S();
unsafe
{
retval = Test.printAddress(out s.i);
retval = Test.printAddress1(ref s.i);
}
if (retval == 0)
System.Console.WriteLine(""Failed."");
return retval;
}
}
unsafe struct S
{
public fixed int i[1];
}
";
var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (24,44): error CS1510: A ref or out argument must be an assignable variable
// retval = Test.printAddress(out s.i);
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "s.i"),
// (25,45): error CS1510: A ref or out argument must be an assignable variable
// retval = Test.printAddress1(ref s.i);
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "s.i"));
}
[Fact, WorkItem(545293, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545293"), WorkItem(881188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/881188")]
public void EmptyAndFixedBufferStructIsInitialized()
{
var text = @"
public struct EmptyStruct { }
unsafe public struct FixedStruct { fixed char c[10]; }
public struct OuterStruct
{
EmptyStruct ES;
FixedStruct FS;
override public string ToString() { return (ES.ToString() + FS.ToString()); }
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes).VerifyDiagnostics(
// (8,17): warning CS0649: Field 'OuterStruct.FS' is never assigned to, and will always have its default value
// FixedStruct FS;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "FS").WithArguments("OuterStruct.FS", "").WithLocation(8, 17),
// (7,17): warning CS0649: Field 'OuterStruct.ES' is never assigned to, and will always have its default value
// EmptyStruct ES;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "ES").WithArguments("OuterStruct.ES", "").WithLocation(7, 17)
);
}
[Fact, WorkItem(545296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545296"), WorkItem(545999, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545999")]
public void FixedBufferAndStatementWithFixedArrayElementAsInitializer()
{
var text = @"
unsafe public struct FixedStruct
{
fixed int i[1];
fixed char c[10];
override public string ToString() {
fixed (char* pc = this.c) { return pc[0].ToString(); }
}
}
";
var comp = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyDiagnostics();
comp.VerifyIL("FixedStruct.ToString", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (pinned char& V_0)
IL_0000: ldarg.0
IL_0001: ldflda ""char* FixedStruct.c""
IL_0006: ldflda ""char FixedStruct.<c>e__FixedBuffer.FixedElementField""
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: conv.u
IL_000e: call ""string char.ToString()""
IL_0013: ret
}
");
}
[Fact]
public void FixedBufferAndStatementWithFixedArrayElementAsInitializerExe()
{
var text = @"
class Program
{
unsafe static void Main(string[] args)
{
FixedStruct s = new FixedStruct();
s.c[0] = 'A';
s.c[1] = 'B';
s.c[2] = 'C';
FixedStruct[] arr = { s };
System.Console.Write(arr[0].ToString());
}
}
unsafe public struct FixedStruct
{
public fixed char c[10];
override public string ToString()
{
fixed (char* pc = this.c)
{
System.Console.Write(pc[0]);
System.Console.Write(pc[1].ToString());
return pc[2].ToString();
}
}
}";
var comp = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "ABC", verify: Verification.Fails).VerifyDiagnostics();
comp.VerifyIL("FixedStruct.ToString", @"
{
// Code size 45 (0x2d)
.maxstack 3
.locals init (pinned char& V_0)
IL_0000: ldarg.0
IL_0001: ldflda ""char* FixedStruct.c""
IL_0006: ldflda ""char FixedStruct.<c>e__FixedBuffer.FixedElementField""
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: conv.u
IL_000e: dup
IL_000f: ldind.u2
IL_0010: call ""void System.Console.Write(char)""
IL_0015: dup
IL_0016: ldc.i4.2
IL_0017: add
IL_0018: call ""string char.ToString()""
IL_001d: call ""void System.Console.Write(string)""
IL_0022: ldc.i4.2
IL_0023: conv.i
IL_0024: ldc.i4.2
IL_0025: mul
IL_0026: add
IL_0027: call ""string char.ToString()""
IL_002c: ret
}
");
}
[Fact, WorkItem(545299, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545299")]
public void FixedStatementInlambda()
{
var text = @"
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
unsafe class C<T> where T : struct
{
public void Goo()
{
Func<T, char> d = delegate
{
fixed (char* p = ""blah"")
{
for (char* pp = p; pp != null; pp++)
return *pp;
}
return 'c';
};
Console.WriteLine(d(default(T)));
}
}
class A
{
static void Main()
{
new C<int>().Goo();
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "b", verify: Verification.Fails);
}
[Fact, WorkItem(546865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546865")]
public void DontStackScheduleLocalPerformingPointerConversion()
{
var text = @"
using System;
unsafe struct S1
{
public char* charPointer;
}
unsafe class Test
{
static void Main()
{
S1 s1 = new S1();
fixed (char* p = ""hello"")
{
s1.charPointer = p;
ulong UserData = (ulong)&s1;
Test1(UserData);
}
}
static void Test1(ulong number)
{
S1* structPointer = (S1*)number;
Console.WriteLine(new string(structPointer->charPointer));
}
static ulong Test2()
{
S1* structPointer = (S1*)null; // null to pointer
int* intPointer = (int*)structPointer; // pointer to pointer
void* voidPointer = (void*)intPointer; // pointer to void
ulong number = (ulong)voidPointer; // pointer to integer
return number;
}
}
";
var verifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "hello", verify: Verification.Fails);
// Note that the pointer local is not scheduled on the stack.
verifier.VerifyIL("Test.Test1", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (S1* V_0) //structPointer
IL_0000: ldarg.0
IL_0001: conv.u
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldfld ""char* S1.charPointer""
IL_0009: newobj ""string..ctor(char*)""
IL_000e: call ""void System.Console.WriteLine(string)""
IL_0013: ret
}");
// All locals retained.
verifier.VerifyIL("Test.Test2", @"
{
// Code size 10 (0xa)
.maxstack 1
.locals init (S1* V_0, //structPointer
int* V_1, //intPointer
void* V_2) //voidPointer
IL_0000: ldc.i4.0
IL_0001: conv.u
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: stloc.1
IL_0005: ldloc.1
IL_0006: stloc.2
IL_0007: ldloc.2
IL_0008: conv.u8
IL_0009: ret
}");
}
[Fact, WorkItem(546807, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546807")]
public void PointerMemberAccessReadonlyField()
{
var text = @"
using System;
unsafe class C
{
public S1* S1;
}
unsafe struct S1
{
public readonly int* X;
public int* Y;
}
unsafe class Test
{
static void Main()
{
S1 s1 = new S1();
C c = new C();
c.S1 = &s1;
Console.WriteLine(null == c.S1->X);
Console.WriteLine(null == c.S1->Y);
}
}
";
var verifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"
True
True");
// NOTE: ldobj before ldfld S1.X, but not before ldfld S1.Y.
verifier.VerifyIL("Test.Main", @"
{
// Code size 64 (0x40)
.maxstack 2
.locals init (S1 V_0, //s1
C V_1) //c
IL_0000: ldloca.s V_0
IL_0002: initobj ""S1""
IL_0008: newobj ""C..ctor()""
IL_000d: stloc.1
IL_000e: ldloc.1
IL_000f: ldloca.s V_0
IL_0011: conv.u
IL_0012: stfld ""S1* C.S1""
IL_0017: ldc.i4.0
IL_0018: conv.u
IL_0019: ldloc.1
IL_001a: ldfld ""S1* C.S1""
IL_001f: ldfld ""int* S1.X""
IL_0024: ceq
IL_0026: call ""void System.Console.WriteLine(bool)""
IL_002b: ldc.i4.0
IL_002c: conv.u
IL_002d: ldloc.1
IL_002e: ldfld ""S1* C.S1""
IL_0033: ldfld ""int* S1.Y""
IL_0038: ceq
IL_003a: call ""void System.Console.WriteLine(bool)""
IL_003f: ret
}
");
}
[Fact, WorkItem(546807, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546807")]
public void PointerMemberAccessCall()
{
var text = @"
using System;
unsafe class C
{
public S1* S1;
}
unsafe struct S1
{
public int X;
public void Instance()
{
Console.WriteLine(this.X);
}
}
static class Extensions
{
public static void Extension(this S1 s1)
{
Console.WriteLine(s1.X);
}
}
unsafe class Test
{
static void Main()
{
S1 s1 = new S1 { X = 2 };
C c = new C();
c.S1 = &s1;
c.S1->Instance();
c.S1->Extension();
}
}
";
var verifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"
2
2");
// NOTE: ldobj before extension call, but not before instance call.
verifier.VerifyIL("Test.Main", @"
{
// Code size 59 (0x3b)
.maxstack 3
.locals init (S1 V_0, //s1
S1 V_1)
IL_0000: ldloca.s V_1
IL_0002: initobj ""S1""
IL_0008: ldloca.s V_1
IL_000a: ldc.i4.2
IL_000b: stfld ""int S1.X""
IL_0010: ldloc.1
IL_0011: stloc.0
IL_0012: newobj ""C..ctor()""
IL_0017: dup
IL_0018: ldloca.s V_0
IL_001a: conv.u
IL_001b: stfld ""S1* C.S1""
IL_0020: dup
IL_0021: ldfld ""S1* C.S1""
IL_0026: call ""void S1.Instance()""
IL_002b: ldfld ""S1* C.S1""
IL_0030: ldobj ""S1""
IL_0035: call ""void Extensions.Extension(S1)""
IL_003a: ret
}");
}
[Fact, WorkItem(531327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531327")]
public void PointerParameter()
{
var text = @"
using System;
unsafe struct S1
{
static void M(N.S2* ps2){}
}
namespace N
{
public struct S2
{
public int F;
}
}
";
var verifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll.WithConcurrentBuild(false), verify: Verification.Passes);
}
[Fact, WorkItem(531327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531327")]
public void PointerReturn()
{
var text = @"
using System;
namespace N
{
public struct S2
{
public int F;
}
}
unsafe struct S1
{
static N.S2* M(int ps2){return null;}
}
";
var verifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll.WithConcurrentBuild(false), verify: Verification.Fails);
}
[Fact, WorkItem(748530, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/748530")]
public void Repro748530()
{
var text = @"
unsafe class A
{
public unsafe struct ListNode
{
internal ListNode(int data, ListNode* pNext)
{
}
}
}
";
var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics();
}
[WorkItem(682584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682584")]
[Fact]
public void UnsafeMathConv()
{
var text = @"
using System;
unsafe class C
{
static void Main(string[] args)
{
byte* data = (byte*)0x76543210;
uint offset = 0x80000000;
byte* wrong = data + offset;
Console.WriteLine(""{0:X}"", (ulong)wrong);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "F6543210", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 36 (0x24)
.maxstack 2
.locals init (byte* V_0, //data
uint V_1, //offset
byte* V_2) //wrong
IL_0000: ldc.i4 0x76543210
IL_0005: conv.i
IL_0006: stloc.0
IL_0007: ldc.i4 0x80000000
IL_000c: stloc.1
IL_000d: ldloc.0
IL_000e: ldloc.1
IL_000f: conv.u
IL_0010: add
IL_0011: stloc.2
IL_0012: ldstr ""{0:X}""
IL_0017: ldloc.2
IL_0018: conv.u8
IL_0019: box ""ulong""
IL_001e: call ""void System.Console.WriteLine(string, object)""
IL_0023: ret
}
");
}
[WorkItem(682584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682584")]
[Fact]
public void UnsafeMathConv001()
{
var text = @"
using System;
unsafe class C
{
static void Main(string[] args)
{
short* data = (short*)0x76543210;
uint offset = 0x40000000;
short* wrong = data + offset;
Console.WriteLine(""{0:X}"", (ulong)wrong);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "F6543210", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 40 (0x28)
.maxstack 3
.locals init (short* V_0, //data
uint V_1, //offset
short* V_2) //wrong
IL_0000: ldc.i4 0x76543210
IL_0005: conv.i
IL_0006: stloc.0
IL_0007: ldc.i4 0x40000000
IL_000c: stloc.1
IL_000d: ldloc.0
IL_000e: ldloc.1
IL_000f: conv.u8
IL_0010: ldc.i4.2
IL_0011: conv.i8
IL_0012: mul
IL_0013: conv.i
IL_0014: add
IL_0015: stloc.2
IL_0016: ldstr ""{0:X}""
IL_001b: ldloc.2
IL_001c: conv.u8
IL_001d: box ""ulong""
IL_0022: call ""void System.Console.WriteLine(string, object)""
IL_0027: ret
}
");
}
[WorkItem(682584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682584")]
[Fact]
public void UnsafeMathConv002()
{
var text = @"
using System;
unsafe class C
{
static void Main(string[] args)
{
byte* data = (byte*)0x76543210;
byte* wrong = data + 0x80000000u;
Console.WriteLine(""{0:X}"", (ulong)wrong);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "F6543210", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 34 (0x22)
.maxstack 2
.locals init (byte* V_0, //data
byte* V_1) //wrong
IL_0000: ldc.i4 0x76543210
IL_0005: conv.i
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4 0x80000000
IL_000d: conv.u
IL_000e: add
IL_000f: stloc.1
IL_0010: ldstr ""{0:X}""
IL_0015: ldloc.1
IL_0016: conv.u8
IL_0017: box ""ulong""
IL_001c: call ""void System.Console.WriteLine(string, object)""
IL_0021: ret
}
");
}
[WorkItem(682584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682584")]
[Fact]
public void UnsafeMathConv002a()
{
var text = @"
using System;
unsafe class C
{
static void Main(string[] args)
{
byte* data = (byte*)0x76543210;
byte* wrong = data + 0x7FFFFFFFu;
Console.WriteLine(""{0:X}"", (ulong)wrong);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "F654320F", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (byte* V_0, //data
byte* V_1) //wrong
IL_0000: ldc.i4 0x76543210
IL_0005: conv.i
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4 0x7fffffff
IL_000d: add
IL_000e: stloc.1
IL_000f: ldstr ""{0:X}""
IL_0014: ldloc.1
IL_0015: conv.u8
IL_0016: box ""ulong""
IL_001b: call ""void System.Console.WriteLine(string, object)""
IL_0020: ret
}
");
}
[WorkItem(857598, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/857598")]
[Fact]
public void VoidToNullable()
{
var text = @"
unsafe class C
{
public int? x = (int?)(void*)0;
}
class c1
{
public static void Main()
{
var x = new C();
System.Console.WriteLine(x.x);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "0", verify: Verification.Passes);
compVerifier.VerifyIL("C..ctor", @"
{
// Code size 21 (0x15)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: conv.i
IL_0003: conv.i4
IL_0004: newobj ""int?..ctor(int)""
IL_0009: stfld ""int? C.x""
IL_000e: ldarg.0
IL_000f: call ""object..ctor()""
IL_0014: ret
}
");
}
[WorkItem(907771, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/907771")]
[Fact]
public void UnsafeBeforeReturn001()
{
var text = @"
using System;
public unsafe class C
{
private static readonly byte[] _emptyArray = new byte[0];
public static void Main()
{
System.Console.WriteLine(ToManagedByteArray(2));
}
public static byte[] ToManagedByteArray(uint byteCount)
{
if (byteCount == 0)
{
return _emptyArray; // degenerate case
}
else
{
byte[] bytes = new byte[byteCount];
fixed (byte* pBytes = bytes)
{
}
return bytes;
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "System.Byte[]", verify: Verification.Fails);
compVerifier.VerifyIL("C.ToManagedByteArray", @"
{
// Code size 42 (0x2a)
.maxstack 3
.locals init (byte* V_0, //pBytes
pinned byte[] V_1)
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0009
IL_0003: ldsfld ""byte[] C._emptyArray""
IL_0008: ret
IL_0009: ldarg.0
IL_000a: newarr ""byte""
IL_000f: dup
IL_0010: dup
IL_0011: stloc.1
IL_0012: brfalse.s IL_0019
IL_0014: ldloc.1
IL_0015: ldlen
IL_0016: conv.i4
IL_0017: brtrue.s IL_001e
IL_0019: ldc.i4.0
IL_001a: conv.u
IL_001b: stloc.0
IL_001c: br.s IL_0027
IL_001e: ldloc.1
IL_001f: ldc.i4.0
IL_0020: ldelema ""byte""
IL_0025: conv.u
IL_0026: stloc.0
IL_0027: ldnull
IL_0028: stloc.1
IL_0029: ret
}
");
}
[WorkItem(907771, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/907771")]
[Fact]
public void UnsafeBeforeReturn002()
{
var text = @"
using System;
public unsafe class C
{
private static readonly byte[] _emptyArray = new byte[0];
public static void Main()
{
System.Console.WriteLine(ToManagedByteArray(2));
}
public static byte[] ToManagedByteArray(uint byteCount)
{
if (byteCount == 0)
{
return _emptyArray; // degenerate case
}
else
{
byte[] bytes = new byte[byteCount];
fixed (byte* pBytes = bytes)
{
}
return bytes;
}
}
}
";
var v = CompileAndVerify(text, options: TestOptions.UnsafeDebugExe, expectedOutput: "System.Byte[]", verify: Verification.Fails);
v.VerifyIL("C.ToManagedByteArray", @"
{
// Code size 64 (0x40)
.maxstack 2
.locals init (bool V_0,
byte[] V_1,
byte[] V_2, //bytes
byte* V_3, //pBytes
pinned byte[] V_4)
-IL_0000: nop
-IL_0001: ldarg.0
IL_0002: ldc.i4.0
IL_0003: ceq
IL_0005: stloc.0
~IL_0006: ldloc.0
IL_0007: brfalse.s IL_0012
-IL_0009: nop
-IL_000a: ldsfld ""byte[] C._emptyArray""
IL_000f: stloc.1
IL_0010: br.s IL_003e
-IL_0012: nop
-IL_0013: ldarg.0
IL_0014: newarr ""byte""
IL_0019: stloc.2
-IL_001a: ldloc.2
IL_001b: dup
IL_001c: stloc.s V_4
IL_001e: brfalse.s IL_0026
IL_0020: ldloc.s V_4
IL_0022: ldlen
IL_0023: conv.i4
IL_0024: brtrue.s IL_002b
IL_0026: ldc.i4.0
IL_0027: conv.u
IL_0028: stloc.3
IL_0029: br.s IL_0035
IL_002b: ldloc.s V_4
IL_002d: ldc.i4.0
IL_002e: ldelema ""byte""
IL_0033: conv.u
IL_0034: stloc.3
-IL_0035: nop
-IL_0036: nop
~IL_0037: ldnull
IL_0038: stloc.s V_4
-IL_003a: ldloc.2
IL_003b: stloc.1
IL_003c: br.s IL_003e
-IL_003e: ldloc.1
IL_003f: ret
}
", sequencePoints: "C.ToManagedByteArray");
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void SystemIntPtrInSignature_BreakingChange()
{
// NOTE: the IL is intentionally not compliant with ECMA spec
// in particular Metadata spec II.23.2.16 (Short form signatures) says that
// [mscorlib]System.IntPtr is not supposed to be used in metadata
// and short-version 'native int' is supposed to be used instead.
var ilSource =
@"
.class public AddressHelper{
.method public hidebysig static valuetype [mscorlib]System.IntPtr AddressOf<T>(!!0& t){
ldarg 0
ldind.i
ret
}
}
";
var csharpSource =
@"
class Program
{
static void Main(string[] args)
{
var s = string.Empty;
var i = AddressHelper.AddressOf(ref s);
System.Console.WriteLine(i);
}
}
";
var cscomp = CreateCompilationWithILAndMscorlib40(csharpSource, ilSource);
var expected = new[] {
// (7,35): error CS0570: 'AddressHelper.AddressOf<T>(?)' is not supported by the language
// var i = AddressHelper.AddressOf(ref s);
Diagnostic(ErrorCode.ERR_BindToBogus, "AddressOf").WithArguments("AddressHelper.AddressOf<T>(?)").WithLocation(7, 35)
};
cscomp.VerifyDiagnostics(expected);
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void SystemIntPtrInSignature_BreakingChange_001()
{
var ilSource =
@"
.class public AddressHelper{
.method public hidebysig static native int AddressOf<T>(!!0& t){
ldc.i4.5
conv.u
ret
}
}
";
var csharpSource =
@"
class Program
{
static void Main(string[] args)
{
var s = string.Empty;
var i = AddressHelper.AddressOf(ref s);
System.Console.WriteLine(i);
}
}
";
var compilation = CreateCompilationWithILAndMscorlib40(csharpSource, ilSource, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
var result = CompileAndVerify(compilation, expectedOutput: "5");
}
[Fact, WorkItem(7550, "https://github.com/dotnet/roslyn/issues/7550")]
public void EnsureNullPointerIsPoppedIfUnused()
{
string source = @"
public class A
{
public unsafe byte* Ptr;
static void Main()
{
unsafe
{
var x = new A();
byte* ptr = (x == null) ? null : x.Ptr;
}
System.Console.WriteLine(""OK"");
}
}
";
CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, expectedOutput: "OK", verify: Verification.Passes);
}
[Fact, WorkItem(40768, "https://github.com/dotnet/roslyn/issues/40768")]
public void DoesNotEmitArrayDotEmptyForEmptyPointerArrayParams()
{
var source = @"
using System;
public static class Program
{
public static unsafe void Main()
{
Console.WriteLine(Test());
}
public static unsafe int Test(params int*[] types)
{
return types.Length;
}
}";
var comp = CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, expectedOutput: "0", verify: Verification.Fails);
comp.VerifyIL("Program.Main", @"
{
// Code size 17 (0x11)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: newarr ""int*""
IL_0006: call ""int Program.Test(params int*[])""
IL_000b: call ""void System.Console.WriteLine(int)""
IL_0010: ret
}");
}
[Fact]
public void DoesEmitArrayDotEmptyForEmptyPointerArrayArrayParams()
{
var source = @"
using System;
public static class Program
{
public static unsafe void Main()
{
Console.WriteLine(Test());
}
public static unsafe int Test(params int*[][] types)
{
return types.Length;
}
}";
var comp = CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, expectedOutput: "0");
comp.VerifyIL("Program.Main", @"
{
// Code size 16 (0x10)
.maxstack 1
IL_0000: call ""int*[][] System.Array.Empty<int*[]>()""
IL_0005: call ""int Program.Test(params int*[][])""
IL_000a: call ""void System.Console.WriteLine(int)""
IL_000f: ret
}");
}
#endregion
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Workspaces/CoreTest/Differencing/TestTreeComparer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Text;
namespace Microsoft.CodeAnalysis.Differencing.UnitTests
{
public class TestTreeComparer : TreeComparer<TestNode>
{
public static readonly TestTreeComparer Instance = new TestTreeComparer();
private TestTreeComparer()
{
}
protected internal override int LabelCount
{
get
{
return TestNode.MaxLabel + 1;
}
}
public override double GetDistance(TestNode left, TestNode right)
=> Math.Abs((double)left.Value - right.Value) / TestNode.MaxValue;
public override bool ValuesEqual(TestNode oldNode, TestNode newNode)
=> oldNode.Value == newNode.Value;
protected internal override IEnumerable<TestNode> GetChildren(TestNode node)
=> node.Children;
protected internal override IEnumerable<TestNode> GetDescendants(TestNode node)
{
yield return node;
foreach (var child in node.Children)
{
foreach (var descendant in GetDescendants(child))
{
yield return descendant;
}
}
}
protected internal override int GetLabel(TestNode node)
=> node.Label;
protected internal override TextSpan GetSpan(TestNode node)
=> new TextSpan(0, 10);
protected internal override int TiedToAncestor(int label)
=> 0;
protected internal override bool TreesEqual(TestNode left, TestNode right)
=> left.Root == right.Root;
protected internal override bool TryGetParent(TestNode node, out TestNode parent)
{
parent = node.Parent;
return parent != null;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Differencing.UnitTests
{
public class TestTreeComparer : TreeComparer<TestNode>
{
public static readonly TestTreeComparer Instance = new TestTreeComparer();
private TestTreeComparer()
{
}
protected internal override int LabelCount
{
get
{
return TestNode.MaxLabel + 1;
}
}
public override double GetDistance(TestNode left, TestNode right)
=> Math.Abs((double)left.Value - right.Value) / TestNode.MaxValue;
public override bool ValuesEqual(TestNode oldNode, TestNode newNode)
=> oldNode.Value == newNode.Value;
protected internal override IEnumerable<TestNode> GetChildren(TestNode node)
=> node.Children;
protected internal override IEnumerable<TestNode> GetDescendants(TestNode node)
{
yield return node;
foreach (var child in node.Children)
{
foreach (var descendant in GetDescendants(child))
{
yield return descendant;
}
}
}
protected internal override int GetLabel(TestNode node)
=> node.Label;
protected internal override TextSpan GetSpan(TestNode node)
=> new TextSpan(0, 10);
protected internal override int TiedToAncestor(int label)
=> 0;
protected internal override bool TreesEqual(TestNode left, TestNode right)
=> left.Root == right.Root;
protected internal override bool TryGetParent(TestNode node, out TestNode parent)
{
parent = node.Parent;
return parent != null;
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Features/Core/Portable/TodoComments/InProcTodoCommentsIncrementalAnalyzerProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.SolutionCrawler;
namespace Microsoft.CodeAnalysis.TodoComments
{
/// <remarks>Note: this is explicitly <b>not</b> exported. We don't want the workspace
/// to automatically load this. Instead, VS waits until it is ready
/// and then calls into the service to tell it to start analyzing the solution. At that point we'll get
/// created and added to the solution crawler.
/// </remarks>
internal sealed class InProcTodoCommentsIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider
{
private readonly ITodoCommentsListener _listener;
public InProcTodoCommentsIncrementalAnalyzerProvider(ITodoCommentsListener listener)
=> _listener = listener;
public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace)
=> new InProcTodoCommentsIncrementalAnalyzer(_listener);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.SolutionCrawler;
namespace Microsoft.CodeAnalysis.TodoComments
{
/// <remarks>Note: this is explicitly <b>not</b> exported. We don't want the workspace
/// to automatically load this. Instead, VS waits until it is ready
/// and then calls into the service to tell it to start analyzing the solution. At that point we'll get
/// created and added to the solution crawler.
/// </remarks>
internal sealed class InProcTodoCommentsIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider
{
private readonly ITodoCommentsListener _listener;
public InProcTodoCommentsIncrementalAnalyzerProvider(ITodoCommentsListener listener)
=> _listener = listener;
public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace)
=> new InProcTodoCommentsIncrementalAnalyzer(_listener);
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/EditorFeatures/Core/Implementation/EditAndContinue/EditAndContinueUIContext.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue
{
internal static class EditAndContinueUIContext
{
/// <summary>
/// Context id that indicates that primary workspace contains a project that supports Edit and Continue.
/// </summary>
internal const string EncCapableProjectExistsInWorkspaceUIContextString = "0C89AE24-6D19-474C-A3AA-DC3B66FDBB5F";
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue
{
internal static class EditAndContinueUIContext
{
/// <summary>
/// Context id that indicates that primary workspace contains a project that supports Edit and Continue.
/// </summary>
internal const string EncCapableProjectExistsInWorkspaceUIContextString = "0C89AE24-6D19-474C-A3AA-DC3B66FDBB5F";
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/AbstractRegexDiagnosticAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Threading;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices;
using Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions;
using Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions.LanguageServices;
namespace Microsoft.CodeAnalysis.Features.EmbeddedLanguages.RegularExpressions
{
/// <summary>
/// Analyzer that reports diagnostics in strings that we know are regex text.
/// </summary>
internal abstract class AbstractRegexDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
public const string DiagnosticId = "RE0001";
private readonly EmbeddedLanguageInfo _info;
protected AbstractRegexDiagnosticAnalyzer(EmbeddedLanguageInfo info)
: base(DiagnosticId,
EnforceOnBuildValues.Regex,
RegularExpressionsOptions.ReportInvalidRegexPatterns,
new LocalizableResourceString(nameof(FeaturesResources.Regex_issue_0), FeaturesResources.ResourceManager, typeof(FeaturesResources)),
new LocalizableResourceString(nameof(FeaturesResources.Regex_issue_0), FeaturesResources.ResourceManager, typeof(FeaturesResources)))
{
_info = info;
}
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterSemanticModelAction(Analyze);
public void Analyze(SemanticModelAnalysisContext context)
{
var semanticModel = context.SemanticModel;
var syntaxTree = semanticModel.SyntaxTree;
var cancellationToken = context.CancellationToken;
var option = context.GetOption(RegularExpressionsOptions.ReportInvalidRegexPatterns, syntaxTree.Options.Language);
if (!option)
{
return;
}
var detector = RegexPatternDetector.TryGetOrCreate(semanticModel.Compilation, _info);
if (detector == null)
{
return;
}
// Use an actual stack object so that we don't blow the actual stack through recursion.
var root = syntaxTree.GetRoot(cancellationToken);
var stack = new Stack<SyntaxNode>();
stack.Push(root);
while (stack.Count != 0)
{
cancellationToken.ThrowIfCancellationRequested();
var current = stack.Pop();
foreach (var child in current.ChildNodesAndTokens())
{
if (child.IsNode)
{
stack.Push(child.AsNode());
}
else
{
AnalyzeToken(context, detector, child.AsToken(), cancellationToken);
}
}
}
}
private void AnalyzeToken(
SemanticModelAnalysisContext context, RegexPatternDetector detector,
SyntaxToken token, CancellationToken cancellationToken)
{
if (token.RawKind == _info.StringLiteralTokenKind)
{
var tree = detector.TryParseRegexPattern(token, context.SemanticModel, cancellationToken);
if (tree != null)
{
foreach (var diag in tree.Diagnostics)
{
context.ReportDiagnostic(DiagnosticHelper.Create(
Descriptor,
Location.Create(context.SemanticModel.SyntaxTree, diag.Span),
ReportDiagnostic.Warn,
additionalLocations: null,
properties: null,
diag.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.
#nullable disable
using System.Collections.Generic;
using System.Threading;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices;
using Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions;
using Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions.LanguageServices;
namespace Microsoft.CodeAnalysis.Features.EmbeddedLanguages.RegularExpressions
{
/// <summary>
/// Analyzer that reports diagnostics in strings that we know are regex text.
/// </summary>
internal abstract class AbstractRegexDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
public const string DiagnosticId = "RE0001";
private readonly EmbeddedLanguageInfo _info;
protected AbstractRegexDiagnosticAnalyzer(EmbeddedLanguageInfo info)
: base(DiagnosticId,
EnforceOnBuildValues.Regex,
RegularExpressionsOptions.ReportInvalidRegexPatterns,
new LocalizableResourceString(nameof(FeaturesResources.Regex_issue_0), FeaturesResources.ResourceManager, typeof(FeaturesResources)),
new LocalizableResourceString(nameof(FeaturesResources.Regex_issue_0), FeaturesResources.ResourceManager, typeof(FeaturesResources)))
{
_info = info;
}
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterSemanticModelAction(Analyze);
public void Analyze(SemanticModelAnalysisContext context)
{
var semanticModel = context.SemanticModel;
var syntaxTree = semanticModel.SyntaxTree;
var cancellationToken = context.CancellationToken;
var option = context.GetOption(RegularExpressionsOptions.ReportInvalidRegexPatterns, syntaxTree.Options.Language);
if (!option)
{
return;
}
var detector = RegexPatternDetector.TryGetOrCreate(semanticModel.Compilation, _info);
if (detector == null)
{
return;
}
// Use an actual stack object so that we don't blow the actual stack through recursion.
var root = syntaxTree.GetRoot(cancellationToken);
var stack = new Stack<SyntaxNode>();
stack.Push(root);
while (stack.Count != 0)
{
cancellationToken.ThrowIfCancellationRequested();
var current = stack.Pop();
foreach (var child in current.ChildNodesAndTokens())
{
if (child.IsNode)
{
stack.Push(child.AsNode());
}
else
{
AnalyzeToken(context, detector, child.AsToken(), cancellationToken);
}
}
}
}
private void AnalyzeToken(
SemanticModelAnalysisContext context, RegexPatternDetector detector,
SyntaxToken token, CancellationToken cancellationToken)
{
if (token.RawKind == _info.StringLiteralTokenKind)
{
var tree = detector.TryParseRegexPattern(token, context.SemanticModel, cancellationToken);
if (tree != null)
{
foreach (var diag in tree.Diagnostics)
{
context.ReportDiagnostic(DiagnosticHelper.Create(
Descriptor,
Location.Create(context.SemanticModel.SyntaxTree, diag.Span),
ReportDiagnostic.Warn,
additionalLocations: null,
properties: null,
diag.Message));
}
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Compilers/Test/Resources/Core/SymbolsTests/Metadata/AttributeTestDef01.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Reflection;
namespace CustomAttribute
{
[AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = true)]
public class AllInheritMultipleAttribute : Attribute
{
public AllInheritMultipleAttribute() { UIntField = 1; }
public AllInheritMultipleAttribute(object p1, BindingFlags p2 = BindingFlags.Static) { UIntField = 2; }
public AllInheritMultipleAttribute(object p1, byte p2, sbyte p3 = -1) { UIntField = 3; }
public AllInheritMultipleAttribute(object p1, long p2, float p3 = 0.123f, short p4 = -2) { UIntField = 4; }
// Char array
public AllInheritMultipleAttribute(char[] ary1, params string[] ary2) { }
public uint UIntField;
public ulong[] AryField;
// uint16 jagged array
object[] propField;
public object[] AryProp
{
get { return propField; }
set { propField = value; }
}
}
// default: Inherited = true, AllowMultiple = false
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property)]
public class BaseAttribute : Attribute
{
public BaseAttribute(object p) { ObjectField = p; }
public object ObjectField;
}
// target (not inherit): 1 same, 2 diff from base
[AttributeUsage(AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Parameter)]
public class DerivedAttribute : BaseAttribute
{
public DerivedAttribute(object p) : base(p) { }
Type _prop;
public Type TypeProp
{
get { return _prop; }
set { _prop = value; }
}
}
// C# - @AttrName
[AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = true)]
public class AttrName : Attribute
{
public ushort UShortField;
}
[AttributeUsage(AttributeTargets.Module, Inherited = false, AllowMultiple = false)]
public class AttrNameAttribute : Attribute
{
public Type TypeField;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Reflection;
namespace CustomAttribute
{
[AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = true)]
public class AllInheritMultipleAttribute : Attribute
{
public AllInheritMultipleAttribute() { UIntField = 1; }
public AllInheritMultipleAttribute(object p1, BindingFlags p2 = BindingFlags.Static) { UIntField = 2; }
public AllInheritMultipleAttribute(object p1, byte p2, sbyte p3 = -1) { UIntField = 3; }
public AllInheritMultipleAttribute(object p1, long p2, float p3 = 0.123f, short p4 = -2) { UIntField = 4; }
// Char array
public AllInheritMultipleAttribute(char[] ary1, params string[] ary2) { }
public uint UIntField;
public ulong[] AryField;
// uint16 jagged array
object[] propField;
public object[] AryProp
{
get { return propField; }
set { propField = value; }
}
}
// default: Inherited = true, AllowMultiple = false
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property)]
public class BaseAttribute : Attribute
{
public BaseAttribute(object p) { ObjectField = p; }
public object ObjectField;
}
// target (not inherit): 1 same, 2 diff from base
[AttributeUsage(AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Parameter)]
public class DerivedAttribute : BaseAttribute
{
public DerivedAttribute(object p) : base(p) { }
Type _prop;
public Type TypeProp
{
get { return _prop; }
set { _prop = value; }
}
}
// C# - @AttrName
[AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = true)]
public class AttrName : Attribute
{
public ushort UShortField;
}
[AttributeUsage(AttributeTargets.Module, Inherited = false, AllowMultiple = false)]
public class AttrNameAttribute : Attribute
{
public Type TypeField;
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/CodeStyle/Core/Analyzers/xlf/CodeStyleResources.it.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="it" original="../CodeStyleResources.resx">
<body>
<trans-unit id="A_language_name_cannot_be_specified_for_this_option">
<source>A language name cannot be specified for this option.</source>
<target state="translated">Non è possibile specificare un nome di linguaggio per questa opzione.</target>
<note />
</trans-unit>
<trans-unit id="A_language_name_must_be_specified_for_this_option">
<source>A language name must be specified for this option.</source>
<target state="translated">È necessario specificare un nome di linguaggio per questa opzione.</target>
<note />
</trans-unit>
<trans-unit id="Arrays_with_more_than_one_dimension_cannot_be_serialized">
<source>Arrays with more than one dimension cannot be serialized.</source>
<target state="translated">Non è possibile serializzare le matrice con più di una dimensione.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_serialize_type_0">
<source>Cannot serialize type '{0}'.</source>
<target state="translated">Non è possibile serializzare il tipo '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="Deserialization_reader_for_0_read_incorrect_number_of_values">
<source>Deserialization reader for '{0}' read incorrect number of values.</source>
<target state="translated">Il numero di valori letto dal lettore di deserializzazioni per '{0}' non è corretto.</target>
<note />
</trans-unit>
<trans-unit id="Error">
<source>Error</source>
<target state="translated">Errore</target>
<note />
</trans-unit>
<trans-unit id="Fix_formatting">
<source>Fix formatting</source>
<target state="translated">Correggi formattazione</target>
<note />
</trans-unit>
<trans-unit id="Indentation_and_spacing">
<source>Indentation and spacing</source>
<target state="translated">Rientro e spaziatura</target>
<note />
</trans-unit>
<trans-unit id="New_line_preferences">
<source>New line preferences</source>
<target state="translated">Preferenze per nuova riga</target>
<note />
</trans-unit>
<trans-unit id="None">
<source>None</source>
<target state="translated">Nessuno</target>
<note />
</trans-unit>
<trans-unit id="Refactoring_Only">
<source>Refactoring Only</source>
<target state="translated">Refactoring Only</target>
<note />
</trans-unit>
<trans-unit id="Stream_is_too_long">
<source>Stream is too long.</source>
<target state="translated">Il flusso è troppo lungo.</target>
<note />
</trans-unit>
<trans-unit id="Suggestion">
<source>Suggestion</source>
<target state="translated">Suggerimento</target>
<note />
</trans-unit>
<trans-unit id="The_type_0_is_not_understood_by_the_serialization_binder">
<source>The type '{0}' is not understood by the serialization binder.</source>
<target state="translated">Il tipo '{0}' non è riconosciuto dal binder di serializzazioni.</target>
<note />
</trans-unit>
<trans-unit id="Value_too_large_to_be_represented_as_a_30_bit_unsigned_integer">
<source>Value too large to be represented as a 30 bit unsigned integer.</source>
<target state="translated">Il valore è troppo grande per essere rappresentato come intero senza segno a 30 bit.</target>
<note />
</trans-unit>
<trans-unit id="Warning">
<source>Warning</source>
<target state="translated">Avviso</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="it" original="../CodeStyleResources.resx">
<body>
<trans-unit id="A_language_name_cannot_be_specified_for_this_option">
<source>A language name cannot be specified for this option.</source>
<target state="translated">Non è possibile specificare un nome di linguaggio per questa opzione.</target>
<note />
</trans-unit>
<trans-unit id="A_language_name_must_be_specified_for_this_option">
<source>A language name must be specified for this option.</source>
<target state="translated">È necessario specificare un nome di linguaggio per questa opzione.</target>
<note />
</trans-unit>
<trans-unit id="Arrays_with_more_than_one_dimension_cannot_be_serialized">
<source>Arrays with more than one dimension cannot be serialized.</source>
<target state="translated">Non è possibile serializzare le matrice con più di una dimensione.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_serialize_type_0">
<source>Cannot serialize type '{0}'.</source>
<target state="translated">Non è possibile serializzare il tipo '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="Deserialization_reader_for_0_read_incorrect_number_of_values">
<source>Deserialization reader for '{0}' read incorrect number of values.</source>
<target state="translated">Il numero di valori letto dal lettore di deserializzazioni per '{0}' non è corretto.</target>
<note />
</trans-unit>
<trans-unit id="Error">
<source>Error</source>
<target state="translated">Errore</target>
<note />
</trans-unit>
<trans-unit id="Fix_formatting">
<source>Fix formatting</source>
<target state="translated">Correggi formattazione</target>
<note />
</trans-unit>
<trans-unit id="Indentation_and_spacing">
<source>Indentation and spacing</source>
<target state="translated">Rientro e spaziatura</target>
<note />
</trans-unit>
<trans-unit id="New_line_preferences">
<source>New line preferences</source>
<target state="translated">Preferenze per nuova riga</target>
<note />
</trans-unit>
<trans-unit id="None">
<source>None</source>
<target state="translated">Nessuno</target>
<note />
</trans-unit>
<trans-unit id="Refactoring_Only">
<source>Refactoring Only</source>
<target state="translated">Refactoring Only</target>
<note />
</trans-unit>
<trans-unit id="Stream_is_too_long">
<source>Stream is too long.</source>
<target state="translated">Il flusso è troppo lungo.</target>
<note />
</trans-unit>
<trans-unit id="Suggestion">
<source>Suggestion</source>
<target state="translated">Suggerimento</target>
<note />
</trans-unit>
<trans-unit id="The_type_0_is_not_understood_by_the_serialization_binder">
<source>The type '{0}' is not understood by the serialization binder.</source>
<target state="translated">Il tipo '{0}' non è riconosciuto dal binder di serializzazioni.</target>
<note />
</trans-unit>
<trans-unit id="Value_too_large_to_be_represented_as_a_30_bit_unsigned_integer">
<source>Value too large to be represented as a 30 bit unsigned integer.</source>
<target state="translated">Il valore è troppo grande per essere rappresentato come intero senza segno a 30 bit.</target>
<note />
</trans-unit>
<trans-unit id="Warning">
<source>Warning</source>
<target state="translated">Avviso</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Features/Core/Portable/CodeFixes/CodeFixService.FixAllDiagnosticProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.CodeFixes
{
internal partial class CodeFixService
{
private class FixAllDiagnosticProvider : FixAllContext.DiagnosticProvider
{
private readonly CodeFixService _codeFixService;
private readonly ImmutableHashSet<string>? _diagnosticIds;
private readonly bool _includeSuppressedDiagnostics;
public FixAllDiagnosticProvider(CodeFixService codeFixService, ImmutableHashSet<string>? diagnosticIds, bool includeSuppressedDiagnostics)
{
Debug.Assert(diagnosticIds == null || !diagnosticIds.Contains(IDEDiagnosticIds.RemoveUnnecessarySuppressionDiagnosticId));
Debug.Assert(!includeSuppressedDiagnostics || diagnosticIds == null);
_codeFixService = codeFixService;
_diagnosticIds = diagnosticIds;
_includeSuppressedDiagnostics = includeSuppressedDiagnostics;
}
public override Task<IEnumerable<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, CancellationToken cancellationToken)
=> _codeFixService.GetDocumentDiagnosticsAsync(document, _diagnosticIds, _includeSuppressedDiagnostics, cancellationToken);
public override Task<IEnumerable<Diagnostic>> GetAllDiagnosticsAsync(Project project, CancellationToken cancellationToken)
=> _codeFixService.GetProjectDiagnosticsAsync(project, true, _diagnosticIds, _includeSuppressedDiagnostics, cancellationToken);
public override Task<IEnumerable<Diagnostic>> GetProjectDiagnosticsAsync(Project project, CancellationToken cancellationToken)
=> _codeFixService.GetProjectDiagnosticsAsync(project, false, _diagnosticIds, _includeSuppressedDiagnostics, cancellationToken);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.CodeFixes
{
internal partial class CodeFixService
{
private class FixAllDiagnosticProvider : FixAllContext.DiagnosticProvider
{
private readonly CodeFixService _codeFixService;
private readonly ImmutableHashSet<string>? _diagnosticIds;
private readonly bool _includeSuppressedDiagnostics;
public FixAllDiagnosticProvider(CodeFixService codeFixService, ImmutableHashSet<string>? diagnosticIds, bool includeSuppressedDiagnostics)
{
Debug.Assert(diagnosticIds == null || !diagnosticIds.Contains(IDEDiagnosticIds.RemoveUnnecessarySuppressionDiagnosticId));
Debug.Assert(!includeSuppressedDiagnostics || diagnosticIds == null);
_codeFixService = codeFixService;
_diagnosticIds = diagnosticIds;
_includeSuppressedDiagnostics = includeSuppressedDiagnostics;
}
public override Task<IEnumerable<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, CancellationToken cancellationToken)
=> _codeFixService.GetDocumentDiagnosticsAsync(document, _diagnosticIds, _includeSuppressedDiagnostics, cancellationToken);
public override Task<IEnumerable<Diagnostic>> GetAllDiagnosticsAsync(Project project, CancellationToken cancellationToken)
=> _codeFixService.GetProjectDiagnosticsAsync(project, true, _diagnosticIds, _includeSuppressedDiagnostics, cancellationToken);
public override Task<IEnumerable<Diagnostic>> GetProjectDiagnosticsAsync(Project project, CancellationToken cancellationToken)
=> _codeFixService.GetProjectDiagnosticsAsync(project, false, _diagnosticIds, _includeSuppressedDiagnostics, cancellationToken);
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedEnumValueFieldSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.PooledObjects;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Represents __value field of an enum.
/// </summary>
internal sealed class SynthesizedEnumValueFieldSymbol : SynthesizedFieldSymbolBase
{
public SynthesizedEnumValueFieldSymbol(SourceNamedTypeSymbol containingEnum)
: base(containingEnum, WellKnownMemberNames.EnumBackingFieldName, isPublic: true, isReadOnly: false, isStatic: false)
{
}
internal override bool SuppressDynamicAttribute
{
get { return true; }
}
internal override TypeWithAnnotations GetFieldType(ConsList<FieldSymbol> fieldsBeingBound)
{
return TypeWithAnnotations.Create(((SourceNamedTypeSymbol)ContainingType).EnumUnderlyingType);
}
internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes)
{
// no attributes should be emitted
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.PooledObjects;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Represents __value field of an enum.
/// </summary>
internal sealed class SynthesizedEnumValueFieldSymbol : SynthesizedFieldSymbolBase
{
public SynthesizedEnumValueFieldSymbol(SourceNamedTypeSymbol containingEnum)
: base(containingEnum, WellKnownMemberNames.EnumBackingFieldName, isPublic: true, isReadOnly: false, isStatic: false)
{
}
internal override bool SuppressDynamicAttribute
{
get { return true; }
}
internal override TypeWithAnnotations GetFieldType(ConsList<FieldSymbol> fieldsBeingBound)
{
return TypeWithAnnotations.Create(((SourceNamedTypeSymbol)ContainingType).EnumUnderlyingType);
}
internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes)
{
// no attributes should be emitted
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/EditorFeatures/CSharpTest/Formatting/CSharpNewDocumentFormattingServiceTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.AddImports;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Test.Utilities.Formatting;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting
{
public class CSharpNewDocumentFormattingServiceTests : AbstractNewDocumentFormattingServiceTests
{
protected override string Language => LanguageNames.CSharp;
protected override TestWorkspace CreateTestWorkspace(string testCode, ParseOptions? parseOptions)
=> TestWorkspace.CreateCSharp(testCode, parseOptions);
[Fact]
public async Task TestFileScopedNamespaces()
{
await TestAsync(testCode: @"
namespace Goo
{
internal class C
{
}
}",
expected: @"
namespace Goo;
internal class C
{
}
",
options: new[]
{
(CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2<NamespaceDeclarationPreference>(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Error))
},
parseOptions: new CSharpParseOptions(LanguageVersion.CSharp10));
}
[Fact]
public async Task TestFileScopedNamespaces_Invalid_MultipleNamespaces()
{
var testCode = @"
namespace Goo
{
}
namespace Bar
{
}";
await TestAsync(
testCode: testCode,
expected: testCode,
options: new[]
{
(CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2<NamespaceDeclarationPreference>(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Error))
},
parseOptions: new CSharpParseOptions(LanguageVersion.CSharp10));
}
[Fact]
public async Task TestFileScopedNamespaces_Invalid_WrongLanguageVersion()
{
var testCode = @"
namespace Goo
{
internal class C
{
}
}";
await TestAsync(
testCode: testCode,
expected: testCode,
options: new[]
{
(CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2<NamespaceDeclarationPreference>(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Error))
},
parseOptions: new CSharpParseOptions(LanguageVersion.CSharp9));
}
[Fact]
public async Task TestBlockScopedNamespaces()
{
await TestAsync(testCode: @"
namespace Goo;
internal class C
{
}
",
expected: @"
namespace Goo
{
internal class C
{
}
}",
options: new[]
{
(CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2<NamespaceDeclarationPreference>(NamespaceDeclarationPreference.BlockScoped, NotificationOption2.Error))
});
}
[Fact]
public async Task TestOrganizeUsingsWithNoUsings()
{
var testCode = @"namespace Goo
{
}";
await TestAsync(
testCode: testCode,
expected: testCode,
options: new[]
{
(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.OutsideNamespace, NotificationOption2.Error))
});
}
[Fact]
public async Task TestFileBanners()
{
await TestAsync(testCode: @"using System;
namespace Goo
{
}",
expected: @"// This is a banner.
using System;
namespace Goo
{
}",
options: new[]
{
(CodeStyleOptions2.FileHeaderTemplate, "This is a banner.")
});
}
[Fact]
public async Task TestAccessibilityModifiers()
{
await TestAsync(testCode: @"using System;
namespace Goo
{
class C
{
}
}",
expected: @"using System;
namespace Goo
{
internal class C
{
}
}",
options: new[]
{
(CodeStyleOptions2.RequireAccessibilityModifiers, new CodeStyleOption2<AccessibilityModifiersRequired>(AccessibilityModifiersRequired.Always, NotificationOption2.Error))
});
}
[Fact]
public async Task TestUsingDirectivePlacement()
{
await TestAsync(testCode: @"using System;
namespace Goo
{
}",
expected: @"namespace Goo
{
using System;
}",
options: new[]
{
(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.InsideNamespace, NotificationOption2.Error))
});
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.AddImports;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Test.Utilities.Formatting;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting
{
public class CSharpNewDocumentFormattingServiceTests : AbstractNewDocumentFormattingServiceTests
{
protected override string Language => LanguageNames.CSharp;
protected override TestWorkspace CreateTestWorkspace(string testCode, ParseOptions? parseOptions)
=> TestWorkspace.CreateCSharp(testCode, parseOptions);
[Fact]
public async Task TestFileScopedNamespaces()
{
await TestAsync(testCode: @"
namespace Goo
{
internal class C
{
}
}",
expected: @"
namespace Goo;
internal class C
{
}
",
options: new[]
{
(CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2<NamespaceDeclarationPreference>(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Error))
},
parseOptions: new CSharpParseOptions(LanguageVersion.CSharp10));
}
[Fact]
public async Task TestFileScopedNamespaces_Invalid_MultipleNamespaces()
{
var testCode = @"
namespace Goo
{
}
namespace Bar
{
}";
await TestAsync(
testCode: testCode,
expected: testCode,
options: new[]
{
(CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2<NamespaceDeclarationPreference>(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Error))
},
parseOptions: new CSharpParseOptions(LanguageVersion.CSharp10));
}
[Fact]
public async Task TestFileScopedNamespaces_Invalid_WrongLanguageVersion()
{
var testCode = @"
namespace Goo
{
internal class C
{
}
}";
await TestAsync(
testCode: testCode,
expected: testCode,
options: new[]
{
(CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2<NamespaceDeclarationPreference>(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Error))
},
parseOptions: new CSharpParseOptions(LanguageVersion.CSharp9));
}
[Fact]
public async Task TestBlockScopedNamespaces()
{
await TestAsync(testCode: @"
namespace Goo;
internal class C
{
}
",
expected: @"
namespace Goo
{
internal class C
{
}
}",
options: new[]
{
(CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2<NamespaceDeclarationPreference>(NamespaceDeclarationPreference.BlockScoped, NotificationOption2.Error))
});
}
[Fact]
public async Task TestOrganizeUsingsWithNoUsings()
{
var testCode = @"namespace Goo
{
}";
await TestAsync(
testCode: testCode,
expected: testCode,
options: new[]
{
(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.OutsideNamespace, NotificationOption2.Error))
});
}
[Fact]
public async Task TestFileBanners()
{
await TestAsync(testCode: @"using System;
namespace Goo
{
}",
expected: @"// This is a banner.
using System;
namespace Goo
{
}",
options: new[]
{
(CodeStyleOptions2.FileHeaderTemplate, "This is a banner.")
});
}
[Fact]
public async Task TestAccessibilityModifiers()
{
await TestAsync(testCode: @"using System;
namespace Goo
{
class C
{
}
}",
expected: @"using System;
namespace Goo
{
internal class C
{
}
}",
options: new[]
{
(CodeStyleOptions2.RequireAccessibilityModifiers, new CodeStyleOption2<AccessibilityModifiersRequired>(AccessibilityModifiersRequired.Always, NotificationOption2.Error))
});
}
[Fact]
public async Task TestUsingDirectivePlacement()
{
await TestAsync(testCode: @"using System;
namespace Goo
{
}",
expected: @"namespace Goo
{
using System;
}",
options: new[]
{
(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.InsideNamespace, NotificationOption2.Error))
});
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./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 | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Compilers/Core/Portable/Desktop/AssemblyPortabilityPolicy.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Xml;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Policy to be used when matching assembly reference to an assembly definition across platforms.
/// </summary>
internal struct AssemblyPortabilityPolicy : IEquatable<AssemblyPortabilityPolicy>
{
// 7cec85d7bea7798e (System, System.Core)
public readonly bool SuppressSilverlightPlatformAssembliesPortability;
// 31bf3856ad364e35 (Microsoft.VisualBasic, System.ComponentModel.Composition)
public readonly bool SuppressSilverlightLibraryAssembliesPortability;
public AssemblyPortabilityPolicy(
bool suppressSilverlightPlatformAssembliesPortability,
bool suppressSilverlightLibraryAssembliesPortability)
{
this.SuppressSilverlightLibraryAssembliesPortability = suppressSilverlightLibraryAssembliesPortability;
this.SuppressSilverlightPlatformAssembliesPortability = suppressSilverlightPlatformAssembliesPortability;
}
public override bool Equals(object obj)
{
return obj is AssemblyPortabilityPolicy && Equals((AssemblyPortabilityPolicy)obj);
}
public bool Equals(AssemblyPortabilityPolicy other)
{
return this.SuppressSilverlightLibraryAssembliesPortability == other.SuppressSilverlightLibraryAssembliesPortability
&& this.SuppressSilverlightPlatformAssembliesPortability == other.SuppressSilverlightPlatformAssembliesPortability;
}
public override int GetHashCode()
{
return (this.SuppressSilverlightLibraryAssembliesPortability ? 1 : 0) |
(this.SuppressSilverlightPlatformAssembliesPortability ? 2 : 0);
}
private static bool ReadToChild(XmlReader reader, int depth, string elementName, string elementNamespace = "")
{
return reader.ReadToDescendant(elementName, elementNamespace) && reader.Depth == depth;
}
private static readonly XmlReaderSettings s_xmlSettings = new XmlReaderSettings()
{
DtdProcessing = DtdProcessing.Prohibit,
};
internal static AssemblyPortabilityPolicy LoadFromXml(Stream input)
{
// Note: Unlike Fusion XML reader the XmlReader doesn't allow whitespace in front of <?xml version=""1.0"" encoding=""utf-8"" ?>
const string ns = "urn:schemas-microsoft-com:asm.v1";
using (XmlReader xml = XmlReader.Create(input, s_xmlSettings))
{
if (!ReadToChild(xml, 0, "configuration") ||
!ReadToChild(xml, 1, "runtime") ||
!ReadToChild(xml, 2, "assemblyBinding", ns) ||
!ReadToChild(xml, 3, "supportPortability", ns))
{
return default(AssemblyPortabilityPolicy);
}
// 31bf3856ad364e35
bool suppressLibrary = false;
// 7cec85d7bea7798e
bool suppressPlatform = false;
do
{
// see CNodeFactory::ProcessSupportPortabilityTag in fusion\inc\nodefact.cpp for details
// - unrecognized attributes ignored.
// - syntax errors within tags causes this tag to be ignored (but not reject entire app.config)
// - multiple <supportPortability> tags ok (if two specify same PKT, all but (implementation defined) one ignored.)
string pkt = xml.GetAttribute("PKT");
string enableAttribute = xml.GetAttribute("enable");
bool? enable =
string.Equals(enableAttribute, "false", StringComparison.OrdinalIgnoreCase) ? false :
string.Equals(enableAttribute, "true", StringComparison.OrdinalIgnoreCase) ? true :
(bool?)null;
if (enable != null)
{
if (string.Equals(pkt, "31bf3856ad364e35", StringComparison.OrdinalIgnoreCase))
{
suppressLibrary = !enable.Value;
}
else if (string.Equals(pkt, "7cec85d7bea7798e", StringComparison.OrdinalIgnoreCase))
{
suppressPlatform = !enable.Value;
}
}
} while (xml.ReadToNextSibling("supportPortability", ns));
return new AssemblyPortabilityPolicy(suppressPlatform, suppressLibrary);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Xml;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Policy to be used when matching assembly reference to an assembly definition across platforms.
/// </summary>
internal struct AssemblyPortabilityPolicy : IEquatable<AssemblyPortabilityPolicy>
{
// 7cec85d7bea7798e (System, System.Core)
public readonly bool SuppressSilverlightPlatformAssembliesPortability;
// 31bf3856ad364e35 (Microsoft.VisualBasic, System.ComponentModel.Composition)
public readonly bool SuppressSilverlightLibraryAssembliesPortability;
public AssemblyPortabilityPolicy(
bool suppressSilverlightPlatformAssembliesPortability,
bool suppressSilverlightLibraryAssembliesPortability)
{
this.SuppressSilverlightLibraryAssembliesPortability = suppressSilverlightLibraryAssembliesPortability;
this.SuppressSilverlightPlatformAssembliesPortability = suppressSilverlightPlatformAssembliesPortability;
}
public override bool Equals(object obj)
{
return obj is AssemblyPortabilityPolicy && Equals((AssemblyPortabilityPolicy)obj);
}
public bool Equals(AssemblyPortabilityPolicy other)
{
return this.SuppressSilverlightLibraryAssembliesPortability == other.SuppressSilverlightLibraryAssembliesPortability
&& this.SuppressSilverlightPlatformAssembliesPortability == other.SuppressSilverlightPlatformAssembliesPortability;
}
public override int GetHashCode()
{
return (this.SuppressSilverlightLibraryAssembliesPortability ? 1 : 0) |
(this.SuppressSilverlightPlatformAssembliesPortability ? 2 : 0);
}
private static bool ReadToChild(XmlReader reader, int depth, string elementName, string elementNamespace = "")
{
return reader.ReadToDescendant(elementName, elementNamespace) && reader.Depth == depth;
}
private static readonly XmlReaderSettings s_xmlSettings = new XmlReaderSettings()
{
DtdProcessing = DtdProcessing.Prohibit,
};
internal static AssemblyPortabilityPolicy LoadFromXml(Stream input)
{
// Note: Unlike Fusion XML reader the XmlReader doesn't allow whitespace in front of <?xml version=""1.0"" encoding=""utf-8"" ?>
const string ns = "urn:schemas-microsoft-com:asm.v1";
using (XmlReader xml = XmlReader.Create(input, s_xmlSettings))
{
if (!ReadToChild(xml, 0, "configuration") ||
!ReadToChild(xml, 1, "runtime") ||
!ReadToChild(xml, 2, "assemblyBinding", ns) ||
!ReadToChild(xml, 3, "supportPortability", ns))
{
return default(AssemblyPortabilityPolicy);
}
// 31bf3856ad364e35
bool suppressLibrary = false;
// 7cec85d7bea7798e
bool suppressPlatform = false;
do
{
// see CNodeFactory::ProcessSupportPortabilityTag in fusion\inc\nodefact.cpp for details
// - unrecognized attributes ignored.
// - syntax errors within tags causes this tag to be ignored (but not reject entire app.config)
// - multiple <supportPortability> tags ok (if two specify same PKT, all but (implementation defined) one ignored.)
string pkt = xml.GetAttribute("PKT");
string enableAttribute = xml.GetAttribute("enable");
bool? enable =
string.Equals(enableAttribute, "false", StringComparison.OrdinalIgnoreCase) ? false :
string.Equals(enableAttribute, "true", StringComparison.OrdinalIgnoreCase) ? true :
(bool?)null;
if (enable != null)
{
if (string.Equals(pkt, "31bf3856ad364e35", StringComparison.OrdinalIgnoreCase))
{
suppressLibrary = !enable.Value;
}
else if (string.Equals(pkt, "7cec85d7bea7798e", StringComparison.OrdinalIgnoreCase))
{
suppressPlatform = !enable.Value;
}
}
} while (xml.ReadToNextSibling("supportPortability", ns));
return new AssemblyPortabilityPolicy(suppressPlatform, suppressLibrary);
}
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Compilers/CSharp/csc/Program.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.CommandLine;
namespace Microsoft.CodeAnalysis.CSharp.CommandLine
{
public class Program
{
public static int Main(string[] args)
{
try
{
return MainCore(args);
}
catch (FileNotFoundException e)
{
// Catch exception from missing compiler assembly.
// Report the exception message and terminate the process.
Console.WriteLine(e.Message);
return CommonCompiler.Failed;
}
}
private static int MainCore(string[] args)
{
using var logger = new CompilerServerLogger($"csc {Process.GetCurrentProcess().Id}");
#if BOOTSTRAP
ExitingTraceListener.Install(logger);
#endif
return BuildClient.Run(args, RequestLanguage.CSharpCompile, Csc.Run, BuildClient.GetCompileOnServerFunc(logger));
}
public static int Run(string[] args, string clientDir, string workingDir, string sdkDir, string tempDir, TextWriter textWriter, IAnalyzerAssemblyLoader analyzerLoader)
=> Csc.Run(args, new BuildPaths(clientDir: clientDir, workingDir: workingDir, sdkDir: sdkDir, tempDir: tempDir), textWriter, analyzerLoader);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.CommandLine;
namespace Microsoft.CodeAnalysis.CSharp.CommandLine
{
public class Program
{
public static int Main(string[] args)
{
try
{
return MainCore(args);
}
catch (FileNotFoundException e)
{
// Catch exception from missing compiler assembly.
// Report the exception message and terminate the process.
Console.WriteLine(e.Message);
return CommonCompiler.Failed;
}
}
private static int MainCore(string[] args)
{
using var logger = new CompilerServerLogger($"csc {Process.GetCurrentProcess().Id}");
#if BOOTSTRAP
ExitingTraceListener.Install(logger);
#endif
return BuildClient.Run(args, RequestLanguage.CSharpCompile, Csc.Run, BuildClient.GetCompileOnServerFunc(logger));
}
public static int Run(string[] args, string clientDir, string workingDir, string sdkDir, string tempDir, TextWriter textWriter, IAnalyzerAssemblyLoader analyzerLoader)
=> Csc.Run(args, new BuildPaths(clientDir: clientDir, workingDir: workingDir, sdkDir: sdkDir, tempDir: tempDir), textWriter, analyzerLoader);
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./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 | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ExpressionCompilerTestBase.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.UnitTests;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.DiaSymReader;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests
{
public abstract class ExpressionCompilerTestBase : CSharpTestBase, IDisposable
{
private readonly ArrayBuilder<IDisposable> _runtimeInstances = ArrayBuilder<IDisposable>.GetInstance();
internal static readonly ImmutableArray<Alias> NoAliases = ImmutableArray<Alias>.Empty;
protected ExpressionCompilerTestBase()
{
// We never want to swallow Exceptions (generate a non-fatal Watson) when running tests.
ExpressionEvaluatorFatalError.IsFailFastEnabled = true;
}
public override void Dispose()
{
base.Dispose();
foreach (var instance in _runtimeInstances)
{
instance.Dispose();
}
_runtimeInstances.Free();
}
internal static void WithRuntimeInstance(Compilation compilation, Action<RuntimeInstance> validator)
{
WithRuntimeInstance(compilation, null, validator: validator);
}
internal static void WithRuntimeInstance(Compilation compilation, IEnumerable<MetadataReference> references, Action<RuntimeInstance> validator)
{
WithRuntimeInstance(compilation, references, includeLocalSignatures: true, includeIntrinsicAssembly: true, validator: validator);
}
internal static void WithRuntimeInstance(
Compilation compilation,
IEnumerable<MetadataReference> references,
bool includeLocalSignatures,
bool includeIntrinsicAssembly,
Action<RuntimeInstance> validator)
{
foreach (var debugFormat in new[] { DebugInformationFormat.Pdb, DebugInformationFormat.PortablePdb })
{
using (var instance = RuntimeInstance.Create(compilation, references, debugFormat, includeLocalSignatures, includeIntrinsicAssembly))
{
validator(instance);
}
}
}
internal RuntimeInstance CreateRuntimeInstance(IEnumerable<ModuleInstance> modules)
{
var instance = RuntimeInstance.Create(modules);
_runtimeInstances.Add(instance);
return instance;
}
internal RuntimeInstance CreateRuntimeInstance(
Compilation compilation,
IEnumerable<MetadataReference> references = null,
DebugInformationFormat debugFormat = DebugInformationFormat.Pdb,
bool includeLocalSignatures = true)
{
var instance = RuntimeInstance.Create(compilation, references, debugFormat, includeLocalSignatures, includeIntrinsicAssembly: true);
_runtimeInstances.Add(instance);
return instance;
}
internal RuntimeInstance CreateRuntimeInstance(
ModuleInstance module,
IEnumerable<MetadataReference> references)
{
var instance = RuntimeInstance.Create(module, references, DebugInformationFormat.Pdb);
_runtimeInstances.Add(instance);
return instance;
}
internal sealed class AppDomain
{
private MetadataContext<CSharpMetadataContext> _metadataContext;
internal MetadataContext<CSharpMetadataContext> GetMetadataContext()
{
return _metadataContext;
}
internal void SetMetadataContext(MetadataContext<CSharpMetadataContext> metadataContext)
{
_metadataContext = metadataContext;
}
internal void RemoveMetadataContext()
{
_metadataContext = default;
}
}
internal static EvaluationContext CreateTypeContext(
AppDomain appDomain,
ImmutableArray<MetadataBlock> blocks,
Guid moduleVersionId,
int typeToken,
MakeAssemblyReferencesKind kind = MakeAssemblyReferencesKind.AllAssemblies)
{
return CSharpExpressionCompiler.CreateTypeContext(
appDomain,
ad => ad.GetMetadataContext(),
blocks,
moduleVersionId,
typeToken,
kind);
}
internal static EvaluationContext CreateMethodContext(
AppDomain appDomain,
ImmutableArray<MetadataBlock> blocks,
ISymUnmanagedReader symReader,
Guid moduleVersionId,
int methodToken,
int methodVersion,
uint ilOffset,
int localSignatureToken,
MakeAssemblyReferencesKind kind = MakeAssemblyReferencesKind.AllAssemblies)
{
return CSharpExpressionCompiler.CreateMethodContext(
appDomain,
ad => ad.GetMetadataContext(),
(ad, mc, report) => ad.SetMetadataContext(mc),
blocks,
symReader,
moduleVersionId,
methodToken,
methodVersion,
ilOffset,
localSignatureToken,
kind);
}
internal static EvaluationContext CreateMethodContext(
AppDomain appDomain,
ImmutableArray<MetadataBlock> blocks,
(Guid ModuleVersionId, ISymUnmanagedReader SymReader, int MethodToken, int LocalSignatureToken, uint ILOffset) state,
MakeAssemblyReferencesKind kind = MakeAssemblyReferencesKind.AllReferences)
{
return CreateMethodContext(
appDomain,
blocks,
state.SymReader,
state.ModuleVersionId,
state.MethodToken,
methodVersion: 1,
state.ILOffset,
state.LocalSignatureToken,
kind);
}
internal static CSharpMetadataContext GetMetadataContext(MetadataContext<CSharpMetadataContext> appDomainContext, Guid mvid = default)
{
var assemblyContexts = appDomainContext.AssemblyContexts;
return assemblyContexts != null && assemblyContexts.TryGetValue(new MetadataContextId(mvid), out CSharpMetadataContext context) ?
context :
default;
}
internal static MetadataContext<CSharpMetadataContext> SetMetadataContext(MetadataContext<CSharpMetadataContext> appDomainContext, Guid mvid, CSharpMetadataContext context)
{
return new MetadataContext<CSharpMetadataContext>(
appDomainContext.MetadataBlocks,
appDomainContext.AssemblyContexts.SetItem(new MetadataContextId(mvid), context));
}
internal static (Guid ModuleVersionId, ISymUnmanagedReader SymReader, int MethodToken, int LocalSignatureToken, uint ILOffset) GetContextState(RuntimeInstance runtime, string methodName)
{
Guid moduleVersionId;
ISymUnmanagedReader symReader;
int methodToken;
int localSignatureToken;
GetContextState(
runtime,
methodName,
out _,
out moduleVersionId,
out symReader,
out methodToken,
out localSignatureToken);
uint ilOffset = ExpressionCompilerTestHelpers.GetOffset(methodToken, symReader);
return (moduleVersionId, symReader, methodToken, localSignatureToken, ilOffset);
}
internal static void GetContextState(
RuntimeInstance runtime,
string methodOrTypeName,
out ImmutableArray<MetadataBlock> blocks,
out Guid moduleVersionId,
out ISymUnmanagedReader symReader,
out int methodOrTypeToken,
out int localSignatureToken)
{
var moduleInstances = runtime.Modules;
blocks = moduleInstances.SelectAsArray(m => m.MetadataBlock);
var compilation = blocks.ToCompilation(default(Guid), MakeAssemblyReferencesKind.AllAssemblies);
var methodOrType = GetMethodOrTypeBySignature(compilation, methodOrTypeName);
var module = (PEModuleSymbol)methodOrType.ContainingModule;
var id = module.Module.GetModuleVersionIdOrThrow();
var moduleInstance = moduleInstances.First(m => m.ModuleVersionId == id);
moduleVersionId = id;
symReader = (ISymUnmanagedReader)moduleInstance.SymReader;
EntityHandle methodOrTypeHandle;
if (methodOrType.Kind == SymbolKind.Method)
{
methodOrTypeHandle = ((PEMethodSymbol)methodOrType).Handle;
localSignatureToken = moduleInstance.GetLocalSignatureToken((MethodDefinitionHandle)methodOrTypeHandle);
}
else
{
methodOrTypeHandle = ((PENamedTypeSymbol)methodOrType).Handle;
localSignatureToken = -1;
}
MetadataReader reader = null; // null should be ok
methodOrTypeToken = reader.GetToken(methodOrTypeHandle);
}
internal static EvaluationContext CreateMethodContext(
RuntimeInstance runtime,
string methodName,
int atLineNumber = -1)
{
ImmutableArray<MetadataBlock> blocks;
Guid moduleVersionId;
ISymUnmanagedReader symReader;
int methodToken;
int localSignatureToken;
GetContextState(runtime, methodName, out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken);
uint ilOffset = ExpressionCompilerTestHelpers.GetOffset(methodToken, symReader, atLineNumber);
return CreateMethodContext(
new AppDomain(),
blocks,
symReader,
moduleVersionId,
methodToken: methodToken,
methodVersion: 1,
ilOffset: ilOffset,
localSignatureToken: localSignatureToken,
kind: MakeAssemblyReferencesKind.AllAssemblies);
}
internal static EvaluationContext CreateTypeContext(
RuntimeInstance runtime,
string typeName)
{
ImmutableArray<MetadataBlock> blocks;
Guid moduleVersionId;
ISymUnmanagedReader symReader;
int typeToken;
int localSignatureToken;
GetContextState(runtime, typeName, out blocks, out moduleVersionId, out symReader, out typeToken, out localSignatureToken);
return CreateTypeContext(
new AppDomain(),
blocks,
moduleVersionId,
typeToken,
kind: MakeAssemblyReferencesKind.AllAssemblies);
}
internal CompilationTestData Evaluate(
string source,
OutputKind outputKind,
string methodName,
string expr,
int atLineNumber = -1,
bool includeSymbols = true)
{
var result = Evaluate(source, outputKind, methodName, expr, out _, out string error, atLineNumber, includeSymbols);
Assert.Null(error);
return result;
}
internal CompilationTestData Evaluate(
CSharpCompilation compilation,
string methodName,
string expr,
int atLineNumber = -1,
bool includeSymbols = true)
{
var result = Evaluate(compilation, methodName, expr, out _, out string error, atLineNumber, includeSymbols);
Assert.Null(error);
return result;
}
internal CompilationTestData Evaluate(
string source,
OutputKind outputKind,
string methodName,
string expr,
out ResultProperties resultProperties,
out string error,
int atLineNumber = -1,
bool includeSymbols = true)
{
var compilation = CreateCompilation(
source,
parseOptions: SyntaxHelpers.ParseOptions,
options: (outputKind == OutputKind.DynamicallyLinkedLibrary) ? TestOptions.DebugDll : TestOptions.DebugExe);
return Evaluate(compilation, methodName, expr, out resultProperties, out error, atLineNumber, includeSymbols);
}
internal CompilationTestData Evaluate(
CSharpCompilation compilation,
string methodName,
string expr,
out ResultProperties resultProperties,
out string error,
int atLineNumber = -1,
bool includeSymbols = true)
{
var runtime = CreateRuntimeInstance(compilation, debugFormat: includeSymbols ? DebugInformationFormat.Pdb : 0);
var context = CreateMethodContext(runtime, methodName, atLineNumber);
var testData = new CompilationTestData();
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
var result = context.CompileExpression(
expr,
DkmEvaluationFlags.TreatAsExpression,
NoAliases,
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData);
Assert.Empty(missingAssemblyIdentities);
return testData;
}
/// <summary>
/// Verify all type parameters from the method
/// are from that method or containing types.
/// </summary>
internal static void VerifyTypeParameters(MethodSymbol method)
{
Assert.True(method.IsContainingSymbolOfAllTypeParameters(method.ReturnType));
AssertEx.All(method.TypeParameters, typeParameter => method.IsContainingSymbolOfAllTypeParameters(typeParameter));
AssertEx.All(method.TypeArgumentsWithAnnotations, typeArgument => method.IsContainingSymbolOfAllTypeParameters(typeArgument.Type));
AssertEx.All(method.Parameters, parameter => method.IsContainingSymbolOfAllTypeParameters(parameter.Type));
VerifyTypeParameters(method.ContainingType);
}
internal static void VerifyLocal(
CompilationTestData testData,
string typeName,
LocalAndMethod localAndMethod,
string expectedMethodName,
string expectedLocalName,
string expectedLocalDisplayName = null,
DkmClrCompilationResultFlags expectedFlags = DkmClrCompilationResultFlags.None,
string expectedILOpt = null,
bool expectedGeneric = false,
[CallerFilePath] string expectedValueSourcePath = null,
[CallerLineNumber] int expectedValueSourceLine = 0)
{
ExpressionCompilerTestHelpers.VerifyLocal<MethodSymbol>(
testData,
typeName,
localAndMethod,
expectedMethodName,
expectedLocalName,
expectedLocalDisplayName ?? expectedLocalName,
expectedFlags,
VerifyTypeParameters,
expectedILOpt,
expectedGeneric,
expectedValueSourcePath,
expectedValueSourceLine);
}
/// <summary>
/// Verify all type parameters from the type
/// are from that type or containing types.
/// </summary>
internal static void VerifyTypeParameters(NamedTypeSymbol type)
{
AssertEx.All(type.TypeParameters, typeParameter => type.IsContainingSymbolOfAllTypeParameters(typeParameter));
AssertEx.All(type.TypeArguments(), typeArgument => type.IsContainingSymbolOfAllTypeParameters(typeArgument));
var container = type.ContainingType;
if ((object)container != null)
{
VerifyTypeParameters(container);
}
}
internal static Symbol GetMethodOrTypeBySignature(Compilation compilation, string signature)
{
string[] parameterTypeNames;
var methodOrTypeName = ExpressionCompilerTestHelpers.GetMethodOrTypeSignatureParts(signature, out parameterTypeNames);
var candidates = compilation.GetMembers(methodOrTypeName);
var methodOrType = (parameterTypeNames == null) ?
candidates.FirstOrDefault() :
candidates.FirstOrDefault(c => parameterTypeNames.SequenceEqual(((MethodSymbol)c).Parameters.Select(p => p.TypeWithAnnotations.Type.Name)));
Assert.False(methodOrType == null, "Could not find method or type with signature '" + signature + "'.");
return methodOrType;
}
internal static Alias VariableAlias(string name, Type type = null)
{
return VariableAlias(name, (type ?? typeof(object)).AssemblyQualifiedName);
}
internal static Alias VariableAlias(string name, string typeAssemblyQualifiedName)
{
return new Alias(DkmClrAliasKind.Variable, name, name, typeAssemblyQualifiedName, default(Guid), null);
}
internal static Alias ObjectIdAlias(uint id, Type type = null)
{
return ObjectIdAlias(id, (type ?? typeof(object)).AssemblyQualifiedName);
}
internal static Alias ObjectIdAlias(uint id, string typeAssemblyQualifiedName)
{
Assert.NotEqual(0u, id); // Not a valid id.
var name = $"${id}";
return new Alias(DkmClrAliasKind.ObjectId, name, name, typeAssemblyQualifiedName, default(Guid), null);
}
internal static Alias ReturnValueAlias(int id = -1, Type type = null)
{
return ReturnValueAlias(id, (type ?? typeof(object)).AssemblyQualifiedName);
}
internal static Alias ReturnValueAlias(int id, string typeAssemblyQualifiedName)
{
var name = $"Method M{(id < 0 ? "" : id.ToString())} returned";
var fullName = id < 0 ? "$ReturnValue" : $"$ReturnValue{id}";
return new Alias(DkmClrAliasKind.ReturnValue, name, fullName, typeAssemblyQualifiedName, default(Guid), null);
}
internal static Alias ExceptionAlias(Type type = null, bool stowed = false)
{
return ExceptionAlias((type ?? typeof(Exception)).AssemblyQualifiedName, stowed);
}
internal static Alias ExceptionAlias(string typeAssemblyQualifiedName, bool stowed = false)
{
var name = "Error";
var fullName = stowed ? "$stowedexception" : "$exception";
var kind = stowed ? DkmClrAliasKind.StowedException : DkmClrAliasKind.Exception;
return new Alias(kind, name, fullName, typeAssemblyQualifiedName, default(Guid), null);
}
internal static Alias Alias(DkmClrAliasKind kind, string name, string fullName, string type, ReadOnlyCollection<byte> payload)
{
return new Alias(kind, name, fullName, type, (payload == null) ? default(Guid) : CustomTypeInfo.PayloadTypeId, payload);
}
internal static MethodDebugInfo<TypeSymbol, LocalSymbol> GetMethodDebugInfo(RuntimeInstance runtime, string qualifiedMethodName, int ilOffset = 0)
{
var peCompilation = runtime.Modules.SelectAsArray(m => m.MetadataBlock).ToCompilation(default(Guid), MakeAssemblyReferencesKind.AllAssemblies);
var peMethod = peCompilation.GlobalNamespace.GetMember<PEMethodSymbol>(qualifiedMethodName);
var peModule = (PEModuleSymbol)peMethod.ContainingModule;
var symReader = runtime.Modules.Single(mi => mi.ModuleVersionId == peModule.Module.GetModuleVersionIdOrThrow()).SymReader;
var symbolProvider = new CSharpEESymbolProvider(peCompilation.SourceAssembly, peModule, peMethod);
return MethodDebugInfo<TypeSymbol, LocalSymbol>.ReadMethodDebugInfo((ISymUnmanagedReader3)symReader, symbolProvider, MetadataTokens.GetToken(peMethod.Handle), methodVersion: 1, ilOffset: ilOffset, isVisualBasicMethod: false);
}
internal static void CheckAttribute(IEnumerable<byte> assembly, MethodSymbol method, AttributeDescription description, bool expected)
{
var module = AssemblyMetadata.CreateFromImage(assembly).GetModules().Single().Module;
var typeName = method.ContainingType.Name;
var typeHandle = module.MetadataReader.TypeDefinitions
.Single(handle => module.GetTypeDefNameOrThrow(handle) == typeName);
var methodName = method.Name;
var methodHandle = module
.GetMethodsOfTypeOrThrow(typeHandle)
.Single(handle => module.GetMethodDefNameOrThrow(handle) == methodName);
var returnParamHandle = module.GetParametersOfMethodOrThrow(methodHandle).FirstOrDefault();
if (returnParamHandle.IsNil)
{
Assert.False(expected);
}
else
{
var attributes = module
.GetCustomAttributesOrThrow(returnParamHandle)
.Where(handle => module.GetTargetAttributeSignatureIndex(handle, description) != -1);
if (expected)
{
Assert.Equal(1, attributes.Count());
}
else
{
Assert.Empty(attributes);
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.UnitTests;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.DiaSymReader;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests
{
public abstract class ExpressionCompilerTestBase : CSharpTestBase, IDisposable
{
private readonly ArrayBuilder<IDisposable> _runtimeInstances = ArrayBuilder<IDisposable>.GetInstance();
internal static readonly ImmutableArray<Alias> NoAliases = ImmutableArray<Alias>.Empty;
protected ExpressionCompilerTestBase()
{
// We never want to swallow Exceptions (generate a non-fatal Watson) when running tests.
ExpressionEvaluatorFatalError.IsFailFastEnabled = true;
}
public override void Dispose()
{
base.Dispose();
foreach (var instance in _runtimeInstances)
{
instance.Dispose();
}
_runtimeInstances.Free();
}
internal static void WithRuntimeInstance(Compilation compilation, Action<RuntimeInstance> validator)
{
WithRuntimeInstance(compilation, null, validator: validator);
}
internal static void WithRuntimeInstance(Compilation compilation, IEnumerable<MetadataReference> references, Action<RuntimeInstance> validator)
{
WithRuntimeInstance(compilation, references, includeLocalSignatures: true, includeIntrinsicAssembly: true, validator: validator);
}
internal static void WithRuntimeInstance(
Compilation compilation,
IEnumerable<MetadataReference> references,
bool includeLocalSignatures,
bool includeIntrinsicAssembly,
Action<RuntimeInstance> validator)
{
foreach (var debugFormat in new[] { DebugInformationFormat.Pdb, DebugInformationFormat.PortablePdb })
{
using (var instance = RuntimeInstance.Create(compilation, references, debugFormat, includeLocalSignatures, includeIntrinsicAssembly))
{
validator(instance);
}
}
}
internal RuntimeInstance CreateRuntimeInstance(IEnumerable<ModuleInstance> modules)
{
var instance = RuntimeInstance.Create(modules);
_runtimeInstances.Add(instance);
return instance;
}
internal RuntimeInstance CreateRuntimeInstance(
Compilation compilation,
IEnumerable<MetadataReference> references = null,
DebugInformationFormat debugFormat = DebugInformationFormat.Pdb,
bool includeLocalSignatures = true)
{
var instance = RuntimeInstance.Create(compilation, references, debugFormat, includeLocalSignatures, includeIntrinsicAssembly: true);
_runtimeInstances.Add(instance);
return instance;
}
internal RuntimeInstance CreateRuntimeInstance(
ModuleInstance module,
IEnumerable<MetadataReference> references)
{
var instance = RuntimeInstance.Create(module, references, DebugInformationFormat.Pdb);
_runtimeInstances.Add(instance);
return instance;
}
internal sealed class AppDomain
{
private MetadataContext<CSharpMetadataContext> _metadataContext;
internal MetadataContext<CSharpMetadataContext> GetMetadataContext()
{
return _metadataContext;
}
internal void SetMetadataContext(MetadataContext<CSharpMetadataContext> metadataContext)
{
_metadataContext = metadataContext;
}
internal void RemoveMetadataContext()
{
_metadataContext = default;
}
}
internal static EvaluationContext CreateTypeContext(
AppDomain appDomain,
ImmutableArray<MetadataBlock> blocks,
Guid moduleVersionId,
int typeToken,
MakeAssemblyReferencesKind kind = MakeAssemblyReferencesKind.AllAssemblies)
{
return CSharpExpressionCompiler.CreateTypeContext(
appDomain,
ad => ad.GetMetadataContext(),
blocks,
moduleVersionId,
typeToken,
kind);
}
internal static EvaluationContext CreateMethodContext(
AppDomain appDomain,
ImmutableArray<MetadataBlock> blocks,
ISymUnmanagedReader symReader,
Guid moduleVersionId,
int methodToken,
int methodVersion,
uint ilOffset,
int localSignatureToken,
MakeAssemblyReferencesKind kind = MakeAssemblyReferencesKind.AllAssemblies)
{
return CSharpExpressionCompiler.CreateMethodContext(
appDomain,
ad => ad.GetMetadataContext(),
(ad, mc, report) => ad.SetMetadataContext(mc),
blocks,
symReader,
moduleVersionId,
methodToken,
methodVersion,
ilOffset,
localSignatureToken,
kind);
}
internal static EvaluationContext CreateMethodContext(
AppDomain appDomain,
ImmutableArray<MetadataBlock> blocks,
(Guid ModuleVersionId, ISymUnmanagedReader SymReader, int MethodToken, int LocalSignatureToken, uint ILOffset) state,
MakeAssemblyReferencesKind kind = MakeAssemblyReferencesKind.AllReferences)
{
return CreateMethodContext(
appDomain,
blocks,
state.SymReader,
state.ModuleVersionId,
state.MethodToken,
methodVersion: 1,
state.ILOffset,
state.LocalSignatureToken,
kind);
}
internal static CSharpMetadataContext GetMetadataContext(MetadataContext<CSharpMetadataContext> appDomainContext, Guid mvid = default)
{
var assemblyContexts = appDomainContext.AssemblyContexts;
return assemblyContexts != null && assemblyContexts.TryGetValue(new MetadataContextId(mvid), out CSharpMetadataContext context) ?
context :
default;
}
internal static MetadataContext<CSharpMetadataContext> SetMetadataContext(MetadataContext<CSharpMetadataContext> appDomainContext, Guid mvid, CSharpMetadataContext context)
{
return new MetadataContext<CSharpMetadataContext>(
appDomainContext.MetadataBlocks,
appDomainContext.AssemblyContexts.SetItem(new MetadataContextId(mvid), context));
}
internal static (Guid ModuleVersionId, ISymUnmanagedReader SymReader, int MethodToken, int LocalSignatureToken, uint ILOffset) GetContextState(RuntimeInstance runtime, string methodName)
{
Guid moduleVersionId;
ISymUnmanagedReader symReader;
int methodToken;
int localSignatureToken;
GetContextState(
runtime,
methodName,
out _,
out moduleVersionId,
out symReader,
out methodToken,
out localSignatureToken);
uint ilOffset = ExpressionCompilerTestHelpers.GetOffset(methodToken, symReader);
return (moduleVersionId, symReader, methodToken, localSignatureToken, ilOffset);
}
internal static void GetContextState(
RuntimeInstance runtime,
string methodOrTypeName,
out ImmutableArray<MetadataBlock> blocks,
out Guid moduleVersionId,
out ISymUnmanagedReader symReader,
out int methodOrTypeToken,
out int localSignatureToken)
{
var moduleInstances = runtime.Modules;
blocks = moduleInstances.SelectAsArray(m => m.MetadataBlock);
var compilation = blocks.ToCompilation(default(Guid), MakeAssemblyReferencesKind.AllAssemblies);
var methodOrType = GetMethodOrTypeBySignature(compilation, methodOrTypeName);
var module = (PEModuleSymbol)methodOrType.ContainingModule;
var id = module.Module.GetModuleVersionIdOrThrow();
var moduleInstance = moduleInstances.First(m => m.ModuleVersionId == id);
moduleVersionId = id;
symReader = (ISymUnmanagedReader)moduleInstance.SymReader;
EntityHandle methodOrTypeHandle;
if (methodOrType.Kind == SymbolKind.Method)
{
methodOrTypeHandle = ((PEMethodSymbol)methodOrType).Handle;
localSignatureToken = moduleInstance.GetLocalSignatureToken((MethodDefinitionHandle)methodOrTypeHandle);
}
else
{
methodOrTypeHandle = ((PENamedTypeSymbol)methodOrType).Handle;
localSignatureToken = -1;
}
MetadataReader reader = null; // null should be ok
methodOrTypeToken = reader.GetToken(methodOrTypeHandle);
}
internal static EvaluationContext CreateMethodContext(
RuntimeInstance runtime,
string methodName,
int atLineNumber = -1)
{
ImmutableArray<MetadataBlock> blocks;
Guid moduleVersionId;
ISymUnmanagedReader symReader;
int methodToken;
int localSignatureToken;
GetContextState(runtime, methodName, out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken);
uint ilOffset = ExpressionCompilerTestHelpers.GetOffset(methodToken, symReader, atLineNumber);
return CreateMethodContext(
new AppDomain(),
blocks,
symReader,
moduleVersionId,
methodToken: methodToken,
methodVersion: 1,
ilOffset: ilOffset,
localSignatureToken: localSignatureToken,
kind: MakeAssemblyReferencesKind.AllAssemblies);
}
internal static EvaluationContext CreateTypeContext(
RuntimeInstance runtime,
string typeName)
{
ImmutableArray<MetadataBlock> blocks;
Guid moduleVersionId;
ISymUnmanagedReader symReader;
int typeToken;
int localSignatureToken;
GetContextState(runtime, typeName, out blocks, out moduleVersionId, out symReader, out typeToken, out localSignatureToken);
return CreateTypeContext(
new AppDomain(),
blocks,
moduleVersionId,
typeToken,
kind: MakeAssemblyReferencesKind.AllAssemblies);
}
internal CompilationTestData Evaluate(
string source,
OutputKind outputKind,
string methodName,
string expr,
int atLineNumber = -1,
bool includeSymbols = true)
{
var result = Evaluate(source, outputKind, methodName, expr, out _, out string error, atLineNumber, includeSymbols);
Assert.Null(error);
return result;
}
internal CompilationTestData Evaluate(
CSharpCompilation compilation,
string methodName,
string expr,
int atLineNumber = -1,
bool includeSymbols = true)
{
var result = Evaluate(compilation, methodName, expr, out _, out string error, atLineNumber, includeSymbols);
Assert.Null(error);
return result;
}
internal CompilationTestData Evaluate(
string source,
OutputKind outputKind,
string methodName,
string expr,
out ResultProperties resultProperties,
out string error,
int atLineNumber = -1,
bool includeSymbols = true)
{
var compilation = CreateCompilation(
source,
parseOptions: SyntaxHelpers.ParseOptions,
options: (outputKind == OutputKind.DynamicallyLinkedLibrary) ? TestOptions.DebugDll : TestOptions.DebugExe);
return Evaluate(compilation, methodName, expr, out resultProperties, out error, atLineNumber, includeSymbols);
}
internal CompilationTestData Evaluate(
CSharpCompilation compilation,
string methodName,
string expr,
out ResultProperties resultProperties,
out string error,
int atLineNumber = -1,
bool includeSymbols = true)
{
var runtime = CreateRuntimeInstance(compilation, debugFormat: includeSymbols ? DebugInformationFormat.Pdb : 0);
var context = CreateMethodContext(runtime, methodName, atLineNumber);
var testData = new CompilationTestData();
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
var result = context.CompileExpression(
expr,
DkmEvaluationFlags.TreatAsExpression,
NoAliases,
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData);
Assert.Empty(missingAssemblyIdentities);
return testData;
}
/// <summary>
/// Verify all type parameters from the method
/// are from that method or containing types.
/// </summary>
internal static void VerifyTypeParameters(MethodSymbol method)
{
Assert.True(method.IsContainingSymbolOfAllTypeParameters(method.ReturnType));
AssertEx.All(method.TypeParameters, typeParameter => method.IsContainingSymbolOfAllTypeParameters(typeParameter));
AssertEx.All(method.TypeArgumentsWithAnnotations, typeArgument => method.IsContainingSymbolOfAllTypeParameters(typeArgument.Type));
AssertEx.All(method.Parameters, parameter => method.IsContainingSymbolOfAllTypeParameters(parameter.Type));
VerifyTypeParameters(method.ContainingType);
}
internal static void VerifyLocal(
CompilationTestData testData,
string typeName,
LocalAndMethod localAndMethod,
string expectedMethodName,
string expectedLocalName,
string expectedLocalDisplayName = null,
DkmClrCompilationResultFlags expectedFlags = DkmClrCompilationResultFlags.None,
string expectedILOpt = null,
bool expectedGeneric = false,
[CallerFilePath] string expectedValueSourcePath = null,
[CallerLineNumber] int expectedValueSourceLine = 0)
{
ExpressionCompilerTestHelpers.VerifyLocal<MethodSymbol>(
testData,
typeName,
localAndMethod,
expectedMethodName,
expectedLocalName,
expectedLocalDisplayName ?? expectedLocalName,
expectedFlags,
VerifyTypeParameters,
expectedILOpt,
expectedGeneric,
expectedValueSourcePath,
expectedValueSourceLine);
}
/// <summary>
/// Verify all type parameters from the type
/// are from that type or containing types.
/// </summary>
internal static void VerifyTypeParameters(NamedTypeSymbol type)
{
AssertEx.All(type.TypeParameters, typeParameter => type.IsContainingSymbolOfAllTypeParameters(typeParameter));
AssertEx.All(type.TypeArguments(), typeArgument => type.IsContainingSymbolOfAllTypeParameters(typeArgument));
var container = type.ContainingType;
if ((object)container != null)
{
VerifyTypeParameters(container);
}
}
internal static Symbol GetMethodOrTypeBySignature(Compilation compilation, string signature)
{
string[] parameterTypeNames;
var methodOrTypeName = ExpressionCompilerTestHelpers.GetMethodOrTypeSignatureParts(signature, out parameterTypeNames);
var candidates = compilation.GetMembers(methodOrTypeName);
var methodOrType = (parameterTypeNames == null) ?
candidates.FirstOrDefault() :
candidates.FirstOrDefault(c => parameterTypeNames.SequenceEqual(((MethodSymbol)c).Parameters.Select(p => p.TypeWithAnnotations.Type.Name)));
Assert.False(methodOrType == null, "Could not find method or type with signature '" + signature + "'.");
return methodOrType;
}
internal static Alias VariableAlias(string name, Type type = null)
{
return VariableAlias(name, (type ?? typeof(object)).AssemblyQualifiedName);
}
internal static Alias VariableAlias(string name, string typeAssemblyQualifiedName)
{
return new Alias(DkmClrAliasKind.Variable, name, name, typeAssemblyQualifiedName, default(Guid), null);
}
internal static Alias ObjectIdAlias(uint id, Type type = null)
{
return ObjectIdAlias(id, (type ?? typeof(object)).AssemblyQualifiedName);
}
internal static Alias ObjectIdAlias(uint id, string typeAssemblyQualifiedName)
{
Assert.NotEqual(0u, id); // Not a valid id.
var name = $"${id}";
return new Alias(DkmClrAliasKind.ObjectId, name, name, typeAssemblyQualifiedName, default(Guid), null);
}
internal static Alias ReturnValueAlias(int id = -1, Type type = null)
{
return ReturnValueAlias(id, (type ?? typeof(object)).AssemblyQualifiedName);
}
internal static Alias ReturnValueAlias(int id, string typeAssemblyQualifiedName)
{
var name = $"Method M{(id < 0 ? "" : id.ToString())} returned";
var fullName = id < 0 ? "$ReturnValue" : $"$ReturnValue{id}";
return new Alias(DkmClrAliasKind.ReturnValue, name, fullName, typeAssemblyQualifiedName, default(Guid), null);
}
internal static Alias ExceptionAlias(Type type = null, bool stowed = false)
{
return ExceptionAlias((type ?? typeof(Exception)).AssemblyQualifiedName, stowed);
}
internal static Alias ExceptionAlias(string typeAssemblyQualifiedName, bool stowed = false)
{
var name = "Error";
var fullName = stowed ? "$stowedexception" : "$exception";
var kind = stowed ? DkmClrAliasKind.StowedException : DkmClrAliasKind.Exception;
return new Alias(kind, name, fullName, typeAssemblyQualifiedName, default(Guid), null);
}
internal static Alias Alias(DkmClrAliasKind kind, string name, string fullName, string type, ReadOnlyCollection<byte> payload)
{
return new Alias(kind, name, fullName, type, (payload == null) ? default(Guid) : CustomTypeInfo.PayloadTypeId, payload);
}
internal static MethodDebugInfo<TypeSymbol, LocalSymbol> GetMethodDebugInfo(RuntimeInstance runtime, string qualifiedMethodName, int ilOffset = 0)
{
var peCompilation = runtime.Modules.SelectAsArray(m => m.MetadataBlock).ToCompilation(default(Guid), MakeAssemblyReferencesKind.AllAssemblies);
var peMethod = peCompilation.GlobalNamespace.GetMember<PEMethodSymbol>(qualifiedMethodName);
var peModule = (PEModuleSymbol)peMethod.ContainingModule;
var symReader = runtime.Modules.Single(mi => mi.ModuleVersionId == peModule.Module.GetModuleVersionIdOrThrow()).SymReader;
var symbolProvider = new CSharpEESymbolProvider(peCompilation.SourceAssembly, peModule, peMethod);
return MethodDebugInfo<TypeSymbol, LocalSymbol>.ReadMethodDebugInfo((ISymUnmanagedReader3)symReader, symbolProvider, MetadataTokens.GetToken(peMethod.Handle), methodVersion: 1, ilOffset: ilOffset, isVisualBasicMethod: false);
}
internal static void CheckAttribute(IEnumerable<byte> assembly, MethodSymbol method, AttributeDescription description, bool expected)
{
var module = AssemblyMetadata.CreateFromImage(assembly).GetModules().Single().Module;
var typeName = method.ContainingType.Name;
var typeHandle = module.MetadataReader.TypeDefinitions
.Single(handle => module.GetTypeDefNameOrThrow(handle) == typeName);
var methodName = method.Name;
var methodHandle = module
.GetMethodsOfTypeOrThrow(typeHandle)
.Single(handle => module.GetMethodDefNameOrThrow(handle) == methodName);
var returnParamHandle = module.GetParametersOfMethodOrThrow(methodHandle).FirstOrDefault();
if (returnParamHandle.IsNil)
{
Assert.False(expected);
}
else
{
var attributes = module
.GetCustomAttributesOrThrow(returnParamHandle)
.Where(handle => module.GetTargetAttributeSignatureIndex(handle, description) != -1);
if (expected)
{
Assert.Equal(1, attributes.Count());
}
else
{
Assert.Empty(attributes);
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/VisualStudio/Xaml/Impl/Features/QuickInfo/IXamlQuickInfoService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.QuickInfo
{
internal interface IXamlQuickInfoService : ILanguageService
{
Task<XamlQuickInfo> GetQuickInfoAsync(TextDocument document, int position, CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.QuickInfo
{
internal interface IXamlQuickInfoService : ILanguageService
{
Task<XamlQuickInfo> GetQuickInfoAsync(TextDocument document, int position, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Compilers/VisualBasic/Test/Semantic/Semantics/TypeArgumentInference.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.IO
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.SpecialType
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Public Class TypeArgumentInference
Inherits BasicTestBase
<Fact>
Public Sub Test1()
Dim compilationDef =
<compilation name="TypeArgumentInference1">
<file name="a.vb">
Imports System.Collections.Generic
Module Module1
Sub Main()
M1(1, Nothing)
M2(2S, Nothing)
M3(New Double() {}, Nothing)
M4(New Dictionary(Of Byte, Boolean)(), Nothing, Nothing)
M1(1, y:=Nothing)
M2(2S, y:=Nothing)
M3(New Double() {}, y:=Nothing)
M4(New Dictionary(Of Byte, Boolean)(), y:=Nothing, z:=Nothing)
M1(x:=1, y:=Nothing)
M2(x:=2S, y:=Nothing)
M3(x:=New Double() {}, y:=Nothing)
M4(x:=New Dictionary(Of Byte, Boolean)(), y:=Nothing, z:=Nothing)
M1(y:=Nothing, x:=1)
M2(y:=Nothing, x:=2S)
M3(y:=Nothing, x:=New Double() {})
M4(y:=Nothing, z:=Nothing, x:=New Dictionary(Of Byte, Boolean)())
End Sub
Sub M1(Of T)(x As T, y As T)
System.Console.WriteLine(x.GetType())
End Sub
Sub M2(Of T)(ByRef x As T, y As T)
System.Console.WriteLine(x.GetType())
End Sub
Sub M3(Of T)(x As T(), y As T)
System.Console.WriteLine(x.GetType())
End Sub
Sub M4(Of T, S)(x As Dictionary(Of T, S), y As T, z As S)
System.Console.WriteLine(x.GetType())
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
System.Int32
System.Int16
System.Double[]
System.Collections.Generic.Dictionary`2[System.Byte,System.Boolean]
System.Int32
System.Int16
System.Double[]
System.Collections.Generic.Dictionary`2[System.Byte,System.Boolean]
System.Int32
System.Int16
System.Double[]
System.Collections.Generic.Dictionary`2[System.Byte,System.Boolean]
System.Int32
System.Int16
System.Double[]
System.Collections.Generic.Dictionary`2[System.Byte,System.Boolean]
]]>)
End Sub
<Fact>
Public Sub Test2()
Dim compilationDef =
<compilation name="TypeArgumentInference2">
<file name="a.vb">
Module Module1
Sub Main()
M1(1I)
M1(1.5, 1S, 2I)
M1(New Date() {})
End Sub
Sub M1(Of T)(ParamArray x As T())
System.Console.WriteLine(x.GetType())
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
System.Int32[]
System.Double[]
System.DateTime[]
]]>)
End Sub
<Fact>
Public Sub Test3()
Dim compilationDef =
<compilation name="TypeArgumentInference3">
<file name="a.vb">
Imports System.Collections.Generic
Module Module1
Sub Main()
M1(New Dictionary(Of Byte, Integer)())
Dim x As New Test1(Of Integer)
Dim y As IDerived(Of Long, Byte) = Nothing
x.Goo(y)
End Sub
Sub M1(Of T, S)(x As IDictionary(Of T, S))
System.Console.WriteLine(CObj(x).GetType())
End Sub
End Module
Interface IBase(Of T, S)
End Interface
Interface IDerived(Of T, S)
Inherits IBase(Of T, S)
End Interface
Class Test1(Of T)
Sub Goo(Of S)(x As IBase(Of T, S))
Dim x1 As T = Nothing
Dim x2 As S = Nothing
System.Console.WriteLine(CObj(x1).GetType())
System.Console.WriteLine(CObj(x2).GetType())
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
System.Collections.Generic.Dictionary`2[System.Byte,System.Int32]
System.Int32
System.Byte
]]>)
End Sub
<Fact>
Public Sub Test4()
Dim compilationDef =
<compilation name="TypeArgumentInference3">
<file name="a.vb">
Module Module1
Sub Main()
Dim x As New Test1(Of Integer)
Dim y As IDerived(Of Long, Byte) = Nothing
x.Goo(y)
End Sub
End Module
Class IBase(Of T, S)
End Class
Class IDerived(Of T, S)
Inherits IBase(Of T, S)
End Class
Class Test1(Of T)
Sub Goo(Of S)(x As IBase(Of T, S))
Dim x1 As T = Nothing
Dim x2 As S = Nothing
System.Console.WriteLine(x1.GetType())
System.Console.WriteLine(x2.GetType())
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30311: Value of type 'IDerived(Of Long, Byte)' cannot be converted to 'IBase(Of Integer, Byte)'.
x.Goo(y)
~
</expected>)
End Sub
<Fact>
Public Sub Test5()
Dim compilationDef =
<compilation name="TypeArgumentInference3">
<file name="a.vb">
Option Strict On
Imports System
Module Module1
Sub Main()
Dim x As Integer
x = M1(x)
End Sub
Function M1(Of T As Structure)(x As Nullable(Of T)) As Nullable(Of T)
Return Nothing
End Function
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30512: Option Strict On disallows implicit conversions from 'Integer?' to 'Integer'.
x = M1(x)
~~~~~
</expected>)
End Sub
<Fact>
Public Sub TestLambda1()
Dim compilationDef =
<compilation name="TypeArgumentInferenceLambda1">
<file name="a.vb">
Option Strict Off
Imports System
Module Module1
Sub Main()
M1(Function() Nothing)
M1(Function()
Return Nothing
End Function)
End Sub
Sub M1(Of T)(x As Func(Of T))
System.Console.WriteLine(x.GetType())
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
System.Func`1[System.Object]
System.Func`1[System.Object]
]]>)
End Sub
<Fact>
Public Sub TestLambda2()
Dim compilationDef =
<compilation name="TypeArgumentInferenceLambda2">
<file name="a.vb">
Option Strict Off
Imports System
Module Module1
Sub Main()
Dim o As New Test(Of Byte)
o.M1(Function(i) Nothing, "")
o.M1(Function(i)
Return Nothing
End Function, "")
End Sub
End Module
Class Test(Of U)
Sub M1(Of T, S)(x As Func(Of T, S), y As T)
System.Console.WriteLine(x.GetType())
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
System.Func`2[System.String,System.Object]
System.Func`2[System.String,System.Object]
]]>)
End Sub
<Fact>
Public Sub TestLambda3()
Dim compilationDef =
<compilation name="TypeArgumentInferenceLambda3">
<file name="a.vb">
Option Strict Off
Imports System
Module Module1
Sub Main()
M1(Function(i) 1, 1.5)
M1(Function(i)
If i > 0 Then
Return 1
Else
Return -1L
End If
End Function, 1.5)
M1(Function(i) As SByte
If i > 0 Then
Return 1
Else
Return -1L
End If
End Function, 1.5)
M2(Function(i As Byte) 1)
M2(Function(i As Short)
If i > 0 Then
Return 1
Else
Return -1L
End If
End Function)
End Sub
Sub M1(Of T, S)(x As Func(Of T, S), y As T)
System.Console.WriteLine(x.GetType())
End Sub
Sub M2(Of T, S)(x As Func(Of T, S))
System.Console.WriteLine(x.GetType())
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
System.Func`2[System.Double,System.Int32]
System.Func`2[System.Double,System.Int64]
System.Func`2[System.Double,System.SByte]
System.Func`2[System.Byte,System.Int32]
System.Func`2[System.Int16,System.Int64]
]]>)
End Sub
<Fact(), WorkItem(545209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545209")>
Public Sub TestLambda4()
Dim compilationDef =
<compilation name="TypeArgumentInferenceLambda4">
<file name="a.vb">
Option Strict On
Imports System
Imports System.Collections.Generic
Module M
Sub Goo(Of T)(ParamArray a As Action(Of List(Of T))())
System.Console.WriteLine(GetType(T))
End Sub
Sub Main()
Goo({Sub(x As IList(Of String)) Exit Sub})
Goo(Sub(x As IList(Of String)) Exit Sub)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompilationUtils.AssertNoErrors(compilation)
CompileAndVerify(compilation,
<![CDATA[
System.String
System.String
]]>)
End Sub
<Fact>
Public Sub TestResolutionBasedOnInferenceKind1()
Dim compilationDef =
<compilation name="TestResolutionBasedOnInferenceKind1">
<file name="a.vb">
Option Strict Off
Module Module1
Sub Main()
Dim val As Integer = 0
M1(1, Function(x As Integer) As Integer
Return 2
End Function, 1, val)
End Sub
Sub M1(Of T, U)(x As T, y As System.Func(Of Integer, Integer), z As U, ParamArray v() As Long)
System.Console.WriteLine(1)
End Sub
Sub M1(Of T)(x As Integer, y As System.Func(Of Integer, T), z As Integer, v As Integer)
System.Console.WriteLine(2)
End Sub
'Sub M1(Of T, U)(x As T, y As System.Func(Of Integer, T), z As U, v As Long)
' System.Console.WriteLine(3)
'End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
1
]]>)
End Sub
<Fact>
Public Sub TestResolutionBasedOnInferenceKind2()
Dim compilationDef =
<compilation name="TestResolutionBasedOnInferenceKind2">
<file name="a.vb">
Option Strict Off
Module Module1
Sub Main()
Dim val As Integer = 0
M1(1, Function(x As Integer) As Integer
Return 2
End Function, 1, val)
End Sub
Sub M1(Of T, U)(x As T, y As System.Func(Of Integer, Integer), z As U, ParamArray v() As Long)
System.Console.WriteLine(1)
End Sub
Sub M1(Of T)(x As Integer, y As System.Func(Of Integer, T), z As Integer, v As Integer)
System.Console.WriteLine(2)
End Sub
Sub M1(Of T, U)(x As T, y As System.Func(Of Integer, T), z As U, v As Long)
System.Console.WriteLine(3)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
2
]]>)
End Sub
<Fact>
Public Sub TestResolutionBasedOnInferenceKind3()
Dim compilationDef =
<compilation name="TestResolutionBasedOnInferenceKind3">
<file name="a.vb">
Option Strict Off
Module Module1
Sub Main()
Dim val As Integer = 0
M1(1, Function(x As Integer) As Integer
Return 2
End Function, 1, v:=val)
End Sub
Sub M1(Of T, U)(x As T, y As System.Func(Of Integer, Integer), z As U, v As Long, ParamArray vv() As Long)
System.Console.WriteLine(1)
End Sub
Sub M1(Of T)(x As Integer, y As System.Func(Of Integer, T), z As Integer, v As Integer)
System.Console.WriteLine(2)
End Sub
'Sub M1(Of T, U)(x As T, y As System.Func(Of Integer, T), z As U, v As Long)
' System.Console.WriteLine(3)
'End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
1
]]>)
End Sub
<Fact>
Public Sub TestResolutionBasedOnInferenceKind4()
Dim compilationDef =
<compilation name="TestResolutionBasedOnInferenceKind4">
<file name="a.vb">
Option Strict Off
Module Module1
Sub Main()
Dim val As Integer = 0
M1(1, Function(x As Integer) As Integer
Return 2
End Function, 1, v:=val)
M1(1, Function(x As Integer) As Integer
Return 2
End Function, 1, val)
End Sub
Sub M1(Of T, U)(x As T, y As System.Func(Of Integer, Integer), z As U, v As Long, ParamArray vv() As Long)
System.Console.WriteLine(1)
End Sub
Sub M1(Of T)(x As Integer, y As System.Func(Of Integer, T), z As Integer, v As Integer)
System.Console.WriteLine(2)
End Sub
Sub M1(Of T, U)(x As T, y As System.Func(Of Integer, T), z As U, v As Long)
System.Console.WriteLine(3)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=
"2
2")
End Sub
<Fact>
Public Sub ERRID_UnboundTypeParam2()
Dim compilationDef =
<compilation name="ERRID_UnboundTypeParam2">
<file name="a.vb">
Module GM
Public Function Fred1(Of T1, T2)(P As T1) As T2
Return Fred1(3)
End Function
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC32050: Type parameter 'T2' for 'Public Function Fred1(Of T1, T2)(P As T1) As T2' cannot be inferred.
Return Fred1(3)
~~~~~
</expected>)
End Sub
<Fact>
Public Sub ERRID_UnboundTypeParam1()
Dim compilationDef =
<compilation name="ERRID_UnboundTypeParam1">
<file name="a.vb">
Module GM
Public Function Fred2(Of T2)(P As Object) As T2
Return Fred2(3)
End Function
Public Function Fred2(Of T1, T2)(P As T1) As T2
return Nothing
End Function
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30518: Overload resolution failed because no accessible 'Fred2' can be called with these arguments:
'Public Function Fred2(Of T2)(P As Object) As T2': Type parameter 'T2' cannot be inferred.
'Public Function Fred2(Of T1, T2)(P As T1) As T2': Type parameter 'T2' cannot be inferred.
Return Fred2(3)
~~~~~
</expected>)
End Sub
<Fact>
Public Sub ERRID_TypeInferenceFailureAmbiguous2()
Dim compilationDef =
<compilation name="ERRID_TypeInferenceFailureAmbiguous2">
<file name="a.vb">
Module GM
Public Function barney1(Of T)(p As T, p1 As T) As T
Return barney1(3, "Zip")
End Function
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36651: Data type(s) of the type parameter(s) in method 'Public Function barney1(Of T)(p As T, p1 As T) As T' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error.
Return barney1(3, "Zip")
~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub ERRID_TypeInferenceFailureAmbiguous1()
Dim compilationDef =
<compilation name="ERRID_TypeInferenceFailureAmbiguous1">
<file name="a.vb">
Module GM
Public Function barney2(Of T)(p As T, p1 As T, x As Integer) As T
Return barney2(3, "Zip", 1)
End Function
Public Function barney2(Of T)(p As T, p1 As T, x As UInteger) As T
Return Nothing
End Function
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30518: Overload resolution failed because no accessible 'barney2' can be called with these arguments:
'Public Function barney2(Of T)(p As T, p1 As T, x As Integer) As T': Data type(s) of the type parameter(s) cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error.
'Public Function barney2(Of T)(p As T, p1 As T, x As UInteger) As T': Data type(s) of the type parameter(s) cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error.
Return barney2(3, "Zip", 1)
~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub ERRID_TypeInferenceFailureNoBest2()
Dim compilationDef =
<compilation name="ERRID_TypeInferenceFailureNoBest2">
<file name="a.vb">
Namespace Case1
Class B
End Class
Class C
End Class
Class D
End Class
End Namespace
Namespace Case2
Class B
End Class
Class C
End Class
Class D
End Class
End Namespace
Module Module2
Sub Goo(Of T)(ByVal x As T, ByVal y As T)
End Sub
Sub Main()
Goo(New Case1.B, New Case1.C)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36657: Data type(s) of the type parameter(s) in method 'Public Sub Goo(Of T)(x As T, y As T)' cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.
Goo(New Case1.B, New Case1.C)
~~~
</expected>)
End Sub
<Fact>
Public Sub ERRID_TypeInferenceFailureNoBest1()
Dim compilationDef =
<compilation name="ERRID_TypeInferenceFailureNoBest1">
<file name="a.vb">
Namespace Case1
Class B
End Class
Class C
End Class
Class D
End Class
End Namespace
Namespace Case2
Class B
End Class
Class C
End Class
Class D
End Class
End Namespace
Module Module2
Sub Goo(Of T)(ByVal x As T, ByVal y As T, z As Integer)
End Sub
Sub Goo(Of T)(ByVal x As T, ByVal y As T, z As UInteger)
End Sub
Sub Main()
Goo(New Case1.B, New Case1.C, 1)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30518: Overload resolution failed because no accessible 'Goo' can be called with these arguments:
'Public Sub Goo(Of T)(x As T, y As T, z As Integer)': Data type(s) of the type parameter(s) cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.
'Public Sub Goo(Of T)(x As T, y As T, z As UInteger)': Data type(s) of the type parameter(s) cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.
Goo(New Case1.B, New Case1.C, 1)
~~~
</expected>)
End Sub
<Fact>
Public Sub ERRID_TypeInferenceFailure2()
Dim compilationDef =
<compilation name="ERRID_TypeInferenceFailure2">
<file name="a.vb">
Module Module2
Sub Sub3(Of X, Y)(ByVal p1 As Y, ByVal p2 As X)
End Sub
Sub Main()
Sub3(10, Nothing)
End Sub
End Module </file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36645: Data type(s) of the type parameter(s) in method 'Public Sub Sub3(Of X, Y)(p1 As Y, p2 As X)' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.
Sub3(10, Nothing)
~~~~
</expected>)
End Sub
<Fact>
Public Sub ERRID_TypeInferenceFailure1()
Dim compilationDef =
<compilation name="ERRID_TypeInferenceFailure1">
<file name="a.vb">
Module Module2
Sub Sub3(Of X, Y)(ByVal p1 As Y, ByVal p2 As X, p3 As Integer)
End Sub
Sub Sub3(Of X, Y)(ByVal p1 As Y, ByVal p2 As X, p3 As UInteger)
End Sub
Sub Main()
Sub3(10, Nothing, 1)
End Sub
End Module </file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30518: Overload resolution failed because no accessible 'Sub3' can be called with these arguments:
'Public Sub Sub3(Of X, Y)(p1 As Y, p2 As X, p3 As Integer)': Data type(s) of the type parameter(s) cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.
'Public Sub Sub3(Of X, Y)(p1 As Y, p2 As X, p3 As UInteger)': Data type(s) of the type parameter(s) cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.
Sub3(10, Nothing, 1)
~~~~
</expected>)
End Sub
<Fact>
Public Sub ERRID_StrictDisallowImplicitObjectLambda()
Dim compilationDef =
<compilation name="ERRID_StrictDisallowImplicitObjectLambda">
<file name="a.vb">
Imports System
Module Module2
Sub HandleFuncOfTST(Of T, S)(x As T, del As Func(Of S, T))
End Sub
Sub Main()
HandleFuncOfTST(20, Function(x) CInt(x) + 1000)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.On))
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36642: Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred.
HandleFuncOfTST(20, Function(x) CInt(x) + 1000)
~
</expected>)
compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Off))
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<Fact>
Public Sub InferFromAddressOf1()
Dim compilationDef =
<compilation name="InferFromAddressOf1">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
M1(AddressOf M2, 1)
M3(AddressOf M4)
End Sub
Sub M1(Of T, S)(x As Func(Of T, S), y As T)
System.Console.WriteLine(x.GetType())
End Sub
Function M2(y As Integer) As Double
Return 0
End Function
Sub M3(Of T)(x As Func(Of T))
System.Console.WriteLine(x.GetType())
End Sub
Function M4() As Integer
Return 0
End Function
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
System.Func`2[System.Int32,System.Double]
System.Func`1[System.Int32]
]]>)
End Sub
<Fact>
Public Sub InferFromAddressOf2()
Dim compilationDef =
<compilation name="InferFromAddressOf2">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
M1(AddressOf M2)
M3(AddressOf M4)
End Sub
Sub M1(Of T)(x As Action(Of Integer))
End Sub
Function M2(y As Integer) As Double
Return 0
End Function
Sub M3(Of T)(x As Func(Of T))
End Sub
Sub M4()
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC32050: Type parameter 'T' for 'Public Sub M1(Of T)(x As Action(Of Integer))' cannot be inferred.
M1(AddressOf M2)
~~
BC36645: Data type(s) of the type parameter(s) in method 'Public Sub M3(Of T)(x As Func(Of T))' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.
M3(AddressOf M4)
~~
</expected>)
End Sub
<Fact>
Public Sub InferForAddressOf1()
Dim compilationDef =
<compilation name="InferForAddressOf1">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim x As Func(Of Integer, Double) = AddressOf M1
x.Invoke(1)
End Sub
Function M1(Of T)(y As Integer) As T
System.Console.WriteLine(y)
Return Nothing
End Function
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:="1")
End Sub
<Fact>
Public Sub InferForAddressOf2()
Dim compilationDef =
<compilation name="InferForAddressOf2">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim x As Action(Of Integer) = AddressOf M1
End Sub
Function M1(Of T)(y As Integer) As T
return Nothing
End Function
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36564: Type arguments could not be inferred from the delegate.
Dim x As Action(Of Integer) = AddressOf M1
~~
</expected>)
End Sub
<WorkItem(540950, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540950")>
<Fact>
Public Sub InferForAddressOf3()
Dim source =
<compilation name="InferForAddressOf2">
<file name="a.vb">
Imports System
Module Program
Sub Main()
Dim x As Func(Of Integer, Long) = AddressOf Goo
End Sub
Function Goo(Of T)(x As T) As T
Return Nothing
End Function
End Module
</file>
</compilation>
Dim comp1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Off))
CompilationUtils.AssertNoErrors(comp1)
Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.On))
CompilationUtils.AssertNoErrors(comp2)
End Sub
<WorkItem(540951, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540951")>
<Fact>
Public Sub InferForAddressOf4()
Dim source =
<compilation name="InferForAddressOf2">
<file name="a.vb">
Option Strict Off
Imports System
Imports System.Collections.Generic
Module Program
Sub Main()
Dim x As Func(Of List(Of Integer)) = AddressOf Goo
End Sub
Function Goo(Of T)() As IList(Of T)
Return Nothing
End Function
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<WorkItem(542040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542040")>
<Fact>
Public Sub InferInPresenceOfOverloadsAndSubLambda()
Dim source =
<compilation name="InferForAddressOf2">
<file name="a.vb">
Option Strict Off
Imports System
Imports System.Collections.Generic
Module M1
Sub goo(Of TT, UU, VV)(x As Func(Of TT, UU, VV),
y As Func(Of UU, VV, TT),
z As Func(Of VV, TT, UU))
End Sub
Sub goo(Of TT, UU)(xx As TT,
yy As UU,
zz As Action)
End Sub
Public Sub Test()
goo(1, 2, Sub()
End Sub)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact()>
Public Sub AnonymousDelegates1()
Dim compilationDef =
<compilation name="TypeArgumentInference3">
<file name="a.vb">
Imports System
Class QueryAble(Of T)
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)()
End Function
Public Function Where(Of S)(x As S) As QueryAble(Of T)
System.Console.WriteLine("Where {0}", x)
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q1 As New QueryAble(Of Integer)
Dim q As Object
q = From i In q1 Where i > 0
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'Where' is not accessible in this context.
q = From i In q1 Where i > 0
~~~~~
BC36648: Data type(s) of the type parameter(s) in method 'Public Function Where(Of S)(x As S) As QueryAble(Of Integer)' cannot be inferred from these arguments.
q = From i In q1 Where i > 0
~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AnonymousDelegates2()
Dim compilationDef =
<compilation name="TypeArgumentInference3">
<file name="a.vb">
Imports System
Class QueryAble(Of T)
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)()
End Function
Public Function Where(Of S)(x As S) As QueryAble(Of T)
System.Console.WriteLine("Where {0}", x)
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q1 As New QueryAble(Of Integer)
Dim q As Object
q = q1.Where(Function(x As Long) x)
Dim f = Function(x As Double) x
q = q1.Where(f)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
Where VB$AnonymousDelegate_0`2[System.Int64,System.Int64]
Where VB$AnonymousDelegate_0`2[System.Double,System.Double]
]]>)
End Sub
<Fact()>
Public Sub AnonymousDelegates3()
Dim compilationDef =
<compilation name="TypeArgumentInference3">
<file name="a.vb">
Imports System
Module Module1
Sub Test1(Of T)(x As Func(Of T))
System.Console.WriteLine(x)
End Sub
Sub Test2(Of T)(x As Action(Of T))
System.Console.WriteLine(x)
End Sub
Sub Test3(Of T, S)(x As Func(Of T, S))
System.Console.WriteLine(x)
End Sub
Sub Test4(Of T, S)(x As Func(Of T, S), y As T)
System.Console.WriteLine(x)
End Sub
Sub Main()
Dim d1 = Function() 1
Test1(d1)
Dim d2 = Sub(x As Long) System.Console.WriteLine(x)
Test2(d2)
Dim d3 = Function(x As Double)
System.Console.WriteLine(x)
Return CInt(x)
End Function
Test3(d3)
Test2(d3)
Test4(d1, 2UI)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
System.Func`1[System.Int32]
System.Action`1[System.Int64]
System.Func`2[System.Double,System.Int32]
System.Action`1[System.Double]
System.Func`2[System.UInt32,System.Int32]
]]>)
End Sub
<Fact()>
Public Sub AnonymousDelegates4()
Dim compilationDef =
<compilation name="TypeArgumentInference3">
<file name="a.vb">
Imports System
Module Module1
Sub Test1(Of T)(x As Func(Of T))
System.Console.WriteLine(x)
End Sub
Delegate Sub Dt2(Of T)(ByRef x As T)
Sub Test2(Of T)(x As Dt2(Of T))
System.Console.WriteLine(x)
End Sub
Sub Test3(Of T, S)(x As Func(Of T, S))
System.Console.WriteLine(x)
End Sub
Sub Test4(Of T, S)(x As Func(Of T, S), y As T)
System.Console.WriteLine(x)
End Sub
Sub Main()
Dim d1 = Function() 1
Test3(d1)
Dim d2 = Sub(x As Long) System.Console.WriteLine(x)
Test2(d2)
Dim d3 = Function(x As Double)
System.Console.WriteLine(x)
Return CInt(x)
End Function
Test1(d3)
Test4(d2, 1UI)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36645: Data type(s) of the type parameter(s) in method 'Public Sub Test3(Of T, S)(x As Func(Of T, S))' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.
Test3(d1)
~~~~~
BC36645: Data type(s) of the type parameter(s) in method 'Public Sub Test2(Of T)(x As Module1.Dt2(Of T))' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.
Test2(d2)
~~~~~
BC36645: Data type(s) of the type parameter(s) in method 'Public Sub Test1(Of T)(x As Func(Of T))' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.
Test1(d3)
~~~~~
BC36645: Data type(s) of the type parameter(s) in method 'Public Sub Test4(Of T, S)(x As Func(Of T, S), y As T)' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.
Test4(d2, 1UI)
~~~~~
</expected>)
End Sub
<Fact()>
Public Sub PropertyInByRefContext1()
Dim compilationDef =
<compilation name="TypeArgumentInference3">
<file name="a.vb">
Imports System
Module Module1
Class B1
Public Property B2 As B2
Public Property B4 As B4
End Class
Class B2
Shared Widening Operator CType(x As B2) As B3
Return Nothing
End Operator
'Shared Widening Operator CType(x As B3) As B2
' Return Nothing
'End Operator
End Class
Class B3
End Class
Class B4
Shared Widening Operator CType(x As B4) As B3
Return Nothing
End Operator
End Class
Sub Test(Of T)(ByRef x As T, y As T, z As T)
System.Console.WriteLine(GetType(T))
End Sub
Sub Main()
Dim x As New B1
Dim y As New B3
Test(x.B2, y, x.B4)
Test(Of B3)(x.B2, y, x.B4)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36657: Data type(s) of the type parameter(s) in method 'Public Sub Test(Of T)(ByRef x As T, y As T, z As T)' cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.
Test(x.B2, y, x.B4)
~~~~
BC33037: Cannot copy the value of 'ByRef' parameter 'x' back to the matching argument because type 'Module1.B3' cannot be converted to type 'Module1.B2'.
Test(Of B3)(x.B2, y, x.B4)
~~~~
</expected>)
End Sub
<Fact()>
Public Sub PropertyInByRefContext2()
Dim compilationDef =
<compilation name="TypeArgumentInference3">
<file name="a.vb">
Imports System
Module Module1
Class B1
Public Property B2 As B2
Public Property B4 As B4
End Class
Class B2
Shared Widening Operator CType(x As B2) As B3
Return Nothing
End Operator
Shared Widening Operator CType(x As B3) As B2
Return Nothing
End Operator
End Class
Class B3
End Class
Class B4
Shared Widening Operator CType(x As B4) As B3
Return Nothing
End Operator
End Class
Sub Test(Of T)(ByRef x As T, y As T, z As T)
System.Console.WriteLine(GetType(T))
End Sub
Sub Main()
Dim x As New B1
Dim y As New B3
Test(x.B2, y, x.B4)
Test(Of B3)(x.B2, y, x.B4)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=
<![CDATA[
Module1+B3
Module1+B3
]]>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<Fact()>
Public Sub PropertyInByRefContext2a()
Dim compilationDef =
<compilation name="TypeArgumentInference3">
<file name="a.vb">
Imports System
Module Module1
Class B1
Public readonly Property B2 As B2
Public readonly Property B4 As B4
End Class
Class B2
Shared Widening Operator CType(x As B2) As B3
Return Nothing
End Operator
'Shared Widening Operator CType(x As B3) As B2
' Return Nothing
'End Operator
End Class
Class B3
End Class
Class B4
Shared Widening Operator CType(x As B4) As B3
Return Nothing
End Operator
End Class
Sub Test(Of T)(ByRef x As T, y As T, z As T)
System.Console.WriteLine(GetType(T))
End Sub
Sub Main()
Dim x As New B1
Dim y As New B3
Test(x.B2, y, x.B4)
Test(Of B3)(x.B2, y, x.B4)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=
<![CDATA[
Module1+B3
Module1+B3
]]>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<Fact()>
Public Sub PropertyInByRefContext2b()
Dim compilationDef =
<compilation name="TypeArgumentInference3">
<file name="a.vb">
Imports System
Module Module1
Class B1
Public readonly Property B2 As B2
Public readonly Property B4 As B4
public sub new
Dim y As New B3
Test(me.B2, y, me.B4)
Test(Of B3)(me.B2, y, me.B4)
end sub
End Class
Class B2
Shared Widening Operator CType(x As B2) As B3
Return Nothing
End Operator
'Shared Widening Operator CType(x As B3) As B2
' Return Nothing
'End Operator
End Class
Class B3
End Class
Class B4
Shared Widening Operator CType(x As B4) As B3
Return Nothing
End Operator
End Class
Sub Test(Of T)(ByRef x As T, y As T, z As T)
System.Console.WriteLine(GetType(T))
End Sub
Sub Main()
dim o as new B1
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36657: Data type(s) of the type parameter(s) in method 'Public Sub Test(Of T)(ByRef x As T, y As T, z As T)' cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.
Test(me.B2, y, me.B4)
~~~~
BC33037: Cannot copy the value of 'ByRef' parameter 'x' back to the matching argument because type 'Module1.B3' cannot be converted to type 'Module1.B2'.
Test(Of B3)(me.B2, y, me.B4)
~~~~~
</expected>)
End Sub
<Fact, WorkItem(545092, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545092")>
Public Sub Bug13357()
Dim compilationDef =
<compilation name="TypeArgumentInference1">
<file name="a.vb">
Imports System
Module Module1
Sub Main(args As String())
Test(New MethodCompiler, New NamespaceSymbol, New SyntaxTree)
End Sub
Sub Test(compiler As MethodCompiler, root As NamespaceSymbol, tree As SyntaxTree)
root.Accept(compiler, Function(sym) sym Is root OrElse sym.IsDefinedInSourceTree(tree))
root.Accept(compiler, Function(sym) sym Is root)
End Sub
End Module
Friend MustInherit Class SymbolVisitor(Of TArgument, TResult)
End Class
Class SyntaxTree
End Class
Class Symbol
Friend Overridable Function IsDefinedInSourceTree(tree As SyntaxTree) As Boolean
Return False
End Function
End Class
Class NamespaceSymbol
Inherits Symbol
Friend Function Accept(Of TArgument, TResult)(visitor As SymbolVisitor(Of TArgument, TResult), arg As TArgument) As TResult
System.Console.WriteLine(GetType(TArgument))
System.Console.WriteLine(GetType(TResult))
Return Nothing
End Function
End Class
Friend Class MethodCompiler
Inherits SymbolVisitor(Of Predicate(Of Symbol), Boolean)
End Class </file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
System.Predicate`1[Symbol]
System.Boolean
System.Predicate`1[Symbol]
System.Boolean
]]>)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.TestExecutionNeedsWindowsTypes)>
Public Sub Regress14477()
Dim compilationDef =
<compilation name="Regress14477">
<file name="a.vb">
Option Strict Off
Imports System
Imports System.Diagnostics
Imports System.Reflection
Imports System.Collections.Generic
Module Module1
Sub Main()
Dim x As Object = New List(Of Integer)
Try
fun(x)
Catch e As Exception
Console.WriteLine(e)
End Try
End Sub
Sub fun(Of X)(ByVal a As List(Of X))
Console.WriteLine("X: " & GetType(X).FullName)
Dim lateBound As Boolean = False
For Each frame As StackFrame In New StackTrace().GetFrames()
If (frame.GetMethod().Name = "Invoke") Then
lateBound = True
End If
Next
If (lateBound) Then
Console.WriteLine("LATE BOUND")
Else
Console.WriteLine("NOT latebound")
End If
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
X: System.Int32
LATE BOUND
]]>)
End Sub
<Fact, WorkItem(545812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545812")>
Public Sub Bug14478()
Dim compilationDef =
<compilation name="TypeArgumentInference2">
<file name="a.vb">
Option Strict On
Imports System
Public Module Test
Delegate Function Func(Of T)() As T
Delegate Function Func(Of A0, T)(arg0 As A0) As T
Public Sub Main()
TestNormal()
End Sub
Sub TestNormal()
f5(AddressOf t5)
End Sub
'-----------------------------------
Sub f5(Of T)(a1 As Func(Of Integer, T))
Console.WriteLine("f5 - T: (" + GetType(T).FullName + ")")
End Sub
' useless to infer on
Function t5(Of S)(a1 As Integer) As S
Return Nothing
End Function
' useful to infer on
Function t5(Of S)(a1 As S) As S
Return Nothing
End Function
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
f5 - T: (System.Int32)
]]>)
End Sub
<Fact, WorkItem(545812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545812")>
Public Sub Bug14478_2()
Dim compilationDef =
<compilation name="TypeArgumentInference2">
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Module Module1
Sub Scen2(Of R As S, S)(ByVal x As R, ByVal y As S)
Dim w As Func(Of R, R) = AddressOf Scen2(Of R)
Gen1A(y, x, w)
End Sub
Sub Gen1A(Of T, U)(ByVal x As T, ByVal y As U, ByVal z As Func(Of T, U))
Console.WriteLine("Gen1A: " & GetType(T).FullName & " - " & GetType(U).FullName)
z(x)
End Sub
Function Scen2(Of K)(ByVal x As K) As K
Console.WriteLine("scen2: " & GetType(K).FullName)
End Function
Sub Main()
Scen2(New CB(), CType(New CB(), CA))
End Sub
End Module
Class CA
End Class
Class CB : Inherits CA
End Class
]]></file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
Gen1A: CB - CB
scen2: CB
]]>)
End Sub
<Fact, WorkItem(629539, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/629539")>
Public Sub Bug629539()
Dim compilationDef =
<compilation>
<file name="a.vb"><![CDATA[
Imports System.Collections.Generic
Imports System.Linq
Class SnapshotSpan
Public Property Length As Integer
Public Property Text As String
Public Function CreateTrackingSpan() As ITrackingSpan
Return Nothing
End Function
End Class
Public Interface ITrackingSpan
End Interface
Module Program
Sub Main()
Dim sourceSpans = New List(Of SnapshotSpan)().AsReadOnly()
Dim replacementSpans = sourceSpans.Select(Function(ss)
If ss.Length = 2 Then
Return ss.Text
Else
Return ss.CreateTrackingSpan()
End If
End Function).ToList()
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilationDef, {SystemCoreRef}, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom))
CompileAndVerify(compilation)
AssertTheseDiagnostics(compilation,
<expected>
BC42021: Cannot infer a return type because more than one type is possible; 'Object' assumed.
Dim replacementSpans = sourceSpans.Select(Function(ss)
~~~~~~~~~~~~
</expected>)
compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On))
AssertTheseDiagnostics(compilation,
<expected>
BC36734: Cannot infer a return type because more than one type is possible. Consider adding an 'As' clause to specify the return type.
Dim replacementSpans = sourceSpans.Select(Function(ss)
~~~~~~~~~~~~
</expected>)
End Sub
<Fact, WorkItem(811902, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/811902")>
Public Sub Bug811902()
Dim compilationDef =
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module Module1
Sub Baz(a As Action)
End Sub
Sub Baz(Of T)(a As Func(Of T))
End Sub
Sub Goo(ByRef a As Integer)
Baz(Sub()
Console.WriteLine(a)
End Sub)
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
AssertTheseDiagnostics(compilation,
<expected>
BC36639: 'ByRef' parameter 'a' cannot be used in a lambda expression.
Console.WriteLine(a)
~
</expected>)
End Sub
<Fact>
<WorkItem(22329, "https://github.com/dotnet/roslyn/issues/22329")>
Public Sub ShapeMismatchInOneArgument_01()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class C3
Shared Sub Main()
Test2(Nullable(New VT(Of Integer, Integer)()), New VT(Of Integer, Integer)())
Test2(New VT(Of Integer, Integer)(), Nullable(New VT(Of Integer, Integer)()))
End Sub
Shared Function Nullable(Of T As Structure)(x As T) As T?
Return x
End Function
Shared Sub Test2(Of T, U)(x As VT(Of T, U), y As VT(Of T, U))
System.Console.Write(1)
End Sub
Public Structure VT(Of T, S)
End Structure
End Class
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC36645: Data type(s) of the type parameter(s) in method 'Public Shared Sub Test2(Of T, U)(x As C3.VT(Of T, U), y As C3.VT(Of T, U))' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.
Test2(Nullable(New VT(Of Integer, Integer)()), New VT(Of Integer, Integer)())
~~~~~
BC36645: Data type(s) of the type parameter(s) in method 'Public Shared Sub Test2(Of T, U)(x As C3.VT(Of T, U), y As C3.VT(Of T, U))' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.
Test2(New VT(Of Integer, Integer)(), Nullable(New VT(Of Integer, Integer)()))
~~~~~
</expected>)
End Sub
<Fact>
<WorkItem(22329, "https://github.com/dotnet/roslyn/issues/22329")>
Public Sub ShapeMismatchInOneArgument_02()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Public Class C3
Shared Sub Main()
Test2(Nullable(New VT(Of Integer, Integer)()), New VT(Of Integer, Integer)())
Test2(New VT(Of Integer, Integer)(), Nullable(New VT(Of Integer, Integer)()))
End Sub
Shared Function Nullable(Of T As Structure)(x As T) As T?
Return x
End Function
Shared Sub Test2(Of T)(x As T, y As T)
System.Console.Write(1)
End Sub
Public Structure VT(Of T, S)
End Structure
End Class
</file>
</compilation>, expectedOutput:=<![CDATA[
11
]]>)
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.IO
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.SpecialType
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Public Class TypeArgumentInference
Inherits BasicTestBase
<Fact>
Public Sub Test1()
Dim compilationDef =
<compilation name="TypeArgumentInference1">
<file name="a.vb">
Imports System.Collections.Generic
Module Module1
Sub Main()
M1(1, Nothing)
M2(2S, Nothing)
M3(New Double() {}, Nothing)
M4(New Dictionary(Of Byte, Boolean)(), Nothing, Nothing)
M1(1, y:=Nothing)
M2(2S, y:=Nothing)
M3(New Double() {}, y:=Nothing)
M4(New Dictionary(Of Byte, Boolean)(), y:=Nothing, z:=Nothing)
M1(x:=1, y:=Nothing)
M2(x:=2S, y:=Nothing)
M3(x:=New Double() {}, y:=Nothing)
M4(x:=New Dictionary(Of Byte, Boolean)(), y:=Nothing, z:=Nothing)
M1(y:=Nothing, x:=1)
M2(y:=Nothing, x:=2S)
M3(y:=Nothing, x:=New Double() {})
M4(y:=Nothing, z:=Nothing, x:=New Dictionary(Of Byte, Boolean)())
End Sub
Sub M1(Of T)(x As T, y As T)
System.Console.WriteLine(x.GetType())
End Sub
Sub M2(Of T)(ByRef x As T, y As T)
System.Console.WriteLine(x.GetType())
End Sub
Sub M3(Of T)(x As T(), y As T)
System.Console.WriteLine(x.GetType())
End Sub
Sub M4(Of T, S)(x As Dictionary(Of T, S), y As T, z As S)
System.Console.WriteLine(x.GetType())
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
System.Int32
System.Int16
System.Double[]
System.Collections.Generic.Dictionary`2[System.Byte,System.Boolean]
System.Int32
System.Int16
System.Double[]
System.Collections.Generic.Dictionary`2[System.Byte,System.Boolean]
System.Int32
System.Int16
System.Double[]
System.Collections.Generic.Dictionary`2[System.Byte,System.Boolean]
System.Int32
System.Int16
System.Double[]
System.Collections.Generic.Dictionary`2[System.Byte,System.Boolean]
]]>)
End Sub
<Fact>
Public Sub Test2()
Dim compilationDef =
<compilation name="TypeArgumentInference2">
<file name="a.vb">
Module Module1
Sub Main()
M1(1I)
M1(1.5, 1S, 2I)
M1(New Date() {})
End Sub
Sub M1(Of T)(ParamArray x As T())
System.Console.WriteLine(x.GetType())
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
System.Int32[]
System.Double[]
System.DateTime[]
]]>)
End Sub
<Fact>
Public Sub Test3()
Dim compilationDef =
<compilation name="TypeArgumentInference3">
<file name="a.vb">
Imports System.Collections.Generic
Module Module1
Sub Main()
M1(New Dictionary(Of Byte, Integer)())
Dim x As New Test1(Of Integer)
Dim y As IDerived(Of Long, Byte) = Nothing
x.Goo(y)
End Sub
Sub M1(Of T, S)(x As IDictionary(Of T, S))
System.Console.WriteLine(CObj(x).GetType())
End Sub
End Module
Interface IBase(Of T, S)
End Interface
Interface IDerived(Of T, S)
Inherits IBase(Of T, S)
End Interface
Class Test1(Of T)
Sub Goo(Of S)(x As IBase(Of T, S))
Dim x1 As T = Nothing
Dim x2 As S = Nothing
System.Console.WriteLine(CObj(x1).GetType())
System.Console.WriteLine(CObj(x2).GetType())
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
System.Collections.Generic.Dictionary`2[System.Byte,System.Int32]
System.Int32
System.Byte
]]>)
End Sub
<Fact>
Public Sub Test4()
Dim compilationDef =
<compilation name="TypeArgumentInference3">
<file name="a.vb">
Module Module1
Sub Main()
Dim x As New Test1(Of Integer)
Dim y As IDerived(Of Long, Byte) = Nothing
x.Goo(y)
End Sub
End Module
Class IBase(Of T, S)
End Class
Class IDerived(Of T, S)
Inherits IBase(Of T, S)
End Class
Class Test1(Of T)
Sub Goo(Of S)(x As IBase(Of T, S))
Dim x1 As T = Nothing
Dim x2 As S = Nothing
System.Console.WriteLine(x1.GetType())
System.Console.WriteLine(x2.GetType())
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30311: Value of type 'IDerived(Of Long, Byte)' cannot be converted to 'IBase(Of Integer, Byte)'.
x.Goo(y)
~
</expected>)
End Sub
<Fact>
Public Sub Test5()
Dim compilationDef =
<compilation name="TypeArgumentInference3">
<file name="a.vb">
Option Strict On
Imports System
Module Module1
Sub Main()
Dim x As Integer
x = M1(x)
End Sub
Function M1(Of T As Structure)(x As Nullable(Of T)) As Nullable(Of T)
Return Nothing
End Function
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30512: Option Strict On disallows implicit conversions from 'Integer?' to 'Integer'.
x = M1(x)
~~~~~
</expected>)
End Sub
<Fact>
Public Sub TestLambda1()
Dim compilationDef =
<compilation name="TypeArgumentInferenceLambda1">
<file name="a.vb">
Option Strict Off
Imports System
Module Module1
Sub Main()
M1(Function() Nothing)
M1(Function()
Return Nothing
End Function)
End Sub
Sub M1(Of T)(x As Func(Of T))
System.Console.WriteLine(x.GetType())
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
System.Func`1[System.Object]
System.Func`1[System.Object]
]]>)
End Sub
<Fact>
Public Sub TestLambda2()
Dim compilationDef =
<compilation name="TypeArgumentInferenceLambda2">
<file name="a.vb">
Option Strict Off
Imports System
Module Module1
Sub Main()
Dim o As New Test(Of Byte)
o.M1(Function(i) Nothing, "")
o.M1(Function(i)
Return Nothing
End Function, "")
End Sub
End Module
Class Test(Of U)
Sub M1(Of T, S)(x As Func(Of T, S), y As T)
System.Console.WriteLine(x.GetType())
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
System.Func`2[System.String,System.Object]
System.Func`2[System.String,System.Object]
]]>)
End Sub
<Fact>
Public Sub TestLambda3()
Dim compilationDef =
<compilation name="TypeArgumentInferenceLambda3">
<file name="a.vb">
Option Strict Off
Imports System
Module Module1
Sub Main()
M1(Function(i) 1, 1.5)
M1(Function(i)
If i > 0 Then
Return 1
Else
Return -1L
End If
End Function, 1.5)
M1(Function(i) As SByte
If i > 0 Then
Return 1
Else
Return -1L
End If
End Function, 1.5)
M2(Function(i As Byte) 1)
M2(Function(i As Short)
If i > 0 Then
Return 1
Else
Return -1L
End If
End Function)
End Sub
Sub M1(Of T, S)(x As Func(Of T, S), y As T)
System.Console.WriteLine(x.GetType())
End Sub
Sub M2(Of T, S)(x As Func(Of T, S))
System.Console.WriteLine(x.GetType())
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
System.Func`2[System.Double,System.Int32]
System.Func`2[System.Double,System.Int64]
System.Func`2[System.Double,System.SByte]
System.Func`2[System.Byte,System.Int32]
System.Func`2[System.Int16,System.Int64]
]]>)
End Sub
<Fact(), WorkItem(545209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545209")>
Public Sub TestLambda4()
Dim compilationDef =
<compilation name="TypeArgumentInferenceLambda4">
<file name="a.vb">
Option Strict On
Imports System
Imports System.Collections.Generic
Module M
Sub Goo(Of T)(ParamArray a As Action(Of List(Of T))())
System.Console.WriteLine(GetType(T))
End Sub
Sub Main()
Goo({Sub(x As IList(Of String)) Exit Sub})
Goo(Sub(x As IList(Of String)) Exit Sub)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompilationUtils.AssertNoErrors(compilation)
CompileAndVerify(compilation,
<![CDATA[
System.String
System.String
]]>)
End Sub
<Fact>
Public Sub TestResolutionBasedOnInferenceKind1()
Dim compilationDef =
<compilation name="TestResolutionBasedOnInferenceKind1">
<file name="a.vb">
Option Strict Off
Module Module1
Sub Main()
Dim val As Integer = 0
M1(1, Function(x As Integer) As Integer
Return 2
End Function, 1, val)
End Sub
Sub M1(Of T, U)(x As T, y As System.Func(Of Integer, Integer), z As U, ParamArray v() As Long)
System.Console.WriteLine(1)
End Sub
Sub M1(Of T)(x As Integer, y As System.Func(Of Integer, T), z As Integer, v As Integer)
System.Console.WriteLine(2)
End Sub
'Sub M1(Of T, U)(x As T, y As System.Func(Of Integer, T), z As U, v As Long)
' System.Console.WriteLine(3)
'End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
1
]]>)
End Sub
<Fact>
Public Sub TestResolutionBasedOnInferenceKind2()
Dim compilationDef =
<compilation name="TestResolutionBasedOnInferenceKind2">
<file name="a.vb">
Option Strict Off
Module Module1
Sub Main()
Dim val As Integer = 0
M1(1, Function(x As Integer) As Integer
Return 2
End Function, 1, val)
End Sub
Sub M1(Of T, U)(x As T, y As System.Func(Of Integer, Integer), z As U, ParamArray v() As Long)
System.Console.WriteLine(1)
End Sub
Sub M1(Of T)(x As Integer, y As System.Func(Of Integer, T), z As Integer, v As Integer)
System.Console.WriteLine(2)
End Sub
Sub M1(Of T, U)(x As T, y As System.Func(Of Integer, T), z As U, v As Long)
System.Console.WriteLine(3)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
2
]]>)
End Sub
<Fact>
Public Sub TestResolutionBasedOnInferenceKind3()
Dim compilationDef =
<compilation name="TestResolutionBasedOnInferenceKind3">
<file name="a.vb">
Option Strict Off
Module Module1
Sub Main()
Dim val As Integer = 0
M1(1, Function(x As Integer) As Integer
Return 2
End Function, 1, v:=val)
End Sub
Sub M1(Of T, U)(x As T, y As System.Func(Of Integer, Integer), z As U, v As Long, ParamArray vv() As Long)
System.Console.WriteLine(1)
End Sub
Sub M1(Of T)(x As Integer, y As System.Func(Of Integer, T), z As Integer, v As Integer)
System.Console.WriteLine(2)
End Sub
'Sub M1(Of T, U)(x As T, y As System.Func(Of Integer, T), z As U, v As Long)
' System.Console.WriteLine(3)
'End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
1
]]>)
End Sub
<Fact>
Public Sub TestResolutionBasedOnInferenceKind4()
Dim compilationDef =
<compilation name="TestResolutionBasedOnInferenceKind4">
<file name="a.vb">
Option Strict Off
Module Module1
Sub Main()
Dim val As Integer = 0
M1(1, Function(x As Integer) As Integer
Return 2
End Function, 1, v:=val)
M1(1, Function(x As Integer) As Integer
Return 2
End Function, 1, val)
End Sub
Sub M1(Of T, U)(x As T, y As System.Func(Of Integer, Integer), z As U, v As Long, ParamArray vv() As Long)
System.Console.WriteLine(1)
End Sub
Sub M1(Of T)(x As Integer, y As System.Func(Of Integer, T), z As Integer, v As Integer)
System.Console.WriteLine(2)
End Sub
Sub M1(Of T, U)(x As T, y As System.Func(Of Integer, T), z As U, v As Long)
System.Console.WriteLine(3)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=
"2
2")
End Sub
<Fact>
Public Sub ERRID_UnboundTypeParam2()
Dim compilationDef =
<compilation name="ERRID_UnboundTypeParam2">
<file name="a.vb">
Module GM
Public Function Fred1(Of T1, T2)(P As T1) As T2
Return Fred1(3)
End Function
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC32050: Type parameter 'T2' for 'Public Function Fred1(Of T1, T2)(P As T1) As T2' cannot be inferred.
Return Fred1(3)
~~~~~
</expected>)
End Sub
<Fact>
Public Sub ERRID_UnboundTypeParam1()
Dim compilationDef =
<compilation name="ERRID_UnboundTypeParam1">
<file name="a.vb">
Module GM
Public Function Fred2(Of T2)(P As Object) As T2
Return Fred2(3)
End Function
Public Function Fred2(Of T1, T2)(P As T1) As T2
return Nothing
End Function
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30518: Overload resolution failed because no accessible 'Fred2' can be called with these arguments:
'Public Function Fred2(Of T2)(P As Object) As T2': Type parameter 'T2' cannot be inferred.
'Public Function Fred2(Of T1, T2)(P As T1) As T2': Type parameter 'T2' cannot be inferred.
Return Fred2(3)
~~~~~
</expected>)
End Sub
<Fact>
Public Sub ERRID_TypeInferenceFailureAmbiguous2()
Dim compilationDef =
<compilation name="ERRID_TypeInferenceFailureAmbiguous2">
<file name="a.vb">
Module GM
Public Function barney1(Of T)(p As T, p1 As T) As T
Return barney1(3, "Zip")
End Function
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36651: Data type(s) of the type parameter(s) in method 'Public Function barney1(Of T)(p As T, p1 As T) As T' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error.
Return barney1(3, "Zip")
~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub ERRID_TypeInferenceFailureAmbiguous1()
Dim compilationDef =
<compilation name="ERRID_TypeInferenceFailureAmbiguous1">
<file name="a.vb">
Module GM
Public Function barney2(Of T)(p As T, p1 As T, x As Integer) As T
Return barney2(3, "Zip", 1)
End Function
Public Function barney2(Of T)(p As T, p1 As T, x As UInteger) As T
Return Nothing
End Function
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30518: Overload resolution failed because no accessible 'barney2' can be called with these arguments:
'Public Function barney2(Of T)(p As T, p1 As T, x As Integer) As T': Data type(s) of the type parameter(s) cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error.
'Public Function barney2(Of T)(p As T, p1 As T, x As UInteger) As T': Data type(s) of the type parameter(s) cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error.
Return barney2(3, "Zip", 1)
~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub ERRID_TypeInferenceFailureNoBest2()
Dim compilationDef =
<compilation name="ERRID_TypeInferenceFailureNoBest2">
<file name="a.vb">
Namespace Case1
Class B
End Class
Class C
End Class
Class D
End Class
End Namespace
Namespace Case2
Class B
End Class
Class C
End Class
Class D
End Class
End Namespace
Module Module2
Sub Goo(Of T)(ByVal x As T, ByVal y As T)
End Sub
Sub Main()
Goo(New Case1.B, New Case1.C)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36657: Data type(s) of the type parameter(s) in method 'Public Sub Goo(Of T)(x As T, y As T)' cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.
Goo(New Case1.B, New Case1.C)
~~~
</expected>)
End Sub
<Fact>
Public Sub ERRID_TypeInferenceFailureNoBest1()
Dim compilationDef =
<compilation name="ERRID_TypeInferenceFailureNoBest1">
<file name="a.vb">
Namespace Case1
Class B
End Class
Class C
End Class
Class D
End Class
End Namespace
Namespace Case2
Class B
End Class
Class C
End Class
Class D
End Class
End Namespace
Module Module2
Sub Goo(Of T)(ByVal x As T, ByVal y As T, z As Integer)
End Sub
Sub Goo(Of T)(ByVal x As T, ByVal y As T, z As UInteger)
End Sub
Sub Main()
Goo(New Case1.B, New Case1.C, 1)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30518: Overload resolution failed because no accessible 'Goo' can be called with these arguments:
'Public Sub Goo(Of T)(x As T, y As T, z As Integer)': Data type(s) of the type parameter(s) cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.
'Public Sub Goo(Of T)(x As T, y As T, z As UInteger)': Data type(s) of the type parameter(s) cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.
Goo(New Case1.B, New Case1.C, 1)
~~~
</expected>)
End Sub
<Fact>
Public Sub ERRID_TypeInferenceFailure2()
Dim compilationDef =
<compilation name="ERRID_TypeInferenceFailure2">
<file name="a.vb">
Module Module2
Sub Sub3(Of X, Y)(ByVal p1 As Y, ByVal p2 As X)
End Sub
Sub Main()
Sub3(10, Nothing)
End Sub
End Module </file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36645: Data type(s) of the type parameter(s) in method 'Public Sub Sub3(Of X, Y)(p1 As Y, p2 As X)' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.
Sub3(10, Nothing)
~~~~
</expected>)
End Sub
<Fact>
Public Sub ERRID_TypeInferenceFailure1()
Dim compilationDef =
<compilation name="ERRID_TypeInferenceFailure1">
<file name="a.vb">
Module Module2
Sub Sub3(Of X, Y)(ByVal p1 As Y, ByVal p2 As X, p3 As Integer)
End Sub
Sub Sub3(Of X, Y)(ByVal p1 As Y, ByVal p2 As X, p3 As UInteger)
End Sub
Sub Main()
Sub3(10, Nothing, 1)
End Sub
End Module </file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30518: Overload resolution failed because no accessible 'Sub3' can be called with these arguments:
'Public Sub Sub3(Of X, Y)(p1 As Y, p2 As X, p3 As Integer)': Data type(s) of the type parameter(s) cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.
'Public Sub Sub3(Of X, Y)(p1 As Y, p2 As X, p3 As UInteger)': Data type(s) of the type parameter(s) cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.
Sub3(10, Nothing, 1)
~~~~
</expected>)
End Sub
<Fact>
Public Sub ERRID_StrictDisallowImplicitObjectLambda()
Dim compilationDef =
<compilation name="ERRID_StrictDisallowImplicitObjectLambda">
<file name="a.vb">
Imports System
Module Module2
Sub HandleFuncOfTST(Of T, S)(x As T, del As Func(Of S, T))
End Sub
Sub Main()
HandleFuncOfTST(20, Function(x) CInt(x) + 1000)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.On))
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36642: Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred.
HandleFuncOfTST(20, Function(x) CInt(x) + 1000)
~
</expected>)
compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Off))
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<Fact>
Public Sub InferFromAddressOf1()
Dim compilationDef =
<compilation name="InferFromAddressOf1">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
M1(AddressOf M2, 1)
M3(AddressOf M4)
End Sub
Sub M1(Of T, S)(x As Func(Of T, S), y As T)
System.Console.WriteLine(x.GetType())
End Sub
Function M2(y As Integer) As Double
Return 0
End Function
Sub M3(Of T)(x As Func(Of T))
System.Console.WriteLine(x.GetType())
End Sub
Function M4() As Integer
Return 0
End Function
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
System.Func`2[System.Int32,System.Double]
System.Func`1[System.Int32]
]]>)
End Sub
<Fact>
Public Sub InferFromAddressOf2()
Dim compilationDef =
<compilation name="InferFromAddressOf2">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
M1(AddressOf M2)
M3(AddressOf M4)
End Sub
Sub M1(Of T)(x As Action(Of Integer))
End Sub
Function M2(y As Integer) As Double
Return 0
End Function
Sub M3(Of T)(x As Func(Of T))
End Sub
Sub M4()
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC32050: Type parameter 'T' for 'Public Sub M1(Of T)(x As Action(Of Integer))' cannot be inferred.
M1(AddressOf M2)
~~
BC36645: Data type(s) of the type parameter(s) in method 'Public Sub M3(Of T)(x As Func(Of T))' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.
M3(AddressOf M4)
~~
</expected>)
End Sub
<Fact>
Public Sub InferForAddressOf1()
Dim compilationDef =
<compilation name="InferForAddressOf1">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim x As Func(Of Integer, Double) = AddressOf M1
x.Invoke(1)
End Sub
Function M1(Of T)(y As Integer) As T
System.Console.WriteLine(y)
Return Nothing
End Function
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:="1")
End Sub
<Fact>
Public Sub InferForAddressOf2()
Dim compilationDef =
<compilation name="InferForAddressOf2">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim x As Action(Of Integer) = AddressOf M1
End Sub
Function M1(Of T)(y As Integer) As T
return Nothing
End Function
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36564: Type arguments could not be inferred from the delegate.
Dim x As Action(Of Integer) = AddressOf M1
~~
</expected>)
End Sub
<WorkItem(540950, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540950")>
<Fact>
Public Sub InferForAddressOf3()
Dim source =
<compilation name="InferForAddressOf2">
<file name="a.vb">
Imports System
Module Program
Sub Main()
Dim x As Func(Of Integer, Long) = AddressOf Goo
End Sub
Function Goo(Of T)(x As T) As T
Return Nothing
End Function
End Module
</file>
</compilation>
Dim comp1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Off))
CompilationUtils.AssertNoErrors(comp1)
Dim comp2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.On))
CompilationUtils.AssertNoErrors(comp2)
End Sub
<WorkItem(540951, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540951")>
<Fact>
Public Sub InferForAddressOf4()
Dim source =
<compilation name="InferForAddressOf2">
<file name="a.vb">
Option Strict Off
Imports System
Imports System.Collections.Generic
Module Program
Sub Main()
Dim x As Func(Of List(Of Integer)) = AddressOf Goo
End Sub
Function Goo(Of T)() As IList(Of T)
Return Nothing
End Function
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<WorkItem(542040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542040")>
<Fact>
Public Sub InferInPresenceOfOverloadsAndSubLambda()
Dim source =
<compilation name="InferForAddressOf2">
<file name="a.vb">
Option Strict Off
Imports System
Imports System.Collections.Generic
Module M1
Sub goo(Of TT, UU, VV)(x As Func(Of TT, UU, VV),
y As Func(Of UU, VV, TT),
z As Func(Of VV, TT, UU))
End Sub
Sub goo(Of TT, UU)(xx As TT,
yy As UU,
zz As Action)
End Sub
Public Sub Test()
goo(1, 2, Sub()
End Sub)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact()>
Public Sub AnonymousDelegates1()
Dim compilationDef =
<compilation name="TypeArgumentInference3">
<file name="a.vb">
Imports System
Class QueryAble(Of T)
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)()
End Function
Public Function Where(Of S)(x As S) As QueryAble(Of T)
System.Console.WriteLine("Where {0}", x)
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q1 As New QueryAble(Of Integer)
Dim q As Object
q = From i In q1 Where i > 0
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36594: Definition of method 'Where' is not accessible in this context.
q = From i In q1 Where i > 0
~~~~~
BC36648: Data type(s) of the type parameter(s) in method 'Public Function Where(Of S)(x As S) As QueryAble(Of Integer)' cannot be inferred from these arguments.
q = From i In q1 Where i > 0
~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AnonymousDelegates2()
Dim compilationDef =
<compilation name="TypeArgumentInference3">
<file name="a.vb">
Imports System
Class QueryAble(Of T)
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)()
End Function
Public Function Where(Of S)(x As S) As QueryAble(Of T)
System.Console.WriteLine("Where {0}", x)
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q1 As New QueryAble(Of Integer)
Dim q As Object
q = q1.Where(Function(x As Long) x)
Dim f = Function(x As Double) x
q = q1.Where(f)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
Where VB$AnonymousDelegate_0`2[System.Int64,System.Int64]
Where VB$AnonymousDelegate_0`2[System.Double,System.Double]
]]>)
End Sub
<Fact()>
Public Sub AnonymousDelegates3()
Dim compilationDef =
<compilation name="TypeArgumentInference3">
<file name="a.vb">
Imports System
Module Module1
Sub Test1(Of T)(x As Func(Of T))
System.Console.WriteLine(x)
End Sub
Sub Test2(Of T)(x As Action(Of T))
System.Console.WriteLine(x)
End Sub
Sub Test3(Of T, S)(x As Func(Of T, S))
System.Console.WriteLine(x)
End Sub
Sub Test4(Of T, S)(x As Func(Of T, S), y As T)
System.Console.WriteLine(x)
End Sub
Sub Main()
Dim d1 = Function() 1
Test1(d1)
Dim d2 = Sub(x As Long) System.Console.WriteLine(x)
Test2(d2)
Dim d3 = Function(x As Double)
System.Console.WriteLine(x)
Return CInt(x)
End Function
Test3(d3)
Test2(d3)
Test4(d1, 2UI)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
System.Func`1[System.Int32]
System.Action`1[System.Int64]
System.Func`2[System.Double,System.Int32]
System.Action`1[System.Double]
System.Func`2[System.UInt32,System.Int32]
]]>)
End Sub
<Fact()>
Public Sub AnonymousDelegates4()
Dim compilationDef =
<compilation name="TypeArgumentInference3">
<file name="a.vb">
Imports System
Module Module1
Sub Test1(Of T)(x As Func(Of T))
System.Console.WriteLine(x)
End Sub
Delegate Sub Dt2(Of T)(ByRef x As T)
Sub Test2(Of T)(x As Dt2(Of T))
System.Console.WriteLine(x)
End Sub
Sub Test3(Of T, S)(x As Func(Of T, S))
System.Console.WriteLine(x)
End Sub
Sub Test4(Of T, S)(x As Func(Of T, S), y As T)
System.Console.WriteLine(x)
End Sub
Sub Main()
Dim d1 = Function() 1
Test3(d1)
Dim d2 = Sub(x As Long) System.Console.WriteLine(x)
Test2(d2)
Dim d3 = Function(x As Double)
System.Console.WriteLine(x)
Return CInt(x)
End Function
Test1(d3)
Test4(d2, 1UI)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36645: Data type(s) of the type parameter(s) in method 'Public Sub Test3(Of T, S)(x As Func(Of T, S))' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.
Test3(d1)
~~~~~
BC36645: Data type(s) of the type parameter(s) in method 'Public Sub Test2(Of T)(x As Module1.Dt2(Of T))' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.
Test2(d2)
~~~~~
BC36645: Data type(s) of the type parameter(s) in method 'Public Sub Test1(Of T)(x As Func(Of T))' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.
Test1(d3)
~~~~~
BC36645: Data type(s) of the type parameter(s) in method 'Public Sub Test4(Of T, S)(x As Func(Of T, S), y As T)' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.
Test4(d2, 1UI)
~~~~~
</expected>)
End Sub
<Fact()>
Public Sub PropertyInByRefContext1()
Dim compilationDef =
<compilation name="TypeArgumentInference3">
<file name="a.vb">
Imports System
Module Module1
Class B1
Public Property B2 As B2
Public Property B4 As B4
End Class
Class B2
Shared Widening Operator CType(x As B2) As B3
Return Nothing
End Operator
'Shared Widening Operator CType(x As B3) As B2
' Return Nothing
'End Operator
End Class
Class B3
End Class
Class B4
Shared Widening Operator CType(x As B4) As B3
Return Nothing
End Operator
End Class
Sub Test(Of T)(ByRef x As T, y As T, z As T)
System.Console.WriteLine(GetType(T))
End Sub
Sub Main()
Dim x As New B1
Dim y As New B3
Test(x.B2, y, x.B4)
Test(Of B3)(x.B2, y, x.B4)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36657: Data type(s) of the type parameter(s) in method 'Public Sub Test(Of T)(ByRef x As T, y As T, z As T)' cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.
Test(x.B2, y, x.B4)
~~~~
BC33037: Cannot copy the value of 'ByRef' parameter 'x' back to the matching argument because type 'Module1.B3' cannot be converted to type 'Module1.B2'.
Test(Of B3)(x.B2, y, x.B4)
~~~~
</expected>)
End Sub
<Fact()>
Public Sub PropertyInByRefContext2()
Dim compilationDef =
<compilation name="TypeArgumentInference3">
<file name="a.vb">
Imports System
Module Module1
Class B1
Public Property B2 As B2
Public Property B4 As B4
End Class
Class B2
Shared Widening Operator CType(x As B2) As B3
Return Nothing
End Operator
Shared Widening Operator CType(x As B3) As B2
Return Nothing
End Operator
End Class
Class B3
End Class
Class B4
Shared Widening Operator CType(x As B4) As B3
Return Nothing
End Operator
End Class
Sub Test(Of T)(ByRef x As T, y As T, z As T)
System.Console.WriteLine(GetType(T))
End Sub
Sub Main()
Dim x As New B1
Dim y As New B3
Test(x.B2, y, x.B4)
Test(Of B3)(x.B2, y, x.B4)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=
<![CDATA[
Module1+B3
Module1+B3
]]>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<Fact()>
Public Sub PropertyInByRefContext2a()
Dim compilationDef =
<compilation name="TypeArgumentInference3">
<file name="a.vb">
Imports System
Module Module1
Class B1
Public readonly Property B2 As B2
Public readonly Property B4 As B4
End Class
Class B2
Shared Widening Operator CType(x As B2) As B3
Return Nothing
End Operator
'Shared Widening Operator CType(x As B3) As B2
' Return Nothing
'End Operator
End Class
Class B3
End Class
Class B4
Shared Widening Operator CType(x As B4) As B3
Return Nothing
End Operator
End Class
Sub Test(Of T)(ByRef x As T, y As T, z As T)
System.Console.WriteLine(GetType(T))
End Sub
Sub Main()
Dim x As New B1
Dim y As New B3
Test(x.B2, y, x.B4)
Test(Of B3)(x.B2, y, x.B4)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=
<![CDATA[
Module1+B3
Module1+B3
]]>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<Fact()>
Public Sub PropertyInByRefContext2b()
Dim compilationDef =
<compilation name="TypeArgumentInference3">
<file name="a.vb">
Imports System
Module Module1
Class B1
Public readonly Property B2 As B2
Public readonly Property B4 As B4
public sub new
Dim y As New B3
Test(me.B2, y, me.B4)
Test(Of B3)(me.B2, y, me.B4)
end sub
End Class
Class B2
Shared Widening Operator CType(x As B2) As B3
Return Nothing
End Operator
'Shared Widening Operator CType(x As B3) As B2
' Return Nothing
'End Operator
End Class
Class B3
End Class
Class B4
Shared Widening Operator CType(x As B4) As B3
Return Nothing
End Operator
End Class
Sub Test(Of T)(ByRef x As T, y As T, z As T)
System.Console.WriteLine(GetType(T))
End Sub
Sub Main()
dim o as new B1
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36657: Data type(s) of the type parameter(s) in method 'Public Sub Test(Of T)(ByRef x As T, y As T, z As T)' cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.
Test(me.B2, y, me.B4)
~~~~
BC33037: Cannot copy the value of 'ByRef' parameter 'x' back to the matching argument because type 'Module1.B3' cannot be converted to type 'Module1.B2'.
Test(Of B3)(me.B2, y, me.B4)
~~~~~
</expected>)
End Sub
<Fact, WorkItem(545092, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545092")>
Public Sub Bug13357()
Dim compilationDef =
<compilation name="TypeArgumentInference1">
<file name="a.vb">
Imports System
Module Module1
Sub Main(args As String())
Test(New MethodCompiler, New NamespaceSymbol, New SyntaxTree)
End Sub
Sub Test(compiler As MethodCompiler, root As NamespaceSymbol, tree As SyntaxTree)
root.Accept(compiler, Function(sym) sym Is root OrElse sym.IsDefinedInSourceTree(tree))
root.Accept(compiler, Function(sym) sym Is root)
End Sub
End Module
Friend MustInherit Class SymbolVisitor(Of TArgument, TResult)
End Class
Class SyntaxTree
End Class
Class Symbol
Friend Overridable Function IsDefinedInSourceTree(tree As SyntaxTree) As Boolean
Return False
End Function
End Class
Class NamespaceSymbol
Inherits Symbol
Friend Function Accept(Of TArgument, TResult)(visitor As SymbolVisitor(Of TArgument, TResult), arg As TArgument) As TResult
System.Console.WriteLine(GetType(TArgument))
System.Console.WriteLine(GetType(TResult))
Return Nothing
End Function
End Class
Friend Class MethodCompiler
Inherits SymbolVisitor(Of Predicate(Of Symbol), Boolean)
End Class </file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
System.Predicate`1[Symbol]
System.Boolean
System.Predicate`1[Symbol]
System.Boolean
]]>)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.TestExecutionNeedsWindowsTypes)>
Public Sub Regress14477()
Dim compilationDef =
<compilation name="Regress14477">
<file name="a.vb">
Option Strict Off
Imports System
Imports System.Diagnostics
Imports System.Reflection
Imports System.Collections.Generic
Module Module1
Sub Main()
Dim x As Object = New List(Of Integer)
Try
fun(x)
Catch e As Exception
Console.WriteLine(e)
End Try
End Sub
Sub fun(Of X)(ByVal a As List(Of X))
Console.WriteLine("X: " & GetType(X).FullName)
Dim lateBound As Boolean = False
For Each frame As StackFrame In New StackTrace().GetFrames()
If (frame.GetMethod().Name = "Invoke") Then
lateBound = True
End If
Next
If (lateBound) Then
Console.WriteLine("LATE BOUND")
Else
Console.WriteLine("NOT latebound")
End If
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
X: System.Int32
LATE BOUND
]]>)
End Sub
<Fact, WorkItem(545812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545812")>
Public Sub Bug14478()
Dim compilationDef =
<compilation name="TypeArgumentInference2">
<file name="a.vb">
Option Strict On
Imports System
Public Module Test
Delegate Function Func(Of T)() As T
Delegate Function Func(Of A0, T)(arg0 As A0) As T
Public Sub Main()
TestNormal()
End Sub
Sub TestNormal()
f5(AddressOf t5)
End Sub
'-----------------------------------
Sub f5(Of T)(a1 As Func(Of Integer, T))
Console.WriteLine("f5 - T: (" + GetType(T).FullName + ")")
End Sub
' useless to infer on
Function t5(Of S)(a1 As Integer) As S
Return Nothing
End Function
' useful to infer on
Function t5(Of S)(a1 As S) As S
Return Nothing
End Function
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
f5 - T: (System.Int32)
]]>)
End Sub
<Fact, WorkItem(545812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545812")>
Public Sub Bug14478_2()
Dim compilationDef =
<compilation name="TypeArgumentInference2">
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Module Module1
Sub Scen2(Of R As S, S)(ByVal x As R, ByVal y As S)
Dim w As Func(Of R, R) = AddressOf Scen2(Of R)
Gen1A(y, x, w)
End Sub
Sub Gen1A(Of T, U)(ByVal x As T, ByVal y As U, ByVal z As Func(Of T, U))
Console.WriteLine("Gen1A: " & GetType(T).FullName & " - " & GetType(U).FullName)
z(x)
End Sub
Function Scen2(Of K)(ByVal x As K) As K
Console.WriteLine("scen2: " & GetType(K).FullName)
End Function
Sub Main()
Scen2(New CB(), CType(New CB(), CA))
End Sub
End Module
Class CA
End Class
Class CB : Inherits CA
End Class
]]></file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
Gen1A: CB - CB
scen2: CB
]]>)
End Sub
<Fact, WorkItem(629539, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/629539")>
Public Sub Bug629539()
Dim compilationDef =
<compilation>
<file name="a.vb"><![CDATA[
Imports System.Collections.Generic
Imports System.Linq
Class SnapshotSpan
Public Property Length As Integer
Public Property Text As String
Public Function CreateTrackingSpan() As ITrackingSpan
Return Nothing
End Function
End Class
Public Interface ITrackingSpan
End Interface
Module Program
Sub Main()
Dim sourceSpans = New List(Of SnapshotSpan)().AsReadOnly()
Dim replacementSpans = sourceSpans.Select(Function(ss)
If ss.Length = 2 Then
Return ss.Text
Else
Return ss.CreateTrackingSpan()
End If
End Function).ToList()
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(compilationDef, {SystemCoreRef}, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom))
CompileAndVerify(compilation)
AssertTheseDiagnostics(compilation,
<expected>
BC42021: Cannot infer a return type because more than one type is possible; 'Object' assumed.
Dim replacementSpans = sourceSpans.Select(Function(ss)
~~~~~~~~~~~~
</expected>)
compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On))
AssertTheseDiagnostics(compilation,
<expected>
BC36734: Cannot infer a return type because more than one type is possible. Consider adding an 'As' clause to specify the return type.
Dim replacementSpans = sourceSpans.Select(Function(ss)
~~~~~~~~~~~~
</expected>)
End Sub
<Fact, WorkItem(811902, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/811902")>
Public Sub Bug811902()
Dim compilationDef =
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module Module1
Sub Baz(a As Action)
End Sub
Sub Baz(Of T)(a As Func(Of T))
End Sub
Sub Goo(ByRef a As Integer)
Baz(Sub()
Console.WriteLine(a)
End Sub)
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
AssertTheseDiagnostics(compilation,
<expected>
BC36639: 'ByRef' parameter 'a' cannot be used in a lambda expression.
Console.WriteLine(a)
~
</expected>)
End Sub
<Fact>
<WorkItem(22329, "https://github.com/dotnet/roslyn/issues/22329")>
Public Sub ShapeMismatchInOneArgument_01()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class C3
Shared Sub Main()
Test2(Nullable(New VT(Of Integer, Integer)()), New VT(Of Integer, Integer)())
Test2(New VT(Of Integer, Integer)(), Nullable(New VT(Of Integer, Integer)()))
End Sub
Shared Function Nullable(Of T As Structure)(x As T) As T?
Return x
End Function
Shared Sub Test2(Of T, U)(x As VT(Of T, U), y As VT(Of T, U))
System.Console.Write(1)
End Sub
Public Structure VT(Of T, S)
End Structure
End Class
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC36645: Data type(s) of the type parameter(s) in method 'Public Shared Sub Test2(Of T, U)(x As C3.VT(Of T, U), y As C3.VT(Of T, U))' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.
Test2(Nullable(New VT(Of Integer, Integer)()), New VT(Of Integer, Integer)())
~~~~~
BC36645: Data type(s) of the type parameter(s) in method 'Public Shared Sub Test2(Of T, U)(x As C3.VT(Of T, U), y As C3.VT(Of T, U))' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.
Test2(New VT(Of Integer, Integer)(), Nullable(New VT(Of Integer, Integer)()))
~~~~~
</expected>)
End Sub
<Fact>
<WorkItem(22329, "https://github.com/dotnet/roslyn/issues/22329")>
Public Sub ShapeMismatchInOneArgument_02()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Public Class C3
Shared Sub Main()
Test2(Nullable(New VT(Of Integer, Integer)()), New VT(Of Integer, Integer)())
Test2(New VT(Of Integer, Integer)(), Nullable(New VT(Of Integer, Integer)()))
End Sub
Shared Function Nullable(Of T As Structure)(x As T) As T?
Return x
End Function
Shared Sub Test2(Of T)(x As T, y As T)
System.Console.Write(1)
End Sub
Public Structure VT(Of T, S)
End Structure
End Class
</file>
</compilation>, expectedOutput:=<![CDATA[
11
]]>)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/EditorFeatures/VisualBasicTest/EndConstructGeneration/EndConstructCommandHandlerTests.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.Implementation.EndConstructGeneration
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor
Imports Moq
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration
<[UseExportProvider]>
Public Class EndConstructCommandHandlerTests
Private ReadOnly _endConstructServiceMock As New Mock(Of IEndConstructGenerationService)(MockBehavior.Strict)
Private ReadOnly _featureOptions As New Mock(Of IOptionService)(MockBehavior.Strict)
Private ReadOnly _textViewMock As New Mock(Of ITextView)(MockBehavior.Strict)
Private ReadOnly _textBufferMock As New Mock(Of ITextBuffer)(MockBehavior.Strict)
#If False Then
' TODO(jasonmal): Figure out how to enable these tests.
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub ServiceNotCompletingShouldCallNextHandler()
_endConstructServiceMock.Setup(Function(s) s.TryDo(It.IsAny(Of ITextView), It.IsAny(Of ITextBuffer), It.IsAny(Of Char))).Returns(False)
_featureOptions.Setup(Function(s) s.GetOption(FeatureOnOffOptions.EndConstruct)).Returns(True)
Dim nextHandlerCalled = False
Dim handler As New EndConstructCommandHandler(_featureOptions.Object, _endConstructServiceMock.Object)
handler.ExecuteCommand_ReturnKeyCommandHandler(New ReturnKeyCommandArgs(_textViewMock.Object, _textBufferMock.Object), Sub() nextHandlerCalled = True)
Assert.True(nextHandlerCalled)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub ServiceCompletingShouldCallNextHandler()
_endConstructServiceMock.Setup(Function(s) s.TryDo(It.IsAny(Of ITextView), It.IsAny(Of ITextBuffer), It.IsAny(Of Char))).Returns(True)
_featureOptions.Setup(Function(s) s.GetOption(FeatureOnOffOptions.EndConstruct)).Returns(True)
Dim nextHandlerCalled = False
Dim handler As New EndConstructCommandHandler(_featureOptions.Object, _endConstructServiceMock.Object)
handler.ExecuteCommand_ReturnKeyCommandHandler(New ReturnKeyCommandArgs(_textViewMock.Object, _textBufferMock.Object), Sub() nextHandlerCalled = True)
Assert.False(nextHandlerCalled)
End Sub
#End If
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
<WorkItem(544556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544556")>
Public Sub EndConstruct_AfterCodeCleanup()
Dim code = <code>Class C
Sub Main(args As String())
Dim z = 1
Dim y = 2
If z >< y Then
End Sub
End Class</code>.Value.Replace(vbLf, vbCrLf)
Dim expected = <code>Class C
Sub Main(args As String())
Dim z = 1
Dim y = 2
If z <> y Then
End If
End Sub
End Class</code>.Value.Replace(vbLf, vbCrLf)
VerifyAppliedAfterReturnUsingCommandHandler(code, {4, -1}, expected, {5, 12})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
<WorkItem(546798, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546798")>
Public Sub EndConstruct_AfterCodeCleanup_FormatOnlyTouched()
Dim code = <code>Class C1
Sub M1()
System.Diagnostics. _Debug.Assert(True)
End Sub
End Class</code>.Value.Replace(vbLf, vbCrLf)
Dim expected = <code>Class C1
Sub M1()
System.Diagnostics. _
Debug.Assert(True)
End Sub
End Class</code>.Value.Replace(vbLf, vbCrLf)
VerifyAppliedAfterReturnUsingCommandHandler(code, {2, 29}, expected, {3, 12})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
<WorkItem(531347, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531347")>
Public Sub EndConstruct_AfterCodeCleanup_FormatOnly_WhenContainsDiagnostics()
Dim code = <code>Module Program
Sub Main(args As String())
Dim a
'Comment
Dim b
Dim c
End Sub
End Module</code>.Value.Replace(vbLf, vbCrLf)
Dim expected = <code>Module Program
Sub Main(args As String())
Dim a
'Comment
Dim b
Dim c
End Sub
End Module</code>.Value.Replace(vbLf, vbCrLf)
VerifyAppliedAfterReturnUsingCommandHandler(code, {4, -1}, expected, {5, 8})
End Sub
<WorkItem(628656, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/628656")>
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub EndConstruct_NotOnLineFollowingToken()
VerifyStatementEndConstructNotApplied(
text:="Class C
",
caret:={2, 0})
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.Implementation.EndConstructGeneration
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor
Imports Moq
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration
<[UseExportProvider]>
Public Class EndConstructCommandHandlerTests
Private ReadOnly _endConstructServiceMock As New Mock(Of IEndConstructGenerationService)(MockBehavior.Strict)
Private ReadOnly _featureOptions As New Mock(Of IOptionService)(MockBehavior.Strict)
Private ReadOnly _textViewMock As New Mock(Of ITextView)(MockBehavior.Strict)
Private ReadOnly _textBufferMock As New Mock(Of ITextBuffer)(MockBehavior.Strict)
#If False Then
' TODO(jasonmal): Figure out how to enable these tests.
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub ServiceNotCompletingShouldCallNextHandler()
_endConstructServiceMock.Setup(Function(s) s.TryDo(It.IsAny(Of ITextView), It.IsAny(Of ITextBuffer), It.IsAny(Of Char))).Returns(False)
_featureOptions.Setup(Function(s) s.GetOption(FeatureOnOffOptions.EndConstruct)).Returns(True)
Dim nextHandlerCalled = False
Dim handler As New EndConstructCommandHandler(_featureOptions.Object, _endConstructServiceMock.Object)
handler.ExecuteCommand_ReturnKeyCommandHandler(New ReturnKeyCommandArgs(_textViewMock.Object, _textBufferMock.Object), Sub() nextHandlerCalled = True)
Assert.True(nextHandlerCalled)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub ServiceCompletingShouldCallNextHandler()
_endConstructServiceMock.Setup(Function(s) s.TryDo(It.IsAny(Of ITextView), It.IsAny(Of ITextBuffer), It.IsAny(Of Char))).Returns(True)
_featureOptions.Setup(Function(s) s.GetOption(FeatureOnOffOptions.EndConstruct)).Returns(True)
Dim nextHandlerCalled = False
Dim handler As New EndConstructCommandHandler(_featureOptions.Object, _endConstructServiceMock.Object)
handler.ExecuteCommand_ReturnKeyCommandHandler(New ReturnKeyCommandArgs(_textViewMock.Object, _textBufferMock.Object), Sub() nextHandlerCalled = True)
Assert.False(nextHandlerCalled)
End Sub
#End If
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
<WorkItem(544556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544556")>
Public Sub EndConstruct_AfterCodeCleanup()
Dim code = <code>Class C
Sub Main(args As String())
Dim z = 1
Dim y = 2
If z >< y Then
End Sub
End Class</code>.Value.Replace(vbLf, vbCrLf)
Dim expected = <code>Class C
Sub Main(args As String())
Dim z = 1
Dim y = 2
If z <> y Then
End If
End Sub
End Class</code>.Value.Replace(vbLf, vbCrLf)
VerifyAppliedAfterReturnUsingCommandHandler(code, {4, -1}, expected, {5, 12})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
<WorkItem(546798, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546798")>
Public Sub EndConstruct_AfterCodeCleanup_FormatOnlyTouched()
Dim code = <code>Class C1
Sub M1()
System.Diagnostics. _Debug.Assert(True)
End Sub
End Class</code>.Value.Replace(vbLf, vbCrLf)
Dim expected = <code>Class C1
Sub M1()
System.Diagnostics. _
Debug.Assert(True)
End Sub
End Class</code>.Value.Replace(vbLf, vbCrLf)
VerifyAppliedAfterReturnUsingCommandHandler(code, {2, 29}, expected, {3, 12})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
<WorkItem(531347, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531347")>
Public Sub EndConstruct_AfterCodeCleanup_FormatOnly_WhenContainsDiagnostics()
Dim code = <code>Module Program
Sub Main(args As String())
Dim a
'Comment
Dim b
Dim c
End Sub
End Module</code>.Value.Replace(vbLf, vbCrLf)
Dim expected = <code>Module Program
Sub Main(args As String())
Dim a
'Comment
Dim b
Dim c
End Sub
End Module</code>.Value.Replace(vbLf, vbCrLf)
VerifyAppliedAfterReturnUsingCommandHandler(code, {4, -1}, expected, {5, 8})
End Sub
<WorkItem(628656, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/628656")>
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub EndConstruct_NotOnLineFollowingToken()
VerifyStatementEndConstructNotApplied(
text:="Class C
",
caret:={2, 0})
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Compilers/VisualBasic/Portable/Syntax/SyntaxKindFacts.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
Partial Public Class SyntaxFacts
''' <summary>
''' Determine if the kind represents a reserved keyword
''' </summary>
Public Shared Function IsReservedKeyword(kind As SyntaxKind) As Boolean
Return kind - SyntaxKind.AddHandlerKeyword <=
SyntaxKind.WendKeyword - SyntaxKind.AddHandlerKeyword OrElse kind = SyntaxKind.NameOfKeyword
End Function
''' <summary>
''' Determine if the kind represents a contextual keyword
''' </summary>
Public Shared Function IsContextualKeyword(kind As SyntaxKind) As Boolean
Return kind = SyntaxKind.ReferenceKeyword OrElse
(SyntaxKind.AggregateKeyword <= kind AndAlso kind <= SyntaxKind.YieldKeyword)
End Function
''' <summary>
''' Determine if the token instance represents 'Me', 'MyBase' or 'MyClass' keywords
''' </summary>
Public Shared Function IsInstanceExpression(kind As SyntaxKind) As Boolean
Select Case kind
Case SyntaxKind.MeKeyword,
SyntaxKind.MyClassKeyword,
SyntaxKind.MyBaseKeyword
Return True
Case Else
Return False
End Select
End Function
''' <summary>
''' Return correspondent expression syntax for 'Me', 'MyBase' and 'MyClass'
''' keywords or SyntaxKind.None for other syntax kinds
''' </summary>
Public Shared Function GetInstanceExpression(kind As SyntaxKind) As SyntaxKind
Select Case kind
Case SyntaxKind.MeKeyword
Return SyntaxKind.MeExpression
Case SyntaxKind.MyClassKeyword
Return SyntaxKind.MyClassExpression
Case SyntaxKind.MyBaseKeyword
Return SyntaxKind.MyBaseExpression
Case Else
Return SyntaxKind.None
End Select
End Function
''' <summary>
''' Determine if the token instance represents a preprocessor keyword
''' </summary>
Public Shared Function IsPreprocessorKeyword(kind As SyntaxKind) As Boolean
Select Case kind
Case SyntaxKind.IfKeyword,
SyntaxKind.ElseIfKeyword,
SyntaxKind.ElseKeyword,
SyntaxKind.EndIfKeyword,
SyntaxKind.RegionKeyword,
SyntaxKind.EndKeyword,
SyntaxKind.ConstKeyword,
SyntaxKind.ReferenceKeyword,
SyntaxKind.EnableKeyword,
SyntaxKind.DisableKeyword,
SyntaxKind.ExternalSourceKeyword,
SyntaxKind.ExternalChecksumKeyword
Return True
Case Else
Return False
End Select
End Function
Private Shared ReadOnly s_reservedKeywords As SyntaxKind() = New SyntaxKind() {
SyntaxKind.AddressOfKeyword,
SyntaxKind.AddHandlerKeyword,
SyntaxKind.AliasKeyword,
SyntaxKind.AndKeyword,
SyntaxKind.AndAlsoKeyword,
SyntaxKind.AsKeyword,
SyntaxKind.BooleanKeyword,
SyntaxKind.ByRefKeyword,
SyntaxKind.ByteKeyword,
SyntaxKind.ByValKeyword,
SyntaxKind.CallKeyword,
SyntaxKind.CaseKeyword,
SyntaxKind.CatchKeyword,
SyntaxKind.CBoolKeyword,
SyntaxKind.CByteKeyword,
SyntaxKind.CCharKeyword,
SyntaxKind.CDateKeyword,
SyntaxKind.CDecKeyword,
SyntaxKind.CDblKeyword,
SyntaxKind.CharKeyword,
SyntaxKind.CIntKeyword,
SyntaxKind.ClassKeyword,
SyntaxKind.CLngKeyword,
SyntaxKind.CObjKeyword,
SyntaxKind.ConstKeyword,
SyntaxKind.ReferenceKeyword,
SyntaxKind.ContinueKeyword,
SyntaxKind.CSByteKeyword,
SyntaxKind.CShortKeyword,
SyntaxKind.CSngKeyword,
SyntaxKind.CStrKeyword,
SyntaxKind.CTypeKeyword,
SyntaxKind.CUIntKeyword,
SyntaxKind.CULngKeyword,
SyntaxKind.CUShortKeyword,
SyntaxKind.DateKeyword,
SyntaxKind.DecimalKeyword,
SyntaxKind.DeclareKeyword,
SyntaxKind.DefaultKeyword,
SyntaxKind.DelegateKeyword,
SyntaxKind.DimKeyword,
SyntaxKind.DirectCastKeyword,
SyntaxKind.DoKeyword,
SyntaxKind.DoubleKeyword,
SyntaxKind.EachKeyword,
SyntaxKind.ElseKeyword,
SyntaxKind.ElseIfKeyword,
SyntaxKind.EndKeyword,
SyntaxKind.EnumKeyword,
SyntaxKind.EraseKeyword,
SyntaxKind.ErrorKeyword,
SyntaxKind.EventKeyword,
SyntaxKind.ExitKeyword,
SyntaxKind.FalseKeyword,
SyntaxKind.FinallyKeyword,
SyntaxKind.ForKeyword,
SyntaxKind.FriendKeyword,
SyntaxKind.FunctionKeyword,
SyntaxKind.GetKeyword,
SyntaxKind.GetTypeKeyword,
SyntaxKind.GetXmlNamespaceKeyword,
SyntaxKind.GlobalKeyword,
SyntaxKind.GoToKeyword,
SyntaxKind.HandlesKeyword,
SyntaxKind.IfKeyword,
SyntaxKind.ImplementsKeyword,
SyntaxKind.ImportsKeyword,
SyntaxKind.InKeyword,
SyntaxKind.InheritsKeyword,
SyntaxKind.IntegerKeyword,
SyntaxKind.InterfaceKeyword,
SyntaxKind.IsKeyword,
SyntaxKind.IsNotKeyword,
SyntaxKind.LetKeyword,
SyntaxKind.LibKeyword,
SyntaxKind.LikeKeyword,
SyntaxKind.LongKeyword,
SyntaxKind.LoopKeyword,
SyntaxKind.MeKeyword,
SyntaxKind.ModKeyword,
SyntaxKind.ModuleKeyword,
SyntaxKind.MustInheritKeyword,
SyntaxKind.MustOverrideKeyword,
SyntaxKind.MyBaseKeyword,
SyntaxKind.MyClassKeyword,
SyntaxKind.NameOfKeyword,
SyntaxKind.NamespaceKeyword,
SyntaxKind.NarrowingKeyword,
SyntaxKind.NextKeyword,
SyntaxKind.NewKeyword,
SyntaxKind.NotKeyword,
SyntaxKind.NothingKeyword,
SyntaxKind.NotInheritableKeyword,
SyntaxKind.NotOverridableKeyword,
SyntaxKind.ObjectKeyword,
SyntaxKind.OfKeyword,
SyntaxKind.OnKeyword,
SyntaxKind.OperatorKeyword,
SyntaxKind.OptionKeyword,
SyntaxKind.OptionalKeyword,
SyntaxKind.OrKeyword,
SyntaxKind.OrElseKeyword,
SyntaxKind.OverloadsKeyword,
SyntaxKind.OverridableKeyword,
SyntaxKind.OverridesKeyword,
SyntaxKind.ParamArrayKeyword,
SyntaxKind.PartialKeyword,
SyntaxKind.PrivateKeyword,
SyntaxKind.PropertyKeyword,
SyntaxKind.ProtectedKeyword,
SyntaxKind.PublicKeyword,
SyntaxKind.RaiseEventKeyword,
SyntaxKind.ReadOnlyKeyword,
SyntaxKind.ReDimKeyword,
SyntaxKind.REMKeyword,
SyntaxKind.RemoveHandlerKeyword,
SyntaxKind.ResumeKeyword,
SyntaxKind.ReturnKeyword,
SyntaxKind.SByteKeyword,
SyntaxKind.SelectKeyword,
SyntaxKind.SetKeyword,
SyntaxKind.ShadowsKeyword,
SyntaxKind.SharedKeyword,
SyntaxKind.ShortKeyword,
SyntaxKind.SingleKeyword,
SyntaxKind.StaticKeyword,
SyntaxKind.StepKeyword,
SyntaxKind.StopKeyword,
SyntaxKind.StringKeyword,
SyntaxKind.StructureKeyword,
SyntaxKind.SubKeyword,
SyntaxKind.SyncLockKeyword,
SyntaxKind.ThenKeyword,
SyntaxKind.ThrowKeyword,
SyntaxKind.ToKeyword,
SyntaxKind.TrueKeyword,
SyntaxKind.TryKeyword,
SyntaxKind.TryCastKeyword,
SyntaxKind.TypeOfKeyword,
SyntaxKind.UIntegerKeyword,
SyntaxKind.ULongKeyword,
SyntaxKind.UShortKeyword,
SyntaxKind.UsingKeyword,
SyntaxKind.WhenKeyword,
SyntaxKind.WhileKeyword,
SyntaxKind.WideningKeyword,
SyntaxKind.WithKeyword,
SyntaxKind.WithEventsKeyword,
SyntaxKind.WriteOnlyKeyword,
SyntaxKind.XorKeyword,
SyntaxKind.EndIfKeyword,
SyntaxKind.GosubKeyword,
SyntaxKind.VariantKeyword,
SyntaxKind.WendKeyword
}
''' <summary>
''' Get all reserved keywords
''' </summary>
Public Shared Function GetReservedKeywordKinds() As IEnumerable(Of SyntaxKind)
Return s_reservedKeywords
End Function
Private Shared ReadOnly s_contextualKeywords As SyntaxKind() = New SyntaxKind() {
SyntaxKind.AggregateKeyword,
SyntaxKind.AllKeyword,
SyntaxKind.AnsiKeyword,
SyntaxKind.AscendingKeyword,
SyntaxKind.AssemblyKeyword,
SyntaxKind.AutoKeyword,
SyntaxKind.BinaryKeyword,
SyntaxKind.ByKeyword,
SyntaxKind.CompareKeyword,
SyntaxKind.CustomKeyword,
SyntaxKind.DescendingKeyword,
SyntaxKind.DisableKeyword,
SyntaxKind.DistinctKeyword,
SyntaxKind.EnableKeyword,
SyntaxKind.EqualsKeyword,
SyntaxKind.ExplicitKeyword,
SyntaxKind.ExternalSourceKeyword,
SyntaxKind.ExternalChecksumKeyword,
SyntaxKind.FromKeyword,
SyntaxKind.GroupKeyword,
SyntaxKind.InferKeyword,
SyntaxKind.IntoKeyword,
SyntaxKind.IsFalseKeyword,
SyntaxKind.IsTrueKeyword,
SyntaxKind.JoinKeyword,
SyntaxKind.KeyKeyword,
SyntaxKind.MidKeyword,
SyntaxKind.OffKeyword,
SyntaxKind.OrderKeyword,
SyntaxKind.OutKeyword,
SyntaxKind.PreserveKeyword,
SyntaxKind.RegionKeyword,
SyntaxKind.ReferenceKeyword,
SyntaxKind.SkipKeyword,
SyntaxKind.StrictKeyword,
SyntaxKind.TakeKeyword,
SyntaxKind.TextKeyword,
SyntaxKind.UnicodeKeyword,
SyntaxKind.UntilKeyword,
SyntaxKind.WarningKeyword,
SyntaxKind.WhereKeyword,
SyntaxKind.TypeKeyword,
SyntaxKind.XmlKeyword,
SyntaxKind.AsyncKeyword,
SyntaxKind.AwaitKeyword,
SyntaxKind.IteratorKeyword,
SyntaxKind.YieldKeyword
}
''' <summary>
''' Get contextual keywords
''' </summary>
Public Shared Function GetContextualKeywordKinds() As IEnumerable(Of SyntaxKind)
Return s_contextualKeywords
End Function
Private Shared ReadOnly s_punctuationKinds As SyntaxKind() = New SyntaxKind() {
SyntaxKind.ExclamationToken,
SyntaxKind.AtToken,
SyntaxKind.CommaToken,
SyntaxKind.HashToken,
SyntaxKind.AmpersandToken,
SyntaxKind.SingleQuoteToken,
SyntaxKind.OpenParenToken,
SyntaxKind.CloseParenToken,
SyntaxKind.OpenBraceToken,
SyntaxKind.CloseBraceToken,
SyntaxKind.SemicolonToken,
SyntaxKind.AsteriskToken,
SyntaxKind.PlusToken,
SyntaxKind.MinusToken,
SyntaxKind.DotToken,
SyntaxKind.SlashToken,
SyntaxKind.ColonToken,
SyntaxKind.LessThanToken,
SyntaxKind.LessThanEqualsToken,
SyntaxKind.LessThanGreaterThanToken,
SyntaxKind.EqualsToken,
SyntaxKind.GreaterThanToken,
SyntaxKind.GreaterThanEqualsToken,
SyntaxKind.BackslashToken,
SyntaxKind.CaretToken,
SyntaxKind.ColonEqualsToken,
SyntaxKind.AmpersandEqualsToken,
SyntaxKind.AsteriskEqualsToken,
SyntaxKind.PlusEqualsToken,
SyntaxKind.MinusEqualsToken,
SyntaxKind.SlashEqualsToken,
SyntaxKind.BackslashEqualsToken,
SyntaxKind.CaretEqualsToken,
SyntaxKind.LessThanLessThanToken,
SyntaxKind.GreaterThanGreaterThanToken,
SyntaxKind.LessThanLessThanEqualsToken,
SyntaxKind.GreaterThanGreaterThanEqualsToken,
SyntaxKind.QuestionToken,
SyntaxKind.DoubleQuoteToken,
SyntaxKind.StatementTerminatorToken,
SyntaxKind.EndOfFileToken,
SyntaxKind.EmptyToken
}
''' <summary>
''' Get punctuations
''' </summary>
Public Shared Function GetPunctuationKinds() As IEnumerable(Of SyntaxKind)
Return s_punctuationKinds
End Function
Private Shared ReadOnly s_preprocessorKeywords As SyntaxKind() = New SyntaxKind() {
SyntaxKind.IfKeyword,
SyntaxKind.ThenKeyword,
SyntaxKind.ElseIfKeyword,
SyntaxKind.ElseKeyword,
SyntaxKind.EndIfKeyword,
SyntaxKind.EndKeyword,
SyntaxKind.RegionKeyword,
SyntaxKind.ConstKeyword,
SyntaxKind.ReferenceKeyword,
SyntaxKind.EnableKeyword,
SyntaxKind.DisableKeyword,
SyntaxKind.WarningKeyword,
SyntaxKind.ExternalSourceKeyword,
SyntaxKind.ExternalChecksumKeyword}
''' <summary>
''' Get preprocessor keywords
''' </summary>
Public Shared Function GetPreprocessorKeywordKinds() As IEnumerable(Of SyntaxKind)
Return s_preprocessorKeywords
End Function
Friend Shared Function IsSpecifier(kind As SyntaxKind) As Boolean
Select Case kind
Case SyntaxKind.PublicKeyword,
SyntaxKind.PrivateKeyword,
SyntaxKind.ProtectedKeyword,
SyntaxKind.FriendKeyword,
SyntaxKind.StaticKeyword,
SyntaxKind.SharedKeyword,
SyntaxKind.ShadowsKeyword,
SyntaxKind.MustInheritKeyword,
SyntaxKind.OverloadsKeyword,
SyntaxKind.NotInheritableKeyword,
SyntaxKind.OverridesKeyword,
SyntaxKind.PartialKeyword,
SyntaxKind.NotOverridableKeyword,
SyntaxKind.OverridableKeyword,
SyntaxKind.MustOverrideKeyword,
SyntaxKind.ReadOnlyKeyword,
SyntaxKind.WriteOnlyKeyword,
SyntaxKind.DimKeyword,
SyntaxKind.ConstKeyword,
SyntaxKind.DefaultKeyword,
SyntaxKind.WithEventsKeyword,
SyntaxKind.WideningKeyword,
SyntaxKind.NarrowingKeyword,
SyntaxKind.CustomKeyword,
SyntaxKind.AsyncKeyword,
SyntaxKind.IteratorKeyword
Return True
End Select
Return False
End Function
Friend Shared Function CanStartSpecifierDeclaration(kind As SyntaxKind) As Boolean
Select Case kind
Case SyntaxKind.PropertyKeyword,
SyntaxKind.IdentifierToken,
SyntaxKind.EnumKeyword,
SyntaxKind.ModuleKeyword,
SyntaxKind.StructureKeyword,
SyntaxKind.InterfaceKeyword,
SyntaxKind.ClassKeyword,
SyntaxKind.DeclareKeyword,
SyntaxKind.EventKeyword,
SyntaxKind.SubKeyword,
SyntaxKind.FunctionKeyword,
SyntaxKind.OperatorKeyword,
SyntaxKind.DelegateKeyword
Return True
End Select
Return False
End Function
' Test whether a given token is a relational operator.
Public Shared Function IsRelationalOperator(kind As SyntaxKind) As Boolean
Select Case kind
Case _
SyntaxKind.LessThanToken,
SyntaxKind.LessThanEqualsToken,
SyntaxKind.EqualsToken,
SyntaxKind.GreaterThanToken,
SyntaxKind.GreaterThanEqualsToken,
SyntaxKind.LessThanGreaterThanToken
Return True
Case Else
Return False
End Select
End Function
Public Shared Function IsOperator(kind As SyntaxKind) As Boolean
Select Case (kind)
Case SyntaxKind.AndKeyword,
SyntaxKind.AndAlsoKeyword,
SyntaxKind.CBoolKeyword,
SyntaxKind.CByteKeyword,
SyntaxKind.CCharKeyword,
SyntaxKind.CDateKeyword,
SyntaxKind.CDecKeyword,
SyntaxKind.CDblKeyword,
SyntaxKind.CIntKeyword,
SyntaxKind.CLngKeyword,
SyntaxKind.CObjKeyword,
SyntaxKind.CSByteKeyword,
SyntaxKind.CShortKeyword,
SyntaxKind.CSngKeyword,
SyntaxKind.CStrKeyword,
SyntaxKind.CTypeKeyword,
SyntaxKind.CUIntKeyword,
SyntaxKind.CULngKeyword,
SyntaxKind.CUShortKeyword,
SyntaxKind.DirectCastKeyword,
SyntaxKind.GetTypeKeyword,
SyntaxKind.NameOfKeyword,
SyntaxKind.IsKeyword,
SyntaxKind.IsFalseKeyword,
SyntaxKind.IsNotKeyword,
SyntaxKind.IsTrueKeyword,
SyntaxKind.LikeKeyword,
SyntaxKind.ModKeyword,
SyntaxKind.NewKeyword,
SyntaxKind.NotKeyword,
SyntaxKind.OrKeyword,
SyntaxKind.OrElseKeyword,
SyntaxKind.TryCastKeyword,
SyntaxKind.TypeOfKeyword,
SyntaxKind.XorKeyword,
SyntaxKind.PlusToken,
SyntaxKind.MinusToken,
SyntaxKind.AsteriskToken,
SyntaxKind.SlashToken,
SyntaxKind.CaretToken,
SyntaxKind.BackslashToken,
SyntaxKind.AmpersandToken,
SyntaxKind.LessThanLessThanToken,
SyntaxKind.GreaterThanGreaterThanToken,
SyntaxKind.EqualsToken,
SyntaxKind.LessThanGreaterThanToken,
SyntaxKind.LessThanToken,
SyntaxKind.LessThanEqualsToken,
SyntaxKind.GreaterThanEqualsToken,
SyntaxKind.GreaterThanToken,
SyntaxKind.ExclamationToken,
SyntaxKind.DotToken,
SyntaxKind.AmpersandEqualsToken,
SyntaxKind.AsteriskEqualsToken,
SyntaxKind.PlusEqualsToken,
SyntaxKind.MinusEqualsToken,
SyntaxKind.SlashEqualsToken,
SyntaxKind.BackslashEqualsToken,
SyntaxKind.CaretEqualsToken,
SyntaxKind.LessThanLessThanEqualsToken,
SyntaxKind.GreaterThanGreaterThanEqualsToken
Return True
Case Else
Return False
End Select
End Function
Public Shared Function IsPreprocessorDirective(kind As SyntaxKind) As Boolean
Select Case kind
Case SyntaxKind.IfDirectiveTrivia,
SyntaxKind.ElseIfDirectiveTrivia,
SyntaxKind.ElseDirectiveTrivia,
SyntaxKind.EndIfDirectiveTrivia,
SyntaxKind.RegionDirectiveTrivia,
SyntaxKind.EndRegionDirectiveTrivia,
SyntaxKind.ConstDirectiveTrivia,
SyntaxKind.ExternalSourceDirectiveTrivia,
SyntaxKind.EndExternalSourceDirectiveTrivia,
SyntaxKind.ExternalChecksumDirectiveTrivia,
SyntaxKind.EnableWarningDirectiveTrivia,
SyntaxKind.DisableWarningDirectiveTrivia,
SyntaxKind.ReferenceDirectiveTrivia,
SyntaxKind.BadDirectiveTrivia
Return True
Case Else
Return False
End Select
End Function
Friend Shared Function SupportsContinueStatement(kind As SyntaxKind) As Boolean
Select Case kind
Case SyntaxKind.WhileBlock,
SyntaxKind.ForBlock,
SyntaxKind.ForEachBlock,
SyntaxKind.SimpleDoLoopBlock,
SyntaxKind.DoWhileLoopBlock,
SyntaxKind.DoUntilLoopBlock
Return True
End Select
Return False
End Function
Friend Shared Function SupportsExitStatement(kind As SyntaxKind) As Boolean
Select Case kind
Case SyntaxKind.WhileBlock,
SyntaxKind.ForBlock,
SyntaxKind.ForEachBlock,
SyntaxKind.SimpleDoLoopBlock,
SyntaxKind.DoWhileLoopBlock,
SyntaxKind.DoUntilLoopBlock,
SyntaxKind.SelectBlock,
SyntaxKind.SubBlock,
SyntaxKind.SingleLineSubLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression,
SyntaxKind.FunctionBlock,
SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.PropertyBlock,
SyntaxKind.TryBlock
Return True
End Select
Return False
End Function
Friend Shared Function IsEndBlockLoopOrNextStatement(kind As SyntaxKind) As Boolean
Select Case (kind)
Case SyntaxKind.EndIfStatement,
SyntaxKind.EndWithStatement,
SyntaxKind.EndSelectStatement,
SyntaxKind.EndWhileStatement,
SyntaxKind.SimpleLoopStatement, SyntaxKind.LoopWhileStatement, SyntaxKind.LoopUntilStatement,
SyntaxKind.NextStatement,
SyntaxKind.EndStructureStatement,
SyntaxKind.EndEnumStatement,
SyntaxKind.EndPropertyStatement,
SyntaxKind.EndEventStatement,
SyntaxKind.EndInterfaceStatement,
SyntaxKind.EndTryStatement,
SyntaxKind.EndClassStatement,
SyntaxKind.EndModuleStatement,
SyntaxKind.EndNamespaceStatement,
SyntaxKind.EndUsingStatement,
SyntaxKind.EndSyncLockStatement,
SyntaxKind.EndSubStatement,
SyntaxKind.EndFunctionStatement,
SyntaxKind.EndOperatorStatement,
SyntaxKind.EndGetStatement,
SyntaxKind.EndSetStatement,
SyntaxKind.EndAddHandlerStatement,
SyntaxKind.EndRemoveHandlerStatement,
SyntaxKind.EndRaiseEventStatement
Return True
Case Else
Return False
End Select
End Function
Friend Shared Function IsXmlSyntax(kind As SyntaxKind) As Boolean
Select Case kind
Case SyntaxKind.XmlDocument,
SyntaxKind.XmlDeclaration,
SyntaxKind.XmlDeclarationOption,
SyntaxKind.XmlElement,
SyntaxKind.XmlText,
SyntaxKind.XmlElementStartTag,
SyntaxKind.XmlElementEndTag,
SyntaxKind.XmlEmptyElement,
SyntaxKind.XmlAttribute,
SyntaxKind.XmlString,
SyntaxKind.XmlName,
SyntaxKind.XmlBracketedName,
SyntaxKind.XmlPrefix,
SyntaxKind.XmlComment,
SyntaxKind.XmlCDataSection,
SyntaxKind.XmlEmbeddedExpression
Return True
End Select
Return False
End Function
Public Shared Function GetKeywordKind(text As String) As SyntaxKind
text = MakeHalfWidthIdentifier(text)
Dim result As SyntaxKind = KeywordTable.TokenOfString(text)
If result <> SyntaxKind.IdentifierToken AndAlso Not IsContextualKeyword(result) Then
Return result
End If
Return SyntaxKind.None
End Function
Public Shared Function GetAccessorStatementKind(keyword As SyntaxKind) As SyntaxKind
Select Case keyword
Case SyntaxKind.GetKeyword
Return SyntaxKind.GetAccessorStatement
Case SyntaxKind.SetKeyword
Return SyntaxKind.SetAccessorStatement
Case SyntaxKind.AddHandlerKeyword
Return SyntaxKind.AddHandlerStatement
Case SyntaxKind.RemoveHandlerKeyword
Return SyntaxKind.RemoveHandlerStatement
Case SyntaxKind.RaiseEventKeyword
Return SyntaxKind.RaiseEventAccessorStatement
Case Else
Return SyntaxKind.None
End Select
End Function
Public Shared Function GetBaseTypeStatementKind(keyword As SyntaxKind) As SyntaxKind
Return If(keyword = SyntaxKind.EnumKeyword, SyntaxKind.EnumStatement, GetTypeStatementKind(keyword))
End Function
Public Shared Function GetTypeStatementKind(keyword As SyntaxKind) As SyntaxKind
Select Case keyword
Case SyntaxKind.ClassKeyword
Return SyntaxKind.ClassStatement
Case SyntaxKind.InterfaceKeyword
Return SyntaxKind.InterfaceStatement
Case SyntaxKind.StructureKeyword
Return SyntaxKind.StructureStatement
Case Else
Return SyntaxKind.None
End Select
End Function
Public Shared Function GetBinaryExpression(keyword As SyntaxKind) As SyntaxKind
Select Case (keyword)
Case SyntaxKind.IsKeyword
Return SyntaxKind.IsExpression
Case SyntaxKind.IsNotKeyword
Return SyntaxKind.IsNotExpression
Case SyntaxKind.LikeKeyword
Return SyntaxKind.LikeExpression
Case SyntaxKind.AndKeyword
Return SyntaxKind.AndExpression
Case SyntaxKind.AndAlsoKeyword
Return SyntaxKind.AndAlsoExpression
Case SyntaxKind.OrKeyword
Return SyntaxKind.OrExpression
Case SyntaxKind.OrElseKeyword
Return SyntaxKind.OrElseExpression
Case SyntaxKind.XorKeyword
Return SyntaxKind.ExclusiveOrExpression
Case SyntaxKind.AmpersandToken
Return SyntaxKind.ConcatenateExpression
Case SyntaxKind.AsteriskToken
Return SyntaxKind.MultiplyExpression
Case SyntaxKind.PlusToken
Return SyntaxKind.AddExpression
Case SyntaxKind.MinusToken
Return SyntaxKind.SubtractExpression
Case SyntaxKind.SlashToken
Return SyntaxKind.DivideExpression
Case SyntaxKind.BackslashToken
Return SyntaxKind.IntegerDivideExpression
Case SyntaxKind.ModKeyword
Return SyntaxKind.ModuloExpression
Case SyntaxKind.CaretToken
Return SyntaxKind.ExponentiateExpression
Case SyntaxKind.LessThanToken
Return SyntaxKind.LessThanExpression
Case SyntaxKind.LessThanEqualsToken
Return SyntaxKind.LessThanOrEqualExpression
Case SyntaxKind.LessThanGreaterThanToken
Return SyntaxKind.NotEqualsExpression
Case SyntaxKind.EqualsToken
Return SyntaxKind.EqualsExpression
Case SyntaxKind.GreaterThanToken
Return SyntaxKind.GreaterThanExpression
Case SyntaxKind.GreaterThanEqualsToken
Return SyntaxKind.GreaterThanOrEqualExpression
Case SyntaxKind.LessThanLessThanToken
Return SyntaxKind.LeftShiftExpression
Case SyntaxKind.GreaterThanGreaterThanToken
Return SyntaxKind.RightShiftExpression
Case Else
Return SyntaxKind.None
End Select
End Function
Private Shared ReadOnly s_contextualKeywordToSyntaxKindMap As Dictionary(Of String, SyntaxKind) =
New Dictionary(Of String, SyntaxKind)(IdentifierComparison.Comparer) From
{
{"aggregate", SyntaxKind.AggregateKeyword},
{"all", SyntaxKind.AllKeyword},
{"ansi", SyntaxKind.AnsiKeyword},
{"ascending", SyntaxKind.AscendingKeyword},
{"assembly", SyntaxKind.AssemblyKeyword},
{"auto", SyntaxKind.AutoKeyword},
{"binary", SyntaxKind.BinaryKeyword},
{"by", SyntaxKind.ByKeyword},
{"compare", SyntaxKind.CompareKeyword},
{"custom", SyntaxKind.CustomKeyword},
{"descending", SyntaxKind.DescendingKeyword},
{"disable", SyntaxKind.DisableKeyword},
{"distinct", SyntaxKind.DistinctKeyword},
{"enable", SyntaxKind.EnableKeyword},
{"equals", SyntaxKind.EqualsKeyword},
{"explicit", SyntaxKind.ExplicitKeyword},
{"externalsource", SyntaxKind.ExternalSourceKeyword},
{"externalchecksum", SyntaxKind.ExternalChecksumKeyword},
{"from", SyntaxKind.FromKeyword},
{"group", SyntaxKind.GroupKeyword},
{"infer", SyntaxKind.InferKeyword},
{"into", SyntaxKind.IntoKeyword},
{"isfalse", SyntaxKind.IsFalseKeyword},
{"istrue", SyntaxKind.IsTrueKeyword},
{"join", SyntaxKind.JoinKeyword},
{"key", SyntaxKind.KeyKeyword},
{"mid", SyntaxKind.MidKeyword},
{"off", SyntaxKind.OffKeyword},
{"order", SyntaxKind.OrderKeyword},
{"out", SyntaxKind.OutKeyword},
{"preserve", SyntaxKind.PreserveKeyword},
{"region", SyntaxKind.RegionKeyword},
{"r", SyntaxKind.ReferenceKeyword},
{"skip", SyntaxKind.SkipKeyword},
{"strict", SyntaxKind.StrictKeyword},
{"take", SyntaxKind.TakeKeyword},
{"text", SyntaxKind.TextKeyword},
{"unicode", SyntaxKind.UnicodeKeyword},
{"until", SyntaxKind.UntilKeyword},
{"warning", SyntaxKind.WarningKeyword},
{"where", SyntaxKind.WhereKeyword},
{"type", SyntaxKind.TypeKeyword},
{"xml", SyntaxKind.XmlKeyword},
{"async", SyntaxKind.AsyncKeyword},
{"await", SyntaxKind.AwaitKeyword},
{"iterator", SyntaxKind.IteratorKeyword},
{"yield", SyntaxKind.YieldKeyword}
}
Public Shared Function GetContextualKeywordKind(text As String) As SyntaxKind
text = MakeHalfWidthIdentifier(text)
Dim kind As SyntaxKind = SyntaxKind.None
Return If(s_contextualKeywordToSyntaxKindMap.TryGetValue(text, kind), kind, SyntaxKind.None)
End Function
Private Shared ReadOnly s_preprocessorKeywordToSyntaxKindMap As Dictionary(Of String, SyntaxKind) =
New Dictionary(Of String, SyntaxKind)(IdentifierComparison.Comparer) From
{
{"if", SyntaxKind.IfKeyword},
{"elseif", SyntaxKind.ElseIfKeyword},
{"else", SyntaxKind.ElseKeyword},
{"endif", SyntaxKind.EndIfKeyword},
{"region", SyntaxKind.RegionKeyword},
{"end", SyntaxKind.EndKeyword},
{"const", SyntaxKind.ConstKeyword},
{"externalsource", SyntaxKind.ExternalSourceKeyword},
{"externalchecksum", SyntaxKind.ExternalChecksumKeyword},
{"r", SyntaxKind.ReferenceKeyword},
{"enable", SyntaxKind.EnableKeyword},
{"disable", SyntaxKind.DisableKeyword}
}
Public Shared Function GetPreprocessorKeywordKind(text As String) As SyntaxKind
text = MakeHalfWidthIdentifier(text)
Dim kind As SyntaxKind = SyntaxKind.None
Return If(s_preprocessorKeywordToSyntaxKindMap.TryGetValue(text, kind), kind, SyntaxKind.None)
End Function
Public Shared Function GetLiteralExpression(token As SyntaxKind) As SyntaxKind
Select Case token
Case SyntaxKind.IntegerLiteralToken, SyntaxKind.DecimalLiteralToken, SyntaxKind.FloatingLiteralToken
Return SyntaxKind.NumericLiteralExpression
Case SyntaxKind.CharacterLiteralToken
Return SyntaxKind.CharacterLiteralExpression
Case SyntaxKind.DateLiteralToken
Return SyntaxKind.DateLiteralExpression
Case SyntaxKind.StringLiteralToken
Return SyntaxKind.StringLiteralExpression
Case SyntaxKind.TrueKeyword
Return SyntaxKind.TrueLiteralExpression
Case SyntaxKind.FalseKeyword
Return SyntaxKind.FalseLiteralExpression
Case SyntaxKind.NothingKeyword
Return SyntaxKind.NothingLiteralExpression
Case Else
Return SyntaxKind.None
End Select
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
Partial Public Class SyntaxFacts
''' <summary>
''' Determine if the kind represents a reserved keyword
''' </summary>
Public Shared Function IsReservedKeyword(kind As SyntaxKind) As Boolean
Return kind - SyntaxKind.AddHandlerKeyword <=
SyntaxKind.WendKeyword - SyntaxKind.AddHandlerKeyword OrElse kind = SyntaxKind.NameOfKeyword
End Function
''' <summary>
''' Determine if the kind represents a contextual keyword
''' </summary>
Public Shared Function IsContextualKeyword(kind As SyntaxKind) As Boolean
Return kind = SyntaxKind.ReferenceKeyword OrElse
(SyntaxKind.AggregateKeyword <= kind AndAlso kind <= SyntaxKind.YieldKeyword)
End Function
''' <summary>
''' Determine if the token instance represents 'Me', 'MyBase' or 'MyClass' keywords
''' </summary>
Public Shared Function IsInstanceExpression(kind As SyntaxKind) As Boolean
Select Case kind
Case SyntaxKind.MeKeyword,
SyntaxKind.MyClassKeyword,
SyntaxKind.MyBaseKeyword
Return True
Case Else
Return False
End Select
End Function
''' <summary>
''' Return correspondent expression syntax for 'Me', 'MyBase' and 'MyClass'
''' keywords or SyntaxKind.None for other syntax kinds
''' </summary>
Public Shared Function GetInstanceExpression(kind As SyntaxKind) As SyntaxKind
Select Case kind
Case SyntaxKind.MeKeyword
Return SyntaxKind.MeExpression
Case SyntaxKind.MyClassKeyword
Return SyntaxKind.MyClassExpression
Case SyntaxKind.MyBaseKeyword
Return SyntaxKind.MyBaseExpression
Case Else
Return SyntaxKind.None
End Select
End Function
''' <summary>
''' Determine if the token instance represents a preprocessor keyword
''' </summary>
Public Shared Function IsPreprocessorKeyword(kind As SyntaxKind) As Boolean
Select Case kind
Case SyntaxKind.IfKeyword,
SyntaxKind.ElseIfKeyword,
SyntaxKind.ElseKeyword,
SyntaxKind.EndIfKeyword,
SyntaxKind.RegionKeyword,
SyntaxKind.EndKeyword,
SyntaxKind.ConstKeyword,
SyntaxKind.ReferenceKeyword,
SyntaxKind.EnableKeyword,
SyntaxKind.DisableKeyword,
SyntaxKind.ExternalSourceKeyword,
SyntaxKind.ExternalChecksumKeyword
Return True
Case Else
Return False
End Select
End Function
Private Shared ReadOnly s_reservedKeywords As SyntaxKind() = New SyntaxKind() {
SyntaxKind.AddressOfKeyword,
SyntaxKind.AddHandlerKeyword,
SyntaxKind.AliasKeyword,
SyntaxKind.AndKeyword,
SyntaxKind.AndAlsoKeyword,
SyntaxKind.AsKeyword,
SyntaxKind.BooleanKeyword,
SyntaxKind.ByRefKeyword,
SyntaxKind.ByteKeyword,
SyntaxKind.ByValKeyword,
SyntaxKind.CallKeyword,
SyntaxKind.CaseKeyword,
SyntaxKind.CatchKeyword,
SyntaxKind.CBoolKeyword,
SyntaxKind.CByteKeyword,
SyntaxKind.CCharKeyword,
SyntaxKind.CDateKeyword,
SyntaxKind.CDecKeyword,
SyntaxKind.CDblKeyword,
SyntaxKind.CharKeyword,
SyntaxKind.CIntKeyword,
SyntaxKind.ClassKeyword,
SyntaxKind.CLngKeyword,
SyntaxKind.CObjKeyword,
SyntaxKind.ConstKeyword,
SyntaxKind.ReferenceKeyword,
SyntaxKind.ContinueKeyword,
SyntaxKind.CSByteKeyword,
SyntaxKind.CShortKeyword,
SyntaxKind.CSngKeyword,
SyntaxKind.CStrKeyword,
SyntaxKind.CTypeKeyword,
SyntaxKind.CUIntKeyword,
SyntaxKind.CULngKeyword,
SyntaxKind.CUShortKeyword,
SyntaxKind.DateKeyword,
SyntaxKind.DecimalKeyword,
SyntaxKind.DeclareKeyword,
SyntaxKind.DefaultKeyword,
SyntaxKind.DelegateKeyword,
SyntaxKind.DimKeyword,
SyntaxKind.DirectCastKeyword,
SyntaxKind.DoKeyword,
SyntaxKind.DoubleKeyword,
SyntaxKind.EachKeyword,
SyntaxKind.ElseKeyword,
SyntaxKind.ElseIfKeyword,
SyntaxKind.EndKeyword,
SyntaxKind.EnumKeyword,
SyntaxKind.EraseKeyword,
SyntaxKind.ErrorKeyword,
SyntaxKind.EventKeyword,
SyntaxKind.ExitKeyword,
SyntaxKind.FalseKeyword,
SyntaxKind.FinallyKeyword,
SyntaxKind.ForKeyword,
SyntaxKind.FriendKeyword,
SyntaxKind.FunctionKeyword,
SyntaxKind.GetKeyword,
SyntaxKind.GetTypeKeyword,
SyntaxKind.GetXmlNamespaceKeyword,
SyntaxKind.GlobalKeyword,
SyntaxKind.GoToKeyword,
SyntaxKind.HandlesKeyword,
SyntaxKind.IfKeyword,
SyntaxKind.ImplementsKeyword,
SyntaxKind.ImportsKeyword,
SyntaxKind.InKeyword,
SyntaxKind.InheritsKeyword,
SyntaxKind.IntegerKeyword,
SyntaxKind.InterfaceKeyword,
SyntaxKind.IsKeyword,
SyntaxKind.IsNotKeyword,
SyntaxKind.LetKeyword,
SyntaxKind.LibKeyword,
SyntaxKind.LikeKeyword,
SyntaxKind.LongKeyword,
SyntaxKind.LoopKeyword,
SyntaxKind.MeKeyword,
SyntaxKind.ModKeyword,
SyntaxKind.ModuleKeyword,
SyntaxKind.MustInheritKeyword,
SyntaxKind.MustOverrideKeyword,
SyntaxKind.MyBaseKeyword,
SyntaxKind.MyClassKeyword,
SyntaxKind.NameOfKeyword,
SyntaxKind.NamespaceKeyword,
SyntaxKind.NarrowingKeyword,
SyntaxKind.NextKeyword,
SyntaxKind.NewKeyword,
SyntaxKind.NotKeyword,
SyntaxKind.NothingKeyword,
SyntaxKind.NotInheritableKeyword,
SyntaxKind.NotOverridableKeyword,
SyntaxKind.ObjectKeyword,
SyntaxKind.OfKeyword,
SyntaxKind.OnKeyword,
SyntaxKind.OperatorKeyword,
SyntaxKind.OptionKeyword,
SyntaxKind.OptionalKeyword,
SyntaxKind.OrKeyword,
SyntaxKind.OrElseKeyword,
SyntaxKind.OverloadsKeyword,
SyntaxKind.OverridableKeyword,
SyntaxKind.OverridesKeyword,
SyntaxKind.ParamArrayKeyword,
SyntaxKind.PartialKeyword,
SyntaxKind.PrivateKeyword,
SyntaxKind.PropertyKeyword,
SyntaxKind.ProtectedKeyword,
SyntaxKind.PublicKeyword,
SyntaxKind.RaiseEventKeyword,
SyntaxKind.ReadOnlyKeyword,
SyntaxKind.ReDimKeyword,
SyntaxKind.REMKeyword,
SyntaxKind.RemoveHandlerKeyword,
SyntaxKind.ResumeKeyword,
SyntaxKind.ReturnKeyword,
SyntaxKind.SByteKeyword,
SyntaxKind.SelectKeyword,
SyntaxKind.SetKeyword,
SyntaxKind.ShadowsKeyword,
SyntaxKind.SharedKeyword,
SyntaxKind.ShortKeyword,
SyntaxKind.SingleKeyword,
SyntaxKind.StaticKeyword,
SyntaxKind.StepKeyword,
SyntaxKind.StopKeyword,
SyntaxKind.StringKeyword,
SyntaxKind.StructureKeyword,
SyntaxKind.SubKeyword,
SyntaxKind.SyncLockKeyword,
SyntaxKind.ThenKeyword,
SyntaxKind.ThrowKeyword,
SyntaxKind.ToKeyword,
SyntaxKind.TrueKeyword,
SyntaxKind.TryKeyword,
SyntaxKind.TryCastKeyword,
SyntaxKind.TypeOfKeyword,
SyntaxKind.UIntegerKeyword,
SyntaxKind.ULongKeyword,
SyntaxKind.UShortKeyword,
SyntaxKind.UsingKeyword,
SyntaxKind.WhenKeyword,
SyntaxKind.WhileKeyword,
SyntaxKind.WideningKeyword,
SyntaxKind.WithKeyword,
SyntaxKind.WithEventsKeyword,
SyntaxKind.WriteOnlyKeyword,
SyntaxKind.XorKeyword,
SyntaxKind.EndIfKeyword,
SyntaxKind.GosubKeyword,
SyntaxKind.VariantKeyword,
SyntaxKind.WendKeyword
}
''' <summary>
''' Get all reserved keywords
''' </summary>
Public Shared Function GetReservedKeywordKinds() As IEnumerable(Of SyntaxKind)
Return s_reservedKeywords
End Function
Private Shared ReadOnly s_contextualKeywords As SyntaxKind() = New SyntaxKind() {
SyntaxKind.AggregateKeyword,
SyntaxKind.AllKeyword,
SyntaxKind.AnsiKeyword,
SyntaxKind.AscendingKeyword,
SyntaxKind.AssemblyKeyword,
SyntaxKind.AutoKeyword,
SyntaxKind.BinaryKeyword,
SyntaxKind.ByKeyword,
SyntaxKind.CompareKeyword,
SyntaxKind.CustomKeyword,
SyntaxKind.DescendingKeyword,
SyntaxKind.DisableKeyword,
SyntaxKind.DistinctKeyword,
SyntaxKind.EnableKeyword,
SyntaxKind.EqualsKeyword,
SyntaxKind.ExplicitKeyword,
SyntaxKind.ExternalSourceKeyword,
SyntaxKind.ExternalChecksumKeyword,
SyntaxKind.FromKeyword,
SyntaxKind.GroupKeyword,
SyntaxKind.InferKeyword,
SyntaxKind.IntoKeyword,
SyntaxKind.IsFalseKeyword,
SyntaxKind.IsTrueKeyword,
SyntaxKind.JoinKeyword,
SyntaxKind.KeyKeyword,
SyntaxKind.MidKeyword,
SyntaxKind.OffKeyword,
SyntaxKind.OrderKeyword,
SyntaxKind.OutKeyword,
SyntaxKind.PreserveKeyword,
SyntaxKind.RegionKeyword,
SyntaxKind.ReferenceKeyword,
SyntaxKind.SkipKeyword,
SyntaxKind.StrictKeyword,
SyntaxKind.TakeKeyword,
SyntaxKind.TextKeyword,
SyntaxKind.UnicodeKeyword,
SyntaxKind.UntilKeyword,
SyntaxKind.WarningKeyword,
SyntaxKind.WhereKeyword,
SyntaxKind.TypeKeyword,
SyntaxKind.XmlKeyword,
SyntaxKind.AsyncKeyword,
SyntaxKind.AwaitKeyword,
SyntaxKind.IteratorKeyword,
SyntaxKind.YieldKeyword
}
''' <summary>
''' Get contextual keywords
''' </summary>
Public Shared Function GetContextualKeywordKinds() As IEnumerable(Of SyntaxKind)
Return s_contextualKeywords
End Function
Private Shared ReadOnly s_punctuationKinds As SyntaxKind() = New SyntaxKind() {
SyntaxKind.ExclamationToken,
SyntaxKind.AtToken,
SyntaxKind.CommaToken,
SyntaxKind.HashToken,
SyntaxKind.AmpersandToken,
SyntaxKind.SingleQuoteToken,
SyntaxKind.OpenParenToken,
SyntaxKind.CloseParenToken,
SyntaxKind.OpenBraceToken,
SyntaxKind.CloseBraceToken,
SyntaxKind.SemicolonToken,
SyntaxKind.AsteriskToken,
SyntaxKind.PlusToken,
SyntaxKind.MinusToken,
SyntaxKind.DotToken,
SyntaxKind.SlashToken,
SyntaxKind.ColonToken,
SyntaxKind.LessThanToken,
SyntaxKind.LessThanEqualsToken,
SyntaxKind.LessThanGreaterThanToken,
SyntaxKind.EqualsToken,
SyntaxKind.GreaterThanToken,
SyntaxKind.GreaterThanEqualsToken,
SyntaxKind.BackslashToken,
SyntaxKind.CaretToken,
SyntaxKind.ColonEqualsToken,
SyntaxKind.AmpersandEqualsToken,
SyntaxKind.AsteriskEqualsToken,
SyntaxKind.PlusEqualsToken,
SyntaxKind.MinusEqualsToken,
SyntaxKind.SlashEqualsToken,
SyntaxKind.BackslashEqualsToken,
SyntaxKind.CaretEqualsToken,
SyntaxKind.LessThanLessThanToken,
SyntaxKind.GreaterThanGreaterThanToken,
SyntaxKind.LessThanLessThanEqualsToken,
SyntaxKind.GreaterThanGreaterThanEqualsToken,
SyntaxKind.QuestionToken,
SyntaxKind.DoubleQuoteToken,
SyntaxKind.StatementTerminatorToken,
SyntaxKind.EndOfFileToken,
SyntaxKind.EmptyToken
}
''' <summary>
''' Get punctuations
''' </summary>
Public Shared Function GetPunctuationKinds() As IEnumerable(Of SyntaxKind)
Return s_punctuationKinds
End Function
Private Shared ReadOnly s_preprocessorKeywords As SyntaxKind() = New SyntaxKind() {
SyntaxKind.IfKeyword,
SyntaxKind.ThenKeyword,
SyntaxKind.ElseIfKeyword,
SyntaxKind.ElseKeyword,
SyntaxKind.EndIfKeyword,
SyntaxKind.EndKeyword,
SyntaxKind.RegionKeyword,
SyntaxKind.ConstKeyword,
SyntaxKind.ReferenceKeyword,
SyntaxKind.EnableKeyword,
SyntaxKind.DisableKeyword,
SyntaxKind.WarningKeyword,
SyntaxKind.ExternalSourceKeyword,
SyntaxKind.ExternalChecksumKeyword}
''' <summary>
''' Get preprocessor keywords
''' </summary>
Public Shared Function GetPreprocessorKeywordKinds() As IEnumerable(Of SyntaxKind)
Return s_preprocessorKeywords
End Function
Friend Shared Function IsSpecifier(kind As SyntaxKind) As Boolean
Select Case kind
Case SyntaxKind.PublicKeyword,
SyntaxKind.PrivateKeyword,
SyntaxKind.ProtectedKeyword,
SyntaxKind.FriendKeyword,
SyntaxKind.StaticKeyword,
SyntaxKind.SharedKeyword,
SyntaxKind.ShadowsKeyword,
SyntaxKind.MustInheritKeyword,
SyntaxKind.OverloadsKeyword,
SyntaxKind.NotInheritableKeyword,
SyntaxKind.OverridesKeyword,
SyntaxKind.PartialKeyword,
SyntaxKind.NotOverridableKeyword,
SyntaxKind.OverridableKeyword,
SyntaxKind.MustOverrideKeyword,
SyntaxKind.ReadOnlyKeyword,
SyntaxKind.WriteOnlyKeyword,
SyntaxKind.DimKeyword,
SyntaxKind.ConstKeyword,
SyntaxKind.DefaultKeyword,
SyntaxKind.WithEventsKeyword,
SyntaxKind.WideningKeyword,
SyntaxKind.NarrowingKeyword,
SyntaxKind.CustomKeyword,
SyntaxKind.AsyncKeyword,
SyntaxKind.IteratorKeyword
Return True
End Select
Return False
End Function
Friend Shared Function CanStartSpecifierDeclaration(kind As SyntaxKind) As Boolean
Select Case kind
Case SyntaxKind.PropertyKeyword,
SyntaxKind.IdentifierToken,
SyntaxKind.EnumKeyword,
SyntaxKind.ModuleKeyword,
SyntaxKind.StructureKeyword,
SyntaxKind.InterfaceKeyword,
SyntaxKind.ClassKeyword,
SyntaxKind.DeclareKeyword,
SyntaxKind.EventKeyword,
SyntaxKind.SubKeyword,
SyntaxKind.FunctionKeyword,
SyntaxKind.OperatorKeyword,
SyntaxKind.DelegateKeyword
Return True
End Select
Return False
End Function
' Test whether a given token is a relational operator.
Public Shared Function IsRelationalOperator(kind As SyntaxKind) As Boolean
Select Case kind
Case _
SyntaxKind.LessThanToken,
SyntaxKind.LessThanEqualsToken,
SyntaxKind.EqualsToken,
SyntaxKind.GreaterThanToken,
SyntaxKind.GreaterThanEqualsToken,
SyntaxKind.LessThanGreaterThanToken
Return True
Case Else
Return False
End Select
End Function
Public Shared Function IsOperator(kind As SyntaxKind) As Boolean
Select Case (kind)
Case SyntaxKind.AndKeyword,
SyntaxKind.AndAlsoKeyword,
SyntaxKind.CBoolKeyword,
SyntaxKind.CByteKeyword,
SyntaxKind.CCharKeyword,
SyntaxKind.CDateKeyword,
SyntaxKind.CDecKeyword,
SyntaxKind.CDblKeyword,
SyntaxKind.CIntKeyword,
SyntaxKind.CLngKeyword,
SyntaxKind.CObjKeyword,
SyntaxKind.CSByteKeyword,
SyntaxKind.CShortKeyword,
SyntaxKind.CSngKeyword,
SyntaxKind.CStrKeyword,
SyntaxKind.CTypeKeyword,
SyntaxKind.CUIntKeyword,
SyntaxKind.CULngKeyword,
SyntaxKind.CUShortKeyword,
SyntaxKind.DirectCastKeyword,
SyntaxKind.GetTypeKeyword,
SyntaxKind.NameOfKeyword,
SyntaxKind.IsKeyword,
SyntaxKind.IsFalseKeyword,
SyntaxKind.IsNotKeyword,
SyntaxKind.IsTrueKeyword,
SyntaxKind.LikeKeyword,
SyntaxKind.ModKeyword,
SyntaxKind.NewKeyword,
SyntaxKind.NotKeyword,
SyntaxKind.OrKeyword,
SyntaxKind.OrElseKeyword,
SyntaxKind.TryCastKeyword,
SyntaxKind.TypeOfKeyword,
SyntaxKind.XorKeyword,
SyntaxKind.PlusToken,
SyntaxKind.MinusToken,
SyntaxKind.AsteriskToken,
SyntaxKind.SlashToken,
SyntaxKind.CaretToken,
SyntaxKind.BackslashToken,
SyntaxKind.AmpersandToken,
SyntaxKind.LessThanLessThanToken,
SyntaxKind.GreaterThanGreaterThanToken,
SyntaxKind.EqualsToken,
SyntaxKind.LessThanGreaterThanToken,
SyntaxKind.LessThanToken,
SyntaxKind.LessThanEqualsToken,
SyntaxKind.GreaterThanEqualsToken,
SyntaxKind.GreaterThanToken,
SyntaxKind.ExclamationToken,
SyntaxKind.DotToken,
SyntaxKind.AmpersandEqualsToken,
SyntaxKind.AsteriskEqualsToken,
SyntaxKind.PlusEqualsToken,
SyntaxKind.MinusEqualsToken,
SyntaxKind.SlashEqualsToken,
SyntaxKind.BackslashEqualsToken,
SyntaxKind.CaretEqualsToken,
SyntaxKind.LessThanLessThanEqualsToken,
SyntaxKind.GreaterThanGreaterThanEqualsToken
Return True
Case Else
Return False
End Select
End Function
Public Shared Function IsPreprocessorDirective(kind As SyntaxKind) As Boolean
Select Case kind
Case SyntaxKind.IfDirectiveTrivia,
SyntaxKind.ElseIfDirectiveTrivia,
SyntaxKind.ElseDirectiveTrivia,
SyntaxKind.EndIfDirectiveTrivia,
SyntaxKind.RegionDirectiveTrivia,
SyntaxKind.EndRegionDirectiveTrivia,
SyntaxKind.ConstDirectiveTrivia,
SyntaxKind.ExternalSourceDirectiveTrivia,
SyntaxKind.EndExternalSourceDirectiveTrivia,
SyntaxKind.ExternalChecksumDirectiveTrivia,
SyntaxKind.EnableWarningDirectiveTrivia,
SyntaxKind.DisableWarningDirectiveTrivia,
SyntaxKind.ReferenceDirectiveTrivia,
SyntaxKind.BadDirectiveTrivia
Return True
Case Else
Return False
End Select
End Function
Friend Shared Function SupportsContinueStatement(kind As SyntaxKind) As Boolean
Select Case kind
Case SyntaxKind.WhileBlock,
SyntaxKind.ForBlock,
SyntaxKind.ForEachBlock,
SyntaxKind.SimpleDoLoopBlock,
SyntaxKind.DoWhileLoopBlock,
SyntaxKind.DoUntilLoopBlock
Return True
End Select
Return False
End Function
Friend Shared Function SupportsExitStatement(kind As SyntaxKind) As Boolean
Select Case kind
Case SyntaxKind.WhileBlock,
SyntaxKind.ForBlock,
SyntaxKind.ForEachBlock,
SyntaxKind.SimpleDoLoopBlock,
SyntaxKind.DoWhileLoopBlock,
SyntaxKind.DoUntilLoopBlock,
SyntaxKind.SelectBlock,
SyntaxKind.SubBlock,
SyntaxKind.SingleLineSubLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression,
SyntaxKind.FunctionBlock,
SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.PropertyBlock,
SyntaxKind.TryBlock
Return True
End Select
Return False
End Function
Friend Shared Function IsEndBlockLoopOrNextStatement(kind As SyntaxKind) As Boolean
Select Case (kind)
Case SyntaxKind.EndIfStatement,
SyntaxKind.EndWithStatement,
SyntaxKind.EndSelectStatement,
SyntaxKind.EndWhileStatement,
SyntaxKind.SimpleLoopStatement, SyntaxKind.LoopWhileStatement, SyntaxKind.LoopUntilStatement,
SyntaxKind.NextStatement,
SyntaxKind.EndStructureStatement,
SyntaxKind.EndEnumStatement,
SyntaxKind.EndPropertyStatement,
SyntaxKind.EndEventStatement,
SyntaxKind.EndInterfaceStatement,
SyntaxKind.EndTryStatement,
SyntaxKind.EndClassStatement,
SyntaxKind.EndModuleStatement,
SyntaxKind.EndNamespaceStatement,
SyntaxKind.EndUsingStatement,
SyntaxKind.EndSyncLockStatement,
SyntaxKind.EndSubStatement,
SyntaxKind.EndFunctionStatement,
SyntaxKind.EndOperatorStatement,
SyntaxKind.EndGetStatement,
SyntaxKind.EndSetStatement,
SyntaxKind.EndAddHandlerStatement,
SyntaxKind.EndRemoveHandlerStatement,
SyntaxKind.EndRaiseEventStatement
Return True
Case Else
Return False
End Select
End Function
Friend Shared Function IsXmlSyntax(kind As SyntaxKind) As Boolean
Select Case kind
Case SyntaxKind.XmlDocument,
SyntaxKind.XmlDeclaration,
SyntaxKind.XmlDeclarationOption,
SyntaxKind.XmlElement,
SyntaxKind.XmlText,
SyntaxKind.XmlElementStartTag,
SyntaxKind.XmlElementEndTag,
SyntaxKind.XmlEmptyElement,
SyntaxKind.XmlAttribute,
SyntaxKind.XmlString,
SyntaxKind.XmlName,
SyntaxKind.XmlBracketedName,
SyntaxKind.XmlPrefix,
SyntaxKind.XmlComment,
SyntaxKind.XmlCDataSection,
SyntaxKind.XmlEmbeddedExpression
Return True
End Select
Return False
End Function
Public Shared Function GetKeywordKind(text As String) As SyntaxKind
text = MakeHalfWidthIdentifier(text)
Dim result As SyntaxKind = KeywordTable.TokenOfString(text)
If result <> SyntaxKind.IdentifierToken AndAlso Not IsContextualKeyword(result) Then
Return result
End If
Return SyntaxKind.None
End Function
Public Shared Function GetAccessorStatementKind(keyword As SyntaxKind) As SyntaxKind
Select Case keyword
Case SyntaxKind.GetKeyword
Return SyntaxKind.GetAccessorStatement
Case SyntaxKind.SetKeyword
Return SyntaxKind.SetAccessorStatement
Case SyntaxKind.AddHandlerKeyword
Return SyntaxKind.AddHandlerStatement
Case SyntaxKind.RemoveHandlerKeyword
Return SyntaxKind.RemoveHandlerStatement
Case SyntaxKind.RaiseEventKeyword
Return SyntaxKind.RaiseEventAccessorStatement
Case Else
Return SyntaxKind.None
End Select
End Function
Public Shared Function GetBaseTypeStatementKind(keyword As SyntaxKind) As SyntaxKind
Return If(keyword = SyntaxKind.EnumKeyword, SyntaxKind.EnumStatement, GetTypeStatementKind(keyword))
End Function
Public Shared Function GetTypeStatementKind(keyword As SyntaxKind) As SyntaxKind
Select Case keyword
Case SyntaxKind.ClassKeyword
Return SyntaxKind.ClassStatement
Case SyntaxKind.InterfaceKeyword
Return SyntaxKind.InterfaceStatement
Case SyntaxKind.StructureKeyword
Return SyntaxKind.StructureStatement
Case Else
Return SyntaxKind.None
End Select
End Function
Public Shared Function GetBinaryExpression(keyword As SyntaxKind) As SyntaxKind
Select Case (keyword)
Case SyntaxKind.IsKeyword
Return SyntaxKind.IsExpression
Case SyntaxKind.IsNotKeyword
Return SyntaxKind.IsNotExpression
Case SyntaxKind.LikeKeyword
Return SyntaxKind.LikeExpression
Case SyntaxKind.AndKeyword
Return SyntaxKind.AndExpression
Case SyntaxKind.AndAlsoKeyword
Return SyntaxKind.AndAlsoExpression
Case SyntaxKind.OrKeyword
Return SyntaxKind.OrExpression
Case SyntaxKind.OrElseKeyword
Return SyntaxKind.OrElseExpression
Case SyntaxKind.XorKeyword
Return SyntaxKind.ExclusiveOrExpression
Case SyntaxKind.AmpersandToken
Return SyntaxKind.ConcatenateExpression
Case SyntaxKind.AsteriskToken
Return SyntaxKind.MultiplyExpression
Case SyntaxKind.PlusToken
Return SyntaxKind.AddExpression
Case SyntaxKind.MinusToken
Return SyntaxKind.SubtractExpression
Case SyntaxKind.SlashToken
Return SyntaxKind.DivideExpression
Case SyntaxKind.BackslashToken
Return SyntaxKind.IntegerDivideExpression
Case SyntaxKind.ModKeyword
Return SyntaxKind.ModuloExpression
Case SyntaxKind.CaretToken
Return SyntaxKind.ExponentiateExpression
Case SyntaxKind.LessThanToken
Return SyntaxKind.LessThanExpression
Case SyntaxKind.LessThanEqualsToken
Return SyntaxKind.LessThanOrEqualExpression
Case SyntaxKind.LessThanGreaterThanToken
Return SyntaxKind.NotEqualsExpression
Case SyntaxKind.EqualsToken
Return SyntaxKind.EqualsExpression
Case SyntaxKind.GreaterThanToken
Return SyntaxKind.GreaterThanExpression
Case SyntaxKind.GreaterThanEqualsToken
Return SyntaxKind.GreaterThanOrEqualExpression
Case SyntaxKind.LessThanLessThanToken
Return SyntaxKind.LeftShiftExpression
Case SyntaxKind.GreaterThanGreaterThanToken
Return SyntaxKind.RightShiftExpression
Case Else
Return SyntaxKind.None
End Select
End Function
Private Shared ReadOnly s_contextualKeywordToSyntaxKindMap As Dictionary(Of String, SyntaxKind) =
New Dictionary(Of String, SyntaxKind)(IdentifierComparison.Comparer) From
{
{"aggregate", SyntaxKind.AggregateKeyword},
{"all", SyntaxKind.AllKeyword},
{"ansi", SyntaxKind.AnsiKeyword},
{"ascending", SyntaxKind.AscendingKeyword},
{"assembly", SyntaxKind.AssemblyKeyword},
{"auto", SyntaxKind.AutoKeyword},
{"binary", SyntaxKind.BinaryKeyword},
{"by", SyntaxKind.ByKeyword},
{"compare", SyntaxKind.CompareKeyword},
{"custom", SyntaxKind.CustomKeyword},
{"descending", SyntaxKind.DescendingKeyword},
{"disable", SyntaxKind.DisableKeyword},
{"distinct", SyntaxKind.DistinctKeyword},
{"enable", SyntaxKind.EnableKeyword},
{"equals", SyntaxKind.EqualsKeyword},
{"explicit", SyntaxKind.ExplicitKeyword},
{"externalsource", SyntaxKind.ExternalSourceKeyword},
{"externalchecksum", SyntaxKind.ExternalChecksumKeyword},
{"from", SyntaxKind.FromKeyword},
{"group", SyntaxKind.GroupKeyword},
{"infer", SyntaxKind.InferKeyword},
{"into", SyntaxKind.IntoKeyword},
{"isfalse", SyntaxKind.IsFalseKeyword},
{"istrue", SyntaxKind.IsTrueKeyword},
{"join", SyntaxKind.JoinKeyword},
{"key", SyntaxKind.KeyKeyword},
{"mid", SyntaxKind.MidKeyword},
{"off", SyntaxKind.OffKeyword},
{"order", SyntaxKind.OrderKeyword},
{"out", SyntaxKind.OutKeyword},
{"preserve", SyntaxKind.PreserveKeyword},
{"region", SyntaxKind.RegionKeyword},
{"r", SyntaxKind.ReferenceKeyword},
{"skip", SyntaxKind.SkipKeyword},
{"strict", SyntaxKind.StrictKeyword},
{"take", SyntaxKind.TakeKeyword},
{"text", SyntaxKind.TextKeyword},
{"unicode", SyntaxKind.UnicodeKeyword},
{"until", SyntaxKind.UntilKeyword},
{"warning", SyntaxKind.WarningKeyword},
{"where", SyntaxKind.WhereKeyword},
{"type", SyntaxKind.TypeKeyword},
{"xml", SyntaxKind.XmlKeyword},
{"async", SyntaxKind.AsyncKeyword},
{"await", SyntaxKind.AwaitKeyword},
{"iterator", SyntaxKind.IteratorKeyword},
{"yield", SyntaxKind.YieldKeyword}
}
Public Shared Function GetContextualKeywordKind(text As String) As SyntaxKind
text = MakeHalfWidthIdentifier(text)
Dim kind As SyntaxKind = SyntaxKind.None
Return If(s_contextualKeywordToSyntaxKindMap.TryGetValue(text, kind), kind, SyntaxKind.None)
End Function
Private Shared ReadOnly s_preprocessorKeywordToSyntaxKindMap As Dictionary(Of String, SyntaxKind) =
New Dictionary(Of String, SyntaxKind)(IdentifierComparison.Comparer) From
{
{"if", SyntaxKind.IfKeyword},
{"elseif", SyntaxKind.ElseIfKeyword},
{"else", SyntaxKind.ElseKeyword},
{"endif", SyntaxKind.EndIfKeyword},
{"region", SyntaxKind.RegionKeyword},
{"end", SyntaxKind.EndKeyword},
{"const", SyntaxKind.ConstKeyword},
{"externalsource", SyntaxKind.ExternalSourceKeyword},
{"externalchecksum", SyntaxKind.ExternalChecksumKeyword},
{"r", SyntaxKind.ReferenceKeyword},
{"enable", SyntaxKind.EnableKeyword},
{"disable", SyntaxKind.DisableKeyword}
}
Public Shared Function GetPreprocessorKeywordKind(text As String) As SyntaxKind
text = MakeHalfWidthIdentifier(text)
Dim kind As SyntaxKind = SyntaxKind.None
Return If(s_preprocessorKeywordToSyntaxKindMap.TryGetValue(text, kind), kind, SyntaxKind.None)
End Function
Public Shared Function GetLiteralExpression(token As SyntaxKind) As SyntaxKind
Select Case token
Case SyntaxKind.IntegerLiteralToken, SyntaxKind.DecimalLiteralToken, SyntaxKind.FloatingLiteralToken
Return SyntaxKind.NumericLiteralExpression
Case SyntaxKind.CharacterLiteralToken
Return SyntaxKind.CharacterLiteralExpression
Case SyntaxKind.DateLiteralToken
Return SyntaxKind.DateLiteralExpression
Case SyntaxKind.StringLiteralToken
Return SyntaxKind.StringLiteralExpression
Case SyntaxKind.TrueKeyword
Return SyntaxKind.TrueLiteralExpression
Case SyntaxKind.FalseKeyword
Return SyntaxKind.FalseLiteralExpression
Case SyntaxKind.NothingKeyword
Return SyntaxKind.NothingLiteralExpression
Case Else
Return SyntaxKind.None
End Select
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Scripting/Core/Hosting/ReplServiceProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
namespace Microsoft.CodeAnalysis.Scripting.Hosting
{
/// <summary>
/// Provides basic REPL functionality.
/// </summary>
internal abstract class ReplServiceProvider
{
public abstract ObjectFormatter ObjectFormatter { get; }
public abstract CommandLineParser CommandLineParser { get; }
public abstract DiagnosticFormatter DiagnosticFormatter { get; }
public abstract string Logo { get; }
public abstract Script<T> CreateScript<T>(string code, ScriptOptions options, Type globalsTypeOpt, InteractiveAssemblyLoader assemblyLoader);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
namespace Microsoft.CodeAnalysis.Scripting.Hosting
{
/// <summary>
/// Provides basic REPL functionality.
/// </summary>
internal abstract class ReplServiceProvider
{
public abstract ObjectFormatter ObjectFormatter { get; }
public abstract CommandLineParser CommandLineParser { get; }
public abstract DiagnosticFormatter DiagnosticFormatter { get; }
public abstract string Logo { get; }
public abstract Script<T> CreateScript<T>(string code, ScriptOptions options, Type globalsTypeOpt, InteractiveAssemblyLoader assemblyLoader);
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Compilers/VisualBasic/Portable/Symbols/Source/SourceLambdaSymbol.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
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
Friend NotInheritable Class SourceLambdaSymbol
Inherits LambdaSymbol
Private ReadOnly _unboundLambda As UnboundLambda
' The anonymous type symbol associated with this lambda
Private _lazyAnonymousDelegateSymbol As NamedTypeSymbol = ErrorTypeSymbol.UnknownResultType
Public Sub New(
syntaxNode As SyntaxNode,
unboundLambda As UnboundLambda,
parameters As ImmutableArray(Of BoundLambdaParameterSymbol),
returnType As TypeSymbol,
binder As Binder)
MyBase.New(syntaxNode, parameters, returnType, binder)
Debug.Assert(returnType IsNot ReturnTypePendingDelegate)
Debug.Assert(unboundLambda IsNot Nothing)
_unboundLambda = unboundLambda
End Sub
Public ReadOnly Property UnboundLambda As UnboundLambda
Get
Return _unboundLambda
End Get
End Property
Public Overrides ReadOnly Property SynthesizedKind As SynthesizedLambdaKind
Get
Return SynthesizedLambdaKind.UserDefined
End Get
End Property
Public Overrides ReadOnly Property IsAsync As Boolean
Get
Return (_unboundLambda.Flags And SourceMemberFlags.Async) <> 0
End Get
End Property
Public Overrides ReadOnly Property IsIterator As Boolean
Get
Return (_unboundLambda.Flags And SourceMemberFlags.Iterator) <> 0
End Get
End Property
Public Overrides ReadOnly Property AssociatedAnonymousDelegate As NamedTypeSymbol
Get
If Me._lazyAnonymousDelegateSymbol Is ErrorTypeSymbol.UnknownResultType Then
Dim newValue As NamedTypeSymbol = MakeAssociatedAnonymousDelegate()
Dim oldValue As NamedTypeSymbol = Interlocked.CompareExchange(Me._lazyAnonymousDelegateSymbol, newValue, ErrorTypeSymbol.UnknownResultType)
Debug.Assert(oldValue Is ErrorTypeSymbol.UnknownResultType OrElse oldValue Is newValue)
End If
Return Me._lazyAnonymousDelegateSymbol
End Get
End Property
Friend Function MakeAssociatedAnonymousDelegate() As NamedTypeSymbol
Dim anonymousDelegateSymbol As NamedTypeSymbol = Me._unboundLambda.InferredAnonymousDelegate.Key
Dim targetSignature As New UnboundLambda.TargetSignature(anonymousDelegateSymbol.DelegateInvokeMethod)
Dim boundLambda As BoundLambda = Me._unboundLambda.Bind(targetSignature)
' NOTE: If the lambda does not have an associated anonymous delegate, but
' NOTE: the target signature of the lambda is the same as its anonymous delegate
' NOTE: would have had if it were created, we still return this delegate.
' NOTE: This is caused by performance trade-offs made in lambda binding
If boundLambda.LambdaSymbol IsNot Me Then
Return Nothing
End If
Return anonymousDelegateSymbol
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
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
Friend NotInheritable Class SourceLambdaSymbol
Inherits LambdaSymbol
Private ReadOnly _unboundLambda As UnboundLambda
' The anonymous type symbol associated with this lambda
Private _lazyAnonymousDelegateSymbol As NamedTypeSymbol = ErrorTypeSymbol.UnknownResultType
Public Sub New(
syntaxNode As SyntaxNode,
unboundLambda As UnboundLambda,
parameters As ImmutableArray(Of BoundLambdaParameterSymbol),
returnType As TypeSymbol,
binder As Binder)
MyBase.New(syntaxNode, parameters, returnType, binder)
Debug.Assert(returnType IsNot ReturnTypePendingDelegate)
Debug.Assert(unboundLambda IsNot Nothing)
_unboundLambda = unboundLambda
End Sub
Public ReadOnly Property UnboundLambda As UnboundLambda
Get
Return _unboundLambda
End Get
End Property
Public Overrides ReadOnly Property SynthesizedKind As SynthesizedLambdaKind
Get
Return SynthesizedLambdaKind.UserDefined
End Get
End Property
Public Overrides ReadOnly Property IsAsync As Boolean
Get
Return (_unboundLambda.Flags And SourceMemberFlags.Async) <> 0
End Get
End Property
Public Overrides ReadOnly Property IsIterator As Boolean
Get
Return (_unboundLambda.Flags And SourceMemberFlags.Iterator) <> 0
End Get
End Property
Public Overrides ReadOnly Property AssociatedAnonymousDelegate As NamedTypeSymbol
Get
If Me._lazyAnonymousDelegateSymbol Is ErrorTypeSymbol.UnknownResultType Then
Dim newValue As NamedTypeSymbol = MakeAssociatedAnonymousDelegate()
Dim oldValue As NamedTypeSymbol = Interlocked.CompareExchange(Me._lazyAnonymousDelegateSymbol, newValue, ErrorTypeSymbol.UnknownResultType)
Debug.Assert(oldValue Is ErrorTypeSymbol.UnknownResultType OrElse oldValue Is newValue)
End If
Return Me._lazyAnonymousDelegateSymbol
End Get
End Property
Friend Function MakeAssociatedAnonymousDelegate() As NamedTypeSymbol
Dim anonymousDelegateSymbol As NamedTypeSymbol = Me._unboundLambda.InferredAnonymousDelegate.Key
Dim targetSignature As New UnboundLambda.TargetSignature(anonymousDelegateSymbol.DelegateInvokeMethod)
Dim boundLambda As BoundLambda = Me._unboundLambda.Bind(targetSignature)
' NOTE: If the lambda does not have an associated anonymous delegate, but
' NOTE: the target signature of the lambda is the same as its anonymous delegate
' NOTE: would have had if it were created, we still return this delegate.
' NOTE: This is caused by performance trade-offs made in lambda binding
If boundLambda.LambdaSymbol IsNot Me Then
Return Nothing
End If
Return anonymousDelegateSymbol
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/VisualStudio/Core/Def/EditorConfigSettings/CodeStyle/View/CodeStyleSeverityControl.xaml.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Windows.Automation;
using System.Windows.Controls;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.CodeStyle.View
{
/// <summary>
/// Interaction logic for CodeStyleSeverityControl.xaml
/// </summary>
internal partial class CodeStyleSeverityControl : UserControl
{
private readonly ComboBox _comboBox;
private readonly CodeStyleSetting _setting;
public CodeStyleSeverityControl(CodeStyleSetting setting)
{
InitializeComponent();
_setting = setting;
_comboBox = new ComboBox()
{
ItemsSource = new[]
{
ServicesVSResources.Refactoring_Only,
ServicesVSResources.Suggestion,
ServicesVSResources.Warning,
ServicesVSResources.Error
}
};
_comboBox.SelectedIndex = setting.Severity switch
{
DiagnosticSeverity.Hidden => 0,
DiagnosticSeverity.Info => 1,
DiagnosticSeverity.Warning => 2,
DiagnosticSeverity.Error => 3,
_ => throw new InvalidOperationException(),
};
_comboBox.SelectionChanged += ComboBox_SelectionChanged;
_comboBox.SetValue(AutomationProperties.NameProperty, ServicesVSResources.Severity);
_ = RootGrid.Children.Add(_comboBox);
}
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var severity = _comboBox.SelectedIndex switch
{
0 => DiagnosticSeverity.Hidden,
1 => DiagnosticSeverity.Info,
2 => DiagnosticSeverity.Warning,
3 => DiagnosticSeverity.Error,
_ => throw new InvalidOperationException(),
};
if (_setting.Severity != severity)
{
_setting.ChangeSeverity(severity);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Windows.Automation;
using System.Windows.Controls;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.CodeStyle.View
{
/// <summary>
/// Interaction logic for CodeStyleSeverityControl.xaml
/// </summary>
internal partial class CodeStyleSeverityControl : UserControl
{
private readonly ComboBox _comboBox;
private readonly CodeStyleSetting _setting;
public CodeStyleSeverityControl(CodeStyleSetting setting)
{
InitializeComponent();
_setting = setting;
_comboBox = new ComboBox()
{
ItemsSource = new[]
{
ServicesVSResources.Refactoring_Only,
ServicesVSResources.Suggestion,
ServicesVSResources.Warning,
ServicesVSResources.Error
}
};
_comboBox.SelectedIndex = setting.Severity switch
{
DiagnosticSeverity.Hidden => 0,
DiagnosticSeverity.Info => 1,
DiagnosticSeverity.Warning => 2,
DiagnosticSeverity.Error => 3,
_ => throw new InvalidOperationException(),
};
_comboBox.SelectionChanged += ComboBox_SelectionChanged;
_comboBox.SetValue(AutomationProperties.NameProperty, ServicesVSResources.Severity);
_ = RootGrid.Children.Add(_comboBox);
}
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var severity = _comboBox.SelectedIndex switch
{
0 => DiagnosticSeverity.Hidden,
1 => DiagnosticSeverity.Info,
2 => DiagnosticSeverity.Warning,
3 => DiagnosticSeverity.Error,
_ => throw new InvalidOperationException(),
};
if (_setting.Severity != severity)
{
_setting.ChangeSeverity(severity);
}
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Features/CSharp/Portable/Structure/Providers/AnonymousMethodExpressionStructureProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Structure;
namespace Microsoft.CodeAnalysis.CSharp.Structure
{
internal class AnonymousMethodExpressionStructureProvider : AbstractSyntaxNodeStructureProvider<AnonymousMethodExpressionSyntax>
{
protected override void CollectBlockSpans(
SyntaxToken previousToken,
AnonymousMethodExpressionSyntax anonymousMethod,
ref TemporaryArray<BlockSpan> spans,
BlockStructureOptionProvider optionProvider,
CancellationToken cancellationToken)
{
// fault tolerance
if (anonymousMethod.Block.IsMissing ||
anonymousMethod.Block.OpenBraceToken.IsMissing ||
anonymousMethod.Block.CloseBraceToken.IsMissing)
{
return;
}
var lastToken = CSharpStructureHelpers.GetLastInlineMethodBlockToken(anonymousMethod);
if (lastToken.Kind() == SyntaxKind.None)
{
return;
}
var startToken = anonymousMethod.ParameterList != null
? anonymousMethod.ParameterList.GetLastToken(includeZeroWidth: true)
: anonymousMethod.DelegateKeyword;
spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan(
anonymousMethod,
startToken,
lastToken,
compressEmptyLines: false,
autoCollapse: false,
type: BlockTypes.Expression,
isCollapsible: true));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Structure;
namespace Microsoft.CodeAnalysis.CSharp.Structure
{
internal class AnonymousMethodExpressionStructureProvider : AbstractSyntaxNodeStructureProvider<AnonymousMethodExpressionSyntax>
{
protected override void CollectBlockSpans(
SyntaxToken previousToken,
AnonymousMethodExpressionSyntax anonymousMethod,
ref TemporaryArray<BlockSpan> spans,
BlockStructureOptionProvider optionProvider,
CancellationToken cancellationToken)
{
// fault tolerance
if (anonymousMethod.Block.IsMissing ||
anonymousMethod.Block.OpenBraceToken.IsMissing ||
anonymousMethod.Block.CloseBraceToken.IsMissing)
{
return;
}
var lastToken = CSharpStructureHelpers.GetLastInlineMethodBlockToken(anonymousMethod);
if (lastToken.Kind() == SyntaxKind.None)
{
return;
}
var startToken = anonymousMethod.ParameterList != null
? anonymousMethod.ParameterList.GetLastToken(includeZeroWidth: true)
: anonymousMethod.DelegateKeyword;
spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan(
anonymousMethod,
startToken,
lastToken,
compressEmptyLines: false,
autoCollapse: false,
type: BlockTypes.Expression,
isCollapsible: true));
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Workspaces/Core/Portable/CodeCleanup/Providers/ExportCodeCleanupProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Composition;
namespace Microsoft.CodeAnalysis.CodeCleanup.Providers
{
/// <summary>
/// Specifies the exact type of the code cleanup exported.
/// </summary>
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class)]
internal class ExportCodeCleanupProvider : ExportAttribute
{
public string Name { get; }
public IEnumerable<string> Languages { get; }
public ExportCodeCleanupProvider(string name, params string[] languages)
: base(typeof(ICodeCleanupProvider))
{
if (languages.Length == 0)
{
throw new ArgumentException("languages");
}
this.Name = name;
this.Languages = languages ?? throw new ArgumentNullException(nameof(languages));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Composition;
namespace Microsoft.CodeAnalysis.CodeCleanup.Providers
{
/// <summary>
/// Specifies the exact type of the code cleanup exported.
/// </summary>
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class)]
internal class ExportCodeCleanupProvider : ExportAttribute
{
public string Name { get; }
public IEnumerable<string> Languages { get; }
public ExportCodeCleanupProvider(string name, params string[] languages)
: base(typeof(ICodeCleanupProvider))
{
if (languages.Length == 0)
{
throw new ArgumentException("languages");
}
this.Name = name;
this.Languages = languages ?? throw new ArgumentNullException(nameof(languages));
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/VisualStudio/Core/Def/Implementation/Venus/ContainedLanguage.IVsContainedCode.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus
{
internal partial class ContainedLanguage : IVsContainedCode
{
public int HostSpansUpdated()
=> VSConstants.S_OK;
/// <summary>
/// Returns the list of code blocks in the generated .cs file that comes from the ASP.NET
/// markup compiler. These blocks of code are delimited by #line directives (ExternSource
/// directives in VB). The TextSpan that we return is the span of the lines between the
/// start #line and ending #line default directives (#End ExternSource in VB), and the
/// cookie is the numeric line number given in the #line directive.
/// </summary>
public int EnumOriginalCodeBlocks(out IVsEnumCodeBlocks ppEnum)
{
IList<TextSpanAndCookie> result = null;
var uiThreadOperationExecutor = ComponentModel.GetService<IUIThreadOperationExecutor>();
uiThreadOperationExecutor.Execute(
"Intellisense",
defaultDescription: "",
allowCancellation: false,
showProgress: false,
action: c => result = EnumOriginalCodeBlocksWorker(c.UserCancellationToken));
ppEnum = new CodeBlockEnumerator(result);
return VSConstants.S_OK;
}
private IList<TextSpanAndCookie> EnumOriginalCodeBlocksWorker(CancellationToken cancellationToken)
{
var snapshot = this.SubjectBuffer.CurrentSnapshot;
var document = snapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return SpecializedCollections.EmptyList<TextSpanAndCookie>();
}
return document.GetVisibleCodeBlocks(cancellationToken)
.Select(tuple => new TextSpanAndCookie
{
CodeSpan = new VsTextSpan
{
iStartLine = snapshot.GetLineNumberFromPosition(tuple.Item1.Start),
iStartIndex = 0,
iEndLine = snapshot.GetLineNumberFromPosition(tuple.Item1.End),
iEndIndex = tuple.Item1.End - snapshot.GetLineFromPosition(tuple.Item1.End).Start,
},
ulHTMLCookie = tuple.Item2,
})
.ToArray();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus
{
internal partial class ContainedLanguage : IVsContainedCode
{
public int HostSpansUpdated()
=> VSConstants.S_OK;
/// <summary>
/// Returns the list of code blocks in the generated .cs file that comes from the ASP.NET
/// markup compiler. These blocks of code are delimited by #line directives (ExternSource
/// directives in VB). The TextSpan that we return is the span of the lines between the
/// start #line and ending #line default directives (#End ExternSource in VB), and the
/// cookie is the numeric line number given in the #line directive.
/// </summary>
public int EnumOriginalCodeBlocks(out IVsEnumCodeBlocks ppEnum)
{
IList<TextSpanAndCookie> result = null;
var uiThreadOperationExecutor = ComponentModel.GetService<IUIThreadOperationExecutor>();
uiThreadOperationExecutor.Execute(
"Intellisense",
defaultDescription: "",
allowCancellation: false,
showProgress: false,
action: c => result = EnumOriginalCodeBlocksWorker(c.UserCancellationToken));
ppEnum = new CodeBlockEnumerator(result);
return VSConstants.S_OK;
}
private IList<TextSpanAndCookie> EnumOriginalCodeBlocksWorker(CancellationToken cancellationToken)
{
var snapshot = this.SubjectBuffer.CurrentSnapshot;
var document = snapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return SpecializedCollections.EmptyList<TextSpanAndCookie>();
}
return document.GetVisibleCodeBlocks(cancellationToken)
.Select(tuple => new TextSpanAndCookie
{
CodeSpan = new VsTextSpan
{
iStartLine = snapshot.GetLineNumberFromPosition(tuple.Item1.Start),
iStartIndex = 0,
iEndLine = snapshot.GetLineNumberFromPosition(tuple.Item1.End),
iEndIndex = tuple.Item1.End - snapshot.GetLineFromPosition(tuple.Item1.End).Start,
},
ulHTMLCookie = tuple.Item2,
})
.ToArray();
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/Compilers/CSharp/Test/Emit/PrivateProtected.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using static Roslyn.Test.Utilities.SigningTestHelpers;
using Xunit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
[CompilerTrait(CompilerFeature.PrivateProtected)]
public class PrivateProtected : CSharpTestBase
{
private static readonly string s_keyPairFile = SigningTestHelpers.KeyPairFile;
private static readonly string s_publicKeyFile = SigningTestHelpers.PublicKeyFile;
private static readonly ImmutableArray<byte> s_publicKey = SigningTestHelpers.PublicKey;
[ConditionalFact(typeof(DesktopOnly))]
public void RejectIncompatibleModifiers()
{
string source =
@"public class Base
{
private internal int Field1;
internal private int Field2;
private internal protected int Field3;
internal protected private int Field4;
private public protected int Field5;
private readonly protected int Field6; // ok
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
// (3,26): error CS0107: More than one protection modifier
// private internal int Field1;
Diagnostic(ErrorCode.ERR_BadMemberProtection, "Field1").WithLocation(3, 26),
// (4,26): error CS0107: More than one protection modifier
// internal private int Field2;
Diagnostic(ErrorCode.ERR_BadMemberProtection, "Field2").WithLocation(4, 26),
// (5,36): error CS0107: More than one protection modifier
// private internal protected int Field3;
Diagnostic(ErrorCode.ERR_BadMemberProtection, "Field3").WithLocation(5, 36),
// (6,36): error CS0107: More than one protection modifier
// internal protected private int Field4;
Diagnostic(ErrorCode.ERR_BadMemberProtection, "Field4").WithLocation(6, 36),
// (7,34): error CS0107: More than one protection modifier
// private public protected int Field5;
Diagnostic(ErrorCode.ERR_BadMemberProtection, "Field5").WithLocation(7, 34)
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void AccessibleWhereRequired_01()
{
string source =
@"public class Base
{
private protected int Field1;
protected private int Field2;
}
public class Derived : Base
{
void M()
{
Field1 = 1;
Field2 = 2;
}
}
";
var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void AccessibleWhereRequired_02()
{
string source1 =
@"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""WantsIVTAccess"")]
public class Base
{
private protected const int Constant = 3;
private protected int Field1;
protected private int Field2;
private protected void Method() { }
private protected event System.Action Event1;
private protected int Property1 { set {} }
public int Property2 { private protected set {} get { return 4; } }
private protected int this[int x] { set { } get { return 6; } }
public int this[string x] { private protected set { } get { return 5; } }
private protected Base() { Event1?.Invoke(); }
}";
var baseCompilation = CreateCompilation(source1, parseOptions: TestOptions.Regular7_2,
options: TestOptions.SigningReleaseDll,
assemblyName: "Paul");
var bb = (NamedTypeSymbol)baseCompilation.GlobalNamespace.GetMember("Base");
foreach (var member in bb.GetMembers())
{
switch (member.Name)
{
case "Property2":
case "get_Property2":
case "this[]":
case "get_Item":
break;
default:
Assert.Equal(Accessibility.ProtectedAndInternal, member.DeclaredAccessibility);
break;
}
}
string source2 =
@"public class Derived : Base
{
void M()
{
Field1 = Constant;
Field2 = Constant;
Method();
Event1 += null;
Property1 = Constant;
Property2 = Constant;
this[1] = 2;
this[string.Empty] = 4;
}
Derived(int x) : base() {}
Derived(long x) {} // implicit base()
}
";
CreateCompilation(source2, parseOptions: TestOptions.Regular7_2,
references: new[] { new CSharpCompilationReference(baseCompilation) },
assemblyName: "WantsIVTAccessButCantHave",
options: TestOptions.SigningReleaseDll)
.VerifyDiagnostics(
// (5,9): error CS0122: 'Base.Field1' is inaccessible due to its protection level
// Field1 = Constant;
Diagnostic(ErrorCode.ERR_BadAccess, "Field1").WithArguments("Base.Field1").WithLocation(5, 9),
// (5,18): error CS0122: 'Base.Constant' is inaccessible due to its protection level
// Field1 = Constant;
Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(5, 18),
// (6,9): error CS0122: 'Base.Field2' is inaccessible due to its protection level
// Field2 = Constant;
Diagnostic(ErrorCode.ERR_BadAccess, "Field2").WithArguments("Base.Field2").WithLocation(6, 9),
// (6,18): error CS0122: 'Base.Constant' is inaccessible due to its protection level
// Field2 = Constant;
Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(6, 18),
// (7,9): error CS0122: 'Base.Method()' is inaccessible due to its protection level
// Method();
Diagnostic(ErrorCode.ERR_BadAccess, "Method").WithArguments("Base.Method()").WithLocation(7, 9),
// (8,9): error CS0122: 'Base.Event1' is inaccessible due to its protection level
// Event1 += null;
Diagnostic(ErrorCode.ERR_BadAccess, "Event1").WithArguments("Base.Event1").WithLocation(8, 9),
// (8,9): error CS0122: 'Base.Event1.add' is inaccessible due to its protection level
// Event1 += null;
Diagnostic(ErrorCode.ERR_BadAccess, "Event1 += null").WithArguments("Base.Event1.add").WithLocation(8, 9),
// (9,9): error CS0122: 'Base.Property1' is inaccessible due to its protection level
// Property1 = Constant;
Diagnostic(ErrorCode.ERR_BadAccess, "Property1").WithArguments("Base.Property1").WithLocation(9, 9),
// (9,21): error CS0122: 'Base.Constant' is inaccessible due to its protection level
// Property1 = Constant;
Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(9, 21),
// (10,9): error CS0272: The property or indexer 'Base.Property2' cannot be used in this context because the set accessor is inaccessible
// Property2 = Constant;
Diagnostic(ErrorCode.ERR_InaccessibleSetter, "Property2").WithArguments("Base.Property2").WithLocation(10, 9),
// (10,21): error CS0122: 'Base.Constant' is inaccessible due to its protection level
// Property2 = Constant;
Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(10, 21),
// (11,14): error CS1503: Argument 1: cannot convert from 'int' to 'string'
// this[1] = 2;
Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "string").WithLocation(11, 14),
// (12,9): error CS0272: The property or indexer 'Base.this[string]' cannot be used in this context because the set accessor is inaccessible
// this[string.Empty] = 4;
Diagnostic(ErrorCode.ERR_InaccessibleSetter, "this[string.Empty]").WithArguments("Base.this[string]").WithLocation(12, 9),
// (14,22): error CS0122: 'Base.Base()' is inaccessible due to its protection level
// Derived(int x) : base() {}
Diagnostic(ErrorCode.ERR_BadAccess, "base").WithArguments("Base.Base()").WithLocation(14, 22),
// (15,5): error CS0122: 'Base.Base()' is inaccessible due to its protection level
// Derived(long x) {} // implicit base()
Diagnostic(ErrorCode.ERR_BadAccess, "Derived").WithArguments("Base.Base()").WithLocation(15, 5)
);
CreateCompilation(source2, parseOptions: TestOptions.Regular7_2,
references: new[] { MetadataReference.CreateFromImage(baseCompilation.EmitToArray()) },
assemblyName: "WantsIVTAccessButCantHave",
options: TestOptions.SigningReleaseDll)
.VerifyDiagnostics(
// (5,9): error CS0122: 'Base.Field1' is inaccessible due to its protection level
// Field1 = Constant;
Diagnostic(ErrorCode.ERR_BadAccess, "Field1").WithArguments("Base.Field1").WithLocation(5, 9),
// (5,18): error CS0122: 'Base.Constant' is inaccessible due to its protection level
// Field1 = Constant;
Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(5, 18),
// (6,9): error CS0122: 'Base.Field2' is inaccessible due to its protection level
// Field2 = Constant;
Diagnostic(ErrorCode.ERR_BadAccess, "Field2").WithArguments("Base.Field2").WithLocation(6, 9),
// (6,18): error CS0122: 'Base.Constant' is inaccessible due to its protection level
// Field2 = Constant;
Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(6, 18),
// (7,9): error CS0122: 'Base.Method()' is inaccessible due to its protection level
// Method();
Diagnostic(ErrorCode.ERR_BadAccess, "Method").WithArguments("Base.Method()").WithLocation(7, 9),
// (8,9): error CS0122: 'Base.Event1' is inaccessible due to its protection level
// Event1 += null;
Diagnostic(ErrorCode.ERR_BadAccess, "Event1").WithArguments("Base.Event1").WithLocation(8, 9),
// (8,9): error CS0122: 'Base.Event1.add' is inaccessible due to its protection level
// Event1 += null;
Diagnostic(ErrorCode.ERR_BadAccess, "Event1 += null").WithArguments("Base.Event1.add").WithLocation(8, 9),
// (9,9): error CS0122: 'Base.Property1' is inaccessible due to its protection level
// Property1 = Constant;
Diagnostic(ErrorCode.ERR_BadAccess, "Property1").WithArguments("Base.Property1").WithLocation(9, 9),
// (9,21): error CS0122: 'Base.Constant' is inaccessible due to its protection level
// Property1 = Constant;
Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(9, 21),
// (10,9): error CS0272: The property or indexer 'Base.Property2' cannot be used in this context because the set accessor is inaccessible
// Property2 = Constant;
Diagnostic(ErrorCode.ERR_InaccessibleSetter, "Property2").WithArguments("Base.Property2").WithLocation(10, 9),
// (10,21): error CS0122: 'Base.Constant' is inaccessible due to its protection level
// Property2 = Constant;
Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(10, 21),
// (11,14): error CS1503: Argument 1: cannot convert from 'int' to 'string'
// this[1] = 2;
Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "string").WithLocation(11, 14),
// (12,9): error CS0272: The property or indexer 'Base.this[string]' cannot be used in this context because the set accessor is inaccessible
// this[string.Empty] = 4;
Diagnostic(ErrorCode.ERR_InaccessibleSetter, "this[string.Empty]").WithArguments("Base.this[string]").WithLocation(12, 9),
// (14,22): error CS0122: 'Base.Base()' is inaccessible due to its protection level
// Derived(int x) : base() {}
Diagnostic(ErrorCode.ERR_BadAccess, "base").WithArguments("Base.Base()").WithLocation(14, 22),
// (15,5): error CS0122: 'Base.Base()' is inaccessible due to its protection level
// Derived(long x) {} // implicit base()
Diagnostic(ErrorCode.ERR_BadAccess, "Derived").WithArguments("Base.Base()").WithLocation(15, 5)
);
CreateCompilation(source2, parseOptions: TestOptions.Regular7_2,
references: new[] { new CSharpCompilationReference(baseCompilation) },
assemblyName: "WantsIVTAccess",
options: TestOptions.SigningReleaseDll)
.VerifyDiagnostics(
);
CreateCompilation(source2, parseOptions: TestOptions.Regular7_2,
references: new[] { MetadataReference.CreateFromImage(baseCompilation.EmitToArray()) },
assemblyName: "WantsIVTAccess",
options: TestOptions.SigningReleaseDll)
.VerifyDiagnostics(
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void NotAccessibleWhereRequired()
{
string source =
@"public class Base
{
private protected int Field1;
protected private int Field2;
}
public class Derived // : Base
{
void M()
{
Base b = null;
b.Field1 = 1;
b.Field2 = 2;
}
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
// (12,11): error CS0122: 'Base.Field1' is inaccessible due to its protection level
// b.Field1 = 1;
Diagnostic(ErrorCode.ERR_BadAccess, "Field1").WithArguments("Base.Field1").WithLocation(12, 11),
// (13,11): error CS0122: 'Base.Field2' is inaccessible due to its protection level
// b.Field2 = 2;
Diagnostic(ErrorCode.ERR_BadAccess, "Field2").WithArguments("Base.Field2").WithLocation(13, 11)
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void NotInStructOrNamespace()
{
string source =
@"protected private struct Struct
{
private protected int Field1;
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
// (1,18): error CS1527: Elements defined in a namespace cannot be explicitly declared as private, protected, protected internal, or private protected
// protected private struct Struct
Diagnostic(ErrorCode.ERR_NoNamespacePrivate, "Struct").WithLocation(1, 26),
// (3,27): error CS0666: 'Struct.Field1': new protected member declared in struct
// private protected int Field1;
Diagnostic(ErrorCode.ERR_ProtectedInStruct, "Field1").WithArguments("Struct.Field1").WithLocation(3, 27)
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void NotInStaticClass()
{
string source =
@"static class C
{
static private protected int Field1 = 2;
}
sealed class D
{
static private protected int Field2 = 2;
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
// (7,34): warning CS0628: 'D.Field2': new protected member declared in sealed type
// static private protected int Field2 = 2;
Diagnostic(ErrorCode.WRN_ProtectedInSealed, "Field2").WithArguments("D.Field2").WithLocation(7, 34),
// (3,34): error CS1057: 'C.Field1': static classes cannot contain protected members
// static private protected int Field1 = 2;
Diagnostic(ErrorCode.ERR_ProtectedInStatic, "Field1").WithArguments("C.Field1").WithLocation(3, 34)
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void NestedTypes()
{
string source =
@"class Outer
{
private protected class Inner
{
}
}
class Derived : Outer
{
public void M()
{
Outer.Inner x = null;
}
}
class NotDerived
{
public void M()
{
Outer.Inner x = null; // error: Outer.Inner not accessible
}
}
struct Struct
{
private protected class Inner // error: protected not allowed in struct
{
}
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
// (23,29): error CS0666: 'Struct.Inner': new protected member declared in struct
// private protected class Inner // error: protected not allowed in struct
Diagnostic(ErrorCode.ERR_ProtectedInStruct, "Inner").WithArguments("Struct.Inner").WithLocation(23, 29),
// (11,21): warning CS0219: The variable 'x' is assigned but its value is never used
// Outer.Inner x = null;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(11, 21),
// (18,15): error CS0122: 'Outer.Inner' is inaccessible due to its protection level
// Outer.Inner x = null; // error: Outer.Inner not accessible
Diagnostic(ErrorCode.ERR_BadAccess, "Inner").WithArguments("Outer.Inner").WithLocation(18, 15)
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void PermittedAccessorProtection()
{
string source =
@"class Class
{
public int Prop1 { get; private protected set; }
protected internal int Prop2 { get; private protected set; }
protected int Prop3 { get; private protected set; }
internal int Prop4 { get; private protected set; }
private protected int Prop5 { get; private set; }
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void ForbiddenAccessorProtection_01()
{
string source =
@"class Class
{
private protected int Prop1 { get; private protected set; }
private int Prop2 { get; private protected set; }
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
// (3,58): error CS0273: The accessibility modifier of the 'Class.Prop1.set' accessor must be more restrictive than the property or indexer 'Class.Prop1'
// private protected int Prop1 { get; private protected set; }
Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("Class.Prop1.set", "Class.Prop1").WithLocation(3, 58),
// (4,48): error CS0273: The accessibility modifier of the 'Class.Prop2.set' accessor must be more restrictive than the property or indexer 'Class.Prop2'
// private int Prop2 { get; private protected set; }
Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("Class.Prop2.set", "Class.Prop2").WithLocation(4, 48)
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void ForbiddenAccessorProtection_02()
{
string source =
@"interface ISomething
{
private protected int M();
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
// (3,27): error CS8503: The modifier 'private protected' is not valid for this item in C# 7.2. Please use language version '8.0' or greater.
// private protected int M();
Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M").WithArguments("private protected", "7.2", "8.0").WithLocation(3, 27),
// (3,27): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface.
// private protected int M();
Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "M").WithLocation(3, 27)
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void AtLeastAsRestrictivePositive_01()
{
string source =
@"
public class C
{
internal class Internal {}
protected class Protected {}
private protected class PrivateProtected {}
private protected void M(Internal x) {} // ok
private protected void M(Protected x) {} // ok
private protected void M(PrivateProtected x) {} // ok
private protected class Nested
{
public void M(Internal x) {} // ok
public void M(Protected x) {} // ok
private protected void M(PrivateProtected x) {} // ok
}
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void AtLeastAsRestrictiveNegative_01()
{
string source =
@"
public class Container
{
private protected class PrivateProtected {}
internal void M1(PrivateProtected x) {} // error: conflicting access
protected void M2(PrivateProtected x) {} // error: conflicting access
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
// (6,20): error CS0051: Inconsistent accessibility: parameter type 'Container.PrivateProtected' is less accessible than method 'Container.M2(Container.PrivateProtected)'
// protected void M2(PrivateProtected x) {} // error: conflicting access
Diagnostic(ErrorCode.ERR_BadVisParamType, "M2").WithArguments("Container.M2(Container.PrivateProtected)", "Container.PrivateProtected").WithLocation(6, 20),
// (5,19): error CS0051: Inconsistent accessibility: parameter type 'Container.PrivateProtected' is less accessible than method 'Container.M1(Container.PrivateProtected)'
// internal void M1(PrivateProtected x) {} // error: conflicting access
Diagnostic(ErrorCode.ERR_BadVisParamType, "M1").WithArguments("Container.M1(Container.PrivateProtected)", "Container.PrivateProtected").WithLocation(5, 19)
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void DuplicateAccessInBinder()
{
string source =
@"
public class Container
{
private public int Field; // 1
private public int Property { get; set; } // 2
private public int M() => 1; // 3
private public class C {} // 4
private public struct S {} // 5
private public enum E {} // 6
private public event System.Action V; // 7
private public interface I {} // 8
private public int this[int index] => 1; // 9
void Q() { V.Invoke(); V = null; }
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
// (7,26): error CS0107: More than one protection modifier
// private public class C {} // 4
Diagnostic(ErrorCode.ERR_BadMemberProtection, "C").WithLocation(7, 26),
// (8,27): error CS0107: More than one protection modifier
// private public struct S {} // 5
Diagnostic(ErrorCode.ERR_BadMemberProtection, "S").WithLocation(8, 27),
// (9,25): error CS0107: More than one protection modifier
// private public enum E {} // 6
Diagnostic(ErrorCode.ERR_BadMemberProtection, "E").WithLocation(9, 25),
// (11,30): error CS0107: More than one protection modifier
// private public interface I {} // 8
Diagnostic(ErrorCode.ERR_BadMemberProtection, "I").WithLocation(11, 30),
// (4,24): error CS0107: More than one protection modifier
// private public int Field; // 1
Diagnostic(ErrorCode.ERR_BadMemberProtection, "Field").WithLocation(4, 24),
// (5,24): error CS0107: More than one protection modifier
// private public int Property { get; set; } // 2
Diagnostic(ErrorCode.ERR_BadMemberProtection, "Property").WithLocation(5, 24),
// (6,24): error CS0107: More than one protection modifier
// private public int M() => 1; // 3
Diagnostic(ErrorCode.ERR_BadMemberProtection, "M").WithLocation(6, 24),
// (10,40): error CS0107: More than one protection modifier
// private public event System.Action V; // 7
Diagnostic(ErrorCode.ERR_BadMemberProtection, "V").WithLocation(10, 40),
// (12,24): error CS0107: More than one protection modifier
// private public int this[int index] => 1; // 9
Diagnostic(ErrorCode.ERR_BadMemberProtection, "this").WithLocation(12, 24),
// (12,43): error CS0107: More than one protection modifier
// private public int this[int index] => 1; // 9
Diagnostic(ErrorCode.ERR_BadMemberProtection, "1").WithLocation(12, 43)
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void NotInVersion71()
{
string source =
@"
public class Container
{
private protected int Field; // 1
private protected int Property { get; set; } // 2
private protected int M() => 1; // 3
private protected class C {} // 4
private protected struct S {} // 5
private protected enum E {} // 6
private protected event System.Action V; // 7
private protected interface I {} // 8
private protected int this[int index] => 1; // 9
void Q() { V.Invoke(); V = null; }
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular7_1)
.VerifyDiagnostics(
// (7,29): error CS8302: Feature 'private protected' is not available in C# 7.1. Please use language version 7.2 or greater.
// private protected class C {} // 4
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "C").WithArguments("private protected", "7.2").WithLocation(7, 29),
// (8,30): error CS8302: Feature 'private protected' is not available in C# 7.1. Please use language version 7.2 or greater.
// private protected struct S {} // 5
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "S").WithArguments("private protected", "7.2").WithLocation(8, 30),
// (9,28): error CS8302: Feature 'private protected' is not available in C# 7.1. Please use language version 7.2 or greater.
// private protected enum E {} // 6
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "E").WithArguments("private protected", "7.2").WithLocation(9, 28),
// (11,33): error CS8302: Feature 'private protected' is not available in C# 7.1. Please use language version 7.2 or greater.
// private protected interface I {} // 8
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "I").WithArguments("private protected", "7.2").WithLocation(11, 33),
// (4,27): error CS8302: Feature 'private protected' is not available in C# 7.1. Please use language version 7.2 or greater.
// private protected int Field; // 1
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "Field").WithArguments("private protected", "7.2").WithLocation(4, 27),
// (5,27): error CS8302: Feature 'private protected' is not available in C# 7.1. Please use language version 7.2 or greater.
// private protected int Property { get; set; } // 2
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "Property").WithArguments("private protected", "7.2").WithLocation(5, 27),
// (6,27): error CS8302: Feature 'private protected' is not available in C# 7.1. Please use language version 7.2 or greater.
// private protected int M() => 1; // 3
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "M").WithArguments("private protected", "7.2").WithLocation(6, 27),
// (10,43): error CS8302: Feature 'private protected' is not available in C# 7.1. Please use language version 7.2 or greater.
// private protected event System.Action V; // 7
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "V").WithArguments("private protected", "7.2").WithLocation(10, 43),
// (12,27): error CS8302: Feature 'private protected' is not available in C# 7.1. Please use language version 7.2 or greater.
// private protected int this[int index] => 1; // 9
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "this").WithArguments("private protected", "7.2").WithLocation(12, 27)
);
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void VerifyPrivateProtectedIL()
{
var text = @"
class Program
{
private protected void M() {}
private protected int F;
}
";
var verifier = CompileAndVerify(
text,
parseOptions: TestOptions.Regular7_2,
expectedSignatures: new[]
{
Signature("Program", "M", ".method famandassem hidebysig instance System.Void M() cil managed"),
Signature("Program", "F", ".field famandassem instance System.Int32 F"),
});
}
[ConditionalFact(typeof(DesktopOnly))]
public void VerifyPartialPartsMatch()
{
var source =
@"class Outer
{
private protected partial class Inner {}
private partial class Inner {}
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
// (3,37): error CS0262: Partial declarations of 'Outer.Inner' have conflicting accessibility modifiers
// private protected partial class Inner {}
Diagnostic(ErrorCode.ERR_PartialModifierConflict, "Inner").WithArguments("Outer.Inner").WithLocation(3, 37)
);
source =
@"class Outer
{
private protected partial class Inner {}
private protected partial class Inner {}
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void VerifyProtectedSemantics()
{
var source =
@"class Base
{
private protected void M()
{
System.Console.WriteLine(this.GetType().Name);
}
}
class Derived : Base
{
public void Main()
{
Derived derived = new Derived();
derived.M();
Base bb = new Base();
bb.M(); // error 1
Other other = new Other();
other.M(); // error 2
}
}
class Other : Base
{
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
// (16,12): error CS1540: Cannot access protected member 'Base.M()' via a qualifier of type 'Base'; the qualifier must be of type 'Derived' (or derived from it)
// bb.M(); // error 1
Diagnostic(ErrorCode.ERR_BadProtectedAccess, "M").WithArguments("Base.M()", "Base", "Derived").WithLocation(16, 12),
// (18,15): error CS1540: Cannot access protected member 'Base.M()' via a qualifier of type 'Other'; the qualifier must be of type 'Derived' (or derived from it)
// other.M(); // error 2
Diagnostic(ErrorCode.ERR_BadProtectedAccess, "M").WithArguments("Base.M()", "Other", "Derived").WithLocation(18, 15)
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void HidingAbstract()
{
var source =
@"abstract class A
{
internal abstract void F();
}
abstract class B : A
{
private protected new void F() { } // No CS0533
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void HidingInaccessible()
{
string source1 =
@"public class A
{
private protected void F() { }
}
";
var compilation1 = CreateCompilation(source1, parseOptions: TestOptions.Regular7_2);
compilation1.VerifyDiagnostics();
string source2 =
@"class B : A
{
new void F() { } // CS0109
}
";
CreateCompilation(source2, parseOptions: TestOptions.Regular7_2,
references: new[] { new CSharpCompilationReference(compilation1) })
.VerifyDiagnostics(
// (3,14): warning CS0109: The member 'B.F()' does not hide an accessible member. The new keyword is not required.
// new void F() { } // CS0109
Diagnostic(ErrorCode.WRN_NewNotRequired, "F").WithArguments("B.F()").WithLocation(3, 14)
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void UnimplementedInaccessible()
{
string source1 =
@"public abstract class A
{
private protected abstract void F();
}
";
var compilation1 = CreateCompilation(source1, parseOptions: TestOptions.Regular7_2);
compilation1.VerifyDiagnostics();
string source2 =
@"class B : A // CS0534
{
}
";
CreateCompilation(source2, parseOptions: TestOptions.Regular7_2,
references: new[] { new CSharpCompilationReference(compilation1) })
.VerifyDiagnostics(
// (1,7): error CS0534: 'B' does not implement inherited abstract member 'A.F()'
// class B : A // CS0534
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.F()").WithLocation(1, 7)
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void ImplementInaccessible()
{
string source1 =
@"public abstract class A
{
private protected abstract void F();
}
";
var compilation1 = CreateCompilation(source1, parseOptions: TestOptions.Regular7_2);
compilation1.VerifyDiagnostics();
string source2 =
@"class B : A // CS0534
{
override private protected void F() {}
}
";
CreateCompilation(source2, parseOptions: TestOptions.Regular7_2,
references: new[] { new CSharpCompilationReference(compilation1) })
.VerifyDiagnostics(
// (3,37): error CS0115: 'B.F()': no suitable method found to override
// override private protected void F() {}
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F").WithArguments("B.F()").WithLocation(3, 37),
// (1,7): error CS0534: 'B' does not implement inherited abstract member 'A.F()'
// class B : A // CS0534
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.F()").WithLocation(1, 7)
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void VerifyPPExtension()
{
string source = @"
static class Extensions
{
static private protected void SomeExtension(this string s) { } // error: no pp in static class
}
class Client
{
public static void M(string s)
{
s.SomeExtension(); // error: no accessible SomeExtension
}
}
";
CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
// (4,35): error CS1057: 'Extensions.SomeExtension(string)': static classes cannot contain protected members
// static private protected void SomeExtension(this string s) { } // error: no pp in static class
Diagnostic(ErrorCode.ERR_ProtectedInStatic, "SomeExtension").WithArguments("Extensions.SomeExtension(string)").WithLocation(4, 35),
// (11,11): error CS1061: 'string' does not contain a definition for 'SomeExtension' and no accessible extension method 'SomeExtension' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// s.SomeExtension(); // error: no accessible SomeExtension
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "SomeExtension").WithArguments("string", "SomeExtension").WithLocation(11, 11)
);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using static Roslyn.Test.Utilities.SigningTestHelpers;
using Xunit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
[CompilerTrait(CompilerFeature.PrivateProtected)]
public class PrivateProtected : CSharpTestBase
{
private static readonly string s_keyPairFile = SigningTestHelpers.KeyPairFile;
private static readonly string s_publicKeyFile = SigningTestHelpers.PublicKeyFile;
private static readonly ImmutableArray<byte> s_publicKey = SigningTestHelpers.PublicKey;
[ConditionalFact(typeof(DesktopOnly))]
public void RejectIncompatibleModifiers()
{
string source =
@"public class Base
{
private internal int Field1;
internal private int Field2;
private internal protected int Field3;
internal protected private int Field4;
private public protected int Field5;
private readonly protected int Field6; // ok
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
// (3,26): error CS0107: More than one protection modifier
// private internal int Field1;
Diagnostic(ErrorCode.ERR_BadMemberProtection, "Field1").WithLocation(3, 26),
// (4,26): error CS0107: More than one protection modifier
// internal private int Field2;
Diagnostic(ErrorCode.ERR_BadMemberProtection, "Field2").WithLocation(4, 26),
// (5,36): error CS0107: More than one protection modifier
// private internal protected int Field3;
Diagnostic(ErrorCode.ERR_BadMemberProtection, "Field3").WithLocation(5, 36),
// (6,36): error CS0107: More than one protection modifier
// internal protected private int Field4;
Diagnostic(ErrorCode.ERR_BadMemberProtection, "Field4").WithLocation(6, 36),
// (7,34): error CS0107: More than one protection modifier
// private public protected int Field5;
Diagnostic(ErrorCode.ERR_BadMemberProtection, "Field5").WithLocation(7, 34)
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void AccessibleWhereRequired_01()
{
string source =
@"public class Base
{
private protected int Field1;
protected private int Field2;
}
public class Derived : Base
{
void M()
{
Field1 = 1;
Field2 = 2;
}
}
";
var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void AccessibleWhereRequired_02()
{
string source1 =
@"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""WantsIVTAccess"")]
public class Base
{
private protected const int Constant = 3;
private protected int Field1;
protected private int Field2;
private protected void Method() { }
private protected event System.Action Event1;
private protected int Property1 { set {} }
public int Property2 { private protected set {} get { return 4; } }
private protected int this[int x] { set { } get { return 6; } }
public int this[string x] { private protected set { } get { return 5; } }
private protected Base() { Event1?.Invoke(); }
}";
var baseCompilation = CreateCompilation(source1, parseOptions: TestOptions.Regular7_2,
options: TestOptions.SigningReleaseDll,
assemblyName: "Paul");
var bb = (NamedTypeSymbol)baseCompilation.GlobalNamespace.GetMember("Base");
foreach (var member in bb.GetMembers())
{
switch (member.Name)
{
case "Property2":
case "get_Property2":
case "this[]":
case "get_Item":
break;
default:
Assert.Equal(Accessibility.ProtectedAndInternal, member.DeclaredAccessibility);
break;
}
}
string source2 =
@"public class Derived : Base
{
void M()
{
Field1 = Constant;
Field2 = Constant;
Method();
Event1 += null;
Property1 = Constant;
Property2 = Constant;
this[1] = 2;
this[string.Empty] = 4;
}
Derived(int x) : base() {}
Derived(long x) {} // implicit base()
}
";
CreateCompilation(source2, parseOptions: TestOptions.Regular7_2,
references: new[] { new CSharpCompilationReference(baseCompilation) },
assemblyName: "WantsIVTAccessButCantHave",
options: TestOptions.SigningReleaseDll)
.VerifyDiagnostics(
// (5,9): error CS0122: 'Base.Field1' is inaccessible due to its protection level
// Field1 = Constant;
Diagnostic(ErrorCode.ERR_BadAccess, "Field1").WithArguments("Base.Field1").WithLocation(5, 9),
// (5,18): error CS0122: 'Base.Constant' is inaccessible due to its protection level
// Field1 = Constant;
Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(5, 18),
// (6,9): error CS0122: 'Base.Field2' is inaccessible due to its protection level
// Field2 = Constant;
Diagnostic(ErrorCode.ERR_BadAccess, "Field2").WithArguments("Base.Field2").WithLocation(6, 9),
// (6,18): error CS0122: 'Base.Constant' is inaccessible due to its protection level
// Field2 = Constant;
Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(6, 18),
// (7,9): error CS0122: 'Base.Method()' is inaccessible due to its protection level
// Method();
Diagnostic(ErrorCode.ERR_BadAccess, "Method").WithArguments("Base.Method()").WithLocation(7, 9),
// (8,9): error CS0122: 'Base.Event1' is inaccessible due to its protection level
// Event1 += null;
Diagnostic(ErrorCode.ERR_BadAccess, "Event1").WithArguments("Base.Event1").WithLocation(8, 9),
// (8,9): error CS0122: 'Base.Event1.add' is inaccessible due to its protection level
// Event1 += null;
Diagnostic(ErrorCode.ERR_BadAccess, "Event1 += null").WithArguments("Base.Event1.add").WithLocation(8, 9),
// (9,9): error CS0122: 'Base.Property1' is inaccessible due to its protection level
// Property1 = Constant;
Diagnostic(ErrorCode.ERR_BadAccess, "Property1").WithArguments("Base.Property1").WithLocation(9, 9),
// (9,21): error CS0122: 'Base.Constant' is inaccessible due to its protection level
// Property1 = Constant;
Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(9, 21),
// (10,9): error CS0272: The property or indexer 'Base.Property2' cannot be used in this context because the set accessor is inaccessible
// Property2 = Constant;
Diagnostic(ErrorCode.ERR_InaccessibleSetter, "Property2").WithArguments("Base.Property2").WithLocation(10, 9),
// (10,21): error CS0122: 'Base.Constant' is inaccessible due to its protection level
// Property2 = Constant;
Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(10, 21),
// (11,14): error CS1503: Argument 1: cannot convert from 'int' to 'string'
// this[1] = 2;
Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "string").WithLocation(11, 14),
// (12,9): error CS0272: The property or indexer 'Base.this[string]' cannot be used in this context because the set accessor is inaccessible
// this[string.Empty] = 4;
Diagnostic(ErrorCode.ERR_InaccessibleSetter, "this[string.Empty]").WithArguments("Base.this[string]").WithLocation(12, 9),
// (14,22): error CS0122: 'Base.Base()' is inaccessible due to its protection level
// Derived(int x) : base() {}
Diagnostic(ErrorCode.ERR_BadAccess, "base").WithArguments("Base.Base()").WithLocation(14, 22),
// (15,5): error CS0122: 'Base.Base()' is inaccessible due to its protection level
// Derived(long x) {} // implicit base()
Diagnostic(ErrorCode.ERR_BadAccess, "Derived").WithArguments("Base.Base()").WithLocation(15, 5)
);
CreateCompilation(source2, parseOptions: TestOptions.Regular7_2,
references: new[] { MetadataReference.CreateFromImage(baseCompilation.EmitToArray()) },
assemblyName: "WantsIVTAccessButCantHave",
options: TestOptions.SigningReleaseDll)
.VerifyDiagnostics(
// (5,9): error CS0122: 'Base.Field1' is inaccessible due to its protection level
// Field1 = Constant;
Diagnostic(ErrorCode.ERR_BadAccess, "Field1").WithArguments("Base.Field1").WithLocation(5, 9),
// (5,18): error CS0122: 'Base.Constant' is inaccessible due to its protection level
// Field1 = Constant;
Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(5, 18),
// (6,9): error CS0122: 'Base.Field2' is inaccessible due to its protection level
// Field2 = Constant;
Diagnostic(ErrorCode.ERR_BadAccess, "Field2").WithArguments("Base.Field2").WithLocation(6, 9),
// (6,18): error CS0122: 'Base.Constant' is inaccessible due to its protection level
// Field2 = Constant;
Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(6, 18),
// (7,9): error CS0122: 'Base.Method()' is inaccessible due to its protection level
// Method();
Diagnostic(ErrorCode.ERR_BadAccess, "Method").WithArguments("Base.Method()").WithLocation(7, 9),
// (8,9): error CS0122: 'Base.Event1' is inaccessible due to its protection level
// Event1 += null;
Diagnostic(ErrorCode.ERR_BadAccess, "Event1").WithArguments("Base.Event1").WithLocation(8, 9),
// (8,9): error CS0122: 'Base.Event1.add' is inaccessible due to its protection level
// Event1 += null;
Diagnostic(ErrorCode.ERR_BadAccess, "Event1 += null").WithArguments("Base.Event1.add").WithLocation(8, 9),
// (9,9): error CS0122: 'Base.Property1' is inaccessible due to its protection level
// Property1 = Constant;
Diagnostic(ErrorCode.ERR_BadAccess, "Property1").WithArguments("Base.Property1").WithLocation(9, 9),
// (9,21): error CS0122: 'Base.Constant' is inaccessible due to its protection level
// Property1 = Constant;
Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(9, 21),
// (10,9): error CS0272: The property or indexer 'Base.Property2' cannot be used in this context because the set accessor is inaccessible
// Property2 = Constant;
Diagnostic(ErrorCode.ERR_InaccessibleSetter, "Property2").WithArguments("Base.Property2").WithLocation(10, 9),
// (10,21): error CS0122: 'Base.Constant' is inaccessible due to its protection level
// Property2 = Constant;
Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(10, 21),
// (11,14): error CS1503: Argument 1: cannot convert from 'int' to 'string'
// this[1] = 2;
Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "string").WithLocation(11, 14),
// (12,9): error CS0272: The property or indexer 'Base.this[string]' cannot be used in this context because the set accessor is inaccessible
// this[string.Empty] = 4;
Diagnostic(ErrorCode.ERR_InaccessibleSetter, "this[string.Empty]").WithArguments("Base.this[string]").WithLocation(12, 9),
// (14,22): error CS0122: 'Base.Base()' is inaccessible due to its protection level
// Derived(int x) : base() {}
Diagnostic(ErrorCode.ERR_BadAccess, "base").WithArguments("Base.Base()").WithLocation(14, 22),
// (15,5): error CS0122: 'Base.Base()' is inaccessible due to its protection level
// Derived(long x) {} // implicit base()
Diagnostic(ErrorCode.ERR_BadAccess, "Derived").WithArguments("Base.Base()").WithLocation(15, 5)
);
CreateCompilation(source2, parseOptions: TestOptions.Regular7_2,
references: new[] { new CSharpCompilationReference(baseCompilation) },
assemblyName: "WantsIVTAccess",
options: TestOptions.SigningReleaseDll)
.VerifyDiagnostics(
);
CreateCompilation(source2, parseOptions: TestOptions.Regular7_2,
references: new[] { MetadataReference.CreateFromImage(baseCompilation.EmitToArray()) },
assemblyName: "WantsIVTAccess",
options: TestOptions.SigningReleaseDll)
.VerifyDiagnostics(
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void NotAccessibleWhereRequired()
{
string source =
@"public class Base
{
private protected int Field1;
protected private int Field2;
}
public class Derived // : Base
{
void M()
{
Base b = null;
b.Field1 = 1;
b.Field2 = 2;
}
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
// (12,11): error CS0122: 'Base.Field1' is inaccessible due to its protection level
// b.Field1 = 1;
Diagnostic(ErrorCode.ERR_BadAccess, "Field1").WithArguments("Base.Field1").WithLocation(12, 11),
// (13,11): error CS0122: 'Base.Field2' is inaccessible due to its protection level
// b.Field2 = 2;
Diagnostic(ErrorCode.ERR_BadAccess, "Field2").WithArguments("Base.Field2").WithLocation(13, 11)
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void NotInStructOrNamespace()
{
string source =
@"protected private struct Struct
{
private protected int Field1;
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
// (1,18): error CS1527: Elements defined in a namespace cannot be explicitly declared as private, protected, protected internal, or private protected
// protected private struct Struct
Diagnostic(ErrorCode.ERR_NoNamespacePrivate, "Struct").WithLocation(1, 26),
// (3,27): error CS0666: 'Struct.Field1': new protected member declared in struct
// private protected int Field1;
Diagnostic(ErrorCode.ERR_ProtectedInStruct, "Field1").WithArguments("Struct.Field1").WithLocation(3, 27)
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void NotInStaticClass()
{
string source =
@"static class C
{
static private protected int Field1 = 2;
}
sealed class D
{
static private protected int Field2 = 2;
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
// (7,34): warning CS0628: 'D.Field2': new protected member declared in sealed type
// static private protected int Field2 = 2;
Diagnostic(ErrorCode.WRN_ProtectedInSealed, "Field2").WithArguments("D.Field2").WithLocation(7, 34),
// (3,34): error CS1057: 'C.Field1': static classes cannot contain protected members
// static private protected int Field1 = 2;
Diagnostic(ErrorCode.ERR_ProtectedInStatic, "Field1").WithArguments("C.Field1").WithLocation(3, 34)
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void NestedTypes()
{
string source =
@"class Outer
{
private protected class Inner
{
}
}
class Derived : Outer
{
public void M()
{
Outer.Inner x = null;
}
}
class NotDerived
{
public void M()
{
Outer.Inner x = null; // error: Outer.Inner not accessible
}
}
struct Struct
{
private protected class Inner // error: protected not allowed in struct
{
}
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
// (23,29): error CS0666: 'Struct.Inner': new protected member declared in struct
// private protected class Inner // error: protected not allowed in struct
Diagnostic(ErrorCode.ERR_ProtectedInStruct, "Inner").WithArguments("Struct.Inner").WithLocation(23, 29),
// (11,21): warning CS0219: The variable 'x' is assigned but its value is never used
// Outer.Inner x = null;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(11, 21),
// (18,15): error CS0122: 'Outer.Inner' is inaccessible due to its protection level
// Outer.Inner x = null; // error: Outer.Inner not accessible
Diagnostic(ErrorCode.ERR_BadAccess, "Inner").WithArguments("Outer.Inner").WithLocation(18, 15)
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void PermittedAccessorProtection()
{
string source =
@"class Class
{
public int Prop1 { get; private protected set; }
protected internal int Prop2 { get; private protected set; }
protected int Prop3 { get; private protected set; }
internal int Prop4 { get; private protected set; }
private protected int Prop5 { get; private set; }
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void ForbiddenAccessorProtection_01()
{
string source =
@"class Class
{
private protected int Prop1 { get; private protected set; }
private int Prop2 { get; private protected set; }
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
// (3,58): error CS0273: The accessibility modifier of the 'Class.Prop1.set' accessor must be more restrictive than the property or indexer 'Class.Prop1'
// private protected int Prop1 { get; private protected set; }
Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("Class.Prop1.set", "Class.Prop1").WithLocation(3, 58),
// (4,48): error CS0273: The accessibility modifier of the 'Class.Prop2.set' accessor must be more restrictive than the property or indexer 'Class.Prop2'
// private int Prop2 { get; private protected set; }
Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("Class.Prop2.set", "Class.Prop2").WithLocation(4, 48)
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void ForbiddenAccessorProtection_02()
{
string source =
@"interface ISomething
{
private protected int M();
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
// (3,27): error CS8503: The modifier 'private protected' is not valid for this item in C# 7.2. Please use language version '8.0' or greater.
// private protected int M();
Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M").WithArguments("private protected", "7.2", "8.0").WithLocation(3, 27),
// (3,27): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface.
// private protected int M();
Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "M").WithLocation(3, 27)
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void AtLeastAsRestrictivePositive_01()
{
string source =
@"
public class C
{
internal class Internal {}
protected class Protected {}
private protected class PrivateProtected {}
private protected void M(Internal x) {} // ok
private protected void M(Protected x) {} // ok
private protected void M(PrivateProtected x) {} // ok
private protected class Nested
{
public void M(Internal x) {} // ok
public void M(Protected x) {} // ok
private protected void M(PrivateProtected x) {} // ok
}
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void AtLeastAsRestrictiveNegative_01()
{
string source =
@"
public class Container
{
private protected class PrivateProtected {}
internal void M1(PrivateProtected x) {} // error: conflicting access
protected void M2(PrivateProtected x) {} // error: conflicting access
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
// (6,20): error CS0051: Inconsistent accessibility: parameter type 'Container.PrivateProtected' is less accessible than method 'Container.M2(Container.PrivateProtected)'
// protected void M2(PrivateProtected x) {} // error: conflicting access
Diagnostic(ErrorCode.ERR_BadVisParamType, "M2").WithArguments("Container.M2(Container.PrivateProtected)", "Container.PrivateProtected").WithLocation(6, 20),
// (5,19): error CS0051: Inconsistent accessibility: parameter type 'Container.PrivateProtected' is less accessible than method 'Container.M1(Container.PrivateProtected)'
// internal void M1(PrivateProtected x) {} // error: conflicting access
Diagnostic(ErrorCode.ERR_BadVisParamType, "M1").WithArguments("Container.M1(Container.PrivateProtected)", "Container.PrivateProtected").WithLocation(5, 19)
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void DuplicateAccessInBinder()
{
string source =
@"
public class Container
{
private public int Field; // 1
private public int Property { get; set; } // 2
private public int M() => 1; // 3
private public class C {} // 4
private public struct S {} // 5
private public enum E {} // 6
private public event System.Action V; // 7
private public interface I {} // 8
private public int this[int index] => 1; // 9
void Q() { V.Invoke(); V = null; }
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
// (7,26): error CS0107: More than one protection modifier
// private public class C {} // 4
Diagnostic(ErrorCode.ERR_BadMemberProtection, "C").WithLocation(7, 26),
// (8,27): error CS0107: More than one protection modifier
// private public struct S {} // 5
Diagnostic(ErrorCode.ERR_BadMemberProtection, "S").WithLocation(8, 27),
// (9,25): error CS0107: More than one protection modifier
// private public enum E {} // 6
Diagnostic(ErrorCode.ERR_BadMemberProtection, "E").WithLocation(9, 25),
// (11,30): error CS0107: More than one protection modifier
// private public interface I {} // 8
Diagnostic(ErrorCode.ERR_BadMemberProtection, "I").WithLocation(11, 30),
// (4,24): error CS0107: More than one protection modifier
// private public int Field; // 1
Diagnostic(ErrorCode.ERR_BadMemberProtection, "Field").WithLocation(4, 24),
// (5,24): error CS0107: More than one protection modifier
// private public int Property { get; set; } // 2
Diagnostic(ErrorCode.ERR_BadMemberProtection, "Property").WithLocation(5, 24),
// (6,24): error CS0107: More than one protection modifier
// private public int M() => 1; // 3
Diagnostic(ErrorCode.ERR_BadMemberProtection, "M").WithLocation(6, 24),
// (10,40): error CS0107: More than one protection modifier
// private public event System.Action V; // 7
Diagnostic(ErrorCode.ERR_BadMemberProtection, "V").WithLocation(10, 40),
// (12,24): error CS0107: More than one protection modifier
// private public int this[int index] => 1; // 9
Diagnostic(ErrorCode.ERR_BadMemberProtection, "this").WithLocation(12, 24),
// (12,43): error CS0107: More than one protection modifier
// private public int this[int index] => 1; // 9
Diagnostic(ErrorCode.ERR_BadMemberProtection, "1").WithLocation(12, 43)
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void NotInVersion71()
{
string source =
@"
public class Container
{
private protected int Field; // 1
private protected int Property { get; set; } // 2
private protected int M() => 1; // 3
private protected class C {} // 4
private protected struct S {} // 5
private protected enum E {} // 6
private protected event System.Action V; // 7
private protected interface I {} // 8
private protected int this[int index] => 1; // 9
void Q() { V.Invoke(); V = null; }
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular7_1)
.VerifyDiagnostics(
// (7,29): error CS8302: Feature 'private protected' is not available in C# 7.1. Please use language version 7.2 or greater.
// private protected class C {} // 4
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "C").WithArguments("private protected", "7.2").WithLocation(7, 29),
// (8,30): error CS8302: Feature 'private protected' is not available in C# 7.1. Please use language version 7.2 or greater.
// private protected struct S {} // 5
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "S").WithArguments("private protected", "7.2").WithLocation(8, 30),
// (9,28): error CS8302: Feature 'private protected' is not available in C# 7.1. Please use language version 7.2 or greater.
// private protected enum E {} // 6
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "E").WithArguments("private protected", "7.2").WithLocation(9, 28),
// (11,33): error CS8302: Feature 'private protected' is not available in C# 7.1. Please use language version 7.2 or greater.
// private protected interface I {} // 8
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "I").WithArguments("private protected", "7.2").WithLocation(11, 33),
// (4,27): error CS8302: Feature 'private protected' is not available in C# 7.1. Please use language version 7.2 or greater.
// private protected int Field; // 1
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "Field").WithArguments("private protected", "7.2").WithLocation(4, 27),
// (5,27): error CS8302: Feature 'private protected' is not available in C# 7.1. Please use language version 7.2 or greater.
// private protected int Property { get; set; } // 2
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "Property").WithArguments("private protected", "7.2").WithLocation(5, 27),
// (6,27): error CS8302: Feature 'private protected' is not available in C# 7.1. Please use language version 7.2 or greater.
// private protected int M() => 1; // 3
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "M").WithArguments("private protected", "7.2").WithLocation(6, 27),
// (10,43): error CS8302: Feature 'private protected' is not available in C# 7.1. Please use language version 7.2 or greater.
// private protected event System.Action V; // 7
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "V").WithArguments("private protected", "7.2").WithLocation(10, 43),
// (12,27): error CS8302: Feature 'private protected' is not available in C# 7.1. Please use language version 7.2 or greater.
// private protected int this[int index] => 1; // 9
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "this").WithArguments("private protected", "7.2").WithLocation(12, 27)
);
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void VerifyPrivateProtectedIL()
{
var text = @"
class Program
{
private protected void M() {}
private protected int F;
}
";
var verifier = CompileAndVerify(
text,
parseOptions: TestOptions.Regular7_2,
expectedSignatures: new[]
{
Signature("Program", "M", ".method famandassem hidebysig instance System.Void M() cil managed"),
Signature("Program", "F", ".field famandassem instance System.Int32 F"),
});
}
[ConditionalFact(typeof(DesktopOnly))]
public void VerifyPartialPartsMatch()
{
var source =
@"class Outer
{
private protected partial class Inner {}
private partial class Inner {}
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
// (3,37): error CS0262: Partial declarations of 'Outer.Inner' have conflicting accessibility modifiers
// private protected partial class Inner {}
Diagnostic(ErrorCode.ERR_PartialModifierConflict, "Inner").WithArguments("Outer.Inner").WithLocation(3, 37)
);
source =
@"class Outer
{
private protected partial class Inner {}
private protected partial class Inner {}
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void VerifyProtectedSemantics()
{
var source =
@"class Base
{
private protected void M()
{
System.Console.WriteLine(this.GetType().Name);
}
}
class Derived : Base
{
public void Main()
{
Derived derived = new Derived();
derived.M();
Base bb = new Base();
bb.M(); // error 1
Other other = new Other();
other.M(); // error 2
}
}
class Other : Base
{
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
// (16,12): error CS1540: Cannot access protected member 'Base.M()' via a qualifier of type 'Base'; the qualifier must be of type 'Derived' (or derived from it)
// bb.M(); // error 1
Diagnostic(ErrorCode.ERR_BadProtectedAccess, "M").WithArguments("Base.M()", "Base", "Derived").WithLocation(16, 12),
// (18,15): error CS1540: Cannot access protected member 'Base.M()' via a qualifier of type 'Other'; the qualifier must be of type 'Derived' (or derived from it)
// other.M(); // error 2
Diagnostic(ErrorCode.ERR_BadProtectedAccess, "M").WithArguments("Base.M()", "Other", "Derived").WithLocation(18, 15)
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void HidingAbstract()
{
var source =
@"abstract class A
{
internal abstract void F();
}
abstract class B : A
{
private protected new void F() { } // No CS0533
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void HidingInaccessible()
{
string source1 =
@"public class A
{
private protected void F() { }
}
";
var compilation1 = CreateCompilation(source1, parseOptions: TestOptions.Regular7_2);
compilation1.VerifyDiagnostics();
string source2 =
@"class B : A
{
new void F() { } // CS0109
}
";
CreateCompilation(source2, parseOptions: TestOptions.Regular7_2,
references: new[] { new CSharpCompilationReference(compilation1) })
.VerifyDiagnostics(
// (3,14): warning CS0109: The member 'B.F()' does not hide an accessible member. The new keyword is not required.
// new void F() { } // CS0109
Diagnostic(ErrorCode.WRN_NewNotRequired, "F").WithArguments("B.F()").WithLocation(3, 14)
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void UnimplementedInaccessible()
{
string source1 =
@"public abstract class A
{
private protected abstract void F();
}
";
var compilation1 = CreateCompilation(source1, parseOptions: TestOptions.Regular7_2);
compilation1.VerifyDiagnostics();
string source2 =
@"class B : A // CS0534
{
}
";
CreateCompilation(source2, parseOptions: TestOptions.Regular7_2,
references: new[] { new CSharpCompilationReference(compilation1) })
.VerifyDiagnostics(
// (1,7): error CS0534: 'B' does not implement inherited abstract member 'A.F()'
// class B : A // CS0534
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.F()").WithLocation(1, 7)
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void ImplementInaccessible()
{
string source1 =
@"public abstract class A
{
private protected abstract void F();
}
";
var compilation1 = CreateCompilation(source1, parseOptions: TestOptions.Regular7_2);
compilation1.VerifyDiagnostics();
string source2 =
@"class B : A // CS0534
{
override private protected void F() {}
}
";
CreateCompilation(source2, parseOptions: TestOptions.Regular7_2,
references: new[] { new CSharpCompilationReference(compilation1) })
.VerifyDiagnostics(
// (3,37): error CS0115: 'B.F()': no suitable method found to override
// override private protected void F() {}
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F").WithArguments("B.F()").WithLocation(3, 37),
// (1,7): error CS0534: 'B' does not implement inherited abstract member 'A.F()'
// class B : A // CS0534
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.F()").WithLocation(1, 7)
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void VerifyPPExtension()
{
string source = @"
static class Extensions
{
static private protected void SomeExtension(this string s) { } // error: no pp in static class
}
class Client
{
public static void M(string s)
{
s.SomeExtension(); // error: no accessible SomeExtension
}
}
";
CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Regular7_2)
.VerifyDiagnostics(
// (4,35): error CS1057: 'Extensions.SomeExtension(string)': static classes cannot contain protected members
// static private protected void SomeExtension(this string s) { } // error: no pp in static class
Diagnostic(ErrorCode.ERR_ProtectedInStatic, "SomeExtension").WithArguments("Extensions.SomeExtension(string)").WithLocation(4, 35),
// (11,11): error CS1061: 'string' does not contain a definition for 'SomeExtension' and no accessible extension method 'SomeExtension' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// s.SomeExtension(); // error: no accessible SomeExtension
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "SomeExtension").WithArguments("string", "SomeExtension").WithLocation(11, 11)
);
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/VisualStudio/IntegrationTest/TestUtilities/Input/SendKeys_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.Threading;
using Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Input
{
internal class SendKeys_InProc : AbstractSendKeys
{
private readonly VisualStudio_InProc _visualStudioInstance;
public SendKeys_InProc(VisualStudio_InProc visualStudioInstance)
{
_visualStudioInstance = visualStudioInstance;
}
protected override void ActivateMainWindow()
{
_visualStudioInstance.ActivateMainWindow();
}
protected override void WaitForApplicationIdle(CancellationToken cancellationToken)
{
_visualStudioInstance.WaitForApplicationIdle(Helper.HangMitigatingTimeout);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Input
{
internal class SendKeys_InProc : AbstractSendKeys
{
private readonly VisualStudio_InProc _visualStudioInstance;
public SendKeys_InProc(VisualStudio_InProc visualStudioInstance)
{
_visualStudioInstance = visualStudioInstance;
}
protected override void ActivateMainWindow()
{
_visualStudioInstance.ActivateMainWindow();
}
protected override void WaitForApplicationIdle(CancellationToken cancellationToken)
{
_visualStudioInstance.WaitForApplicationIdle(Helper.HangMitigatingTimeout);
}
}
}
| -1 |
dotnet/roslyn | 55,522 | Call new document formatting service from extract type | This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | davidwengier | 2021-08-10T01:07:17Z | 2021-08-12T23:53:19Z | d1e617ded188343ba43d24590802dd51e68e8e32 | 84383fa5f482ada0cdd51c2a4e94af4cd3886924 | Call new document formatting service from extract type. This makes Extract Type/Interface use the new document formatting service, so it now supports file header templates from .editorconfig, and using directive placement options, and other fun things. | ./src/EditorFeatures/Core/EditorConfigSettings/Updater/AnalyzerSettingsUpdater.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater
{
internal class AnalyzerSettingsUpdater : SettingsUpdaterBase<AnalyzerSetting, DiagnosticSeverity>
{
public AnalyzerSettingsUpdater(Workspace workspace, string editorconfigPath) : base(workspace, editorconfigPath)
{
}
protected override SourceText? GetNewText(SourceText sourceText,
IReadOnlyList<(AnalyzerSetting option, DiagnosticSeverity value)> settingsToUpdate,
CancellationToken token)
=> SettingsUpdateHelper.TryUpdateAnalyzerConfigDocument(sourceText, EditorconfigPath, settingsToUpdate);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater
{
internal class AnalyzerSettingsUpdater : SettingsUpdaterBase<AnalyzerSetting, DiagnosticSeverity>
{
public AnalyzerSettingsUpdater(Workspace workspace, string editorconfigPath) : base(workspace, editorconfigPath)
{
}
protected override SourceText? GetNewText(SourceText sourceText,
IReadOnlyList<(AnalyzerSetting option, DiagnosticSeverity value)> settingsToUpdate,
CancellationToken token)
=> SettingsUpdateHelper.TryUpdateAnalyzerConfigDocument(sourceText, EditorconfigPath, settingsToUpdate);
}
}
| -1 |
dotnet/roslyn | 55,504 | Format new document namespace declarations | Fixes https://github.com/dotnet/roslyn/issues/55417
| davidwengier | 2021-08-09T07:51:27Z | 2021-08-10T11:42:04Z | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | 782f71d3ada7ae95e42af182405824aeff12daeb | Format new document namespace declarations. Fixes https://github.com/dotnet/roslyn/issues/55417
| ./src/EditorFeatures/CSharpTest/Formatting/CSharpNewDocumentFormattingServiceTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.AddImports;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities.Formatting;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting
{
public class CSharpNewDocumentFormattingServiceTests : AbstractNewDocumentFormattingServiceTests
{
protected override string Language => LanguageNames.CSharp;
protected override TestWorkspace CreateTestWorkspace(string testCode)
=> TestWorkspace.CreateCSharp(testCode);
[Fact]
public async Task TestOrganizeUsingsWithNoUsings()
{
var testCode = @"namespace Goo
{
}";
await TestAsync(
testCode: testCode,
expected: testCode,
options:
(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.OutsideNamespace, NotificationOption2.Error)));
}
[Fact]
public async Task TestFileBanners()
{
await TestAsync(testCode: @"using System;
namespace Goo
{
}",
expected: @"// This is a banner.
using System;
namespace Goo
{
}",
options:
(CodeStyleOptions2.FileHeaderTemplate, "This is a banner."));
}
[Fact]
public async Task TestAccessibilityModifiers()
{
await TestAsync(testCode: @"using System;
namespace Goo
{
class C
{
}
}",
expected: @"using System;
namespace Goo
{
internal class C
{
}
}",
options:
(CodeStyleOptions2.RequireAccessibilityModifiers, new CodeStyleOption2<AccessibilityModifiersRequired>(AccessibilityModifiersRequired.Always, NotificationOption2.Error)));
}
[Fact]
public async Task TestUsingDirectivePlacement()
{
await TestAsync(testCode: @"using System;
namespace Goo
{
}",
expected: @"namespace Goo
{
using System;
}",
options:
(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.InsideNamespace, NotificationOption2.Error)));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.AddImports;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Test.Utilities.Formatting;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting
{
public class CSharpNewDocumentFormattingServiceTests : AbstractNewDocumentFormattingServiceTests
{
protected override string Language => LanguageNames.CSharp;
protected override TestWorkspace CreateTestWorkspace(string testCode, ParseOptions? parseOptions)
=> TestWorkspace.CreateCSharp(testCode, parseOptions);
[Fact]
public async Task TestFileScopedNamespaces()
{
await TestAsync(testCode: @"
namespace Goo
{
internal class C
{
}
}",
expected: @"
namespace Goo;
internal class C
{
}
",
options: new[]
{
(CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2<NamespaceDeclarationPreference>(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Error))
},
parseOptions: new CSharpParseOptions(LanguageVersion.CSharp10));
}
[Fact]
public async Task TestFileScopedNamespaces_Invalid_MultipleNamespaces()
{
var testCode = @"
namespace Goo
{
}
namespace Bar
{
}";
await TestAsync(
testCode: testCode,
expected: testCode,
options: new[]
{
(CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2<NamespaceDeclarationPreference>(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Error))
},
parseOptions: new CSharpParseOptions(LanguageVersion.CSharp10));
}
[Fact]
public async Task TestFileScopedNamespaces_Invalid_WrongLanguageVersion()
{
var testCode = @"
namespace Goo
{
internal class C
{
}
}";
await TestAsync(
testCode: testCode,
expected: testCode,
options: new[]
{
(CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2<NamespaceDeclarationPreference>(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Error))
},
parseOptions: new CSharpParseOptions(LanguageVersion.CSharp9));
}
[Fact]
public async Task TestBlockScopedNamespaces()
{
await TestAsync(testCode: @"
namespace Goo;
internal class C
{
}
",
expected: @"
namespace Goo
{
internal class C
{
}
}",
options: new[]
{
(CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2<NamespaceDeclarationPreference>(NamespaceDeclarationPreference.BlockScoped, NotificationOption2.Error))
});
}
[Fact]
public async Task TestOrganizeUsingsWithNoUsings()
{
var testCode = @"namespace Goo
{
}";
await TestAsync(
testCode: testCode,
expected: testCode,
options: new[]
{
(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.OutsideNamespace, NotificationOption2.Error))
});
}
[Fact]
public async Task TestFileBanners()
{
await TestAsync(testCode: @"using System;
namespace Goo
{
}",
expected: @"// This is a banner.
using System;
namespace Goo
{
}",
options: new[]
{
(CodeStyleOptions2.FileHeaderTemplate, "This is a banner.")
});
}
[Fact]
public async Task TestAccessibilityModifiers()
{
await TestAsync(testCode: @"using System;
namespace Goo
{
class C
{
}
}",
expected: @"using System;
namespace Goo
{
internal class C
{
}
}",
options: new[]
{
(CodeStyleOptions2.RequireAccessibilityModifiers, new CodeStyleOption2<AccessibilityModifiersRequired>(AccessibilityModifiersRequired.Always, NotificationOption2.Error))
});
}
[Fact]
public async Task TestUsingDirectivePlacement()
{
await TestAsync(testCode: @"using System;
namespace Goo
{
}",
expected: @"namespace Goo
{
using System;
}",
options: new[]
{
(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.InsideNamespace, NotificationOption2.Error))
});
}
}
}
| 1 |
dotnet/roslyn | 55,504 | Format new document namespace declarations | Fixes https://github.com/dotnet/roslyn/issues/55417
| davidwengier | 2021-08-09T07:51:27Z | 2021-08-10T11:42:04Z | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | 782f71d3ada7ae95e42af182405824aeff12daeb | Format new document namespace declarations. Fixes https://github.com/dotnet/roslyn/issues/55417
| ./src/EditorFeatures/TestUtilities/Formatting/AbstractNewDocumentFormattingServiceTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Test.Utilities;
namespace Microsoft.CodeAnalysis.Test.Utilities.Formatting
{
[UseExportProvider]
public abstract class AbstractNewDocumentFormattingServiceTests
{
protected abstract string Language { get; }
protected abstract TestWorkspace CreateTestWorkspace(string testCode);
internal Task TestAsync<T>(string testCode, string expected, params (PerLanguageOption2<T>, T)[] options)
{
return TestCoreAsync<T>(testCode,
expected,
options.Select(o => (new OptionKey(o.Item1, Language), o.Item2)).ToArray());
}
internal Task TestAsync<T>(string testCode, string expected, params (Option2<T>, T)[] options)
{
return TestCoreAsync<T>(testCode,
expected,
options.Select(o => (new OptionKey(o.Item1), o.Item2)).ToArray());
}
private async Task TestCoreAsync<T>(string testCode, string expected, (OptionKey, T)[] options)
{
using (var workspace = CreateTestWorkspace(testCode))
{
var workspaceOptions = workspace.Options;
foreach (var option in options)
{
workspaceOptions = workspaceOptions.WithChangedOption(option.Item1, option.Item2);
}
workspace.SetOptions(workspaceOptions);
var document = workspace.CurrentSolution.Projects.First().Documents.First();
var formattingService = document.GetRequiredLanguageService<INewDocumentFormattingService>();
var formattedDocument = await formattingService.FormatNewDocumentAsync(document, hintDocument: null, CancellationToken.None);
// Format to match what AbstractEditorFactory does
formattedDocument = await Formatter.FormatAsync(formattedDocument);
var actual = await formattedDocument.GetTextAsync();
AssertEx.EqualOrDiff(expected, actual.ToString());
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Test.Utilities;
namespace Microsoft.CodeAnalysis.Test.Utilities.Formatting
{
[UseExportProvider]
public abstract class AbstractNewDocumentFormattingServiceTests
{
protected abstract string Language { get; }
protected abstract TestWorkspace CreateTestWorkspace(string testCode, ParseOptions? parseOptions);
internal Task TestAsync(string testCode, string expected)
{
return TestCoreAsync<object>(testCode, expected, options: null, parseOptions: null);
}
internal Task TestAsync<T>(string testCode, string expected, (PerLanguageOption2<T>, T)[]? options = null, ParseOptions? parseOptions = null)
{
return TestCoreAsync<T>(testCode,
expected,
options.Select(o => (new OptionKey(o.Item1, Language), o.Item2)).ToArray(),
parseOptions);
}
internal Task TestAsync<T>(string testCode, string expected, (Option2<T>, T)[]? options = null, ParseOptions? parseOptions = null)
{
return TestCoreAsync<T>(testCode,
expected,
options.Select(o => (new OptionKey(o.Item1), o.Item2)).ToArray(),
parseOptions);
}
private async Task TestCoreAsync<T>(string testCode, string expected, (OptionKey, T)[]? options, ParseOptions? parseOptions)
{
using (var workspace = CreateTestWorkspace(testCode, parseOptions))
{
if (options is not null)
{
var workspaceOptions = workspace.Options;
foreach (var option in options)
{
workspaceOptions = workspaceOptions.WithChangedOption(option.Item1, option.Item2);
}
workspace.SetOptions(workspaceOptions);
}
var document = workspace.CurrentSolution.Projects.First().Documents.First();
var formattingService = document.GetRequiredLanguageService<INewDocumentFormattingService>();
var formattedDocument = await formattingService.FormatNewDocumentAsync(document, hintDocument: null, CancellationToken.None);
// Format to match what AbstractEditorFactory does
formattedDocument = await Formatter.FormatAsync(formattedDocument);
var actual = await formattedDocument.GetTextAsync();
AssertEx.EqualOrDiff(expected, actual.ToString());
}
}
}
}
| 1 |
dotnet/roslyn | 55,504 | Format new document namespace declarations | Fixes https://github.com/dotnet/roslyn/issues/55417
| davidwengier | 2021-08-09T07:51:27Z | 2021-08-10T11:42:04Z | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | 782f71d3ada7ae95e42af182405824aeff12daeb | Format new document namespace declarations. Fixes https://github.com/dotnet/roslyn/issues/55417
| ./src/EditorFeatures/VisualBasicTest/Formatting/VisualBasicNewDocumentFormattingServiceTests.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.CodeStyle
Imports Microsoft.CodeAnalysis.Editor.UnitTests
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Test.Utilities.Formatting
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Formatting
Public Class VisualBasicNewDocumentFormattingServiceTests
Inherits AbstractNewDocumentFormattingServiceTests
Protected Overrides ReadOnly Property Language As String = LanguageNames.VisualBasic
Protected Overrides Function CreateTestWorkspace(testCode As String) As TestWorkspace
Return TestWorkspace.CreateVisualBasic(testCode)
End Function
<Fact>
Public Async Function TestFileBanners() As Task
Await TestAsync(
testCode:="Imports System
Namespace Goo
End Namespace",
expected:="' This is a banner.
Imports System
Namespace Goo
End Namespace",
(CodeStyleOptions2.FileHeaderTemplate, "This is a banner."))
End Function
<Fact>
Public Async Function TestOrganizeUsings() As Task
Await TestAsync(
testCode:="Imports Aaa
Imports System
Namespace Goo
End Namespace",
expected:="Imports System
Imports Aaa
Namespace Goo
End Namespace",
Array.Empty(Of (Option2(Of Object), Object)))
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.CodeStyle
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Test.Utilities.Formatting
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Formatting
Public Class VisualBasicNewDocumentFormattingServiceTests
Inherits AbstractNewDocumentFormattingServiceTests
Protected Overrides ReadOnly Property Language As String = LanguageNames.VisualBasic
Protected Overrides Function CreateTestWorkspace(testCode As String, parseOptions As ParseOptions) As TestWorkspace
Return TestWorkspace.CreateVisualBasic(testCode, parseOptions)
End Function
<Fact>
Public Async Function TestFileBanners() As Task
Await TestAsync(
testCode:="Imports System
Namespace Goo
End Namespace",
expected:="' This is a banner.
Imports System
Namespace Goo
End Namespace",
options:={(CodeStyleOptions2.FileHeaderTemplate, "This is a banner.")})
End Function
<Fact>
Public Async Function TestOrganizeUsings() As Task
Await TestAsync(
testCode:="Imports Aaa
Imports System
Namespace Goo
End Namespace",
expected:="Imports System
Imports Aaa
Namespace Goo
End Namespace")
End Function
End Class
End Namespace
| 1 |
dotnet/roslyn | 55,504 | Format new document namespace declarations | Fixes https://github.com/dotnet/roslyn/issues/55417
| davidwengier | 2021-08-09T07:51:27Z | 2021-08-10T11:42:04Z | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | 782f71d3ada7ae95e42af182405824aeff12daeb | Format new document namespace declarations. Fixes https://github.com/dotnet/roslyn/issues/55417
| ./src/Features/CSharp/Portable/CodeRefactorings/LambdaSimplifier/LambdaSimplifierCodeRefactoringProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.LambdaSimplifier
{
// Disabled due to: https://github.com/dotnet/roslyn/issues/5835 & https://github.com/dotnet/roslyn/pull/6642
// [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.SimplifyLambda)]
internal partial class LambdaSimplifierCodeRefactoringProvider : CodeRefactoringProvider
{
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, textSpan, cancellationToken) = context;
if (cancellationToken.IsCancellationRequested)
{
return;
}
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
{
return;
}
var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
var lambda = await context.TryGetRelevantNodeAsync<LambdaExpressionSyntax>().ConfigureAwait(false);
if (lambda == null)
{
return;
}
if (!CanSimplify(semanticDocument, lambda as SimpleLambdaExpressionSyntax, cancellationToken) &&
!CanSimplify(semanticDocument, lambda as ParenthesizedLambdaExpressionSyntax, cancellationToken))
{
return;
}
context.RegisterRefactoring(
new MyCodeAction(
CSharpFeaturesResources.Simplify_lambda_expression,
c => SimplifyLambdaAsync(document, lambda, c)),
lambda.Span);
context.RegisterRefactoring(
new MyCodeAction(
CSharpFeaturesResources.Simplify_all_occurrences,
c => SimplifyAllLambdasAsync(document, c)),
lambda.Span);
}
private static async Task<Document> SimplifyLambdaAsync(
Document document,
SyntaxNode lambda,
CancellationToken cancellationToken)
{
var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
var rewriter = new Rewriter(semanticDocument, n => n == lambda, cancellationToken);
var result = rewriter.Visit(semanticDocument.Root);
return document.WithSyntaxRoot(result);
}
private static async Task<Document> SimplifyAllLambdasAsync(
Document document,
CancellationToken cancellationToken)
{
var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
var rewriter = new Rewriter(semanticDocument, n => true, cancellationToken);
var result = rewriter.Visit(semanticDocument.Root);
return document.WithSyntaxRoot(result);
}
private static bool CanSimplify(
SemanticDocument document,
SimpleLambdaExpressionSyntax node,
CancellationToken cancellationToken)
{
if (node == null)
{
return false;
}
var paramName = node.Parameter.Identifier;
var invocation = TryGetInvocationExpression(node.Body);
return CanSimplify(document, node, new List<SyntaxToken>() { paramName }, invocation, cancellationToken);
}
private static bool CanSimplify(
SemanticDocument document,
ParenthesizedLambdaExpressionSyntax node,
CancellationToken cancellationToken)
{
if (node == null)
{
return false;
}
var paramNames = node.ParameterList.Parameters.Select(p => p.Identifier).ToList();
var invocation = TryGetInvocationExpression(node.Body);
return CanSimplify(document, node, paramNames, invocation, cancellationToken);
}
private static bool CanSimplify(
SemanticDocument document,
ExpressionSyntax lambda,
List<SyntaxToken> paramNames,
InvocationExpressionSyntax invocation,
CancellationToken cancellationToken)
{
if (invocation == null)
{
return false;
}
if (invocation.ArgumentList.Arguments.Count != paramNames.Count)
{
return false;
}
for (var i = 0; i < paramNames.Count; i++)
{
var argument = invocation.ArgumentList.Arguments[i];
if (argument.NameColon != null ||
argument.RefOrOutKeyword.Kind() != SyntaxKind.None ||
!argument.Expression.IsKind(SyntaxKind.IdentifierName, out IdentifierNameSyntax identifierName))
{
return false;
}
if (identifierName.Identifier.ValueText != paramNames[i].ValueText)
{
return false;
}
}
var semanticModel = document.SemanticModel;
var lambdaSemanticInfo = semanticModel.GetSymbolInfo(lambda, cancellationToken);
var invocationSemanticInfo = semanticModel.GetSymbolInfo(invocation, cancellationToken);
if (lambdaSemanticInfo.Symbol == null ||
invocationSemanticInfo.Symbol == null)
{
// Don't offer this if there are any errors or ambiguities.
return false;
}
if (!(lambdaSemanticInfo.Symbol is IMethodSymbol lambdaMethod) || !(invocationSemanticInfo.Symbol is IMethodSymbol invocationMethod))
{
return false;
}
// TODO(cyrusn): Handle extension methods as well.
if (invocationMethod.IsExtensionMethod)
{
return false;
}
// Check if any of the parameter is of Type Dynamic
foreach (var parameter in lambdaMethod.Parameters)
{
if (parameter.Type != null && parameter.Type.Kind == SymbolKind.DynamicType)
{
return false;
}
}
// Check if the parameter and return types match between the lambda and the
// invocation. Note: return types can be covariant and argument types can be
// contravariant.
if (lambdaMethod.ReturnsVoid != invocationMethod.ReturnsVoid ||
lambdaMethod.Parameters.Length != invocationMethod.Parameters.Length)
{
return false;
}
if (!lambdaMethod.ReturnsVoid)
{
// Return type has to be covariant.
var conversion = document.SemanticModel.Compilation.ClassifyConversion(
invocationMethod.ReturnType, lambdaMethod.ReturnType);
if (!conversion.IsIdentityOrImplicitReference())
{
return false;
}
}
// Parameter types have to be contravariant.
for (var i = 0; i < lambdaMethod.Parameters.Length; i++)
{
var conversion = document.SemanticModel.Compilation.ClassifyConversion(
lambdaMethod.Parameters[i].Type, invocationMethod.Parameters[i].Type);
if (!conversion.IsIdentityOrImplicitReference())
{
return false;
}
}
if (WouldCauseAmbiguity(lambda, invocation, semanticModel, cancellationToken))
{
return false;
}
// Looks like something we can simplify.
return true;
}
// Ensure that if we replace the invocation with its expression that its expression will
// bind unambiguously. This can happen with awesome cases like:
#if false
static void Goo<T>(T x) where T : class { }
static void Bar(Action<int> x) { }
static void Bar(Action<string> x) { }
static void Main()
{
Bar(x => Goo(x)); // error CS0121: The call is ambiguous between the following methods or properties: 'A.Bar(System.Action<int>)' and 'A.Bar(System.Action<string>)'
}
#endif
private static bool WouldCauseAmbiguity(
ExpressionSyntax lambda,
InvocationExpressionSyntax invocation,
SemanticModel oldSemanticModel,
CancellationToken cancellationToken)
{
var annotation = new SyntaxAnnotation();
// In order to check if there will be a problem, we actually make the change, fork the
// compilation, and then verify that the new expression bound unambiguously.
var oldExpression = invocation.Expression.WithAdditionalAnnotations(annotation);
var oldCompilation = oldSemanticModel.Compilation;
var oldTree = oldSemanticModel.SyntaxTree;
var oldRoot = oldTree.GetRoot(cancellationToken);
var newRoot = oldRoot.ReplaceNode(lambda, oldExpression);
var newTree = oldTree.WithRootAndOptions(newRoot, oldTree.Options);
var newCompilation = oldCompilation.ReplaceSyntaxTree(oldTree, newTree);
var newExpression = newTree.GetRoot(cancellationToken).GetAnnotatedNodesAndTokens(annotation).First().AsNode();
var newSemanticModel = newCompilation.GetSemanticModel(newTree);
var info = newSemanticModel.GetSymbolInfo(newExpression, cancellationToken);
return info.CandidateReason != CandidateReason.None;
}
private static InvocationExpressionSyntax TryGetInvocationExpression(
SyntaxNode lambdaBody)
{
if (lambdaBody is ExpressionSyntax exprBody)
{
return exprBody.WalkDownParentheses() as InvocationExpressionSyntax;
}
else if (lambdaBody is BlockSyntax block)
{
if (block.Statements.Count == 1)
{
var statement = block.Statements.First();
if (statement is ReturnStatementSyntax returnStatement)
{
return returnStatement.Expression.WalkDownParentheses() as InvocationExpressionSyntax;
}
else if (statement is ExpressionStatementSyntax exprStatement)
{
return exprStatement.Expression.WalkDownParentheses() as InvocationExpressionSyntax;
}
}
}
return null;
}
private class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument)
: base(title, createChangedDocument, title)
{
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.LambdaSimplifier
{
// Disabled due to: https://github.com/dotnet/roslyn/issues/5835 & https://github.com/dotnet/roslyn/pull/6642
// [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.SimplifyLambda)]
internal partial class LambdaSimplifierCodeRefactoringProvider : CodeRefactoringProvider
{
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, textSpan, cancellationToken) = context;
if (cancellationToken.IsCancellationRequested)
{
return;
}
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
{
return;
}
var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
var lambda = await context.TryGetRelevantNodeAsync<LambdaExpressionSyntax>().ConfigureAwait(false);
if (lambda == null)
{
return;
}
if (!CanSimplify(semanticDocument, lambda as SimpleLambdaExpressionSyntax, cancellationToken) &&
!CanSimplify(semanticDocument, lambda as ParenthesizedLambdaExpressionSyntax, cancellationToken))
{
return;
}
context.RegisterRefactoring(
new MyCodeAction(
CSharpFeaturesResources.Simplify_lambda_expression,
c => SimplifyLambdaAsync(document, lambda, c)),
lambda.Span);
context.RegisterRefactoring(
new MyCodeAction(
CSharpFeaturesResources.Simplify_all_occurrences,
c => SimplifyAllLambdasAsync(document, c)),
lambda.Span);
}
private static async Task<Document> SimplifyLambdaAsync(
Document document,
SyntaxNode lambda,
CancellationToken cancellationToken)
{
var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
var rewriter = new Rewriter(semanticDocument, n => n == lambda, cancellationToken);
var result = rewriter.Visit(semanticDocument.Root);
return document.WithSyntaxRoot(result);
}
private static async Task<Document> SimplifyAllLambdasAsync(
Document document,
CancellationToken cancellationToken)
{
var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
var rewriter = new Rewriter(semanticDocument, n => true, cancellationToken);
var result = rewriter.Visit(semanticDocument.Root);
return document.WithSyntaxRoot(result);
}
private static bool CanSimplify(
SemanticDocument document,
SimpleLambdaExpressionSyntax node,
CancellationToken cancellationToken)
{
if (node == null)
{
return false;
}
var paramName = node.Parameter.Identifier;
var invocation = TryGetInvocationExpression(node.Body);
return CanSimplify(document, node, new List<SyntaxToken>() { paramName }, invocation, cancellationToken);
}
private static bool CanSimplify(
SemanticDocument document,
ParenthesizedLambdaExpressionSyntax node,
CancellationToken cancellationToken)
{
if (node == null)
{
return false;
}
var paramNames = node.ParameterList.Parameters.Select(p => p.Identifier).ToList();
var invocation = TryGetInvocationExpression(node.Body);
return CanSimplify(document, node, paramNames, invocation, cancellationToken);
}
private static bool CanSimplify(
SemanticDocument document,
ExpressionSyntax lambda,
List<SyntaxToken> paramNames,
InvocationExpressionSyntax invocation,
CancellationToken cancellationToken)
{
if (invocation == null)
{
return false;
}
if (invocation.ArgumentList.Arguments.Count != paramNames.Count)
{
return false;
}
for (var i = 0; i < paramNames.Count; i++)
{
var argument = invocation.ArgumentList.Arguments[i];
if (argument.NameColon != null ||
argument.RefOrOutKeyword.Kind() != SyntaxKind.None ||
!argument.Expression.IsKind(SyntaxKind.IdentifierName, out IdentifierNameSyntax identifierName))
{
return false;
}
if (identifierName.Identifier.ValueText != paramNames[i].ValueText)
{
return false;
}
}
var semanticModel = document.SemanticModel;
var lambdaSemanticInfo = semanticModel.GetSymbolInfo(lambda, cancellationToken);
var invocationSemanticInfo = semanticModel.GetSymbolInfo(invocation, cancellationToken);
if (lambdaSemanticInfo.Symbol == null ||
invocationSemanticInfo.Symbol == null)
{
// Don't offer this if there are any errors or ambiguities.
return false;
}
if (!(lambdaSemanticInfo.Symbol is IMethodSymbol lambdaMethod) || !(invocationSemanticInfo.Symbol is IMethodSymbol invocationMethod))
{
return false;
}
// TODO(cyrusn): Handle extension methods as well.
if (invocationMethod.IsExtensionMethod)
{
return false;
}
// Check if any of the parameter is of Type Dynamic
foreach (var parameter in lambdaMethod.Parameters)
{
if (parameter.Type != null && parameter.Type.Kind == SymbolKind.DynamicType)
{
return false;
}
}
// Check if the parameter and return types match between the lambda and the
// invocation. Note: return types can be covariant and argument types can be
// contravariant.
if (lambdaMethod.ReturnsVoid != invocationMethod.ReturnsVoid ||
lambdaMethod.Parameters.Length != invocationMethod.Parameters.Length)
{
return false;
}
if (!lambdaMethod.ReturnsVoid)
{
// Return type has to be covariant.
var conversion = document.SemanticModel.Compilation.ClassifyConversion(
invocationMethod.ReturnType, lambdaMethod.ReturnType);
if (!conversion.IsIdentityOrImplicitReference())
{
return false;
}
}
// Parameter types have to be contravariant.
for (var i = 0; i < lambdaMethod.Parameters.Length; i++)
{
var conversion = document.SemanticModel.Compilation.ClassifyConversion(
lambdaMethod.Parameters[i].Type, invocationMethod.Parameters[i].Type);
if (!conversion.IsIdentityOrImplicitReference())
{
return false;
}
}
if (WouldCauseAmbiguity(lambda, invocation, semanticModel, cancellationToken))
{
return false;
}
// Looks like something we can simplify.
return true;
}
// Ensure that if we replace the invocation with its expression that its expression will
// bind unambiguously. This can happen with awesome cases like:
#if false
static void Goo<T>(T x) where T : class { }
static void Bar(Action<int> x) { }
static void Bar(Action<string> x) { }
static void Main()
{
Bar(x => Goo(x)); // error CS0121: The call is ambiguous between the following methods or properties: 'A.Bar(System.Action<int>)' and 'A.Bar(System.Action<string>)'
}
#endif
private static bool WouldCauseAmbiguity(
ExpressionSyntax lambda,
InvocationExpressionSyntax invocation,
SemanticModel oldSemanticModel,
CancellationToken cancellationToken)
{
var annotation = new SyntaxAnnotation();
// In order to check if there will be a problem, we actually make the change, fork the
// compilation, and then verify that the new expression bound unambiguously.
var oldExpression = invocation.Expression.WithAdditionalAnnotations(annotation);
var oldCompilation = oldSemanticModel.Compilation;
var oldTree = oldSemanticModel.SyntaxTree;
var oldRoot = oldTree.GetRoot(cancellationToken);
var newRoot = oldRoot.ReplaceNode(lambda, oldExpression);
var newTree = oldTree.WithRootAndOptions(newRoot, oldTree.Options);
var newCompilation = oldCompilation.ReplaceSyntaxTree(oldTree, newTree);
var newExpression = newTree.GetRoot(cancellationToken).GetAnnotatedNodesAndTokens(annotation).First().AsNode();
var newSemanticModel = newCompilation.GetSemanticModel(newTree);
var info = newSemanticModel.GetSymbolInfo(newExpression, cancellationToken);
return info.CandidateReason != CandidateReason.None;
}
private static InvocationExpressionSyntax TryGetInvocationExpression(
SyntaxNode lambdaBody)
{
if (lambdaBody is ExpressionSyntax exprBody)
{
return exprBody.WalkDownParentheses() as InvocationExpressionSyntax;
}
else if (lambdaBody is BlockSyntax block)
{
if (block.Statements.Count == 1)
{
var statement = block.Statements.First();
if (statement is ReturnStatementSyntax returnStatement)
{
return returnStatement.Expression.WalkDownParentheses() as InvocationExpressionSyntax;
}
else if (statement is ExpressionStatementSyntax exprStatement)
{
return exprStatement.Expression.WalkDownParentheses() as InvocationExpressionSyntax;
}
}
}
return null;
}
private class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument)
: base(title, createChangedDocument, title)
{
}
}
}
}
| -1 |
dotnet/roslyn | 55,504 | Format new document namespace declarations | Fixes https://github.com/dotnet/roslyn/issues/55417
| davidwengier | 2021-08-09T07:51:27Z | 2021-08-10T11:42:04Z | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | 782f71d3ada7ae95e42af182405824aeff12daeb | Format new document namespace declarations. Fixes https://github.com/dotnet/roslyn/issues/55417
| ./src/Features/Core/Portable/ExtractClass/IExtractClassOptionsService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.ExtractClass
{
internal interface IExtractClassOptionsService : IWorkspaceService
{
Task<ExtractClassOptions?> GetExtractClassOptionsAsync(Document document, INamedTypeSymbol originalType, ISymbol? selectedMember);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.ExtractClass
{
internal interface IExtractClassOptionsService : IWorkspaceService
{
Task<ExtractClassOptions?> GetExtractClassOptionsAsync(Document document, INamedTypeSymbol originalType, ISymbol? selectedMember);
}
}
| -1 |
dotnet/roslyn | 55,504 | Format new document namespace declarations | Fixes https://github.com/dotnet/roslyn/issues/55417
| davidwengier | 2021-08-09T07:51:27Z | 2021-08-10T11:42:04Z | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | 782f71d3ada7ae95e42af182405824aeff12daeb | Format new document namespace declarations. Fixes https://github.com/dotnet/roslyn/issues/55417
| ./src/Features/VisualBasic/Portable/Structure/Providers/MultiLineIfBlockStructureProvider.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.[Shared].Collections
Imports Microsoft.CodeAnalysis.Structure
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Structure
Friend Class MultiLineIfBlockStructureProvider
Inherits AbstractSyntaxNodeStructureProvider(Of MultiLineIfBlockSyntax)
Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken,
node As MultiLineIfBlockSyntax,
ByRef spans As TemporaryArray(Of BlockSpan),
optionProvider As BlockStructureOptionProvider,
cancellationToken As CancellationToken)
spans.AddIfNotNull(CreateBlockSpanFromBlock(
node, node.IfStatement, autoCollapse:=False,
type:=BlockTypes.Conditional, isCollapsible:=True))
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.[Shared].Collections
Imports Microsoft.CodeAnalysis.Structure
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Structure
Friend Class MultiLineIfBlockStructureProvider
Inherits AbstractSyntaxNodeStructureProvider(Of MultiLineIfBlockSyntax)
Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken,
node As MultiLineIfBlockSyntax,
ByRef spans As TemporaryArray(Of BlockSpan),
optionProvider As BlockStructureOptionProvider,
cancellationToken As CancellationToken)
spans.AddIfNotNull(CreateBlockSpanFromBlock(
node, node.IfStatement, autoCollapse:=False,
type:=BlockTypes.Conditional, isCollapsible:=True))
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,504 | Format new document namespace declarations | Fixes https://github.com/dotnet/roslyn/issues/55417
| davidwengier | 2021-08-09T07:51:27Z | 2021-08-10T11:42:04Z | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | 782f71d3ada7ae95e42af182405824aeff12daeb | Format new document namespace declarations. Fixes https://github.com/dotnet/roslyn/issues/55417
| ./src/Features/VisualBasic/Portable/InvertIf/VisualBasicInvertIfCodeRefactoringProvider.SingleLine.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports System.Diagnostics.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.InvertIf
<ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.InvertIf), [Shared]>
Friend NotInheritable Class VisualBasicInvertSingleLineIfCodeRefactoringProvider
Inherits VisualBasicInvertIfCodeRefactoringProvider(Of SingleLineIfStatementSyntax)
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New()
End Sub
Protected Overrides Function IsElseless(ifNode As SingleLineIfStatementSyntax) As Boolean
Return ifNode.ElseClause Is Nothing
End Function
Protected Overrides Function CanInvert(ifNode As SingleLineIfStatementSyntax) As Boolean
Return TypeOf ifNode.Parent IsNot SingleLineLambdaExpressionSyntax AndAlso
Not ifNode.Statements.Any(Function(n) n.IsKind(SyntaxKind.LocalDeclarationStatement)) AndAlso
Not If(ifNode.ElseClause?.Statements.Any(Function(n) n.IsKind(SyntaxKind.LocalDeclarationStatement)), False)
End Function
Protected Overrides Function GetCondition(ifNode As SingleLineIfStatementSyntax) As SyntaxNode
Return ifNode.Condition
End Function
Protected Overrides Function GetIfBody(ifNode As SingleLineIfStatementSyntax) As SyntaxList(Of StatementSyntax)
Return ifNode.Statements
End Function
Protected Overrides Function GetElseBody(ifNode As SingleLineIfStatementSyntax) As SyntaxList(Of StatementSyntax)
Return ifNode.ElseClause.Statements
End Function
Protected Overrides Function UpdateIf(
sourceText As SourceText,
ifNode As SingleLineIfStatementSyntax,
condition As SyntaxNode,
trueStatements As SyntaxList(Of StatementSyntax),
Optional falseStatements As SyntaxList(Of StatementSyntax) = Nothing) As SingleLineIfStatementSyntax
Dim isSingleLine = sourceText.AreOnSameLine(ifNode.GetFirstToken(), ifNode.GetLastToken())
If isSingleLine AndAlso falseStatements.Count > 0 Then
' If statement Is on a single line, And we're swapping the true/false parts.
' In that case, try to swap the trailing trivia between the true/false parts.
' That way the trailing comments/newlines at the end of the 'if' stay there,
' And the spaces after the true-part stay where they are.
Dim lastTrue = trueStatements.LastOrDefault()
Dim lastFalse = falseStatements.LastOrDefault()
If lastTrue IsNot Nothing AndAlso lastFalse IsNot Nothing Then
Dim newLastTrue = lastTrue.WithTrailingTrivia(lastFalse.GetTrailingTrivia())
Dim newLastFalse = lastFalse.WithTrailingTrivia(lastTrue.GetTrailingTrivia())
trueStatements = trueStatements.Replace(lastTrue, newLastTrue)
falseStatements = falseStatements.Replace(lastFalse, newLastFalse)
End If
End If
Dim updatedIf = ifNode _
.WithCondition(DirectCast(condition, ExpressionSyntax)) _
.WithStatements(trueStatements)
If falseStatements.Count <> 0 Then
Dim elseClause =
If(updatedIf.ElseClause IsNot Nothing,
updatedIf.ElseClause.WithStatements(falseStatements),
SyntaxFactory.SingleLineElseClause(falseStatements))
updatedIf = updatedIf.WithElseClause(elseClause)
End If
Return updatedIf
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports System.Diagnostics.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.InvertIf
<ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.InvertIf), [Shared]>
Friend NotInheritable Class VisualBasicInvertSingleLineIfCodeRefactoringProvider
Inherits VisualBasicInvertIfCodeRefactoringProvider(Of SingleLineIfStatementSyntax)
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New()
End Sub
Protected Overrides Function IsElseless(ifNode As SingleLineIfStatementSyntax) As Boolean
Return ifNode.ElseClause Is Nothing
End Function
Protected Overrides Function CanInvert(ifNode As SingleLineIfStatementSyntax) As Boolean
Return TypeOf ifNode.Parent IsNot SingleLineLambdaExpressionSyntax AndAlso
Not ifNode.Statements.Any(Function(n) n.IsKind(SyntaxKind.LocalDeclarationStatement)) AndAlso
Not If(ifNode.ElseClause?.Statements.Any(Function(n) n.IsKind(SyntaxKind.LocalDeclarationStatement)), False)
End Function
Protected Overrides Function GetCondition(ifNode As SingleLineIfStatementSyntax) As SyntaxNode
Return ifNode.Condition
End Function
Protected Overrides Function GetIfBody(ifNode As SingleLineIfStatementSyntax) As SyntaxList(Of StatementSyntax)
Return ifNode.Statements
End Function
Protected Overrides Function GetElseBody(ifNode As SingleLineIfStatementSyntax) As SyntaxList(Of StatementSyntax)
Return ifNode.ElseClause.Statements
End Function
Protected Overrides Function UpdateIf(
sourceText As SourceText,
ifNode As SingleLineIfStatementSyntax,
condition As SyntaxNode,
trueStatements As SyntaxList(Of StatementSyntax),
Optional falseStatements As SyntaxList(Of StatementSyntax) = Nothing) As SingleLineIfStatementSyntax
Dim isSingleLine = sourceText.AreOnSameLine(ifNode.GetFirstToken(), ifNode.GetLastToken())
If isSingleLine AndAlso falseStatements.Count > 0 Then
' If statement Is on a single line, And we're swapping the true/false parts.
' In that case, try to swap the trailing trivia between the true/false parts.
' That way the trailing comments/newlines at the end of the 'if' stay there,
' And the spaces after the true-part stay where they are.
Dim lastTrue = trueStatements.LastOrDefault()
Dim lastFalse = falseStatements.LastOrDefault()
If lastTrue IsNot Nothing AndAlso lastFalse IsNot Nothing Then
Dim newLastTrue = lastTrue.WithTrailingTrivia(lastFalse.GetTrailingTrivia())
Dim newLastFalse = lastFalse.WithTrailingTrivia(lastTrue.GetTrailingTrivia())
trueStatements = trueStatements.Replace(lastTrue, newLastTrue)
falseStatements = falseStatements.Replace(lastFalse, newLastFalse)
End If
End If
Dim updatedIf = ifNode _
.WithCondition(DirectCast(condition, ExpressionSyntax)) _
.WithStatements(trueStatements)
If falseStatements.Count <> 0 Then
Dim elseClause =
If(updatedIf.ElseClause IsNot Nothing,
updatedIf.ElseClause.WithStatements(falseStatements),
SyntaxFactory.SingleLineElseClause(falseStatements))
updatedIf = updatedIf.WithElseClause(elseClause)
End If
Return updatedIf
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,504 | Format new document namespace declarations | Fixes https://github.com/dotnet/roslyn/issues/55417
| davidwengier | 2021-08-09T07:51:27Z | 2021-08-10T11:42:04Z | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | 782f71d3ada7ae95e42af182405824aeff12daeb | Format new document namespace declarations. Fixes https://github.com/dotnet/roslyn/issues/55417
| ./src/VisualStudio/Core/Impl/CodeModel/InternalElements/CodeImport.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements
{
[ComVisible(true)]
[ComDefaultInterface(typeof(EnvDTE80.CodeImport))]
public sealed class CodeImport : AbstractCodeElement, EnvDTE80.CodeImport
{
internal static EnvDTE80.CodeImport Create(
CodeModelState state,
FileCodeModel fileCodeModel,
AbstractCodeElement parent,
string dottedName)
{
var element = new CodeImport(state, fileCodeModel, parent, dottedName);
var result = (EnvDTE80.CodeImport)ComAggregate.CreateAggregatedObject(element);
return result;
}
internal static EnvDTE80.CodeImport CreateUnknown(
CodeModelState state,
FileCodeModel fileCodeModel,
int nodeKind,
string dottedName)
{
var element = new CodeImport(state, fileCodeModel, nodeKind, dottedName);
return (EnvDTE80.CodeImport)ComAggregate.CreateAggregatedObject(element);
}
private readonly ParentHandle<AbstractCodeElement> _parentHandle; // parent object -- if parent is FCM then NULL else ref'd
private readonly string _dottedName;
private CodeImport(
CodeModelState state,
FileCodeModel fileCodeModel,
AbstractCodeElement parent,
string dottedName)
: base(state, fileCodeModel)
{
_parentHandle = new ParentHandle<AbstractCodeElement>(parent);
_dottedName = dottedName;
}
private CodeImport(
CodeModelState state,
FileCodeModel fileCodeModel,
int nodeKind,
string dottedName)
: base(state, fileCodeModel, nodeKind)
{
_dottedName = dottedName;
}
internal override bool TryLookupNode(out SyntaxNode node)
{
node = null;
var parentNode = _parentHandle.Value != null
? _parentHandle.Value.LookupNode()
: FileCodeModel.GetSyntaxRoot();
if (parentNode == null)
{
return false;
}
if (!CodeModelService.TryGetImportNode(parentNode, _dottedName, out var importNode))
{
return false;
}
node = importNode;
return node != null;
}
internal override ISymbol LookupSymbol()
{
Debug.Fail("CodeImports aren't backed by symbols");
throw new InvalidOperationException();
}
public override EnvDTE.vsCMElement Kind
{
get { return EnvDTE.vsCMElement.vsCMElementImportStmt; }
}
public override object Parent
{
get
{
if (_parentHandle.Value != null)
{
return _parentHandle.Value;
}
else
{
return FileCodeModel;
}
}
}
public string Alias
{
get
{
return CodeModelService.GetImportAlias(LookupNode());
}
set
{
// TODO: Implement
throw new NotImplementedException();
}
}
public string Namespace
{
get
{
return CodeModelService.GetImportNamespaceOrType(LookupNode());
}
set
{
// TODO: Implement
throw new NotImplementedException();
}
}
public override EnvDTE.CodeElements Children
{
get { return EmptyCollection.Create(this.State, this); }
}
protected override string GetName()
=> CodeModelService.GetName(LookupNode());
protected override void SetName(string value)
=> throw Exceptions.ThrowEFail();
protected override string GetFullName()
=> CodeModelService.GetFullName(LookupNode(), semanticModel: null);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements
{
[ComVisible(true)]
[ComDefaultInterface(typeof(EnvDTE80.CodeImport))]
public sealed class CodeImport : AbstractCodeElement, EnvDTE80.CodeImport
{
internal static EnvDTE80.CodeImport Create(
CodeModelState state,
FileCodeModel fileCodeModel,
AbstractCodeElement parent,
string dottedName)
{
var element = new CodeImport(state, fileCodeModel, parent, dottedName);
var result = (EnvDTE80.CodeImport)ComAggregate.CreateAggregatedObject(element);
return result;
}
internal static EnvDTE80.CodeImport CreateUnknown(
CodeModelState state,
FileCodeModel fileCodeModel,
int nodeKind,
string dottedName)
{
var element = new CodeImport(state, fileCodeModel, nodeKind, dottedName);
return (EnvDTE80.CodeImport)ComAggregate.CreateAggregatedObject(element);
}
private readonly ParentHandle<AbstractCodeElement> _parentHandle; // parent object -- if parent is FCM then NULL else ref'd
private readonly string _dottedName;
private CodeImport(
CodeModelState state,
FileCodeModel fileCodeModel,
AbstractCodeElement parent,
string dottedName)
: base(state, fileCodeModel)
{
_parentHandle = new ParentHandle<AbstractCodeElement>(parent);
_dottedName = dottedName;
}
private CodeImport(
CodeModelState state,
FileCodeModel fileCodeModel,
int nodeKind,
string dottedName)
: base(state, fileCodeModel, nodeKind)
{
_dottedName = dottedName;
}
internal override bool TryLookupNode(out SyntaxNode node)
{
node = null;
var parentNode = _parentHandle.Value != null
? _parentHandle.Value.LookupNode()
: FileCodeModel.GetSyntaxRoot();
if (parentNode == null)
{
return false;
}
if (!CodeModelService.TryGetImportNode(parentNode, _dottedName, out var importNode))
{
return false;
}
node = importNode;
return node != null;
}
internal override ISymbol LookupSymbol()
{
Debug.Fail("CodeImports aren't backed by symbols");
throw new InvalidOperationException();
}
public override EnvDTE.vsCMElement Kind
{
get { return EnvDTE.vsCMElement.vsCMElementImportStmt; }
}
public override object Parent
{
get
{
if (_parentHandle.Value != null)
{
return _parentHandle.Value;
}
else
{
return FileCodeModel;
}
}
}
public string Alias
{
get
{
return CodeModelService.GetImportAlias(LookupNode());
}
set
{
// TODO: Implement
throw new NotImplementedException();
}
}
public string Namespace
{
get
{
return CodeModelService.GetImportNamespaceOrType(LookupNode());
}
set
{
// TODO: Implement
throw new NotImplementedException();
}
}
public override EnvDTE.CodeElements Children
{
get { return EmptyCollection.Create(this.State, this); }
}
protected override string GetName()
=> CodeModelService.GetName(LookupNode());
protected override void SetName(string value)
=> throw Exceptions.ThrowEFail();
protected override string GetFullName()
=> CodeModelService.GetFullName(LookupNode(), semanticModel: null);
}
}
| -1 |
dotnet/roslyn | 55,504 | Format new document namespace declarations | Fixes https://github.com/dotnet/roslyn/issues/55417
| davidwengier | 2021-08-09T07:51:27Z | 2021-08-10T11:42:04Z | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | 782f71d3ada7ae95e42af182405824aeff12daeb | Format new document namespace declarations. Fixes https://github.com/dotnet/roslyn/issues/55417
| ./src/VisualStudio/Core/Def/Implementation/ProjectSystem/IVisualStudioHostDocument.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Operations;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
[Obsolete("This is a compatibility shim for TypeScript; please do not use it.")]
internal interface IVisualStudioHostDocument
{
/// <summary>
/// The workspace document Id for this document.
/// </summary>
DocumentId Id { get; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Operations;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
[Obsolete("This is a compatibility shim for TypeScript; please do not use it.")]
internal interface IVisualStudioHostDocument
{
/// <summary>
/// The workspace document Id for this document.
/// </summary>
DocumentId Id { get; }
}
}
| -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.