New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
C# 8 nullable reference type support #115
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
# EditorConfig is awesome: http://EditorConfig.org | ||
|
||
# top-most EditorConfig file | ||
root = true | ||
|
||
# Editor default newlines with a newline ending every file | ||
[*] | ||
insert_final_newline = true | ||
charset = utf-8 | ||
indent_style = space | ||
indent_size = 2 | ||
trim_trailing_whitespace = true | ||
|
||
[*.cs] | ||
indent_size = 4 | ||
indent_style = space |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
namespace PublicApiGenerator | ||
{ | ||
internal static class CSharpAlias | ||
{ | ||
public static string Get(string typeName) | ||
{ | ||
switch (typeName) | ||
{ | ||
case "System.Byte": | ||
return "byte"; | ||
case "System.SByte": | ||
return "sbyte"; | ||
case "System.Int16": | ||
return "short"; | ||
case "System.UInt16": | ||
return "ushort"; | ||
case "System.Int32": | ||
return "int"; | ||
case "System.UInt32": | ||
return "uint"; | ||
case "System.Int64": | ||
return "long"; | ||
case "System.UInt64": | ||
return "ulong"; | ||
case "System.Single": | ||
return "float"; | ||
case "System.Double": | ||
return "double"; | ||
case "System.Decimal": | ||
return "decimal"; | ||
case "System.Object": | ||
return "object"; | ||
case "System.String": | ||
return "string"; | ||
case "System.Boolean": | ||
return "bool"; | ||
default: | ||
return typeName; | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,156 @@ | ||
using Mono.Cecil; | ||
using System; | ||
using System.CodeDom; | ||
using System.Collections.Generic; | ||
using System.Linq; | ||
|
||
namespace PublicApiGenerator | ||
{ | ||
internal static class CodeTypeReferenceBuilder | ||
{ | ||
private const int MAX_COUNT = 100; | ||
|
||
internal static CodeTypeReference CreateCodeTypeReference(this TypeReference type, ICustomAttributeProvider attributeProvider = null, NullableMode mode = NullableMode.Default) | ||
{ | ||
return CreateCodeTypeReferenceWithNullabilityMap(type, attributeProvider.GetNullabilityMap().GetEnumerator(), mode, false); | ||
} | ||
|
||
static CodeTypeReference CreateCodeTypeReferenceWithNullabilityMap(TypeReference type, IEnumerator<bool?> nullabilityMap, NullableMode mode, bool disableNested) | ||
{ | ||
var typeName = GetTypeName(type, nullabilityMap, mode, disableNested); | ||
if (type.IsValueType && type.Name == "Nullable`1" && type.Namespace == "System") | ||
{ | ||
// unwrap System.Nullable<Type> into Type? for readability | ||
var genericArgs = type is IGenericInstance instance ? instance.GenericArguments : type.HasGenericParameters ? type.GenericParameters.Cast<TypeReference>() : null; | ||
return CreateCodeTypeReferenceWithNullabilityMap(genericArgs.Single(), nullabilityMap, NullableMode.Force, disableNested); | ||
} | ||
else | ||
{ | ||
return new CodeTypeReference(typeName, CreateGenericArguments(type, nullabilityMap)); | ||
} | ||
} | ||
|
||
static CodeTypeReference[] CreateGenericArguments(TypeReference type, IEnumerator<bool?> nullabilityMap) | ||
{ | ||
// ReSharper disable once RedundantEnumerableCastCall | ||
var genericArgs = type is IGenericInstance instance ? instance.GenericArguments : type.HasGenericParameters ? type.GenericParameters.Cast<TypeReference>() : null; | ||
if (genericArgs == null) return null; | ||
|
||
var genericArguments = new List<CodeTypeReference>(); | ||
foreach (var argument in genericArgs) | ||
{ | ||
genericArguments.Add(CreateCodeTypeReferenceWithNullabilityMap(argument, nullabilityMap, NullableMode.Default, false)); | ||
} | ||
return genericArguments.ToArray(); | ||
} | ||
|
||
internal static IEnumerable<bool?> GetNullabilityMap(this ICustomAttributeProvider attributeProvider) | ||
{ | ||
var nullableAttr = attributeProvider?.CustomAttributes.SingleOrDefault(d => d.AttributeType.FullName == "System.Runtime.CompilerServices.NullableAttribute"); | ||
|
||
if (nullableAttr == null) | ||
{ | ||
foreach (var provider in NullableContext.Providers) | ||
{ | ||
nullableAttr = provider.CustomAttributes.SingleOrDefault(d => d.AttributeType.FullName == "System.Runtime.CompilerServices.NullableContextAttribute"); | ||
if (nullableAttr != null) | ||
break; | ||
} | ||
} | ||
|
||
if (nullableAttr == null) | ||
return Enumerable.Repeat((bool?)null, MAX_COUNT); | ||
|
||
var value = nullableAttr.ConstructorArguments[0].Value; | ||
if (value is CustomAttributeArgument[] arguments) | ||
return arguments.Select(a => Convert((byte)a.Value)); | ||
|
||
return Enumerable.Repeat(Convert((byte)value), MAX_COUNT); | ||
|
||
// https://github.com/dotnet/roslyn/blob/master/docs/features/nullable-metadata.md | ||
// returns: | ||
// true : explicitly nullable | ||
// false: explicitly not nullable | ||
// null : oblivious | ||
bool? Convert(byte value) | ||
{ | ||
switch (value) | ||
{ | ||
case 2: return true; | ||
case 1: return false; | ||
case 0: return null; | ||
default: throw new NotSupportedException(value.ToString()); | ||
} | ||
} | ||
} | ||
|
||
// The compiler optimizes the size of metadata bypassing a sequence of bytes for value types. | ||
// Thus, it can even delete the entire NullableAttribute if the whole signature consists only of value types, | ||
// for example KeyValuePair<int, int?>, thus we can call IsNullable() only by looking first deep into the signature | ||
private static bool HasAnyReferenceType(TypeReference type) | ||
{ | ||
if (!type.IsValueType) | ||
return true; | ||
|
||
// ReSharper disable once RedundantEnumerableCastCall | ||
var genericArgs = type is IGenericInstance instance ? instance.GenericArguments : type.HasGenericParameters ? type.GenericParameters.Cast<TypeReference>() : null; | ||
if (genericArgs == null) return false; | ||
|
||
foreach (var argument in genericArgs) | ||
{ | ||
if (HasAnyReferenceType(argument)) | ||
return true; | ||
} | ||
|
||
return false; | ||
} | ||
|
||
static string GetTypeName(TypeReference type, IEnumerator<bool?> nullabilityMap, NullableMode mode, bool disableNested) | ||
{ | ||
bool nullable = mode != NullableMode.Disable && (mode == NullableMode.Force || HasAnyReferenceType(type) && IsNullable()); | ||
|
||
var typeName = GetTypeNameCore(type, nullabilityMap, nullable, disableNested); | ||
|
||
if (nullable && typeName != "System.Void") | ||
typeName = CSharpAlias.Get(typeName) + "?"; | ||
|
||
return typeName; | ||
|
||
bool IsNullable() | ||
{ | ||
if (nullabilityMap == null) | ||
return false; | ||
|
||
if (!nullabilityMap.MoveNext()) | ||
{ | ||
throw new InvalidOperationException("Not enough nullability information"); | ||
} | ||
return nullabilityMap.Current == true; | ||
} | ||
} | ||
|
||
static string GetTypeNameCore(TypeReference type, IEnumerator<bool?> nullabilityMap, bool nullable, bool disableNested) | ||
{ | ||
if (type.IsGenericParameter) | ||
{ | ||
return type.Name; | ||
} | ||
|
||
if (type is ArrayType array) | ||
{ | ||
if (nullable) | ||
return CSharpAlias.Get(GetTypeName(array.ElementType, nullabilityMap, NullableMode.Default, disableNested)) + "[]"; | ||
else | ||
return GetTypeName(array.ElementType, nullabilityMap, NullableMode.Default, disableNested) + "[]"; | ||
} | ||
|
||
if (!type.IsNested || disableNested) | ||
{ | ||
var name = type is RequiredModifierType modType ? modType.ElementType.Name : type.Name; | ||
return (!string.IsNullOrEmpty(type.Namespace) ? (type.Namespace + ".") : "") + name; | ||
} | ||
|
||
return GetTypeName(type.DeclaringType, null, NullableMode.Default, false) + "." + GetTypeName(type, null, NullableMode.Default, true); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
using Mono.Cecil; | ||
using System; | ||
using System.Collections.Generic; | ||
|
||
namespace PublicApiGenerator | ||
{ | ||
// https://github.com/dotnet/roslyn/blob/master/docs/features/nullable-metadata.md#nullablecontextattribute | ||
internal class NullableContext | ||
{ | ||
[ThreadStatic] | ||
private static Stack<ICustomAttributeProvider> _nullableContextProviders; | ||
|
||
private static Stack<ICustomAttributeProvider> NullableContextProviders | ||
{ | ||
get | ||
{ | ||
if (_nullableContextProviders == null) | ||
_nullableContextProviders = new Stack<ICustomAttributeProvider>(); | ||
return _nullableContextProviders; | ||
} | ||
} | ||
|
||
internal static IDisposable Push(ICustomAttributeProvider provider) => new PopDisposable(provider); | ||
|
||
internal static IEnumerable<ICustomAttributeProvider> Providers => NullableContextProviders; | ||
|
||
private sealed class PopDisposable : IDisposable | ||
{ | ||
public PopDisposable(ICustomAttributeProvider provider) | ||
{ | ||
NullableContextProviders.Push(provider); | ||
} | ||
|
||
public void Dispose() | ||
{ | ||
NullableContextProviders.Pop(); | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
namespace PublicApiGenerator | ||
{ | ||
enum NullableMode | ||
{ | ||
Default, | ||
Force, | ||
Disable | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm a fan of this change. 'Alias' means something specific in C#, so I'd call it
CSharpTypeKeyword
or something.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe