Skip to content

Commit

Permalink
Disallow span conversions between spans which are not structs (#74587)
Browse files Browse the repository at this point in the history
* Disallow span conversions between spans which are not structs

* Require ref struct
  • Loading branch information
jjonescz authored Aug 2, 2024
1 parent 4ba990b commit 3e83e7b
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/Compilers/CSharp/Portable/Symbols/TypeSymbolExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1343,6 +1343,8 @@ internal static bool IsSpan(this TypeSymbol type)
return type is NamedTypeSymbol
{
Name: "Span",
IsValueType: true,
IsRefLikeType: true,
Arity: 1,
ContainingType: null,
ContainingNamespace: { Name: nameof(System), ContainingNamespace.IsGlobalNamespace: true },
Expand All @@ -1354,6 +1356,8 @@ internal static bool IsReadOnlySpan(this TypeSymbol type)
return type is NamedTypeSymbol
{
Name: "ReadOnlySpan",
IsValueType: true,
IsRefLikeType: true,
Arity: 1,
ContainingType: null,
ContainingNamespace: { Name: nameof(System), ContainingNamespace.IsGlobalNamespace: true },
Expand Down
22 changes: 22 additions & 0 deletions src/Compilers/CSharp/Test/Emit3/FirstClassSpanTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,28 @@ public readonly ref struct Span<T>
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "arr()").WithArguments("System.Span<T>", "op_Implicit").WithLocation(2, 15));
}

[Theory, CombinatorialData]
public void Conversion_Array_Span_Implicit_SpanNotRefStruct(
[CombinatorialValues("class", "struct", "readonly struct", "record", "record struct", "readonly record struct")] string kind,
[CombinatorialValues("Span", "ReadOnlySpan")] string type)
{
var source = $$"""
using System;
{{type}}<int> s =
arr();
static int[] arr() => new int[] { 1, 2, 3 };
namespace System
{
public {{kind}} {{type}}<T>;
}
""";
CreateCompilation(source).VerifyDiagnostics(
// (3,5): error CS0029: Cannot implicitly convert type 'int[]' to 'System.Span<int>'
// arr();
Diagnostic(ErrorCode.ERR_NoImplicitConv, "arr()").WithArguments("int[]", $"System.{type}<int>").WithLocation(3, 5));
}

[Theory, CombinatorialData]
public void Conversion_Array_Span_Implicit_DifferentOperator(
[CombinatorialValues("int[]", "T[][]")] string parameterType)
Expand Down

0 comments on commit 3e83e7b

Please # to comment.