bootsharp
bootsharp copied to clipboard
Detect when to emit nullable defines in auto-generated C# files
Due to #68 compiler now require #nullable enable
defines when nullable reference type annotations are used in the auto-generated files.
I'm not aware of a reliable way to detect whether a nullable annotation is used in the analyzed syntax tree, so the generators always emit #nullable
defines (#71), which could cause issues when the consumer doesn't have nullable reference types enabled.
If anyone have any idea how to detect whether the nullable define should be emitted (eg, by checking whether a nullable annotation is used anywhere in the analyzed syntax tree):
https://github.com/Elringus/DotNetJS/blob/1c11d8c8ac71d786fde85dad82f3c45a16f07f9a/DotNet/Generator/GeneratedClass.cs#L19-L21
— please let us know here.
If you are talking about warnings, you could do something like this
#nullable enable
#pragma warning disable
// CODE
#pragma warning restore
#nullable restore
Used this for some of my source nuget packages, worked like a charm
Yeah, I've thought about muting the warnings, but hopefully we can find a way to detect whether the nullable defines are actually required. If not, disabling the warnings will work, thanks for the tip.
Oh, then you could use this API to detect if the project enabled nullables:
if (compilation.Options.NullableContextOptions != NullableContextOptions.Disable) { }
Or use a more controlled example, should work with manual #nullable enable
in usercode
if (compilation.GetSemanticModel(syntax.SyntaxTree).GetNullableContext(syntax.SpanStart) != NullableContext.Disabled) { }
I do think the second method should use something better than != Disabled
Thanks for the info! I've actually tried compilation.Options.NullableContextOptions
, but it didn't work in unit tests. Probably because the tests project had nullables disabled, but it also ignored the define in the sources.