12 — The shadow corelib (BCL in C#)
Policy (ADR 0023): the shadows are for the runtime-coupled
System.Private.CoreLibsurface; 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 newsrc/Csharpc/upstream-types/<library>.txt(same name as the doc); for a size program it moves, that program’stests/size/budgets/<program>.txt(its lines and the reason, as a comment). Its NativeAOT column comes fromtools/il-first/measure-aot.shon the library’s program intools/il-first/bench(add one when the library has none).tools/il-first/ownership.tsvis 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 foldedIntPtr.Size) is wrong on a 4-byte-pointer target. The build cuts the same roots twice: from the shared framework’s 64-bit CoreLib intoCsharpcUpstream.dll, and from the 32-bit CoreCLR CoreLib (Microsoft.NETCore.App.Runtime.linux-arm, the same version, verified withdotnet nuget verifyagainst the Microsoft author certificate pinned insrc/Csharpc/nuget-signers.txt) intoupstream32/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-sizelists 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.PowersOf10anduint.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’scsharpcprofile) 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 ownSystem.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-digitsNumberBridgethe 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 aQCall!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 returnsList<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>.Enumeratoras 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), sonew List<int>().ToString()printsSystem.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 throughobject). - 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.#ifmay testCSHARPC_TARGET_*(the OS:LINUX/MACOS/WINDOWS/WASI; the architecture:X64/ARM64/WASM32), the globalization modes and any program symbol (neverDEBUG, which is left out): each distinct set of tested symbols is its own assembly.--corelib source(orCSHARPC_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.cctorchecked on every static field access of the type. - Code generated into the program (the resource and
TypeDescriptor.GetConverterhooks) can only use public corelib members; the corelib reaches generated program code throughCoreIntrinsicshooks (ResourceObjectHook/TypeConverterHookcallCsharpcCoreLib.ProgramHookswhen the program has it). #nullable disableat 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=1binds 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 trailingStringComparisonargument that is a constantOrdinal/OrdinalIgnoreCasebinds 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 LLVMminsize: 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>(+Enumeratorstruct, 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>andReadOnlyDictionaryare 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 andPriorityQueuecome from System.Collections.dll’s IL.ArrayList,BitArrayandHashtableare still corelib shadows (#372,docs/il-first/System.Collections.Hashtable.md). -
Concurrent collections are the framework’s own code:
ConcurrentDictionary<TKey,TValue>andConcurrentQueue<T>are System.Private.CoreLib types served from its IL (src/Csharpc/upstream-types/System.Collections.Concurrent.txt, #399), soConcurrentDictionaryenumerates in .NET’s order (striped locks fromEnvironment.ProcessorCount, non-randomized hashing of string keys under the default/Ordinal/OrdinalIgnoreCase comparers through the contract’sUpstreamNonRandomizedStringEqualityComparer);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/TakeFromAnywait on several of them withWaitHandle.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, andWaitAlltakes an auto-reset event back (Set) when another handle isn’t signaled yet;CancellationToken.WaitHandleandSemaphoreSlim.AvailableWaitHandleareManualResetEvents kept in step as .NET’s).Parallel.For/ForEachwith aParallelLoopState, an index, thread-local state,ParallelOptionsor a partitioner,Parallel.Invoke(options, ...),ForEachAsyncandForAsyncare corelib C# (corelib/Tasks/ParallelState.cs: .NET’s flags:Stopstarts nothing new,Breaklets 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 anAggregateExceptionaround 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 aBreakrun differs, andEnumerable.Rangeis not anIList<int>here (.NET loops over its positions: aBreakin aForEachover a range stops at a different iteration);ForEachAsyncover anIAsyncEnumerable<T>has no implementation yet (explicit CSLLVM0002). -
Observable behavior follows .NET’s implementations:
Listgrowth (Capacity),Dictionary/HashSetbucket+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 inList.Sort/Array.Sort), stableOrderBy,GroupByfirst-appearance order, exception types and messages. -
LINQ: not in the corelib.
System.Linqis the framework’s own IL (ADR 0023, #267), withVector<T>served as 16-byte LLVM vectors (FunctionCodeGen.Simd.cs) for its vectorizedSum/Min/Max; query syntax is Roslyn’s (ITranslatedQueryOperation). -
Value types:
Guid(port of .NET’sGuid.cs: same field layout, soToByteArray/TryWriteBytes, hashing and ordering match; every parse format and its compat forms with .NET’s exception types and messages;NewGuidfrom OS entropy as on Unix;CreateVersion7(), also from aDateTimeOffset),ArraySegment<T>(+Enumerator, theIList<T>/IReadOnlyList<T>views, conversions toSpan/Memory,MemoryExtensions.AsSpan/AsMemory),DateOnly/TimeOnly,HashCode,DateTimeOffset(port of .NET’sDateTimeOffset.cs: same layout, equality and ordering on the UTC instant, formatting and parsing through the portedDateTimeFormat/DateTimeParsewith the offset, the local zone from libc likeDateTime; 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 withEqualityComparer<T>.Defaultsemantics (SpanEquality.cs), plus theIEqualityComparer<T>overloads. -
System.Convert: port of .NET’sConvert.csandParseNumbers.csfor the primitive, string (providers and bases 2/8/10/16) andDateTimeoverloads; the always-failingIConvertibleconversions throw .NET’sInvalidCastException. Hex and Base64 are inConvertExtras.cs; theobjectoverloads butToString(object)andChangeTypeare not implemented (CSLLVM0002). -
Members-only shadows:
string.Join<T>/Join(IEnumerable)/Concat<T>/Compare,double/floatIsNaN/IsInfinity/IsFinite…, genericSystem.Arrayhelpers (Sortincl. keys+items,Reverse,IndexOf,Resize,Fill,Find*,Exists,TrueForAll,ConvertAll,BinarySearch,Empty). -
Reflection handles and member lookup (
corelib/Reflection/Handles.cs,MemberLookup.cs):ParameterModifieris .NET’s struct;RuntimeTypeHandleholds the runtime’s Type object (Type.TypeHandle,GetTypeFromHandle,GetTypeHandle, equality,Value; an ILldtokenpassed as a handle becomes one), andRuntimeHelpers.RunClassConstructor(typeof(X).TypeHandle)runs X’s lazy static initialization (a handle only known at run time is a diagnostic).DefaultValueAttributeis a shadow of .NET’s class (all constructors, theIsSupportedswitch).Type.GetMember(s)and TypeInfo’sGetDeclared*/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 aMemberInfo[](csharpc arrays carry their element type, and aMethodInfo[]would not be anIEnumerable<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 throwsNotSupportedExceptionfor other types, as doDeclaredNestedTypesand askingGetMemberfor nested types alone, whileMemberTypes.All,GetMembersandDeclaredMembersleave them out. -
System.MathFand floating-point math (CodeGen/Intrinsics.csAddMathF,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/Minas 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, … thatIFloatingPointIeee754<T>needs) are copied fromSingle.cs/Double.csof 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/ReciprocalSqrtEstimatereturn the exact1 / x(.NET usesRCPSS/FRECPEwhere 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/Log2of a negative number return the positive quiet NaN on Unix as .NET does (Windows passes its C runtime’s through). -
System.Text.RegularExpressionsis 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);ResourceManagerover the IL assemblies’ embedded string resources andAppContextover runtimeconfig data (Resources.cs; both read constants codegen builds through theResourceStrings()/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.GetCustomAttributesover the IL assemblies’ metadata, the[Serializable]pseudo-attribute, a[TypeConverter(string)]type named in it kept for creation),Type.Attributes,Enum.Format(Type, ...)andEnum.GetValuesAsUnderlyingTypefor run-time Types,ArrayList.Adapter, and the negative answers of COM (Marshal.IsComObject,ComWrappers.TryGetComInstance;Marshal.Releaseis aPlatformNotSupportedException: no COM object exists). The front end (Frontend/ResourceConverters.cs) still generatesProgramHooks.ResourceObjectfor the types a program’s preserialized.resourcesname, whichResourceManager.GetObjectcreates withConvertFromInvariantStringasDeserializingResourceReaderdoes. Resources stored as BinaryFormatter data, byte arrays or activator streams (Bitmap,Icon,ResXFileRef) are explicitNotSupportedExceptions naming the type. -
ResourceSet,GetResourceSetandGetStream(corelib/ResourceSets.cs,Resources.cs):ResourceManagerkeeps the neutral culture’s set (RuntimeResourceSet) as .NET’s does, soGetString/GetObjectandGetResourceSetshare it (closing it closes it for the manager untilReleaseAllResources). A culture other than the invariant one gets the neutral set only withtryParents(there are no satellite assemblies), and a set found through the fallback is remembered under the cultures asked for.ResourceSethasGetString/GetObjectwithignoreCase, 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 anInvalidCastException), byte arrays andStreamentries are created on every read, objectsDeserializingResourceReadercreates from preserialized types are made again each time;GetStringof a non-string names the type code ('Int32','ByteArray','Stream') for the former and the type for the latter.GetStreamis a new read-onlyUnmanagedMemoryStreamover a native copy of the bytes (shared per entry, never freed, as the assembly’s image is),GetObjectof aStreamentry itsUnmanagedMemoryStreamWrapper. The front end now keepsStreamentries’ bytes (ResourcesFile). Not provided (rejected at compile time):new ResourceSet(file|stream|reader)and subclassingResourceSet. A resource set the closed world has no table for is still the explicitNotSupportedExceptionofGetString. -
System.Text.Json: no longer a shadow, it comes from the framework’s IL (see System.Text.Json). -
EventSource,EventListenerand 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,SendCommandand 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 nestedKeywords,TasksandOpcodesclasses), kept becauseEventSourcecarries[DynamicallyAccessedMembers]on the class, which csharpc applies to every derived class as NativeAOT does (ModuleCodeGen.NoteAnnotatedHierarchy, nested types inModuleCodeGen.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.IsSupportedis 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 aNotSupportedExceptionnaming 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)andUri.TryCreate(Uri, ...)(CombineUri),GetComponents/GetLeftPart/Compare/IsBaseOf,IsWellFormedOriginalString,TryFormat,CheckHostNamefor DNS and IPv4 names,EscapeUriString,TryEscapeDataString,HexEscape/HexUnescape/FromHex,UriCreationOptions(the canonicalization-off option is aNotSupportedException). 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.Compiledselects 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.dllof the targeting pack, linked into csharpc like the JSON andLibraryImportgenerators,Frontend/SourceGenerators.cs) runs, and itsRegexRunner-derived classes run against the realRegex. Its diagnostics (SYSLIB1040-1043) andGetType()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
Regexlinks the framework’s engine: about 1.4x the size the port had fornew Regex(pattern), and about 3.6x once it calls a constructor or static method that takesRegexOptions, 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 throughSystem.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 toMakeGenericTypeis 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,requiredmembers and BCL types),[Nullable]/[NullableContext], required-member attributes, inherited attributes,Typeas anICustomAttributeProviderandMethodInfo.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 explicitNotSupportedException, 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) andException.Sourceof a thrown exception whoseSourcewas 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 ownInvalidOperationException(“Reflection-based serialization has been disabled for this application…”). What the program states explicitly gets what .NET evaluates for it:JsonSerializerIsReflectionEnabledByDefault(a project property,#:propertyor the runtimeconfig option) always wins, and an explicitPublishAot=falseleaves reflection on (.NET leaves the switch unset then; a program given as IL has only its runtimeconfig.json, wherePublishAot=falseleaves no trace, so it opts in with the switch itself). File-based apps already got the PublishAot switches (dotnet run app.cssets 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 otherSystem.Text.Json.*feature switches are runtime-config properties the framework reads throughAppContext. - 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_TypeInfotable (layout insrc/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.cspasses 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 andtypeof(X).Nameprograms are byte-for-byte the same size as before).- Interface lists keep only interfaces a
Typeobject can exist for (the program’s interface identity tables), plus variant instantiations whose definition the program uses elsewhere (IEnumerable<string>fortypeof(IEnumerable<object>).IsAssignableFrom(typeof(List<string>))).int’s thirty generic-math interfaces don’t reach the binary unless the program names one. Arrays listSystem.Array’s interfaces;IList<T>and its relatives are answered from the element type, covariance included. csrt_TypeNameTableforType.FullName/AssemblyQualifiedName: only the types whoseFullNamediffers fromToString()(generic instantiations print assembly-qualified arguments,List1[[System.Int32, System.Private.CoreLib, Version=11.0.0.0, …]]; generic parameters have none), soFullName` 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, default1.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 ofshared/Microsoft.NETCore.App/11.*with System.Reflection.Metadata (Frontend/SharedFramework.cs):List<T>binds against theSystem.Collectionsreference assembly but lives inSystem.Private.CoreLib.Assembly,AssemblyNameandVersionare corelib C# (corelib/Reflection/Assembly.cs), oneAssemblyobject 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 manifestModule,EntryPointand, 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[]asIList<U>,Nullable<T>fromT, 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/ICompareron tuple element types throwNotSupportedExceptionwhen executed. (Boxed structs do have interface maps: the corelib’s struct enumerators areIEnumerator<T>/IEnumerator/IDisposablewhen boxed, as in .NET.) System.Collections.Immutableis not shadowed: it is compiled from the shared framework’s IL (ADR 0013).SortedDictionary/SortedSetuse sorted arrays (same order, O(n) insertion).ObjectiveCMarshal(corelib/ObjectiveCMarshal.cs, the hooks of the .NET for macOS / iOS bindings): off macOS every member throwsPlatformNotSupportedExceptionas .NET does. On macOS the reference tracking works as in NativeAOT:Initializeregisters the begin/end,isReferencedand entered-finalization callbacks with the collector; a class with[ObjectiveCTrackedType]and a finalizer gets tagged memory (GetOrCreateReferenceTrackingMemory) and reference-tracking handles (CreateReferenceTrackingHandle); each collection asksisReferenced(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).SetMessageSendCallbackoverrides libobjc’sobjc_msgSendfamily (the P/Invoke stubs of those entry points call the registered function) andSetMessageSendPendingExceptionstores 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).