Skip to content
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
15 changes: 10 additions & 5 deletions src/Csharpc/CodeGen/ModuleCodeGen.Bcl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,9 @@ private bool HasInterfaceMethodTable(string metadataName) =>
/// </summary>
public LLVMValueRef EnumMethodTable(INamedTypeSymbol enumType)
{
enumType = enumType.OriginalDefinition;
// An enum nested in a generic type is a type per instantiation, as any nested type (typeof(G<int>.E) != typeof(G<string>.E), and a
// boxed one is not the other); a definition of its own otherwise.
enumType = (INamedTypeSymbol)TypeSubstitution.EraseTupleNames(enumType, Compilation);
if (_enumMethodTables.TryGetValue(enumType, out var existing)) return existing;
var underlying = enumType.EnumUnderlyingType!;
var valueType = Types.Value(underlying);
Expand Down Expand Up @@ -163,7 +165,7 @@ void SetMap(LLVMValueRef[] entries)
constant: true, linkage: LLVMLinkage.Internal);
Native.LLVMSetInitializer(global, Llvm.ConstStruct(
ExternalGlobal("csrt_Object_MT"),
CString(Mangler.MetadataName(enumType)),
CString(DescribedName(enumType)),
Llvm.ConstInt(Llvm.I32, 8 + (long)Types.Target.SizeOf(valueType)),
Llvm.ConstInt(Llvm.I32, 64 | 128 /* CSRT_MT_VALUE_TYPE | CSRT_MT_ENUM */),
map, Llvm.ConstInt(Llvm.I32, entries.Length), Llvm.ConstInt(Llvm.I32, ElementKind(underlying)),
Expand Down Expand Up @@ -370,13 +372,16 @@ private LLVMValueRef TypeOnlyMethodTable(INamedTypeSymbol type)
// Type.ToString prints it; definitions list their parameters ("System.Collections.Generic.List`1[T]").
// One table per constructed type: List<int> and List<string> are different types for typeof and
// for the type arguments generic variance compares at run time.
var name = Mangler.MetadataName(type);
if (IsDef(type) && ChainArguments(type) is { Count: > 0 } parameters)
name += "[" + string.Join(",", parameters.Select(p => p.Name)) + "]";
var name = DescribedName(type);
var key = "type:" + IdentityKey(CoreLib.Map(TypeSubstitution.EraseTupleNames(type, Compilation)));
return NameOnlyMethodTable(key, name, type.TypeKind == TypeKind.Interface ? 2 /* CSRT_MT_INTERFACE */ : 0, type);
}

/// <summary>The name a method table carries: the CLR name, a generic definition's with its parameters.</summary>
private static string DescribedName(INamedTypeSymbol type) =>
IsDef(type) && ChainArguments(type) is { Count: > 0 } parameters
? Mangler.MetadataName(type) + "[" + string.Join(",", parameters.Select(p => p.Name)) + "]" : Mangler.MetadataName(type);

private LLVMValueRef NameOnlyMethodTable(string key, string name, int flags, ITypeSymbol type)
{
if (_arrayMethodTables.TryGetValue(key, out var existing)) return existing;
Expand Down
34 changes: 24 additions & 10 deletions src/Csharpc/CodeGen/ModuleCodeGen.TypeInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -316,9 +316,7 @@ LLVMValueRef InterfaceList(IEnumerable<object> interfaces, out int count)
var itf = (INamedTypeSymbol)entry;
var interfaces = InterfaceList(ClrInterfaceOrder(itf), out var interfaceCount);
var arguments = itf.TypeArguments;
var variance = 0;
for (var k = 0; k < itf.TypeParameters.Length; k++)
variance |= itf.OriginalDefinition.TypeParameters[k].Variance switch { VarianceKind.Out => 1, VarianceKind.In => 2, _ => 0 } << (2 * k);
var variance = VarianceBits(itf.OriginalDefinition, 0);
var info = Llvm.ConstStruct(none, none, none, itf.IsGenericType ? MetadataMethodTable(itf.OriginalDefinition) : none, none,
arguments.Length == 0 ? none : MtArray("args", [.. arguments.Select(MetadataMethodTable)]), interfaces,
NamespaceOf(itf) is { } ns ? CString(ns) : none, AssemblyOf(itf) is { } assembly ? CString(assembly) : none,
Expand Down Expand Up @@ -516,7 +514,7 @@ private LLVMValueRef HiddenInterfaceDescription(HiddenInterface hidden, LLVMValu
{
var none = LlvmContext.Null(Llvm.Ptr);
var variance = 0;
for (var k = 0; k < hidden.Variances.Count && k < hidden.Arguments.Count; k++) variance |= (hidden.Variances[k] & 3) << (2 * k);
for (var k = 0; k < hidden.Variances.Count && k < hidden.Arguments.Count && k < 16; k++) variance |= (hidden.Variances[k] & 3) << (2 * k);
var flags = TI.Interface | TI.Abstract | TI.NotPublic | TI.ReferenceType
| (hidden.Arguments.Count > 0 ? TI.GenericType | TI.ConstructedGeneric : TI.TypeDefinition);
var assembly = AssemblyOf(Compilation.GetSpecialType(SpecialType.System_Object)) is { } coreLib && hidden.Assembly == "System.Private.CoreLib"
Expand Down Expand Up @@ -642,6 +640,7 @@ private TypeInfoRecord TypeInfoRecordFor(LLVMValueRef mt, object described)
else baseMt = MetadataMethodTable(constraint);
declaring = MetadataMethodTable(gp.Owner);
rank = gp.Position;
variance = GenericParameterAttributes((ITypeParameterSymbol)ChainArguments((INamedTypeSymbol)CoreLib.Unmap(gp.Owner))[gp.Position]);
namespaceName = Str(NamespaceOf(gp.Owner));
assembly = Str(AssemblyOf(gp.Owner));
}
Expand Down Expand Up @@ -705,12 +704,7 @@ private TypeInfoRecord TypeInfoRecordFor(LLVMValueRef mt, object described)
? [.. chain.Select((_, i) => GenericParameterMethodTable(owner, i))]
: [.. chain.Select(MetadataMethodTable)]);
argumentCount = chain.Count;
if (!IsDef(named) && named.ContainingType is null)
for (var k = 0; k < named.TypeParameters.Length; k++)
variance |= named.OriginalDefinition.TypeParameters[k].Variance switch
{
VarianceKind.Out => 1, VarianceKind.In => 2, _ => 0,
} << (2 * k);
if (!IsDef(named)) variance = VarianceBits(named.OriginalDefinition, chain.Count - named.TypeParameters.Length);
}
if (named.ContainingType is { } outer) declaring = MetadataMethodTable(outer.OriginalDefinition);
break;
Expand All @@ -725,6 +719,26 @@ private TypeInfoRecord TypeInfoRecordFor(LLVMValueRef mt, object described)
};
}

/// <summary>
/// csrt_TypeInfo.variance of an instantiation: 2 bits for each of the first 16 arguments (the type's own follow
/// <paramref name="offset"/> of its declaring types'); csrt asks the definition's parameters about the rest.
/// </summary>
private static int VarianceBits(INamedTypeSymbol definition, int offset)
{
var variance = 0;
for (var k = 0; k < definition.TypeParameters.Length && offset + k < 16; k++)
variance |= definition.TypeParameters[k].Variance switch { VarianceKind.Out => 1, VarianceKind.In => 2, _ => 0 } << (2 * (offset + k));
return variance;
}

/// <summary>System.Reflection.GenericParameterAttributes as the compiler writes them in metadata.</summary>
private static int GenericParameterAttributes(ITypeParameterSymbol p) =>
p.Variance switch { VarianceKind.Out => 1, VarianceKind.In => 2, _ => 0 }
| (p.HasReferenceTypeConstraint ? 4 : 0)
| (p.HasValueTypeConstraint || p.HasUnmanagedTypeConstraint ? 8 | 16 : 0) // struct (and unmanaged) also says new()
| (p.HasConstructorConstraint ? 16 : 0)
| (p.AllowsRefLikeType ? 32 : 0);

private static readonly string[] s_arrayInterfaces =
[
"System.Collections.Generic.IList`1", "System.Collections.Generic.ICollection`1", "System.Collections.Generic.IEnumerable`1",
Expand Down
11 changes: 9 additions & 2 deletions src/runtime/type.c
Original file line number Diff line number Diff line change
Expand Up @@ -511,18 +511,25 @@ static bool element_compatible(const csrt_MethodTable* to_mt, const csrt_MethodT
return (from->flags & CSRT_TI_REFERENCE_TYPE) && assignable(to, from);
}

/// The variance of a generic argument past the 16 whose bits a csrt_TypeInfo holds: its definition's parameter says.
static uint32_t parameter_variance(const csrt_TypeInfo* info, uint32_t k) {
const csrt_TypeInfo* definition = info->definition ? lookup_info(info->definition) : NULL;
const csrt_TypeInfo* parameter = definition && k < definition->generic_count ? lookup_info(definition->generic_args[k]) : NULL;
return parameter && (parameter->flags & CSRT_TI_GENERIC_PARAMETER) ? parameter->variance & 3 : 0;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Enclosing variance flips after sixteen

Medium Severity

VarianceBits packs only a nested type's own parameters and leaves enclosing arguments invariant. Past the 16th argument, parameter_variance instead uses that chain slot's real variance, including an enclosing in or out parameter. IsAssignableFrom then treats the same enclosing parameter differently on either side of the boundary.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 6f19ea6. Configure here.

}

/// `from` converts to `to` through generic variance: the same definition, and every argument
/// identical or related as its parameter's variance allows (reference types only).
static bool variant_compatible(const csrt_TypeInfo* to, const csrt_TypeInfo* from) {
if (!to->variance || !(to->flags & CSRT_TI_CONSTRUCTED_GENERIC) || to->definition != from->definition
if ((!to->variance && to->generic_count <= 16) || !(to->flags & CSRT_TI_CONSTRUCTED_GENERIC) || to->definition != from->definition
|| !(from->flags & CSRT_TI_CONSTRUCTED_GENERIC))
return false;
for (uint32_t k = 0; k < to->generic_count; k++) {
if (to->generic_args[k] == from->generic_args[k]) continue;
const csrt_TypeInfo* a = info_for(to->generic_args[k]);
const csrt_TypeInfo* b = a ? info_for(from->generic_args[k]) : NULL;
if (!b) return false;
uint32_t v = (to->variance >> (2 * k)) & 3;
uint32_t v = k < 16 ? (to->variance >> (2 * k)) & 3 : parameter_variance(to, k);
if (v == 1 && (b->flags & CSRT_TI_REFERENCE_TYPE) && assignable(a, b)) continue;
if (v == 2 && (a->flags & CSRT_TI_REFERENCE_TYPE) && assignable(b, a)) continue;
return false;
Expand Down
81 changes: 81 additions & 0 deletions tests/samples/1850_reflection_variance.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// Type.IsAssignableFrom / IsAssignableTo / IsInstanceOfType / IsSubclassOf over generic variance: interfaces and delegates of the
// program at top level, nested in a class and in a generic class, with 1, 3, 16 and 17 type parameters, framework ones, nested
// variance, value-type arguments (no variance), and constructed types that appear only in typeof. Also
// GenericParameterAttributes and positions.
using System;
using System.Collections.Generic;
using System.Linq;

interface IVar<out A, in B, C> { }
class VarC : IVar<string, object, int> { }
class Outer
{
public interface INested<out T, in U> { }
public class NC : INested<string, object> { }
public delegate R NestedD<in T, out R>(T t);
}
class GOuter<T>
{
public interface IInner<out U> { }
public class Impl : IInner<string> { }
public delegate void D<in U>(U u);
}
interface I16<in A1, in A2, in A3, in A4, in A5, in A6, in A7, in A8, in A9, in A10, in A11, in A12, in A13, in A14, in A15, in A16> { }
class C16 : I16<object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object> { }
delegate R D17<in A1, in A2, in A3, in A4, in A5, in A6, in A7, in A8, in A9, in A10, in A11, in A12, in A13, in A14, in A15, in A16, out R>();
interface I18<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, out A18> { }
class C18 : I18<int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, string> { }
class Con<A, B, C, D, E, F> where A : class, IDisposable, new() where B : unmanaged where C : VarC, IComparable<C> where D : A where E : notnull where F : struct, Enum { }
ref struct Stack<T> where T : allows ref struct { }

class Program
{
static void Rel(string name, Type to, Type from, object? instance = null) =>
Console.WriteLine($"{name}: {to.IsAssignableFrom(from)} {from.IsAssignableTo(to)} {from.IsAssignableFrom(to)} {from.IsSubclassOf(to)} {to.IsInstanceOfType(instance)}");

static void Parameters(Type definition)
{
Console.WriteLine(definition.Name + ": " + string.Join(" ", definition.GetGenericArguments().Select(a =>
a.Name + "=" + (int)a.GenericParameterAttributes + "@" + a.GenericParameterPosition + (a.DeclaringType == definition ? "" : "!"))));
}

static void Main()
{
Rel("top", typeof(IVar<object, string, int>), typeof(VarC), new VarC());
Rel("top invariant", typeof(IVar<object, string, object>), typeof(VarC), new VarC());
Rel("top interface", typeof(IVar<object, string, int>), typeof(IVar<string, object, int>));
Rel("nested", typeof(Outer.INested<object, string>), typeof(Outer.NC), new Outer.NC());
Rel("nested wrong", typeof(Outer.INested<Uri, string>), typeof(Outer.NC), new Outer.NC());
Rel("nested delegate", typeof(Outer.NestedD<string, object>), typeof(Outer.NestedD<object, string>), (Outer.NestedD<object, string>)(_ => ""));
Rel("in generic", typeof(GOuter<int>.IInner<object>), typeof(GOuter<int>.Impl), new GOuter<int>.Impl());
Rel("in other generic", typeof(GOuter<long>.IInner<object>), typeof(GOuter<int>.Impl), new GOuter<int>.Impl());
Rel("in generic invariant outer", typeof(GOuter<object>.IInner<object>), typeof(GOuter<string>.IInner<object>));
Rel("in generic delegate", typeof(GOuter<int>.D<string>), typeof(GOuter<int>.D<object>));
Rel("16", typeof(I16<string, string, string, string, string, string, string, string, string, string, string, string, string, string, string, string>), typeof(C16), new C16());
Rel("17", typeof(D17<object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>),
typeof(D17<object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, string>));
Rel("18", typeof(I18<int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, object>), typeof(C18), new C18());
Rel("18 invariant", typeof(I18<int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, long, object>), typeof(C18), new C18());
Rel("framework", typeof(IEnumerable<object>), typeof(List<string>), new List<string>());
Rel("value argument", typeof(IEnumerable<object>), typeof(List<int>), new List<int>());
Rel("nested variance", typeof(IEnumerable<IEnumerable<object>>), typeof(List<List<string>>), new List<List<string>>());
Rel("Func", typeof(Func<string, object>), typeof(Func<object, string>), (Func<object, string>)(_ => ""));
Rel("Func value", typeof(Func<object>), typeof(Func<int>), (Func<int>)(() => 1));
Rel("definition", typeof(IVar<,,>), typeof(VarC));

Parameters(typeof(IVar<,,>));
Parameters(typeof(Outer.INested<,>));
Parameters(typeof(GOuter<>.IInner<>));
Parameters(typeof(GOuter<>));
Parameters(typeof(D17<,,,,,,,,,,,,,,,,>));
Parameters(typeof(Con<,,,,,>));
Parameters(typeof(Stack<>));
Parameters(typeof(IEnumerable<>));
Parameters(typeof(Func<,>));
Parameters(typeof(Dictionary<,>));
Parameters(typeof(Nullable<>));
Parameters(typeof(IComparable<>));
Parameters(typeof(Lazy<>));
Parameters(typeof(WeakReference<>));
}
}
34 changes: 34 additions & 0 deletions tests/samples/1850_reflection_variance.expected
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
top: True True False False True
top invariant: False False False False False
top interface: True True False False False
nested: True True False False True
nested wrong: False False False False False
nested delegate: True True False False True
in generic: True True False False True
in other generic: False False False False False
in generic invariant outer: False False False False False
in generic delegate: True True False False False
16: True True False False True
17: True True False False False
18: True True False False True
18 invariant: False False False False False
framework: True True False False True
value argument: False False False False False
nested variance: True True False False True
Func: True True False False True
Func value: False False False False False
definition: False False False False False
IVar`3: A=1@0 B=2@1 C=0@2
INested`2: T=1@0 U=2@1
IInner`1: T=0@0 U=1@1
GOuter`1: T=0@0
D17`17: A1=2@0 A2=2@1 A3=2@2 A4=2@3 A5=2@4 A6=2@5 A7=2@6 A8=2@7 A9=2@8 A10=2@9 A11=2@10 A12=2@11 A13=2@12 A14=2@13 A15=2@14 A16=2@15 R=1@16
Con`6: A=20@0 B=24@1 C=0@2 D=0@3 E=0@4 F=24@5
Stack`1: T=32@0
IEnumerable`1: T=33@0
Func`2: T=34@0 TResult=33@1
Dictionary`2: TKey=0@0 TValue=0@1
Nullable`1: T=24@0
IComparable`1: T=34@0
Lazy`1: T=0@0
WeakReference`1: T=4@0
Loading
Loading