Skip to content
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

Forbid unsafe types in records #76588

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
27 changes: 27 additions & 0 deletions docs/compilers/CSharp/Compiler Breaking Changes - DotNet 10.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,3 +156,30 @@ struct S
public static void M([UnscopedRef] ref int x) { }
}
```

## `record` and `record struct` types cannot define pointer type members, even when providing their own Equals implementations

PROTOTYPE: Figure what version this is going into

***Introduced in Visual Studio 2022 version 17.14***

The specification for `record class` and `record struct` types indicated that any unsafe types are disallowed. However, this was not
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

indicated that any unsafe types are disallowed

This sounds too broad. The spec says:

It is an error for an instance field of a record to have an unsafe type.

enforced correctly in 2 scenarios:

1. When the `record class` or `record struct` type defined its own `Equals` implementation.
2. When the field type only used the unsafe type in a nested context, such as `int*[]`.
Copy link
Contributor

@AlekseyTs AlekseyTs Jan 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When the field type only used the unsafe type in a nested context, such as int*[].

I couldn't find a clear definition of "unsafe type" in the language spec. Therefore, it is not clear whether such array type should be considered as unsafe.


The compiler now correctly forbids both scenarios.

```cs
unsafe record struct R1(
int* P // Previously fine, now CS8908
)
{
public bool Equals(R other) => true;
}

unsafe record struct R2(
int*[] P // Previously fine, now CS8908
);
```
Original file line number Diff line number Diff line change
Expand Up @@ -3022,7 +3022,7 @@ private bool MethodGroupConversionHasErrors(
return true;
}

if ((selectedMethod.HasParameterContainingPointerType() || selectedMethod.ReturnType.ContainsPointer())
if ((selectedMethod.HasParameterContainingPointerType() || selectedMethod.ReturnType.ContainsPointerOrFunctionPointer())
&& ReportUnsafeIfNotAllowed(syntax, diagnostics))
{
return true;
Expand Down
4 changes: 2 additions & 2 deletions src/Compilers/CSharp/Portable/Binder/Binder_Expressions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -561,7 +561,7 @@ private void CheckContextForPointerTypes(ExpressionSyntax node, BindingDiagnosti
if (!expr.HasAnyErrors && !IsInsideNameof)
{
TypeSymbol exprType = expr.Type;
if ((object)exprType != null && exprType.ContainsPointer())
if ((object)exprType != null && exprType.ContainsPointerOrFunctionPointer())
{
ReportUnsafeIfNotAllowed(node, diagnostics);
//CONSIDER: Return a bad expression so that HasErrors is true?
Expand Down Expand Up @@ -3666,7 +3666,7 @@ void createParamsCollection(
void reportUnsafeIfNeeded(MemberResolutionResult<TMember> methodResult, BindingDiagnosticBag diagnostics, BoundExpression argument, TypeWithAnnotations parameterTypeWithAnnotations)
{
// NOTE: for some reason, dev10 doesn't report this for indexer accesses.
if (!methodResult.Member.IsIndexer() && !argument.HasAnyErrors && parameterTypeWithAnnotations.Type.ContainsPointer())
if (!methodResult.Member.IsIndexer() && !argument.HasAnyErrors && parameterTypeWithAnnotations.Type.ContainsPointerOrFunctionPointer())
{
// CONSIDER: dev10 uses the call syntax, but this seems clearer.
ReportUnsafeIfNotAllowed(argument.Syntax, diagnostics);
Expand Down
2 changes: 1 addition & 1 deletion src/Compilers/CSharp/Portable/Binder/Binder_Symbols.cs
Original file line number Diff line number Diff line change
Expand Up @@ -915,7 +915,7 @@ protected NamespaceOrTypeOrAliasSymbolWithAnnotations BindNonGenericSimpleNamesp
ReportUseSiteDiagnosticForDynamic(diagnostics, node);
}

if (type.ContainsPointer())
if (type.ContainsPointerOrFunctionPointer())
{
ReportUnsafeIfNotAllowed(node, diagnostics);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Compilers/CSharp/Portable/BoundTree/UnboundLambda.cs
Original file line number Diff line number Diff line change
Expand Up @@ -919,7 +919,7 @@ private void ValidateUnsafeParameters(BindingDiagnosticBag diagnostics, Immutabl
var numParametersToCheck = Math.Min(targetParameterTypes.Length, ParameterCount);
for (int i = 0; i < numParametersToCheck; i++)
{
if (targetParameterTypes[i].Type.ContainsPointer())
if (targetParameterTypes[i].Type.ContainsPointerOrFunctionPointer())
{
this.Binder.ReportUnsafeIfNotAllowed(this.ParameterLocation(i), diagnostics);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ internal static bool HasParameterContainingPointerType(this Symbol member)
{
foreach (var parameterType in member.GetParameterTypes())
{
if (parameterType.Type.ContainsPointer())
if (parameterType.Type.ContainsPointerOrFunctionPointer())
{
return true;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,15 +57,20 @@ protected void TypeChecks(TypeSymbol type, BindingDiagnosticBag diagnostics)
}
else if (type.IsVoidType())
{
diagnostics.Add(ErrorCode.ERR_FieldCantHaveVoidType, TypeSyntax?.Location ?? this.GetFirstLocation());
diagnostics.Add(ErrorCode.ERR_FieldCantHaveVoidType, getTypeErrorLocation());
}
else if (type.IsRestrictedType(ignoreSpanLikeTypes: true))
{
diagnostics.Add(ErrorCode.ERR_FieldCantBeRefAny, TypeSyntax?.Location ?? this.GetFirstLocation(), type);
diagnostics.Add(ErrorCode.ERR_FieldCantBeRefAny, getTypeErrorLocation(), type);
}
else if (type.IsRefLikeOrAllowsRefLikeType() && (this.IsStatic || !containingType.IsRefLikeType))
{
diagnostics.Add(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, TypeSyntax?.Location ?? this.GetFirstLocation(), type);
diagnostics.Add(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, getTypeErrorLocation(), type);
}
else if (!this.IsStatic && type.ContainsPointerOrFunctionPointer() && (ContainingType.IsRecord || ContainingType.IsRecordStruct))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(ContainingType.IsRecord || ContainingType.IsRecordStruct)

I assume this check is cheaper than the type check for pointers. Consider performing reordering the checks.

{
// The type '{0}' may not be used for a field of a record.
diagnostics.Add(ErrorCode.ERR_BadFieldTypeInRecord, getTypeErrorLocation(), type);
}
else if (IsConst && !type.CanBeConst())
{
Expand Down Expand Up @@ -96,6 +101,11 @@ protected void TypeChecks(TypeSymbol type, BindingDiagnosticBag diagnostics)
}

diagnostics.Add(this.ErrorLocation, useSiteInfo);

Location getTypeErrorLocation()
{
return TypeSyntax?.Location ?? this.GetFirstLocation();
}
}

public abstract bool HasInitializer { get; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1839,9 +1839,18 @@ protected virtual void ValidatePropertyType(BindingDiagnosticBag diagnostics)
{
diagnostics.Add(ErrorCode.ERR_FieldCantBeRefAny, TypeLocation, type);
}
else if (this.IsAutoPropertyOrUsesFieldKeyword && type.IsRefLikeOrAllowsRefLikeType() && (this.IsStatic || !this.ContainingType.IsRefLikeType))

if (this.IsAutoPropertyOrUsesFieldKeyword)
{
diagnostics.Add(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, TypeLocation, type);
if (!this.IsStatic && type.ContainsPointerOrFunctionPointer() && (ContainingType.IsRecord || ContainingType.IsRecordStruct))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(ContainingType.IsRecord || ContainingType.IsRecordStruct)

Similar suggestion

{
// The type '{0}' may not be used for a field of a record.
diagnostics.Add(ErrorCode.ERR_BadFieldTypeInRecord, TypeLocation, type);
}
else if (type.IsRefLikeOrAllowsRefLikeType() && (this.IsStatic || !this.ContainingType.IsRefLikeType))
{
diagnostics.Add(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, TypeLocation, type);
}
}

if (type.IsStatic)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,12 +136,7 @@ internal override void GenerateMethodBody(TypeCompilationState compilationState,
fields.Add(f);

var parameterType = f.Type;
if (parameterType.IsPointerOrFunctionPointer())
{
diagnostics.Add(ErrorCode.ERR_BadFieldTypeInRecord, f.GetFirstLocationOrNone(), parameterType);
foundBadField = true;
}
else if (parameterType.IsRestrictedType())
if (parameterType.ContainsPointerOrFunctionPointer() || parameterType.IsRestrictedType())
{
// We'll have reported a diagnostic elsewhere (SourceMemberFieldSymbol.TypeChecks)
foundBadField = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1278,7 +1278,7 @@ internal static bool ContainsTupleNames(this TypeSymbol type) =>
internal static bool ContainsFunctionPointer(this TypeSymbol type) =>
type.VisitType((TypeSymbol t, object? _, bool _) => t.IsFunctionPointer(), null) is object;

internal static bool ContainsPointer(this TypeSymbol type) =>
internal static bool ContainsPointerOrFunctionPointer(this TypeSymbol type) =>
type.VisitType((TypeSymbol t, object? _, bool _) => t.TypeKind is TypeKind.Pointer or TypeKind.FunctionPointer, null) is object;

/// <summary>
Expand Down
Loading
Loading