提交 948ac1bc 编写于 作者: C Cyrus Najmabadi

Do not introduce conditional conversions when they are not legal.

上级 7d89cccc
......@@ -8417,5 +8417,44 @@ public static nint N(nint a, int b)
await test.RunAsync();
}
[WorkItem(50000, "https://github.com/dotnet/roslyn/issues/50000")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryCast)]
public async Task KeepNecessaryCastIfRemovalWouldCreateIllegalConditionalExpression()
{
await new VerifyCS.Test
{
TestCode = @"
class C
{
ushort Goo(string s)
=> s is null ? (ushort)1234 : ushort.Parse(s);
}
",
LanguageVersion = LanguageVersion.CSharp8,
}.RunAsync();
}
[WorkItem(50000, "https://github.com/dotnet/roslyn/issues/50000")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryCast)]
public async Task RemoveUnnecessaryCastWhenConditionalExpressionIsLegal()
{
await new VerifyCS.Test
{
TestCode = @"
class C
{
ushort Goo(string s)
=> s is null ? [|(ushort)|]1234 : ushort.Parse(s);
}",
FixedCode = @"
class C
{
ushort Goo(string s)
=> s is null ? 1234 : ushort.Parse(s);
}",
LanguageVersion = LanguageVersion.CSharp9,
}.RunAsync();
}
}
}
......@@ -342,6 +342,17 @@ protected override bool ReplacementChangesSemanticsForNodeLanguageSpecific(Synta
{
var newExpression = (ConditionalExpressionSyntax)currentReplacedNode;
// If we removed a cast, causing a conditional expression to now use a conditional *conversion*, then that is always
// an error before CSharp9, and should not be allowed.
var originalConditionalConversion = this.OriginalSemanticModel.GetConversion(originalExpression);
var newConditionalConversion = this.SpeculativeSemanticModel.GetConversion(newExpression);
if (newConditionalConversion.IsConditionalExpression &&
!originalConditionalConversion.IsConditionalExpression &&
!ConditionalExpressionConversionsAreAllowed(originalExpression))
{
return true;
}
if (originalExpression.Condition != previousOriginalNode)
{
ExpressionSyntax originalOtherPartOfConditional, newOtherPartOfConditional;
......@@ -719,9 +730,12 @@ private bool ReplacementBreaksQueryClause(QueryClauseSyntax originalClause, Quer
private static bool IsPotentiallyTargetTypedConditionalExpression(ExpressionSyntax expressionSyntax)
{
return expressionSyntax is ConditionalExpressionSyntax &&
((CSharpParseOptions)expressionSyntax.SyntaxTree.Options).LanguageVersion >= LanguageVersion.CSharp9;
ConditionalExpressionConversionsAreAllowed(expressionSyntax);
}
private static bool ConditionalExpressionConversionsAreAllowed(ExpressionSyntax expressionSyntax)
=> ((CSharpParseOptions)expressionSyntax.SyntaxTree.Options).LanguageVersion >= LanguageVersion.CSharp9;
protected override bool ReplacementIntroducesErrorType(ExpressionSyntax originalExpression, ExpressionSyntax newExpression)
{
// The base implementation will see that the type of the new expression may potentially change to null,
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册