Skip to content

Commit 7eccea4

Browse files
committed
Always cast RHS of bitshift operators to int
This is to fix: #611 Always casting to int will work because C# only allows ints as the RHS parameter for bitshifts: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions#1211-shift-operators
1 parent 837b632 commit 7eccea4

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.VisitStmt.cs

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,22 @@ private void VisitBinaryOperator(BinaryOperator binaryOperator)
4141
outputBuilder.Write(' ');
4242
outputBuilder.Write(binaryOperator.OpcodeStr);
4343
outputBuilder.Write(' ');
44-
Visit(binaryOperator.RHS);
44+
45+
if (binaryOperator.IsShiftOp || binaryOperator.IsShiftAssignOp)
46+
{
47+
// RHS of shift operation in C# must be an int
48+
outputBuilder.Write("(int)");
49+
outputBuilder.Write('(');
50+
51+
Visit(binaryOperator.RHS);
52+
53+
outputBuilder.Write(')');
54+
}
55+
else
56+
{
57+
Visit(binaryOperator.RHS);
58+
}
59+
4560
StopCSharpCode();
4661
}
4762

tests/ClangSharp.PInvokeGenerator.UnitTests/CTest.cs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -283,14 +283,18 @@ public static partial class Methods
283283
[Test]
284284
public Task UnsignedIntBitshiftTest()
285285
{
286-
var inputContents = @"#define BITSHIFT 1 << 1U";
286+
var inputContents = @"#define LEFT 1 << 1U
287+
#define RIGHT 1 >> 1U";
287288

288289
var expectedOutputContents = @"namespace ClangSharp.Test
289290
{
290291
public static partial class Methods
291292
{
292-
[NativeTypeName(""#define BITSHIFT 1 << 1U"")]
293-
public const int BITSHIFT = 1 << (int)(1U);
293+
[NativeTypeName(""#define LEFT 1 << 1U"")]
294+
public const int LEFT = 1 << (int)(1U);
295+
296+
[NativeTypeName(""#define RIGHT 1 >> 1U"")]
297+
public const int RIGHT = 1 >> (int)(1U);
294298
}
295299
}
296300
";

0 commit comments

Comments
 (0)