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

Merged
merged 7 commits into from
Jan 17, 2025
Merged
Show file tree
Hide file tree
Changes from 5 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
20 changes: 20 additions & 0 deletions docs/compilers/CSharp/Compiler Breaking Changes - DotNet 10.md
Original file line number Diff line number Diff line change
Expand Up @@ -193,3 +193,23 @@ namespace Microsoft.CodeAnalysis;
// Previously, sometimes allowed. Now, CS9271
public class EmbeddedAttribute : Attribute {}
```

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

***Introduced in Visual Studio 2022 version 17.14***
333fred marked this conversation as resolved.
Show resolved Hide resolved

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

The specification for `record class` and `record struct` types indicated that any pointer types are disallowed as instance fields.
However, this was not enforced correctly when the `record class` or `record struct` type defined its own `Equals` implementation.

The compiler now correctly forbids this.

```cs
unsafe record struct R(
int* P // Previously fine, now CS8908
)
{
public bool Equals(R other) => true;
}
```
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 && (ContainingType.IsRecord || ContainingType.IsRecordStruct) && type.IsPointerOrFunctionPointer())
{
// 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,17 @@ protected virtual void ValidatePropertyType(BindingDiagnosticBag diagnostics)
{
diagnostics.Add(ErrorCode.ERR_FieldCantBeRefAny, TypeLocation, type);
}
else if (this.IsAutoPropertyOrUsesFieldKeyword && type.IsRefLikeOrAllowsRefLikeType() && (this.IsStatic || !this.ContainingType.IsRefLikeType))
else if (this.IsAutoPropertyOrUsesFieldKeyword)
{
diagnostics.Add(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, TypeLocation, type);
if (!this.IsStatic && (ContainingType.IsRecord || ContainingType.IsRecordStruct) && type.IsPointerOrFunctionPointer())
{
// 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.IsPointerOrFunctionPointer() || 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