Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.Predicates.cs
Original file line number Diff line number Diff line change
Expand Up @@ -946,6 +946,19 @@ private bool IsUnchecked(string targetTypeName, Stmt stmt)
targetTypeName = transparentStruct.Name;
}
}
else
{
// The platform-dependent narrowing that could overflow on a 32-bit target only happens
// when the generator emits the explicit `(nint)`/`(nuint)` cast, which it only does for
// `VarDecl` initializers (see `UncheckStmt`). Outside of that context an expression keeps
// its natural C# type and never needs an `unchecked` scope, so evaluate native-sized
// integer targets against their widest equivalent.
targetTypeName = targetTypeName switch {
"nint" or "IntPtr" => "long",
"nuint" or "UIntPtr" => "ulong",
_ => targetTypeName,
};
}

switch (stmt.StmtClass)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ public static unsafe partial class Methods
[return: NativeTypeName("_Bool")]
public static bool SDL_size_add_check_overflow([NativeTypeName("size_t")] nuint a, [NativeTypeName("size_t")] nuint b, [NativeTypeName("size_t *")] nuint* ret)
{
if (b > unchecked(18446744073709551615U) - a)
if (b > (18446744073709551615U) - a)
{
return (0) != 0;
}
Expand Down
7 changes: 3 additions & 4 deletions tests/ClangSharp.PInvokeGenerator.UnitTests/CTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,7 @@ public Task CLongDefinesTestUnix()
public Task CLongDefinesRegressionTestUnix()
{
// This test is to catch a potential regression when changing how native integers are handled
// Specifically, (18446744073709551615U) became unchecked(18446744073709551615U)
// Specifically, (18446744073709551615U) must not be wrapped in an unnecessary unchecked scope

// Macro values are taken from the Linux headers when using Clang
// Some values are substituted for simplicity
Expand All @@ -406,9 +406,8 @@ bool SDL_size_add_check_overflow(size_t a, size_t b, size_t *ret)
}
";

// The expected below currently does not represent the ideal behavior.
// Ideally, the unchecked keywork is removed as it is unnecessary.
// This issue is tracked here: https://github.com/dotnet/ClangSharp/issues/709
// The unnecessary unchecked scope around the `ulong` literal is now elided; see
// https://github.com/dotnet/ClangSharp/issues/709
return ValidateGeneratedCSharpLatestUnixBaselineAsync(inputContents, commandLineArgs: DefaultCClangCommandLineArgs, language: "c", languageStandard: DefaultCStandard);
}

Expand Down
Loading