From 506488625902ac81c269b72572c4bee62140da81 Mon Sep 17 00:00:00 2001 From: Tanner Gooding Date: Sat, 14 Nov 2026 14:47:41 -0800 Subject: [PATCH] Avoid double int casts when shifting by C++ enumerators Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- Directory.Build.props | 2 +- .../PInvokeGenerator.VisitStmt.cs | 13 +++++-- .../Baseline/BaselineAssertions.cs | 16 +++++++-- .../Baseline/BaselineAssertionsTest.cs | 20 +++++++++++ .../EnumeratorShiftTest.CSharp.cs | 25 +++++++++++++ .../EnumeratorShiftTest.Xml.xml | 36 +++++++++++++++++++ ...teWithHelperTypes.CSharp.Latest.Windows.cs | 2 +- ...tributeInTypeMode.CSharp.Latest.Windows.cs | 6 ++-- ...ateInTypeMode.CSharp.Compatible.Windows.cs | 8 ++--- ...lyWithHelperTypes.CSharp.Latest.Windows.cs | 6 ++-- ...dAfterMethodClass.CSharp.Latest.Windows.cs | 2 +- ...odClassFileScoped.CSharp.Latest.Windows.cs | 2 +- ...leScopedNamespace.CSharp.Latest.Windows.cs | 2 +- ...InSharedNamespace.CSharp.Latest.Windows.cs | 2 +- ...eratesValidHelper.CSharp.Latest.Windows.cs | 2 +- .../FunctionDeclarationBodyImportTest.cs | 23 ++++++++++++ 16 files changed, 145 insertions(+), 22 deletions(-) create mode 100644 tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/BaselineAssertionsTest.cs create mode 100644 tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/FunctionDeclarationBodyImport/EnumeratorShiftTest.CSharp.cs create mode 100644 tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/FunctionDeclarationBodyImport/EnumeratorShiftTest.Xml.xml diff --git a/Directory.Build.props b/Directory.Build.props index 415001755..ef42ec072 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -47,7 +47,7 @@ 17.0.0 ClangSharp ClangSharp - 23.1.5.0 + 23.1.5.1 rc1 pr diff --git a/sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.VisitStmt.cs b/sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.VisitStmt.cs index 4dcfa407d..064a32466 100644 --- a/sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.VisitStmt.cs +++ b/sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.VisitStmt.cs @@ -86,8 +86,17 @@ private void VisitBinaryOperator(BinaryOperator binaryOperator) // A C enumerator has type int, but it is emitted as a member of its generated enum, which C# cannot shift by case Expr when IsStmtAsWritten(rhs, out var declRefExpr, removeParens: true) && (declRefExpr.Decl is EnumConstantDecl): { - outputBuilder.Write("(int)"); - ParenthesizeStmt(binaryOperator.RHS); + // In C++ the enumerator is promoted via an implicit cast to int, which already emits the `(int)` cast + // except within an enumerator initializer, where the reference is emitted without a cast + if ((rhs is ImplicitCastExpr { Type.CanonicalType.Kind: CXType_Int }) && !IsPrevContextDecl(out _, out _)) + { + Visit(binaryOperator.RHS); + } + else + { + outputBuilder.Write("(int)"); + ParenthesizeStmt(binaryOperator.RHS); + } break; } // Already the correct type or implicitly castable diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/BaselineAssertions.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/BaselineAssertions.cs index 9ab3effb2..94f400284 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/BaselineAssertions.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/BaselineAssertions.cs @@ -1,5 +1,6 @@ // Copyright (c) .NET Foundation and Contributors. All Rights Reserved. Licensed under the MIT License (MIT). See License.md in the repository root for more information. +using System; using System.IO; using System.Threading.Tasks; using NUnit.Framework; @@ -9,16 +10,25 @@ namespace ClangSharp.UnitTests.Baseline; // Shared baseline read/write core used by both the matrix-parameterized BaselineTest and the // single-variant StandaloneBaselineTest. Given the already-generated output for a case+variant, it either // (re)writes the checked-in baseline under UPDATE_BASELINES, or resolves the baseline via the fallback -// chain and asserts byte-for-byte equality. +// chain and asserts equality after resolving the generator version placeholder. internal static class BaselineAssertions { + private const string GeneratedCodeAttributePlaceholder = "GeneratedCode(\"ClangSharp\", \"{ClangSharpVersion}\")"; + private static readonly string s_generatedCodeAttribute = $"GeneratedCode(\"ClangSharp\", \"{typeof(PInvokeGenerator).Assembly.GetName().Version}\")"; + + internal static string NormalizeGeneratedCodeVersion(string actual) + => actual.Replace(s_generatedCodeAttribute, GeneratedCodeAttributePlaceholder, StringComparison.Ordinal); + + internal static string ResolveGeneratedCodeVersion(string expected) + => expected.Replace(GeneratedCodeAttributePlaceholder, s_generatedCodeAttribute, StringComparison.Ordinal); + public static async Task AssertOrUpdateAsync(string area, string caseName, BaselineVariant variant, string actual) { if (BaselineHarness.ShouldUpdateBaselines) { var path = BaselineHarness.MostSpecificPath(area, caseName, variant); _ = Directory.CreateDirectory(Path.GetDirectoryName(path)!); - await File.WriteAllTextAsync(path, actual).ConfigureAwait(false); + await File.WriteAllTextAsync(path, NormalizeGeneratedCodeVersion(actual)).ConfigureAwait(false); return; } @@ -26,6 +36,6 @@ public static async Task AssertOrUpdateAsync(string area, string caseName, Basel Assert.That(resolved, Is.Not.Null, $"No baseline found for case '{caseName}' variant '{variant}'. Run with UPDATE_BASELINES=1 (Windows variants) or seed from the legacy tests (Unix variants)."); var expected = await File.ReadAllTextAsync(resolved!).ConfigureAwait(false); - Assert.That(actual, Is.EqualTo(expected)); + Assert.That(actual, Is.EqualTo(ResolveGeneratedCodeVersion(expected))); } } diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/BaselineAssertionsTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/BaselineAssertionsTest.cs new file mode 100644 index 000000000..a3d55fd43 --- /dev/null +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/BaselineAssertionsTest.cs @@ -0,0 +1,20 @@ +// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +using NUnit.Framework; + +namespace ClangSharp.UnitTests.Baseline; + +public sealed class BaselineAssertionsTest +{ + [Test] + public void GeneratedCodeVersionIsResolvedAndNormalized() + { + const string baseline = "[assembly: GeneratedCode(\"ClangSharp\", \"{ClangSharpVersion}\")]"; + var actual = $"[assembly: GeneratedCode(\"ClangSharp\", \"{typeof(PInvokeGenerator).Assembly.GetName().Version}\")]"; + + Assert.That(BaselineAssertions.ResolveGeneratedCodeVersion(baseline), Is.EqualTo(actual)); + Assert.That(BaselineAssertions.NormalizeGeneratedCodeVersion(actual), Is.EqualTo(baseline)); + Assert.That(BaselineAssertions.NormalizeGeneratedCodeVersion("GeneratedCode(\"ClangSharp\", \"wrong\")"), Is.EqualTo("GeneratedCode(\"ClangSharp\", \"wrong\")")); + Assert.That("[assembly: GeneratedCode(\"ClangSharp\", \"wrong\")]", Is.Not.EqualTo(BaselineAssertions.ResolveGeneratedCodeVersion(baseline))); + } +} diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/FunctionDeclarationBodyImport/EnumeratorShiftTest.CSharp.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/FunctionDeclarationBodyImport/EnumeratorShiftTest.CSharp.cs new file mode 100644 index 000000000..72227d5d7 --- /dev/null +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/FunctionDeclarationBodyImport/EnumeratorShiftTest.CSharp.cs @@ -0,0 +1,25 @@ +using static ClangSharp.Test.MyEnum; + +namespace ClangSharp.Test +{ + public enum MyEnum + { + MyEnum_Shift = 24, + MyEnum_Value = 1 << (int)(MyEnum_Shift), + } + + public static partial class Methods + { + [return: NativeTypeName("unsigned char")] + public static byte MyFunction([NativeTypeName("unsigned int")] uint x) + { + return (byte)(x >> (int)(MyEnum_Shift)); + } + + [return: NativeTypeName("unsigned int")] + public static uint MyFunction2([NativeTypeName("unsigned int")] uint x) + { + return x << (int)(MyEnum_Shift); + } + } +} diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/FunctionDeclarationBodyImport/EnumeratorShiftTest.Xml.xml b/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/FunctionDeclarationBodyImport/EnumeratorShiftTest.Xml.xml new file mode 100644 index 000000000..dba9a6e0c --- /dev/null +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/FunctionDeclarationBodyImport/EnumeratorShiftTest.Xml.xml @@ -0,0 +1,36 @@ + + + + + int + + int + + 24 + + + + int + + 1 << (int)(MyEnum_Shift) + + + + + + byte + + uint + + return (byte)(x >> (int)(MyEnum_Shift)); + + + uint + + uint + + return x << (int)(MyEnum_Shift); + + + + diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/GeneratedCodeAttribute/EmitsAssemblyAttributeWithHelperTypes.CSharp.Latest.Windows.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/GeneratedCodeAttribute/EmitsAssemblyAttributeWithHelperTypes.CSharp.Latest.Windows.cs index e87c1e86f..5d82e9059 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/GeneratedCodeAttribute/EmitsAssemblyAttributeWithHelperTypes.CSharp.Latest.Windows.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/GeneratedCodeAttribute/EmitsAssemblyAttributeWithHelperTypes.CSharp.Latest.Windows.cs @@ -3,7 +3,7 @@ using System.Diagnostics; using System.Runtime.InteropServices; -[assembly: GeneratedCode("ClangSharp", "23.1.5.0")] +[assembly: GeneratedCode("ClangSharp", "{ClangSharpVersion}")] namespace ClangSharp.Test { diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/GeneratedCodeAttribute/EmitsPerTypeAttributeInTypeMode.CSharp.Latest.Windows.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/GeneratedCodeAttribute/EmitsPerTypeAttributeInTypeMode.CSharp.Latest.Windows.cs index 7017a3694..0c804e331 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/GeneratedCodeAttribute/EmitsPerTypeAttributeInTypeMode.CSharp.Latest.Windows.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/GeneratedCodeAttribute/EmitsPerTypeAttributeInTypeMode.CSharp.Latest.Windows.cs @@ -3,19 +3,19 @@ namespace ClangSharp.Test { - [GeneratedCode("ClangSharp", "23.1.5.0")] + [GeneratedCode("ClangSharp", "{ClangSharpVersion}")] public enum MyEnum { MyEnum_Value, } - [GeneratedCode("ClangSharp", "23.1.5.0")] + [GeneratedCode("ClangSharp", "{ClangSharpVersion}")] public partial struct MyStruct { public int value; } - [GeneratedCode("ClangSharp", "23.1.5.0")] + [GeneratedCode("ClangSharp", "{ClangSharpVersion}")] public static unsafe partial class Methods { [DllImport("ClangSharpPInvokeGenerator", CallingConvention = CallingConvention.Cdecl, EntryPoint = "?MyFunction@@YAXP6AXH@Z@Z", ExactSpelling = true)] diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/GeneratedCodeAttribute/EmitsPerTypeAttributeOnDelegateInTypeMode.CSharp.Compatible.Windows.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/GeneratedCodeAttribute/EmitsPerTypeAttributeOnDelegateInTypeMode.CSharp.Compatible.Windows.cs index acfc05b79..978980bcb 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/GeneratedCodeAttribute/EmitsPerTypeAttributeOnDelegateInTypeMode.CSharp.Compatible.Windows.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/GeneratedCodeAttribute/EmitsPerTypeAttributeOnDelegateInTypeMode.CSharp.Compatible.Windows.cs @@ -4,23 +4,23 @@ namespace ClangSharp.Test { - [GeneratedCode("ClangSharp", "23.1.5.0")] + [GeneratedCode("ClangSharp", "{ClangSharpVersion}")] public enum MyEnum { MyEnum_Value, } - [GeneratedCode("ClangSharp", "23.1.5.0")] + [GeneratedCode("ClangSharp", "{ClangSharpVersion}")] public partial struct MyStruct { public int value; } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - [GeneratedCode("ClangSharp", "23.1.5.0")] + [GeneratedCode("ClangSharp", "{ClangSharpVersion}")] public delegate void MyCallback(int value); - [GeneratedCode("ClangSharp", "23.1.5.0")] + [GeneratedCode("ClangSharp", "{ClangSharpVersion}")] public static partial class Methods { [DllImport("ClangSharpPInvokeGenerator", CallingConvention = CallingConvention.Cdecl, EntryPoint = "?MyFunction@@YAXP6AXH@Z@Z", ExactSpelling = true)] diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/GeneratedCodeAttribute/EmitsPerTypeInsteadOfAssemblyWithHelperTypes.CSharp.Latest.Windows.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/GeneratedCodeAttribute/EmitsPerTypeInsteadOfAssemblyWithHelperTypes.CSharp.Latest.Windows.cs index 7aef75732..63f237140 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/GeneratedCodeAttribute/EmitsPerTypeInsteadOfAssemblyWithHelperTypes.CSharp.Latest.Windows.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/GeneratedCodeAttribute/EmitsPerTypeInsteadOfAssemblyWithHelperTypes.CSharp.Latest.Windows.cs @@ -5,19 +5,19 @@ namespace ClangSharp.Test { - [GeneratedCode("ClangSharp", "23.1.5.0")] + [GeneratedCode("ClangSharp", "{ClangSharpVersion}")] public enum MyEnum { MyEnum_Value, } - [GeneratedCode("ClangSharp", "23.1.5.0")] + [GeneratedCode("ClangSharp", "{ClangSharpVersion}")] public partial struct MyStruct { public int value; } - [GeneratedCode("ClangSharp", "23.1.5.0")] + [GeneratedCode("ClangSharp", "{ClangSharpVersion}")] public static unsafe partial class Methods { [DllImport("ClangSharpPInvokeGenerator", CallingConvention = CallingConvention.Cdecl, EntryPoint = "?MyFunction@@YAXP6AXH@Z@Z", ExactSpelling = true)] diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/HelperTypes/HelperTypesEmittedAfterMethodClass.CSharp.Latest.Windows.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/HelperTypes/HelperTypesEmittedAfterMethodClass.CSharp.Latest.Windows.cs index 1a359a07c..a8fca7d48 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/HelperTypes/HelperTypesEmittedAfterMethodClass.CSharp.Latest.Windows.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/HelperTypes/HelperTypesEmittedAfterMethodClass.CSharp.Latest.Windows.cs @@ -3,7 +3,7 @@ using System.Diagnostics; using System.Runtime.InteropServices; -[assembly: GeneratedCode("ClangSharp", "23.1.5.0")] +[assembly: GeneratedCode("ClangSharp", "{ClangSharpVersion}")] namespace ClangSharp.Test { diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/HelperTypes/HelperTypesEmittedAfterMethodClassFileScoped.CSharp.Latest.Windows.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/HelperTypes/HelperTypesEmittedAfterMethodClassFileScoped.CSharp.Latest.Windows.cs index fec9429dc..96165cac0 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/HelperTypes/HelperTypesEmittedAfterMethodClassFileScoped.CSharp.Latest.Windows.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/HelperTypes/HelperTypesEmittedAfterMethodClassFileScoped.CSharp.Latest.Windows.cs @@ -3,7 +3,7 @@ using System.Diagnostics; using System.Runtime.InteropServices; -[assembly: GeneratedCode("ClangSharp", "23.1.5.0")] +[assembly: GeneratedCode("ClangSharp", "{ClangSharpVersion}")] namespace ClangSharp.Test; diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/HelperTypes/HelperTypesEmittedInSharedFileScopedNamespace.CSharp.Latest.Windows.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/HelperTypes/HelperTypesEmittedInSharedFileScopedNamespace.CSharp.Latest.Windows.cs index 99dd7e35e..0a8302fde 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/HelperTypes/HelperTypesEmittedInSharedFileScopedNamespace.CSharp.Latest.Windows.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/HelperTypes/HelperTypesEmittedInSharedFileScopedNamespace.CSharp.Latest.Windows.cs @@ -2,7 +2,7 @@ using System.CodeDom.Compiler; using System.Diagnostics; -[assembly: GeneratedCode("ClangSharp", "23.1.5.0")] +[assembly: GeneratedCode("ClangSharp", "{ClangSharpVersion}")] namespace ClangSharp.Test; diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/HelperTypes/HelperTypesEmittedInSharedNamespace.CSharp.Latest.Windows.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/HelperTypes/HelperTypesEmittedInSharedNamespace.CSharp.Latest.Windows.cs index f11fcca87..9f6dc9cd7 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/HelperTypes/HelperTypesEmittedInSharedNamespace.CSharp.Latest.Windows.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/HelperTypes/HelperTypesEmittedInSharedNamespace.CSharp.Latest.Windows.cs @@ -2,7 +2,7 @@ using System.CodeDom.Compiler; using System.Diagnostics; -[assembly: GeneratedCode("ClangSharp", "23.1.5.0")] +[assembly: GeneratedCode("ClangSharp", "{ClangSharpVersion}")] namespace ClangSharp.Test { diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/TransparentStruct/BooleanKindGeneratesValidHelper.CSharp.Latest.Windows.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/TransparentStruct/BooleanKindGeneratesValidHelper.CSharp.Latest.Windows.cs index 751f0c479..2b1e70723 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/TransparentStruct/BooleanKindGeneratesValidHelper.CSharp.Latest.Windows.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/Baselines/TransparentStruct/BooleanKindGeneratesValidHelper.CSharp.Latest.Windows.cs @@ -2,7 +2,7 @@ using System.CodeDom.Compiler; using System.Diagnostics; -[assembly: GeneratedCode("ClangSharp", "23.1.5.0")] +[assembly: GeneratedCode("ClangSharp", "{ClangSharpVersion}")] namespace ClangSharp.Test { diff --git a/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/FunctionDeclarationBodyImportTest.cs b/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/FunctionDeclarationBodyImportTest.cs index 5bdecde7f..6b5e71a41 100644 --- a/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/FunctionDeclarationBodyImportTest.cs +++ b/tests/ClangSharp.PInvokeGenerator.UnitTests/Baseline/FunctionDeclarationBodyImportTest.cs @@ -258,6 +258,29 @@ static inline int MyFunction(MyEnum x) return ValidateAsync(nameof(CompareMultipleEnumTest), inputContents); } + [Test] + public Task EnumeratorShiftTest() + { + var inputContents = @"enum MyEnum : int +{ + MyEnum_Shift = 24, + MyEnum_Value = 1 << MyEnum_Shift, +}; + +static inline unsigned char MyFunction(unsigned int x) +{ + return (unsigned char)(x >> MyEnum_Shift); +} + +static inline unsigned int MyFunction2(unsigned int x) +{ + return x << (MyEnum_Shift); +} +"; + + return ValidateAsync(nameof(EnumeratorShiftTest), inputContents); + } + [Test] public Task ConditionalOperatorTest() {