提交 3dff8b3c 编写于 作者: N Neal Gafter 提交者: GitHub

Fix a bug in code gen for switch on byte or ushort (#18521)

Fixes #18188
上级 434e4105
......@@ -3014,6 +3014,72 @@ void M(bool b)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion1, "b").WithArguments("switch on boolean type", "2"));
}
[Fact]
public void SmallUnsignedEdgeCase01()
{
var source = @"
using System;
class C
{
static void Main(string[] args)
{
RunTest(126);
RunTest(127);
RunTest(128);
RunTest(129);
void RunTest(byte testByte)
{
switch (testByte)
{
case 127: // 0111 1111
case 128: // 1000 0000
Console.Write(0);
break;
default:
Console.Write(1);
break;
}
}
}
}";
var comp = CompileAndVerify(source, expectedOutput: @"1001");
comp.VerifyDiagnostics();
}
[Fact]
public void SmallUnsignedEdgeCase02()
{
var source = @"
using System;
class C
{
static void Main(string[] args)
{
RunTest(32766);
RunTest(32767);
RunTest(32768);
RunTest(32769);
void RunTest(ushort testUshort)
{
switch (testUshort)
{
case 32767: // 0111 1111 1111 1111
case 32768: // 1000 0000 0000 0000
Console.Write(0);
break;
default:
Console.Write(1);
break;
}
}
}
}";
var comp = CompileAndVerify(source, expectedOutput: @"1001");
comp.VerifyDiagnostics();
}
#endregion
}
}
......@@ -466,7 +466,20 @@ private void EmitRangeCheckedBranch(ConstantValue startConstant, ConstantValue e
}
else
{
_builder.EmitIntConstant(endConstant.Int32Value - startConstant.Int32Value);
int Int32Value(ConstantValue value)
{
// ConstantValue does not correctly convert byte and ushort values to int.
// It sign extends them rather than padding them. We compensate for that here.
// See also https://github.com/dotnet/roslyn/issues/18579
switch (value.Discriminator)
{
case ConstantValueTypeDiscriminator.Byte: return value.ByteValue;
case ConstantValueTypeDiscriminator.UInt16: return value.UInt16Value;
default: return value.Int32Value;
}
}
_builder.EmitIntConstant(Int32Value(endConstant) - Int32Value(startConstant));
}
_builder.EmitBranch(ILOpCode.Ble_un, targetLabel, ILOpCode.Bgt_un);
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册