Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
829bb94
Marshal.SizeOf/OffsetOf of structs with fixed-size buffers
filipnavara Nov 9, 2026
0500a34
A Type local that is exactly typeof(T) stands for T in per-type lower…
filipnavara Nov 10, 2026
d8f86a6
[DynamicallyAccessedMembers] on properties and fields keeps the membe…
filipnavara Nov 10, 2026
89fe75a
Uri: relative references and implicit file paths with spaces
filipnavara Nov 10, 2026
b3811fe
Renumber sample 1304 to 1340 (upstream has its own 1304 now)
filipnavara Nov 10, 2026
4906a4e
Renumber sample 1306 to 1342 (upstream has its own 1306 now)
filipnavara Nov 10, 2026
2b02244
Renumber sample 1307 to 1343 (upstream has its own 1307 now)
filipnavara Nov 10, 2026
584359e
Renumber sample 1308 to 1344 (upstream has its own 1308 now)
filipnavara Nov 10, 2026
2251718
P/Invoke delegate parameters
filipnavara Nov 10, 2026
7f9ce9a
P/Invoke SafeHandle parameters
filipnavara Nov 10, 2026
cc3a392
Structs by value in delegates marshalled to native code
filipnavara Nov 10, 2026
85c60a9
Merge remote-tracking branch 'origin/main' into pr-291
jonathanperis Nov 27, 2026
740c8a0
Merge remote-tracking branch 'origin/main' into pr-279
jonathanperis Nov 27, 2026
348a4e6
Merge remote-tracking branch 'origin/main' into pr-284
jonathanperis Nov 27, 2026
3b0a258
Merge remote-tracking branch 'origin/main' into pr-297
jonathanperis Nov 27, 2026
b1a3eb4
Merge remote-tracking branch 'origin/main' into pr-298
jonathanperis Nov 27, 2026
1087f50
Merge remote-tracking branch 'origin/main' into pr-283
jonathanperis Nov 27, 2026
6255cd0
Merge remote-tracking branch 'origin/main' into pr-299
jonathanperis Nov 27, 2026
2be9b73
Merge branch 'feat/preserialized-bytes-stream' into pr-291
jonathanperis Nov 27, 2026
605cbff
Merge branch 'pr-291' into pr-279
jonathanperis Nov 27, 2026
96db974
Merge branch 'pr-279' into pr-284
jonathanperis Nov 27, 2026
c3a0953
Merge branch 'pr-284' into pr-297
jonathanperis Nov 27, 2026
234d011
Merge P/Invoke delegate parameters (#297) under SafeHandle parameters
jonathanperis Nov 27, 2026
bc9be68
Merge branch 'feat/preserialized-bytes-stream' into pr-291
jonathanperis Nov 27, 2026
7dbd2bc
Merge branch 'pr-291' into pr-279
jonathanperis Nov 27, 2026
ab99772
Merge branch 'pr-279' into pr-284
jonathanperis Nov 27, 2026
48211e7
Merge branch 'pr-284' into pr-297
jonathanperis Nov 27, 2026
9e2db3c
Merge branch 'pr-297' into pr-298
jonathanperis Nov 27, 2026
a1d1980
Merge branch 'pr-298' into pr-283
jonathanperis Nov 27, 2026
315e4c7
Merge branch 'pr-283' into pr-299
jonathanperis Nov 27, 2026
da0d90f
Keep backslashes in relative URIs; such references are not well formed
jonathanperis Nov 27, 2026
b9a398e
Merge branch 'pr-291' into pr-279
jonathanperis Nov 27, 2026
4e7a5c1
Merge branch 'pr-279' into pr-284
jonathanperis Nov 27, 2026
ee42a0f
Merge branch 'pr-284' into pr-297
jonathanperis Nov 27, 2026
3859740
Merge branch 'pr-297' into pr-298
jonathanperis Nov 27, 2026
cafa14c
Merge branch 'pr-298' into pr-283
jonathanperis Nov 27, 2026
d402342
Merge branch 'pr-283' into pr-299
jonathanperis Nov 27, 2026
242e1eb
Merge remote-tracking branch 'origin/main' into pr-299
jonathanperis Nov 27, 2026
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
2 changes: 1 addition & 1 deletion src/Csharpc/CodeGen/BclValueTypes.Reflection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ BclHandler frameworkTypeAttributes(string method, string frameworkMethod) => (g,
// isn't constructed. .NET's argument checks are corelib C# (ReflectionRuntime.GetUninitializedObject).
t["System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject(System.Type)"] = (g, _, _, a, at) =>
{
if (at is Microsoft.CodeAnalysis.Operations.IInvocationOperation { Arguments: [var argument] } && FunctionCodeGen.TypeOfOperand(argument.Value) is { } created)
if (at is Microsoft.CodeAnalysis.Operations.IInvocationOperation { Arguments: [var argument] } && g.ExactTypeOf(argument.Value) is { } created)
g.NoteConstructedType(created is INamedTypeSymbol { OriginalDefinition.SpecialType: SpecialType.System_Nullable_T, TypeArguments: [var underlying] } ? underlying : created);
return g.CallCoreLib("ReflectionRuntime", "GetUninitializedObject", a[0]);
};
Expand Down
2 changes: 1 addition & 1 deletion src/Csharpc/CodeGen/FunctionCodeGen.Enums.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public sealed partial class FunctionCodeGen
// The Type overloads (Enum.GetValues(typeof(Color))): with a typeof operand they are the
// generic ones in disguise; the leading Type argument is dropped.
if (target.Parameters.FirstOrDefault()?.Type is not { Name: "Type", ContainingNamespace.Name: "System" }) return null;
if (TypeOfOperand(args[0].Value) is not { } typeOperand || S(typeOperand) is not INamedTypeSymbol { TypeKind: TypeKind.Enum } named)
if (ExactTypeOf(args[0].Value) is not { } typeOperand || S(typeOperand) is not INamedTypeSymbol { TypeKind: TypeKind.Enum } named)
{
// Configuration.Binder and similar pass a run-time Type into Enum.Parse/IsDefined:
// lower to a corelib helper (NotSupportedException until a full run-time enum table exists)
Expand Down
14 changes: 13 additions & 1 deletion src/Csharpc/CodeGen/FunctionCodeGen.Expressions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -211,9 +211,21 @@ private LLVMValueRef FieldAddress(IFieldReferenceOperation f)
private LLVMValueRef EmitSimpleAssignment(ISimpleAssignmentOperation a)
{
if (a.IsRef) return EmitRefAssignment(a);
if (a.Target is IPropertyReferenceOperation { Property.RefKind: RefKind.None } p) return EmitPropertySet(p, () => EmitValue(a.Value), TypeOf(a.Value));
if (a.Target is IPropertyReferenceOperation { Property.RefKind: RefKind.None } p)
{
// An assignment is the setter's call: an annotated value parameter (or property) keeps the assigned typeof's members.
if (p.Property.SetMethod is { } setter && KnownTypeofValues(a.Value) is { Count: > 0 } assigned)
foreach (var known in assigned)
_m.NoteDynamicallyAccessedArguments(S(setter), i => i == setter.Parameters.Length - 1 ? S(known) : null);
return EmitPropertySet(p, () => EmitValue(a.Value), TypeOf(a.Value));
}
if (a.Target is IFlowCaptureReferenceOperation r && _cfg!.PropertyCaptures.TryGetValue(r.Id, out var pc))
return SetCapturedProperty(pc, Coerce(EmitValue(a.Value), TypeOf(a.Value), pc.Property.Type));
// `[DynamicallyAccessedMembers(K)] Type field = typeof(X)` (an initializer or an assignment): X keeps its members of
// kinds K, as the IL front-end's NoteDynamicallyAccessedField does.
if (a.Target is IFieldReferenceOperation { Field: var annotatedField } && IsSystemType(annotatedField.Type)
&& ModuleCodeGen.DamKindsOf(annotatedField.OriginalDefinition.GetAttributes()) is var fieldKinds and not 0)
foreach (var known in KnownTypeofValues(a.Value)) _m.MarkDynamicallyAccessed(S(known), fieldKinds);

var targetType = TypeOf(a.Target)!;
var address = StoreAddress(a.Target, out var covariant); // C#: target sub-expressions are evaluated first
Expand Down
2 changes: 1 addition & 1 deletion src/Csharpc/CodeGen/FunctionCodeGen.IlInstructions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -914,7 +914,7 @@ private IlValueOperation IlOperand(IlEntry e, ITypeSymbol type, bool lvalue = fa
return new IlValueOperation(il.Syntax, type, () => IlTyped(e, type), nonNull: e.NonNull || e.IsThis)
{
Constant = e.Constant is null ? default : TypedConstant(e.Constant, type),
TypeOfOperand = e is { Kind: IlKind.Ref, Symbol: ITypeSymbol known } ? known : null,
TypeOfOperand = e is { Kind: IlKind.Ref, Symbol: ITypeSymbol known } ? known : e is { Kind: IlKind.Ref, FromLocal: { } local } ? IlExactTypeofLocal(local) : null,
BoxedFrom = e is { Kind: IlKind.Ref, Unboxed: { Type: { } boxedType } boxed } && !boxed.Value.IsNull ? IlOperand(boxed, boxedType) : null,
IsNullLiteral = e is { Kind: IlKind.Ref, Type: null } && !e.Value.IsNull && Native.LLVMIsNull(e.Value) != 0,
EntryType = e.Type,
Expand Down
27 changes: 23 additions & 4 deletions src/Csharpc/CodeGen/FunctionCodeGen.MarshalLayout.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ private sealed class NativeLayout(ITypeSymbol type, NativeKind kind)
public int BoolSize { get; set; } = 4;
public List<NativeField> Fields { get; } = [];
public bool IsClass { get; set; }
/// <summary>A fixed-size buffer anywhere in the layout: sizes and offsets are known, element conversion is not modelled.</summary>
public bool HasFixedBuffer { get; set; }
}

/// <summary>What the marshaller would refuse (an ArgumentException at run time) versus what csharpc can't do yet.</summary>
Expand Down Expand Up @@ -106,7 +108,11 @@ private NativeLayout NativeLayoutOfType(ITypeSymbol type, bool sizeOf)
if (type is not INamedTypeSymbol { TypeKind: TypeKind.Struct or TypeKind.Class } structure)
throw notMarshalable;
if (!_m.IsUserType(structure)) throw new NativeLayoutException(false, $"Marshal layout of library type '{name}'");
return BuildNativeLayout(structure, notMarshalable);
var layout = BuildNativeLayout(structure, notMarshalable);
// .NET's marshaller converts only a fixed-size buffer's first element (the generated struct's one field) and
// zeroes the rest: SizeOf/OffsetOf are exact, copying such a struct is left unsupported rather than approximated.
if (!sizeOf && layout.HasFixedBuffer) throw new NativeLayoutException(false, $"marshalling the contents of a fixed-size buffer in '{name}'");
return layout;
}

/// <summary>A field or element of a primitive, native-int, enum, bool, char or opaque (decimal, Guid) type; null for anything else.</summary>
Expand Down Expand Up @@ -159,14 +165,27 @@ private NativeLayout BuildNativeLayout(INamedTypeSymbol type, NativeLayoutExcept
var align = 1;
foreach (var field in type.GetMembers().OfType<IFieldSymbol>().Where(f => !f.IsStatic && !f.IsConst))
{
if (field.IsFixedSizeBuffer) throw new NativeLayoutException(false, $"Marshal layout of fixed-size buffer '{field.Name}'");
var fieldType = S(field.Type);
var leaf = NativeScalarLayout(fieldType, field, charSet, notMarshalable);
NativeLayout? leaf;
if (field.IsFixedSizeBuffer)
{
// The compiler's <name>e__FixedBuffer struct: one element field (marshalled with the container's CharSet)
// and StructLayout.Size = FixedSize elements of managed size, so it is at least that large and aligned as its element.
var element = fieldType is IPointerTypeSymbol { PointedAtType: var pointed } ? S(pointed)
: throw new NativeLayoutException(false, $"Marshal layout of fixed-size buffer '{field.Name}'");
var elementLeaf = NativeScalarLayout(element, null, charSet, notMarshalable)
?? throw new NativeLayoutException(false, $"Marshal layout of fixed-size buffer '{field.Name}' of '{element}'");
var managedBytes = field.FixedSize * (int)T.Target.SizeOf(T.Storage(element));
leaf = new NativeLayout(fieldType, NativeKind.Opaque) { Size = Math.Max(elementLeaf.Size, managedBytes), Align = elementLeaf.Align };
layout.HasFixedBuffer = true;
}
else leaf = NativeScalarLayout(fieldType, field, charSet, notMarshalable);
if (leaf is null)
{
if (fieldType is not INamedTypeSymbol { TypeKind: TypeKind.Struct } nestedType || !_m.IsUserType(nestedType) )
throw new NativeLayoutException(false, $"Marshal layout of field '{field.Name}' of type '{fieldType}'");
leaf = BuildNativeLayout(nestedType, notMarshalable);
layout.HasFixedBuffer |= leaf.HasFixedBuffer;
}
var fieldAlign = pack == 0 ? leaf.Align : Math.Min(leaf.Align, pack);
long offset;
Expand Down Expand Up @@ -221,7 +240,7 @@ private NativeLayout BuildNativeLayout(INamedTypeSymbol type, NativeLayoutExcept
/// <summary>The type an argument of type Type (typeof(X)) or object (the structure) stands for, when it is known statically.</summary>
private ITypeSymbol? MarshalTypeOf(IOperation argument, bool structure)
{
if (!structure) return TypeOfOperand(argument) is { } typeOf ? S(typeOf) : null;
if (!structure) return ExactTypeOf(argument) is { } typeOf ? S(typeOf) : null;
var value = argument;
while (value is IConversionOperation { Operand: var operand } conversion && !conversion.Conversion.IsUserDefined && !conversion.Conversion.IsNumeric && !conversion.Conversion.IsNullable)
value = operand;
Expand Down
64 changes: 64 additions & 0 deletions src/Csharpc/CodeGen/FunctionCodeGen.TypeofLocals.cs
Original file line number Diff line number Diff line change
Expand Up @@ -107,4 +107,68 @@ private IReadOnlyList<ITypeSymbol> IlTypeofStoredIn(int local)
}
return _ilTypeofLocals.TryGetValue(local, out var known) ? known : [];
}

// ---- exact values: a local that holds `typeof(T)` wherever it is read ----
// Unlike the flow-insensitive lists above (metadata: extra types are harmless), these feed lowerings that need the one
// type an argument is (Assembly.GetCustomAttributes(t), Enum.GetName(t, v), Marshal.SizeOf(t)): a local qualifies only
// when its single store is a typeof and nothing else can change it (`Type t = typeof(A); asm.GetCustomAttributes(t, false)`,
// as the Mono-derived WinForms' Control.ProductName does).

/// <summary>T when <paramref name="operation"/> is `typeof(T)`, in source or in IL, or a local that is exactly `typeof(T)`; null otherwise.</summary>
internal ITypeSymbol? ExactTypeOf(IOperation operation)
{
if (TypeOfOperand(operation) is { } known) return known;
while (operation is IConversionOperation { Operand: { } inner }) operation = inner;
return operation is ILocalReferenceOperation { Local: { IsConst: false, RefKind: RefKind.None } local } ? ExactTypeofLocal(local) : null;
}

private readonly Dictionary<ILocalSymbol, ITypeSymbol?> _exactTypeofLocals = new(SymbolEqualityComparer.Default);

/// <summary>
/// T when a source local is declared `= typeof(T)` and never written again: no assignment (deconstructions included),
/// no ref/out argument, no `ref` to it, anywhere in its member (lambdas and local functions too).
/// </summary>
private ITypeSymbol? ExactTypeofLocal(ILocalSymbol local)
{
if (_exactTypeofLocals.TryGetValue(local, out var cached)) return cached;
ITypeSymbol? result = null;
if (IsSystemType(local.Type)
&& local.DeclaringSyntaxReferences is [var reference] && reference.GetSyntax() is VariableDeclaratorSyntax { Initializer: { } initializer } declarator
&& _m.Compilation.ContainsSyntaxTree(declarator.SyntaxTree))
{
var model = _m.Compilation.GetSemanticModel(declarator.SyntaxTree);
IOperation? value = model.GetOperation(initializer.Value);
while (value is IConversionOperation { Operand: { } inner }) value = inner;
SyntaxNode scope = declarator.Ancestors().FirstOrDefault(n => n is MemberDeclarationSyntax and not GlobalStatementSyntax)
?? declarator.SyntaxTree.GetRoot();
if (value is ITypeOfOperation typeOf && !scope.DescendantNodes().OfType<IdentifierNameSyntax>().Any(id =>
id.Identifier.ValueText == local.Name && IsWrite(id) && SymbolEqualityComparer.Default.Equals(model.GetSymbolInfo(id).Symbol, local)))
result = typeOf.TypeOperand;
}
return _exactTypeofLocals[local] = result;

static bool IsWrite(IdentifierNameSyntax id) =>
id.Ancestors().OfType<AssignmentExpressionSyntax>().Any(a => a.Left.Span.Contains(id.Span))
|| id.Parent is ArgumentSyntax { RefKindKeyword.RawKind: (int)SyntaxKind.RefKeyword or (int)SyntaxKind.OutKeyword }
|| id.Parent is RefExpressionSyntax;
}

/// <summary>
/// T when IL local <paramref name="local"/> is exactly `typeof(T)` wherever it is read: its one store is
/// `ldtoken T; call Type.GetTypeFromHandle` and its address is never taken.
/// </summary>
private ITypeSymbol? IlExactTypeofLocal(int local)
{
if (IlTypeofStoredIn(local) is not [var type]) return null;
var stores = 0;
foreach (var instruction in IlBody.Instructions)
{
var op = instruction.OpCode;
int? index = op is ILOpCode.Stloc_0 or ILOpCode.Stloc_1 or ILOpCode.Stloc_2 or ILOpCode.Stloc_3 ? op - ILOpCode.Stloc_0
: op is ILOpCode.Stloc_s or ILOpCode.Stloc or ILOpCode.Ldloca_s or ILOpCode.Ldloca ? (int)instruction.Int : null;
if (index != local) continue;
if (op is ILOpCode.Ldloca_s or ILOpCode.Ldloca || ++stores > 1) return null;
}
return type;
}
}
4 changes: 2 additions & 2 deletions src/Csharpc/CodeGen/Intrinsics.cs
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ private static FrozenDictionary<string, IntrinsicHandler> BuildMethods()
{
var self = g.EmitValue(inv.Instance!);
Arg(g, inv, 1); // `inherit`: evaluated, no effect for assemblies
return FunctionCodeGen.TypeOfOperand(inv.Arguments.First(a => a.Parameter!.Ordinal == 0).Value) is INamedTypeSymbol attributeType
return g.ExactTypeOf(inv.Arguments.First(a => a.Parameter!.Ordinal == 0).Value) is INamedTypeSymbol attributeType
? g.AssemblyCustomAttributes((INamedTypeSymbol)g.Substitution.Apply(attributeType), self, inv)
: throw CompileError.Unsupported("Assembly.GetCustomAttributes with a Type that is not typeof(an attribute)", inv);
};
Expand Down Expand Up @@ -238,7 +238,7 @@ private static FrozenDictionary<string, IntrinsicHandler> BuildMethods()
};
t["System.Enum.GetName(System.Type, object)"] = (g, inv) =>
{
if (FunctionCodeGen.TypeOfOperand(inv.Arguments.First(a => a.Parameter!.Ordinal == 0).Value) is not INamedTypeSymbol { TypeKind: TypeKind.Enum } enumType)
if (g.ExactTypeOf(inv.Arguments.First(a => a.Parameter!.Ordinal == 0).Value) is not INamedTypeSymbol { TypeKind: TypeKind.Enum } enumType)
throw CompileError.Unsupported("Enum.GetName with a non-constant Type", inv);
var raw = UnboxEnum(inv.Arguments.First(a => a.Parameter!.Ordinal == 1).Value);
var value = g.Coerce(g.EmitValue(raw), raw.Type, enumType.EnumUnderlyingType!);
Expand Down
Loading