tonybaloney / CSnakes

https://tonybaloney.github.io/CSnakes/
MIT License
335 stars 25 forks source link

Fix optionality of function parameters & return #299

Open atifaziz opened 1 month ago

atifaziz commented 1 month ago

This PR fixes #295. It does this primarily by moving the decision of nullability to TypeReflection.AsPredefinedType, where the Optional type hint is considered. As a result of this, the literalExpressionSyntax in ArgumentReflection.ArgumentSyntax also becomes a simple switch expression that's solely based on the PythonConstant of the parameter's default value.

This also fixes some tests that were incorrect previously, like:

https://github.com/tonybaloney/CSnakes/blob/048e011b5d70849edb1d0c26fa9b985f8a48f6dc/src/CSnakes.Tests/GeneratedSignatureTests.cs#L30

The b parameter cannot have a default value of None per the type hint of str. The C# signature is correct, but because it was based on the presence of None as the default value.

MethodReflection.ProcessMethodWithReturnType needed some bigger changes because the return type's nullability needed to be handled with some extra care. PyObject.As<T> isn't good enough since it uses reflection based on type of T and isn't aware of nullability. As a result, MethodReflection.ProcessMethodWithReturnType generates code to check for None and return null instead when the return type is Optional. I've added integration tests for this (see test_optional.py), where you can see this in action along the lines of:

public long? TestInt(long? n)
{
    using (GIL.Acquire())
    {
        // ...
        return __result_pyObject.IsNone() ? null : __result_pyObject.As<long>();
    }
}
tonybaloney commented 3 weeks ago

The b parameter cannot have a default value of None per the type hint of str.

I added that test because type hints are just hints. Python developers often (although it is wrong) use default of None with a parameter that is not marked as optional either via Optional[str] or Union[str, None] or str | None

atifaziz commented 2 weeks ago

type hints are just hints

I understand, but they're fairly critical for the source generator to produce sensible wrappers.

Python developers often (although it is wrong) use default of None with a parameter that is

Doesn't that leave the door open for other forms of type hint sloppiness? It could be the start of a slippery slope. Where do you draw the line?