csharpc

12 — The shadow corelib (BCL in C#)

Policy (ADR 0023): the shadows are for the runtime-coupled System.Private.CoreLib surface; a library of the rest of the framework is compiled from its IL (ADR 0013) where a per-library measurement (CSHARPC_IL_FIRST, tools/il-first/ab.sh) says so, and its shadow is deleted in the same change.

Where a flip writes (one file per library, so flips of different libraries run in parallel without conflicts; ADR 0025, decision 6): its row of the ADR 0023 table in a new docs/il-first/<library>.md (copy the header from any file there); for a CoreLib type, the type names in a new src/Csharpc/upstream-types/<library>.txt (same name as the doc); for a size program it moves, that program’s tests/size/budgets/<program>.txt (its lines and the reason, as a comment). Its NativeAOT column comes from tools/il-first/measure-aot.sh on the library’s program in tools/il-first/bench (add one when the library has none). tools/il-first/ownership.tsv is generated on demand (tools/il-first/ownership.sh) and not committed; ownership.cs overrides of deleted files can stay.

Two slices, one per pointer size (#382): CoreLib is compiled per target, so IL compiled under TARGET_64BIT (8-byte widths, a folded IntPtr.Size) is wrong on a 4-byte-pointer target. The build cuts the same roots twice: from the shared framework’s 64-bit CoreLib into CsharpcUpstream.dll, and from the 32-bit CoreCLR CoreLib (Microsoft.NETCore.App.Runtime.linux-arm, the same version, verified with dotnet nuget verify against the Microsoft author certificate pinned in src/Csharpc/nuget-signers.txt) into upstream32/CsharpcUpstream.dll. The compiler picks the slice by the target’s pointer size (Frontend/UpstreamSlice.cs; wasm32 takes the 32-bit one, and a missing 32-bit slice is an error, never a fallback). Slicer pointer-size lists the members compiled differently for 32-bit targets at every build (obj/.../slicer/pointer-size.md). Corelib members the slices call must exist for both widths (ulong.PowersOf10 and uint.PowersOf10).

The contract layer between the corelib and the CoreLib types sliced from the framework’s IL (tools/il-first/slicer, CsharpcUpstream.dll; chosen by the slicer’s csharpc profile) is kept thin, and every member of it is listed here:

  • corelib/UpstreamSupport.cs: the members the slice calls into the corelib for: SR texts, the string-comparer family, the throw helpers.
  • corelib/NumberUpstream.cs, the other direction: number formatting and parsing are CoreLib’s own System.Number (#426), and the compiler’s paths that do not go through a primitive’s public member (string concatenation, interpolation holes, boxed values, Console.Write) reach it through these [UnsafeAccessor(StaticMethod)] + [UnsafeAccessorType] declarations, with CoreLib’s own signatures. (This replaced the shortest-digits NumberBridge the slicer used to emit.)
  • corelib/UpstreamTracing.cs: the runtime QCalls System.Diagnostics.Tracing’s IL makes (EventPipe’s), bound by entry-point name like the libSystem.Native contract ([RuntimeExport] with a QCall! trigger, ModuleCodeGen.PInvoke): a disabled EventPipe and the thread’s activity id. A QCall without a contract is a stub that ends the program with the “not supported by csharpc yet” diagnostic if called.

csharpc’s route to drop-in BCL coverage: library types re-implemented in C#, compiled by csharpc together with the user’s program (closed world: monomorphized, inlined and optimized by LLVM along with user code). User code keeps binding against the real .NET reference assemblies, so Roslyn’s overload resolution, nullability, diagnostics and the IDE experience stay exact. Codegen redirects.

user code:   var d = new Dictionary<string,int>();  d["x"] = 1;   words.Where(...).OrderBy(...)
Roslyn:      System.Collections.Generic.Dictionary<string,int>.set_Item(string, int)   (real metadata)
csharpc:     CsharpcCoreLib.DictionaryImpl<string,int>.set_Item(string, int)           (corelib C#)

Layout

Path What
src/Csharpc/corelib/*.cs the corelib sources (copied next to the compiler; compiled once into CsharpcCoreLib.dll, ADR 0015)
src/Csharpc/Frontend/CoreLibAssembly.cs builds and caches that assembly (~/.cache/csharpc/corelib-<key>.dll) and its shadow index
src/Csharpc/CodeGen/CoreLib.cs discovery of shadows + symbol mapping (types, methods, properties, fields)
src/Csharpc/CodeGen/FunctionCodeGen.CoreLib.cs CoreIntrinsics codegen, property lvalue captures, value-type null folds
src/Csharpc/CodeGen/ModuleCodeGen.CoreLib.cs arrays / strings as BCL interfaces
src/Csharpc/corelib/Globalization/ .NET’s globalization (cultures, formats, calendars, collation, casing) over ICU, see 19
src/Csharpc/corelib/Dynamic/ ExpandoObject’s and DynamicObject’s side of dynamic (the meta-object protocol’s calls and binders), see ADR 0019

Declaring a shadow

[Shadows("System.Collections.Generic.List`1")]           // CLR metadata name; same generic arity
public class ListImpl<T> : IList<T>, IReadOnlyList<T> { ... }

[Shadows("System.Collections.Generic.List`1+Enumerator")]  // nested types: '+'
public struct Enumerator { ... }                           // declared inside ListImpl<T>

[ShadowMembers("System.String")]                           // members only: the type itself is not replaced
internal static class StringExtras { public static string Join<T>(string separator, IEnumerable<T> values) ... }
  • Matching. A library member maps to the shadow member with the same metadata name, generic arity, static-ness and canonical signature (parameter types with shadow types spelled by their real names and type parameters by position). Return types are not compared, so GetEnumerator() may return the shadow struct while the real one returns List<T>.Enumerator — they are the same type after mapping.
  • Type arguments are never rewritten; only the generic definition is swapped (List<List<int>> → ListImpl<List<int>>). That keeps exactly one instantiation per real type.
  • Where the redirect applies: FunctionCodeGen.S() / TypeOf() (every symbol/type codegen reads goes through substitution, then the redirect), GetFunction, GetLayout (incl. user classes deriving from a shadowed class, e.g. class ByLength : Comparer<string>, and override roots), struct layouts/TypeMapper (KeyValuePair<K,V>, List<T>.Enumerator as fields/array elements/tuple elements), static fields, boxing/type tests (MethodTableFor), interface implementation lookup, delegate creation.
  • Priority: hand-written intrinsics (Intrinsics.cs, runtime C) win over shadows.
  • Diagnostics: a library member with neither intrinsic nor shadow still reports CSLLVM0002 '<member>' has no implementation in the csharpc runtime yet.
  • Runtime type names: shadows report their BCL names (Mangler.RealNameOf), so new List<int>().ToString() prints System.Collections.Generic.List1[System.Int32]` like .NET.

Writing corelib code

  • Refer to BCL types by their real names (List<T>, KeyValuePair<K,V>, IEnumerable<T>); use the shadow name only inside its own class (or via a cast through object).
  • The corelib is compiled on its own, as CsharpcCoreLib.dll, once per symbol set and cached (ADR 0015); programs reference it and its methods are lowered from IL as they are reached. #if may test CSHARPC_TARGET_* (the OS: LINUX/MACOS/WINDOWS/WASI; the architecture: X64/ARM64/WASM32), the globalization modes and any program symbol (never DEBUG, which is left out): each distinct set of tested symbols is its own assembly. --corelib source (or CSHARPC_CORELIB=source) still parses the sources into the program’s compilation instead; keep the code valid both ways and stay conservative (no primary constructors, no collection expressions).
  • Prefer lazy static data (static T[] s_x; static T[] X => s_x ??= ...) to static field initializers: an initializer becomes a .cctor checked on every static field access of the type.
  • Code generated into the program (the resource and TypeDescriptor.GetConverter hooks) can only use public corelib members; the corelib reaches generated program code through CoreIntrinsics hooks (ResourceObjectHook/TypeConverterHook call CsharpcCoreLib.ProgramHooks when the program has it).
  • #nullable disable at the top; corelib diagnostics are never shown to users. A corelib that doesn’t compile fails every compile with Roslyn’s errors; CSHARPC_CHECK_CORELIB=1 binds the sources inside a program’s compilation (the source corelib) and reports them all, warnings included.
  • Lowering is flow-insensitive: everything a reached method references is lowered and linked, and its virtual call sites keep the overrides of the classes the program constructs (pruning, docs/03-lowering.md; CSHARPC_WHY_LOWERED=<substring> shows what referenced a function). Keep rarely needed work (big tables, culture-sensitive fallbacks, composite formatting in exception messages) out of common paths, or behind something only the programs that need it reference. A trailing StringComparison argument that is a constant Ordinal/OrdinalIgnoreCase binds to a <Name>Ordinal / <Name>OrdinalIgnoreCase (or, against an ASCII constant, <Name>AsciiIgnoreCase) method of the same class when there is one (FunctionCodeGen.OrdinalComparisons.cs).
  • [OptimizeForSize] on a class compiles its methods with LLVM minsize: for code that runs once (building culture data), not per operation.

CoreIntrinsics

CsharpcCoreLib.CoreIntrinsics declares extern generic helpers whose bodies codegen synthesizes per instantiation, giving the default comparers .NET semantics without boxing primitives:

Intrinsic Semantics
AreEqual<T>(a, b) EqualityComparer<T>.Default.Equals: inline for primitives (double.NaN equals NaN), ordinal for strings, IEquatable<T> if implemented, else virtual Equals(object); element-wise for tuples
HashOf<T>(v) EqualityComparer<T>.Default.GetHashCode (inline for primitives; 0 for null)
Compare<T>(a, b) Comparer<T>.Default.Compare: primitives inline (NaN first), strings with culture collation, IComparable<T> / IComparable, null first; otherwise InvalidOperationException("Failed to compare two elements in the array.")
IsValueType<T>(), Box<T>(v), Unbox<T>(o) helpers for generic code (boxing of types without a boxed form throws NotSupportedException at run time only)
IsInstanceOfType Type.IsInstanceOfType (base-chain and interface-map walks in src/runtime/type.c)

Arrays and strings as interfaces

All arrays share one runtime method table (two, since the GC split primitive arrays), so they can’t carry interface maps. Instead, when the program converts T[] (or string) to a BCL interface, codegen builds a slot table of CsharpcCoreLib.SZArrayHelper<T> (StringInterfaces) static methods — named <interface metadata name without backtick>_<member> — and stores it in the interface’s identity table (interfaces field for arrays, base field for strings). csrt_interface_slots / csrt_isinst_class fall back to it. Calls whose receiver is statically an array/string are bound directly to the helper. Limitation: object is IEnumerable<X> on an array can’t check the element type at run time.

What’s implemented

  • Collections: List<T> (+Enumerator struct, version checks), Dictionary<TKey,TValue> (+KeyCollection, ValueCollection, enumerators), KeyValuePair<K,V> (+KeyValuePair.Create), HashSet<T> (full set algebra), Queue<T>, Stack<T>, LinkedList<T>/LinkedListNode<T>, PriorityQueue<TElement,TPriority>, SortedList<K,V>, SortedDictionary<K,V>, SortedSet<T>, EqualityComparer<T>, Comparer<T> (Default, Create, subclassing), CollectionExtensions (GetValueOrDefault, TryAdd, Remove). List<T>, Dictionary, HashSet<T>, Queue<T>, Collection<T>, ReadOnlyCollection<T> and ReadOnlyDictionary are the framework’s own code, served from System.Private.CoreLib’s IL (src/Csharpc/upstream-types/, ADR 0023); Stack<T>, LinkedList<T>, the sorted collections and PriorityQueue come from System.Collections.dll’s IL. ArrayList, BitArray and Hashtable are still corelib shadows (#372, docs/il-first/System.Collections.Hashtable.md).

  • Concurrent collections are the framework’s own code: ConcurrentDictionary<TKey,TValue> and ConcurrentQueue<T> are System.Private.CoreLib types served from its IL (src/Csharpc/upstream-types/System.Collections.Concurrent.txt, #399), so ConcurrentDictionary enumerates in .NET’s order (striped locks from Environment.ProcessorCount, non-randomized hashing of string keys under the default/Ordinal/OrdinalIgnoreCase comparers through the contract’s UpstreamNonRandomizedStringEqualityComparer); BlockingCollection<T>, ConcurrentBag<T>, ConcurrentStack<T> and the partitioners come from System.Collections.Concurrent.dll’s IL (docs/il-first/System.Collections.md). BlockingCollection’s waits are SemaphoreSlim waits over the runtime’s events; AddToAny/TakeFromAny wait on several of them with WaitHandle.WaitAny, corelib/Threading/WaitHandles.cs: the runtime has no multi-object wait, so a wait that has to block sleeps on the first handle in 1-4 ms slices and re-checks the others, and WaitAll takes an auto-reset event back (Set) when another handle isn’t signaled yet; CancellationToken.WaitHandle and SemaphoreSlim.AvailableWaitHandle are ManualResetEvents kept in step as .NET’s). Parallel.For / ForEach with a ParallelLoopState, an index, thread-local state, ParallelOptions or a partitioner, Parallel.Invoke(options, ...), ForEachAsync and ForAsync are corelib C# (corelib/Tasks/ParallelState.cs: .NET’s flags: Stop starts nothing new, Break lets lower iterations finish and starts none above it, an orderable partitioner’s keys are the iteration indexes); the plain loops run on the runtime’s pool loop and throw an AggregateException around the body’s exception, as .NET’s. Differences: workers claim indexes one by one (not in .NET’s growing ranges), so how many iterations above a Break run differs, and Enumerable.Range is not an IList<int> here (.NET loops over its positions: a Break in a ForEach over a range stops at a different iteration); ForEachAsync over an IAsyncEnumerable<T> has no implementation yet (explicit CSLLVM0002).

  • Observable behavior follows .NET’s implementations: List growth (Capacity), Dictionary/HashSet bucket+entries+free-list design (iteration order after removals, prime sizes, FastMod), PriorityQueue’s 4-ary heap (dequeue order of equal priorities), the introsort port (order of equal keys in List.Sort / Array.Sort), stable OrderBy, GroupBy first-appearance order, exception types and messages.

  • LINQ: not in the corelib. System.Linq is the framework’s own IL (ADR 0023, #267), with Vector<T> served as 16-byte LLVM vectors (FunctionCodeGen.Simd.cs) for its vectorized Sum/Min/Max; query syntax is Roslyn’s (ITranslatedQueryOperation).

  • Value types: Guid (port of .NET’s Guid.cs: same field layout, so ToByteArray/TryWriteBytes, hashing and ordering match; every parse format and its compat forms with .NET’s exception types and messages; NewGuid from OS entropy as on Unix; CreateVersion7(), also from a DateTimeOffset), ArraySegment<T> (+Enumerator, the IList<T>/IReadOnlyList<T> views, conversions to Span/Memory, MemoryExtensions.AsSpan/AsMemory), DateOnly/TimeOnly, HashCode, DateTimeOffset (port of .NET’s DateTimeOffset.cs: same layout, equality and ordering on the UTC instant, formatting and parsing through the ported DateTimeFormat/DateTimeParse with the offset, the local zone from libc like DateTime; binary serialization is not implemented).

  • System.Buffers: ArrayPool<T> (keeps returned arrays as .NET’s shared pool does: one per size bucket per thread, then 32 per bucket shared, up to 1 Mi elements), IMemoryOwner<T>. System.Memory (MemoryPool<T>, ReadOnlySequence<T>, SequenceReader<T>, ArrayBufferWriter<T>, EncodingExtensions) comes from the framework’s IL (ADR 0023).

  • MemoryExtensions: searches and comparisons compare integers, chars, bools and enums byte-wise in the runtime and every other element type with EqualityComparer<T>.Default semantics (SpanEquality.cs), plus the IEqualityComparer<T> overloads.

  • System.Convert: port of .NET’s Convert.cs and ParseNumbers.cs for the primitive, string (providers and bases 2/8/10/16) and DateTime overloads; the always-failing IConvertible conversions throw .NET’s InvalidCastException. Hex and Base64 are in ConvertExtras.cs; the object overloads but ToString(object) and ChangeType are not implemented (CSLLVM0002).

  • Members-only shadows: string.Join<T>/Join(IEnumerable)/Concat<T>/Compare, double/float IsNaN/IsInfinity/IsFinite…, generic System.Array helpers (Sort incl. keys+items, Reverse, IndexOf, Resize, Fill, Find*, Exists, TrueForAll, ConvertAll, BinarySearch, Empty).

  • Reflection handles and member lookup (corelib/Reflection/Handles.cs, MemberLookup.cs): ParameterModifier is .NET’s struct; RuntimeTypeHandle holds the runtime’s Type object (Type.TypeHandle, GetTypeFromHandle, GetTypeHandle, equality, Value; an IL ldtoken passed as a handle becomes one), and RuntimeHelpers.RunClassConstructor(typeof(X).TypeHandle) runs X’s lazy static initialization (a handle only known at run time is a diagnostic). DefaultValueAttribute is a shadow of .NET’s class (all constructors, the IsSupported switch). Type.GetMember(s) and TypeInfo’s GetDeclared*/Declared* are composed from the per-kind queries in RuntimeType’s order (methods, constructors, properties, events, fields) with its name filter (exact, IgnoreCase, trailing *) and always return a MemberInfo[] (csharpc arrays carry their element type, and a MethodInfo[] would not be an IEnumerable<MemberInfo>). Nested types are described for a type whose nested types reach a [DynamicallyAccessedMembers(PublicNestedTypes | NonPublicNestedTypes)] location (each kept nested type whole, as ILLink keeps it): Type.GetNestedType(s) answers for those (corelib/Reflection/NestedTypes.cs) and throws NotSupportedException for other types, as do DeclaredNestedTypes and asking GetMember for nested types alone, while MemberTypes.All, GetMembers and DeclaredMembers leave them out.

  • System.MathF and floating-point math (CodeGen/Intrinsics.cs AddMathF, corelib/FloatingPointMath.cs): what .NET calls through the C runtime is libm’s float function (sinf, powf, acoshf, …) or an exact LLVM intrinsic (Sqrt, Floor, Round, FusedMultiplyAdd, CopySign, Max/Min as IEEE 754-2019); the members that are C# in .NET are ports of dotnet/runtime’s own (BitIncrement, IEEERemainder, ILogB, ScaleB, Round(x, digits, mode) exact on the decimal value, MaxMagnitude, Sign…). The float and double generic-math statics (float.Hypot, double.Lerp, T.SinPi(x), RootN, Exp2/Exp10, the degree conversions, MaxNumber, IsNormal, … that IFloatingPointIeee754<T> needs) are copied from Single.cs/Double.cs of the .NET 11 runtime and checked against it bit for bit (a differential run of every member over edge values and a few hundred pseudo-random inputs). ReciprocalEstimate / ReciprocalSqrtEstimate return the exact 1 / x (.NET uses RCPSS/FRECPE where the hardware has them, so its answer differs between CPUs and is only an estimate). Results of the libm functions follow the platform’s libm (glibc here, as .NET on Linux), so a few differ in the last bit on WebAssembly’s libc; Math.Log/Log2 of a negative number return the positive quiet NaN on Unix as .NET does (Windows passes its C runtime’s through).

  • System.Text.RegularExpressions is not a shadow: it is compiled from the framework’s IL (Regular expressions).

  • Compiled-code support for the IL front-end (docs/adr/0010-il-frontend.md): async method builders, AsyncIteratorMethodBuilder, ManualResetValueTaskSourceCore<T>, ConfiguredCancelableAsyncEnumerable<T>, ExceptionDispatchInfo (AsyncBuilders.cs, AsyncIterators.cs, ExceptionDispatchInfo.cs, see 10-async.md); ResourceManager over the IL assemblies’ embedded string resources and AppContext over runtimeconfig data (Resources.cs; both read constants codegen builds through the ResourceStrings()/RuntimeConfig() core intrinsics).

  • TypeConverter / TypeDescriptor: not in the corelib. System.ComponentModel, System.ComponentModel.Primitives and System.ComponentModel.TypeConverter come from the framework’s IL (ADR 0023, #276); the corelib serves what that code asks of the runtime: the attributes of framework types (Type.GetCustomAttributes over the IL assemblies’ metadata, the [Serializable] pseudo-attribute, a [TypeConverter(string)] type named in it kept for creation), Type.Attributes, Enum.Format(Type, ...) and Enum.GetValuesAsUnderlyingType for run-time Types, ArrayList.Adapter, and the negative answers of COM (Marshal.IsComObject, ComWrappers.TryGetComInstance; Marshal.Release is a PlatformNotSupportedException: no COM object exists). The front end (Frontend/ResourceConverters.cs) still generates ProgramHooks.ResourceObject for the types a program’s preserialized .resources name, which ResourceManager.GetObject creates with ConvertFromInvariantString as DeserializingResourceReader does. Resources stored as BinaryFormatter data, byte arrays or activator streams (Bitmap, Icon, ResXFileRef) are explicit NotSupportedExceptions naming the type.

  • ResourceSet, GetResourceSet and GetStream (corelib/ResourceSets.cs, Resources.cs): ResourceManager keeps the neutral culture’s set (RuntimeResourceSet) as .NET’s does, so GetString/GetObject and GetResourceSet share it (closing it closes it for the manager until ReleaseAllResources). A culture other than the invariant one gets the neutral set only with tryParents (there are no satellite assemblies), and a set found through the fallback is remembered under the cultures asked for. ResourceSet has GetString/GetObject with ignoreCase, the enumerator, GetDefaultReader/GetDefaultWriter, Close/Dispose. Values stored by type code (ResourceWriter’s primitives) are boxed once and cached (reading one as a string afterwards is an InvalidCastException), byte arrays and Stream entries are created on every read, objects DeserializingResourceReader creates from preserialized types are made again each time; GetString of a non-string names the type code ('Int32', 'ByteArray', 'Stream') for the former and the type for the latter. GetStream is a new read-only UnmanagedMemoryStream over a native copy of the bytes (shared per entry, never freed, as the assembly’s image is), GetObject of a Stream entry its UnmanagedMemoryStreamWrapper. The front end now keeps Stream entries’ bytes (ResourcesFile). Not provided (rejected at compile time): new ResourceSet(file|stream|reader) and subclassing ResourceSet. A resource set the closed world has no table for is still the explicit NotSupportedException of GetString.

  • System.Text.Json: no longer a shadow, it comes from the framework’s IL (see System.Text.Json).

  • EventSource, EventListener and the event counters are not shadows: System.Diagnostics.Tracing comes from CoreLib’s IL (src/Csharpc/upstream-types/System.Diagnostics.Tracing.txt, System.Diagnostics.Tracing.md): the manifest, the listener dispatch, Write<T> (TraceLogging), GenerateManifest, SendCommand and the counters’ polling thread are the framework’s code. What it asks of the runtime is csharpc’s: the reflection over an event source class (its [Event] methods, their parameters, the constants of the nested Keywords, Tasks and Opcodes classes), kept because EventSource carries [DynamicallyAccessedMembers] on the class, which csharpc applies to every derived class as NativeAOT does (ModuleCodeGen.NoteAnnotatedHierarchy, nested types in ModuleCodeGen.NestedTypes.cs); and EventPipe’s QCalls, a disabled EventPipe (corelib/UpstreamTracing.cs): no session ever exists, so the runtime’s own provider never delivers events, while the thread’s activity id is kept per thread. The runtime and library event sources .NET creates on its own (Microsoft-Windows-DotNETRuntime, System.Runtime, TplEventSource …) are not created, so a listener sees the program’s own. Without #:property EventSourceSupport=true (the file-based app default) EventSource.IsSupported is false and the framework’s code turns event sources off, as in .NET.

  • System.Uri (corelib/Net/Uri.cs, UriRelative.cs, UriMembers.cs): the URIs whose .NET behaviour needs no escaping rules (absolute http, https, ftp, ws and wss URIs with a DNS name or canonical IPv4 host, plain file paths, relative references of plain text); everything else is a NotSupportedException naming the case. On those it is exact, down to messages: dot-segment removal (Uri.Compress), MakeRelativeUri / MakeRelative (PathDifference, the case-insensitive DOS-path comparison, the ./ guard for a ’:’ in the first segment), new Uri(Uri, string/Uri) and Uri.TryCreate(Uri, ...) (CombineUri), GetComponents / GetLeftPart / Compare / IsBaseOf, IsWellFormedOriginalString, TryFormat, CheckHostName for DNS and IPv4 names, EscapeUriString, TryEscapeDataString, HexEscape / HexUnescape / FromHex, UriCreationOptions (the canonicalization-off option is a NotSupportedException). Resolving against a file URI, references with a ’:’ in the first segment (g:h, http:g) and IPv6/IDN/user info hosts are not covered.

Regular expressions

System.Text.RegularExpressions has no corelib port: the framework’s own assembly is compiled from its IL (ADR 0013, ADR 0023), so every engine, option, Match/Group/Capture type, Replace/Split/Count/EnumerateMatches, the static cache, RegexParseException and RegexMatchTimeoutException are .NET’s code, and deriving from RegexRunner works. The port that stood here (16 830 lines, interpreter only) was deleted by the flip.

  • Engines: whatever the framework picks: the interpreter, and RegexOptions.NonBacktracking’s symbolic engine. RegexOptions.Compiled selects the Reflection.Emit code generator in .NET; run-time code generation is not possible under csharpc (as in NativeAOT), so the framework’s own fallback to the interpreter applies and the results are the same.
  • [GeneratedRegex]: the SDK’s own generator (System.Text.RegularExpressions.Generator.dll of the targeting pack, linked into csharpc like the JSON and LibraryImport generators, Frontend/SourceGenerators.cs) runs, and its RegexRunner-derived classes run against the real Regex. Its diagnostics (SYSLIB1040-1043) and GetType() are .NET’s. In a program given as IL the SDK’s generator already ran and its output is ordinary IL.
  • Cost: nothing when unused (hello world is byte-identical). A program that uses Regex links the framework’s engine: about 1.4x the size the port had for new Regex(pattern), and about 3.6x once it calls a constructor or static method that takes RegexOptions, which reaches the NonBacktracking engine (ADR 0023 has the table). The owner accepted the size for exactness and speed (the framework’s code is 1.4x faster on the throughput program).

System.Text.Json

System.Text.Json and System.Text.Encodings.Web are compiled from the shared framework’s IL (ADR 0023, issue 286); the hand-written port that used to live in src/Csharpc/corelib/Json/ (16.6k lines) is gone, and so is the front end that synthesized [JsonSerializable] contexts for reflection-style calls. The JSON source generator still runs for the program’s own [JsonSerializable] contexts.

  • Reflection-based calls. JsonSerializer’s reflection path is the framework’s own code, which reads the program’s types through System.Reflection. csharpc keeps reflection metadata only for the types a program roots, as NativeAOT does, so the framework’s calls are rooted by the trimmer’s rule (FunctionCodeGen.ReflectionRoots.cs, ModuleCodeGen.ReflectionRoots.cs): a call to a framework method marked [RequiresUnreferencedCode] roots the types it names (type arguments, typeof/GetType() and value arguments, and the types of the members of those); every open generic definition the framework passes to MakeGenericType is instantiated over the roots in the argument shapes frameworks build them with. Nothing in this rule is specific to JSON.
  • Reflection answers. NullabilityInfoContext (for records, required members and BCL types), [Nullable]/[NullableContext], required-member attributes, inherited attributes, Type as an ICustomAttributeProvider and MethodInfo.CreateDelegate<T> follow .NET. Where an attribute list cannot be reproduced exactly (the attributes the C# compiler synthesizes into a type it does not own), the program’s own query is an explicit NotSupportedException, and the framework’s own IL gets the attributes csharpc models: it filters for classes the compiler never synthesizes. Two answers are partial for the framework’s IL only: the non-public fields of a BCL type (hidden by its reference assembly; System.Text.Json only keeps non-public fields marked [JsonInclude], which BCL types never carry) and Exception.Source of a thrown exception whose Source was never set (null instead of the throwing assembly’s name; the serializer only compares it with its own rethrow token).
  • Reflection-based JSON is off by default, as under NativeAOT (owner decision 2026-11-10, #320). csharpc is the program’s AOT compiler: a program that says nothing gets System.Text.Json.JsonSerializer.IsReflectionEnabledByDefault=false, the value a PublishAot build writes, and the framework’s own code throws its own InvalidOperationException (“Reflection-based serialization has been disabled for this application…”). What the program states explicitly gets what .NET evaluates for it: JsonSerializerIsReflectionEnabledByDefault (a project property, #:property or the runtimeconfig option) always wins, and an explicit PublishAot=false leaves reflection on (.NET leaves the switch unset then; a program given as IL has only its runtimeconfig.json, where PublishAot=false leaves no trace, so it opts in with the switch itself). File-based apps already got the PublishAot switches (dotnet run app.cs sets them too, so the JIT oracle agrees). [FeatureSwitchDefinition] properties fold to the value the runtime config sets, as ILCompiler folds them, so with the switch off the reflection resolver is dead code: a reflection-JSON program that does not opt in compiles in 48 s of cpu and 544 MB of memory instead of 744 s and 3.3 GB. The other System.Text.Json.* feature switches are runtime-config properties the framework reads through AppContext.
  • Code size and compile time. The framework’s serializer is bigger than the port was (ADR 0023 has the table); programs that do not use System.Text.Json are unchanged.

Type metadata (System.Type reflection)

System.Type objects are runtime objects (src/runtime/type.c): one per method table, so typeof(X) == obj.GetType() is a pointer comparison, and Name / Namespace / ToString() come from the method table’s CLR name. Everything else reflection answers about a type is generated at compile time (closed world, ADR 0006) by ModuleCodeGen.TypeInfo.cs, and only for programs that ask:

  • csrt_TypeInfo table (layout in src/runtime/csrt.h): one entry per method table the program has — classes, boxed structs and enums, interface identity tables, arrays, delegates, boxed primitives, name-only tables for types that are never instantiated (typeof(List<>), typeof(int*), typeof(int[,]), generic parameters) — plus, transitively, every type an entry points to (base type, element type, generic definition and arguments, declaring type). Each entry has the boolean properties as flag bits (IsClass, IsValueType, IsGenericType, IsNestedPublic, … computed from the Roslyn symbol of the real BCL type, not its corelib shadow), the related method tables, the implemented interfaces, generic variance, and the assembly’s full name. Codegen emits the table when lowering the first member that needs it (BclValueTypes.Reflection.cs passes it to the runtime function as an argument) and fills it in after the last function is lowered, alternating with the worklists until no new method table appears (Generate(); describing a type can create the method table of a base class or generic argument). Programs that use none of these members carry no table and no extra code (hello world and typeof(X).Name programs are byte-for-byte the same size as before).
  • Interface lists keep only interfaces a Type object can exist for (the program’s interface identity tables), plus variant instantiations whose definition the program uses elsewhere (IEnumerable<string> for typeof(IEnumerable<object>).IsAssignableFrom(typeof(List<string>))). int’s thirty generic-math interfaces don’t reach the binary unless the program names one. Arrays list System.Array’s interfaces; IList<T> and its relatives are answered from the element type, covariance included.
  • csrt_TypeNameTable for Type.FullName / AssemblyQualifiedName: only the types whose FullName differs from ToString() (generic instantiations print assembly-qualified arguments, List1[[System.Int32, System.Private.CoreLib, Version=11.0.0.0, …]]; generic parameters have none), so FullName` of non-generic types costs a few hundred bytes of table at most.
  • Assemblies: the program’s own types report the project’s assembly name and the version the SDK stamps (Version / AssemblyVersion, default 1.0.0.0; projects folded into one program keep their own names); IL assemblies report their metadata identity; BCL types report the shared framework implementation assembly .NET loads them from, found by following the type forwards of shared/Microsoft.NETCore.App/11.* with System.Reflection.Metadata (Frontend/SharedFramework.cs): List<T> binds against the System.Collections reference assembly but lives in System.Private.CoreLib. Assembly, AssemblyName and Version are corelib C# (corelib/Reflection/Assembly.cs), one Assembly object per name so == holds. The program’s own and the IL assemblies also have a compiled-in type list (GetTypes, ExportedTypes, Module.GetTypes, in metadata order, csc’s synthesized types included: the program is emitted once with Roslyn to read them), a manifest Module, EntryPoint and, for the program, GetReferencedAssemblies (ADR 0018).
  • Assignability (type.c, assignable) follows the CLR: base chains, interfaces, generic variance (reference-type arguments only), array covariance for reference elements and for primitives sharing storage (int[]/uint[]/enum arrays), T[] as IList<U>, Nullable<T> from T, delegates.

Implemented: IsAssignableFrom/IsAssignableTo/IsInstanceOfType/IsSubclassOf, every Is* predicate of the kind/visibility/generic families, BaseType, GetElementType, GetArrayRank, DeclaringType, GetGenericTypeDefinition, GetGenericArguments, GenericTypeArguments, GenericParameterPosition, UnderlyingSystemType, Nullable.GetUnderlyingType, FullName, AssemblyQualifiedName, Assembly, Assembly.GetExecutingAssembly/GetEntryAssembly, with .NET’s exception types and messages. Member reflection — constructors, methods, properties, fields, events, parameters, attributes, Invoke, GetValue/SetValue, CreateDelegate (closed over a target, static, or open instance with the receiver as first parameter), GetInterfaces, Activator.CreateInstance(Type), and MakeGenericType over the instantiations the program has — works over metadata kept for what [DynamicallyAccessedMembers] and constant typeof(X).GetMethod("Name") patterns reach, as under NativeAOT (ADR 0018). Members that would need code or metadata the closed world doesn’t have (IsSerializable) are compile-time “not supported by csharpc yet” errors. Where an entry can’t be described faithfully (open generic types’ base types and interfaces, corelib-internal types with no .NET counterpart, signed assemblies), the query throws NotSupportedException at run time rather than answering wrong. Samples: tests/samples/400_type_assignability … 403_type_assembly.

Cost

Hello world: identical binary size. Compile time: the corelib assembly is built once per machine, corelib version and symbol set (~6 s); afterwards a compile stats the sources (~45 ms) and lowers the corelib methods the program reaches from IL, with no parsing or binding of the corelib (ADR 0015).

Gaps

  • Non-generic IEnumerator.Current / IComparer on tuple element types throw NotSupportedException when executed. (Boxed structs do have interface maps: the corelib’s struct enumerators are IEnumerator<T>/IEnumerator/IDisposable when boxed, as in .NET.)
  • System.Collections.Immutable is not shadowed: it is compiled from the shared framework’s IL (ADR 0013).
  • SortedDictionary/SortedSet use sorted arrays (same order, O(n) insertion).
  • ObjectiveCMarshal (corelib/ObjectiveCMarshal.cs, the hooks of the .NET for macOS / iOS bindings): off macOS every member throws PlatformNotSupportedException as .NET does. On macOS the reference tracking works as in NativeAOT: Initialize registers the begin/end, isReferenced and entered-finalization callbacks with the collector; a class with [ObjectiveCTrackedType] and a finalizer gets tagged memory (GetOrCreateReferenceTrackingMemory) and reference-tracking handles (CreateReferenceTrackingHandle); each collection asks isReferenced(taggedMemory) about the tracked objects nothing else reached (a referenced one survives with what it reaches), and announces an object entering the finalizer queue (04-runtime.md, ADR 0021). SetMessageSendCallback overrides libobjc’s objc_msgSend family (the P/Invoke stubs of those entry points call the registered function) and SetMessageSendPendingException stores an exception the stub throws when the call returns. Verified on the macOS runner against real .NET (samples 970, 977, 978). The unhandled-exception propagation handler is stored but never called (an exception escaping an [UnmanagedCallersOnly] method ends the process).