Skip to content

Commit

Permalink
Add unsafe modifier when necessary
Browse files Browse the repository at this point in the history
  • Loading branch information
jnm2 committed Nov 2, 2019
1 parent 134ad56 commit fabfb46
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/PublicApiGenerator/ApiGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -626,6 +626,9 @@ static void AddMethodToTypeDeclaration(CodeTypeDeclaration typeDeclaration, Meth

var returnType = member.ReturnType.CreateCodeTypeReference(member.MethodReturnType);

if (IsUnsafeSignatureType(member.ReturnType) || member.Parameters.Any(p => IsUnsafeSignatureType(p.ParameterType)))
returnType = MakeUnsafe(returnType);

var method = new CodeMemberMethod
{
Name = memberName,
Expand All @@ -640,6 +643,22 @@ static void AddMethodToTypeDeclaration(CodeTypeDeclaration typeDeclaration, Meth
typeDeclaration.Members.Add(method);
}

static bool IsUnsafeSignatureType(TypeReference typeReference)
{
while (true)
{
if (typeReference.IsPointer) return true;

if (typeReference.IsArray || typeReference.IsByReference)
{
typeReference = typeReference.GetElementType();
continue;
}

return false;
}
}

static bool IsExtensionMethod(ICustomAttributeProvider method)
{
return method.CustomAttributes.Any(a => a.AttributeType.FullName == "System.Runtime.CompilerServices.ExtensionAttribute");
Expand Down Expand Up @@ -889,6 +908,9 @@ static void AddFieldToTypeDeclaration(CodeTypeDeclaration typeDeclaration, Field
var codeTypeReference = memberInfo.FieldType.CreateCodeTypeReference(memberInfo);
if (memberInfo.IsInitOnly)
codeTypeReference = MakeReadonly(codeTypeReference);
if (IsUnsafeSignatureType(memberInfo.FieldType))
codeTypeReference = MakeUnsafe(codeTypeReference);

var field = new CodeMemberField(codeTypeReference, memberInfo.Name)
{
Attributes = attributes,
Expand All @@ -906,6 +928,11 @@ static CodeTypeReference MakeReadonly(CodeTypeReference typeReference)
return ModifyCodeTypeReference(typeReference, "readonly");
}

static CodeTypeReference MakeUnsafe(CodeTypeReference typeReference)
{
return ModifyCodeTypeReference(typeReference, "unsafe");
}

static CodeTypeReference ModifyCodeTypeReference(CodeTypeReference typeReference, string modifier)
{
using (var provider = new CSharpCodeProvider())
Expand Down

0 comments on commit fabfb46

Please sign in to comment.