Release notes
G# is pre-1.0. The repository's version base is currently 0.6, and product versions are derived by Nerdbank.GitVersioning from that base and the Git commit. Until the project reaches a stable compatibility promise, release notes should be read as implementation status notes rather than a long-term compatibility contract.
Reading these notes
The published 0.5 documentation snapshot and all current installation/download examples target 0.5.767. Older 0.4 and 0.3 snapshots retain their own commands. Select Next only for development features.
Unreleased (0.6 line)
-
Emit reference
!!on nullable collection navigations feeding EF CoreThenIncludechains incs2gs(Part of #6353).CSharpToGSharpTranslator.TranslateLambdanow gates expression-tree lambdas (IsExpressionTreeLambda) feedingMicrosoft.EntityFrameworkCore.EntityFrameworkQueryableExtensionsInclude/ThenIncludeinto the collectionThenInclude(IIncludableQueryable<TEntity, IEnumerable<TPreviousProperty>>, ...)overload (for both extension-method and static-call forms), asserting nullable reference navigations (annotatedT?or translator-promoted via the shared dependency-only/stored-member contract, excluding value types, flow-narrowed captures and statically non-null expressions, and platform-typed frozen metadata) with!!so G# satisfies EF Core's non-nullIEnumerable<TPreviousProperty>bound whileExpressionTreeLowerererases the reference!!to preserve the exact runtimeMemberExpressiontree. -
Reify constructed imported generic and nullable arguments in
SignatureEncoderdelegate CLR resolution (Fixes #6386).SignatureEncoder.ResolveDelegateArgClrTypeandSignatureEncoder.ResolveAsyncDelegateClrTypenow recursively reify constructed imported generics (viaImportedTypeSymbol.ReifyClosedClrType()and reference-context generic reconstruction), unwrap reference-nullable, platform, and nullability-annotated wrappers, lift value-type nullables into the target reference context, and rebuild slice/array/nested-function shapes instead of reading erased binding-timeClrTypes such asTask<object>or unliftedint32, keeping emitted delegate.ctor/Invokesignatures verifiable under ILVerify while preserving safe fallback for open type-parameter-bearing generics. -
Import C# 15 union types (
[Union]/IUnion/IUnionMembers) — conversions, pattern matching, non-boxing access, and exhaustiveness (Fixes #6366; part of #5765). AddsUnionTypeMetadataacross bothMetadataLoadContextand handle-backed metadata (ADR-0209, verified inMetadataModelComparisonviaQ2.union-type), reading[Union]structs/classes,IUnionMembersproviders, single-parameter constructors (by-value/in) andstatic Createfactories,Value, optionalHasValue, and optionalTryGetValue(out T)in deterministic order with weak caching.UnionTypeOperationsandConversionClassifiersupport implicit union conversions (including generic unions, nullable struct unionsU?, user-defined conversion operator precedence, overload-resolution ranking, and ambiguity rejection) usingADR-0186/ADR-0193receiver-aware nullability readers.PatternBinder,SlotPlanner, andMethodBodyEmitter.Patternssupportis,switchexpressions, andswitchstatements over imported unions with single scrutinee evaluation, non-boxingTryGetValue/HasValuedispatch,Valuefallback, union self-type patterns, andnilunwrapping.ExhaustivenessAnalyzertreats imported unions as exhaustive discriminants (requiringnilfor nullable/platform discriminants or nullable/platform case types, and excluding constrained type parameters per C# 15 rules), reportingGS0177/GS0178on missing cases. -
Import C# 14/15 extension properties, extension indexers, and static extension members in
gsc(Fixes #6335; part of #5765).gscnow reads C# 14/15 extension-block metadata (ExtensionMarkerAttribute, grouping types, marker<Extension>$methods,DefaultMemberAttribute, and lowered static implementation methods) across bothMetadataLoadContextand handle-backedReferenceImageSet(ADR-0209) paths with deterministic metadata-token ordering and resolver-scoped caching. Callers in G# can consume imported instance extension properties (reads, writes, single-evaluation compound assignments,?.,ref/in/value-type receivers,ref-returning properties, generic blocks with constraints, and ADR-0186/ADR-0193 receiver-aware nullability), C# 15 instance extension indexers (single/multi-index reads, writes, compound assignments,?[, overloaded indexers, customDefaultMemberAttributenames, and generic indexers coexisting with instance indexers), extension-block instance methods (includingrefreceivers), and C# 14 static extension properties and methods. Instance members always take precedence, synthetic<G>$.../<M>$...nested types are hidden from user-visible lookup,SemanticModel.LookupMembersexposes imported extension properties, and invalid or ambiguous usages report existing diagnostics (GS0116,GS0127,GS0158,GS0160,GS0266). -
Reject overloads whose parameter signatures differ only in reference nullability with
GS0264(Fixes #4971).BoundScope.SigTypesEquivalentnow strips reference nullability annotations (T?,T!, and metadata annotation wrappers) viaTypeSymbol.StripToBareShape()before comparing overload signatures, so declarations sharing a CLR metadata signature (such asfunc pickS(x string)andfunc pickS(x string?), nested reference-nullable container/tuple/slice/generic-class parameters, methods, constructors, and extensions) are rejected at declaration withGS0264/GS0284instead of emitting duplicate CLR signatures or failing later withGS0266at call sites, while distinct value-typeNullable<T>(int32vsint32?), by-ref, array-rank, and generic-arity overloads remain valid. -
Diagnose unsupported C# interface and explicit-interface conversion operator declarations early in
cs2gs(Fixes #6378).CSharpToGSharpTranslator.TranslateConversionOperatornow routes conversion-operator representability throughTryGetUnsupportedConversionOperatorMessage, rejecting interfacestatic abstract/static virtualand explicit-interface (I.operator T) implicit/explicit conversion declarations withCS2GS-UNSUPPORTED-OPERATORanchored at the offending declaration instead of emitting unparseable interfacefunc operatormembers (GS0005/CS2GS-ROUNDTRIP) or silently dropping the explicit interface qualifier to expose a public conversion operator, while preserving#6376checked-declaration diagnostic priority, ordinary conversion siblings (includingcheckedbodies), and types nested inside interfaces. -
Diagnose unsupported C# checked conversion operator declarations early in
cs2gs(Fixes #6376).CSharpToGSharpTranslator.TranslateConversionOperatornow inspectsConversionOperatorDeclarationSyntax.CheckedKeywordand rejects C# 11explicit operator checkeddeclarations (including block-bodied, interfacestatic abstract, and explicit interface implementations) withCS2GS-UNSUPPORTED-OPERATORanchored at the offending declaration instead of dropping checked semantics and emitting a colliding duplicatefunc operator explicit, while preserving required unchecked conversion siblings and ordinary conversions whose bodies containcheckedexpressions or statements. -
Diagnose unsupported C# user-defined
true/falseandcheckedoperator declarations early incs2gs(Fixes #6368).CSharpToGSharpTranslator.TranslateOperatornow checks operator declarations against the canonical G#OperatorNamesrepresentability guard (IsSupportedOperatorDeclaration), rejectingoperator true,operator false, andoperator checkedbinary, unary, and C# 14 compound-assignment declarations (including interfacestatic abstractand explicit interface implementations) withCS2GS-UNSUPPORTED-OPERATORanchored at the offending declaration instead of emitting invalid G# (CS2GS-ROUNDTRIP) or colliding unchecked duplicates, while keeping all supported unchecked binary, unary, and compound-assignment operators intact. -
Allow assigning own shared
letfields directly insideshared { init { ... } }(Fixes #6319).ExpressionBinder.IsReadOnlyFieldAssignmentAllowed,FieldSymbol.IsStaticAddressLegal,StructSymbol.IsSameOpenOwner, andReflectionMetadataEmitter.IsStaticFieldAddressLegalHerenow funnel static read-only field assignment and addressability through one open-owner static-initializer rule across bare, own-qualified, generic-qualified, compound, null-coalescing, multi-assignment, and struct-member writes (includingshared class,struct,partial, and open generic self-constructions), while keepingGS0127for ordinary methods, accessors, nested lambdas/local functions, field-initializer expressions, derived/nested/unrelated types, closed generic instantiations,constfields, and importedinitonlyfields, and preserving CLRInitOnlyemission, required static definite-assignment checks, andcs2gsstatic readonly+ static constructor migration parity. -
Ignore JSON-RPC requests and notifications in
WaikikiHoverAuditTests.ReadLspResponseForIdAsync(Fixes #6357). The stdio test helper intest/LanguageServer.Tests/WaikikiHoverAuditTests.gsnow matches only JSON-RPC response frames (no"method"member, matching integer"id", and exclusively"result"or an object"error", never both) so server-to-client requests such asworkspace/diagnostic/refreshsharing the same numeric ID are ignored instead of being mistaken for the hover or shutdown response. This is a test-helper fix; language server behavior is unchanged. -
Enforce inner nullability on implicit conversion operator results for imported parameters (Fixes #6311; related to #4321).
ExpressionBinder.MakeSymbolicArgumentConversionClassifier,ConversionClassifier.IsUserDefinedImplicitConversionNullabilityRejection,ConversionClassifier.BindClrParameterConversions,BoundClrConversionCallExpression.CanApplyImplicitClrConversion,ConditionalReturnNarrowing,ClrNullability.HasAllowNull,NullabilityImportRule.ApplyAllowNullInput,MemberLookupuser-conversion repair, andApplySymbolicClrArgumentConversionsnow validate both same-compilation and imported user-definedop_Implicitoperand and result types against the full receiver- and substitution-aware nullability parameter contract via canonical funnel readers, honoring[AllowNull]/@AllowNullon non-value reference inputs across both selection and operand binding without weakening inner nullability and narrowing[return: NotNullIfNotNull]viaBinder.SatisfiesNotNullConstraint(preserving original non-null operand proofs across non-liftedNullable<V>wrapping and rewrites, preserving nullable returns for unconstrained andclass?type parameters, and preserving existing platform-typed ordinary calls). Non-container and imported wrong-result operators such asOther -> List[string]at importedList[string?]parameters now reportGS0154with inner nullability displayed and emit no image on sole overloads while allowing valid covariant or expandedparamsoverloads to win (matching G# source overload selection and preserving built-in container-mismatch rejection such asstring.Join), and safe-result operators (Other -> List[string?],Other -> string?), platform widening (List[string!] -> List[string?]), and constrained open generic targets (IConstrainedSink[U].Take(List[U?])) bind and evaluate once.cs2gsTranslateLambdanow also widens the logical return position on exact-target function literals targeting imported oblivious delegate returns (Func[T!],Func[Task[T!]], andFunc[ValueTask[T!]], keeping retainedValueTask[T?]and nested task envelopes intact) when a return expression converts through a declared-nullableop_Implicitor yields a nullable reference, avoiding invalid non-null emissions without introducing runtime!!assertions, whileLambdaBinder.WrapAsTaskretains the closed CLR type argument for nullable imported async lambda results so delegate overload resolution seesTask<T>/ValueTask<T>instead ofobject. -
Diagnose unsupported C# user-defined
++/--operator declarations early incs2gs(Fixes #6318).CSharpToGSharpTranslator.TranslateOperatornow rejects C# user-defined increment and decrement operator declarations (operator ++,operator --,operator checked ++,operator checked --, C# 14 instance++/--, and interfacestatic abstract/explicit implementations) withCS2GS-UNSUPPORTED-OPERATORanchored at the offending declaration instead of emitting unparseable G# that fails later with genericCS2GS-ROUNDTRIP, while keeping supported neighboring binary, unary, and compound-assignment operators intact. -
Take framework effect trust from the build's resolved targeting pack (Fixes #6365; ADR-0208 amendment A5). A narrowing that crossed a framework call such as
object.ReferenceEqualsdepended on the host .NET install. When the build referenced theMicrosoft.NETCore.Apptargeting pack from the NuGet package folder, a host without that pack under its dotnet root dropped the narrowing and reportedGS0158/GS0159, and a host with the pack kept it, so a!!at the same site reportedGS0536. The SDK now passes the targeting pack that MSBuild resolved togscas/targetingpack:<dir>.gscreads the pack'sdata/FrameworkList.xmland trusts a reference only when aManagedentry of that pack lists, at its path inside the pack, an image with the same identity and bytes; the host packs and runtime do not apply. A directgscrun without the option keeps host discovery. Identity and public-key trust stay rejected. -
Widen sound
Finalclassification underPrefixRemainder.Nothing(later-type) inBindPrefix(Fixes #6247; ADR-0225).PrefixBindingContext.MayDependOnLaterTypenow builds a compilation-wide syntax index from the active trees (preserving chained-vs-scratch equivalence) and widens opt-inFinalproof to: generic functions and types whose in-scope type parameters resolve before source types (while rejecting keyword-spelled type parameters with hideable constraints), source receivers and members reached throughthis/ extension receivers / same-package source types with member-type and alias tracking (guarded against open/partial enclosing-type nested shadowing), nested-statement narrowing and pure reads (following keyword narrowings while keeping hideable nested guards and dependent sibling brancheslater-type), qualified imported type clauses blocked from hiding by an independent in-scope type parameter or a closed non-partial same-package declaration, and pure-keyword top-level statements and built-in array/switch/implicit-void-literal forms. Also closes #6241 adversarial soundness gaps for binary/unary receiver operators, header initializers (if/for/using), inlineout vardeclarations, andout-parameterreturncontrol flow. -
Support C# 15 closed hierarchies (
IsClosedTypeAttribute) in switch exhaustiveness and emit interop onnet11.0+(Fixes #6361; part of #5765). AddsClosedTypeMetadataacross bothMetadataLoadContextand handle-backed metadata (ADR-0209, verified inMetadataModelComparisonviaQ2.closed-type), decodingIsClosedTypeAttribute.DerivedTypeswith deterministic same-assembly fallback scanning when the property is omitted.ExhaustivenessAnalyzernow treats imported[IsClosedType]classes (and type parameters constrained to them) as exhaustive switch discriminants, enforcing C# 15 non-transitivity, accessibility withInternalsVisibleTo, zero-subtype rules, unconditional type patterns, and generic subtype unification while rejecting cross-assembly derivation (GS0181) even without constructor feature markers. Onnet11.0+targets whereIsClosedTypeAttributeis present in the target reference pack,gscmarks payload-enum base classesabstractand emits[IsClosedTypeAttribute(DerivedTypes = ...)]plus[CompilerFeatureRequired("ClosedClasses")]constructor markers on abstractsealed classhierarchies and payload-enum bases (while keeping concretesealed classtypes directly constructible across assemblies), enabling exhaustive C# 15 switches over G#-emitted closed hierarchies. -
Parenthesize low-precedence postfix targets in
cs2gsprinting (Fixes #6308).GSharpPrinter.RenderPostfixTargetnow groups low-precedence and non-postfix-chainable expressions (binary, unary,await, lambda,with,throw, pattern test unless already wrapped, prefix/postfix increment/decrement,if/if let/switch/block expressions, bare numeric literals, and empty[n]Tarray allocations) across member access, calls, indexing,?., and!!targets (leavingConditionalAccessExpressionunparenthesized for pointer chains andw?.Value!!, and avoiding double parentheses onAssignmentExpression,ParenthesizedExpression, andBinaryPattern), so static-form (Use.Pack(p + "s")) and bare-form (Pack(p + "b")) source extension calls preserve receiver binding, generic type arguments, single evaluation, and native C# parity. -
Complete
.NET 11Runtime Async lowering parity, struct receivers, closures, generics, and Portable PDB support (ADR-0232 Slice 2) (Fixes #6355; part of #5765). WiresChannelOperationRewriter,AsyncExceptionHandlerRewriter(preserving native CLRtry/finallyacross suspension whenfinallyhas noawait, lifting awaitedcatch/finally/using/await using/deferhandlers, and funnelingcatchexits through liftedfinallyblocks),SpillSequenceSpiller.RewriteForRuntimeAsync(preserving direct two-callcall+AsyncHelpers.Awaitadjacency while spilling compound, short-circuit, coalesce, expression-block, and struct-receiver awaits),RefInitializationHoister(eliminating addressableref/ByRefTypeSymbollocals across suspension points), protected-regionreturn-to-epilogueleavelowering, andBaseCallForwarderRewriterbypass for directbase.calls in Runtime Async class methods (eliminating<>n__Nforwarders while preserving forwarding inside nested lambdas andgobodies). Implements prologue by-value*thissnapshot lowering (ldarg.0; ldobj T; stloc thisCopy) for non-generic and generic struct instance methods so mutations inside Runtime Async struct methods never leak to caller storage before or after suspension. Promotes eligible async lambdas (capturing display-classInvokeand non-capturing static/host methods) and async local functions (including generic local functions) to directMethodImplAttributes.Async(0x2000) emission with no nested<...>d__Nstate-machine struct, preserves Portable PDB sequence points/locals withoutAsyncMethodSteppingInformationon Runtime Async methods and lambdas, keeps all permanent ADR-0023 fallbacks (async void, async iterators, custom[AsyncMethodBuilder],Synchronized,stackalloc,suspend func), and keeps default (RuntimeAsync == false) PE and Portable PDB output bit-for-bit identical. -
Skip overlapping periodic idle-trim timer ticks in
LspServerand holdTestAfterPinSnapshotuntil explicit test release (Fixes #6350).LspServer.OnIdleTrimTicknow guards periodicWeakIdleTrimHandlesweeps with anInterlocked.CompareExchangenon-reentrancy gate (reset infinally, with volatile shutdown visibility and disarmed-then-armed timer startup) so overlapping timer callbacks drop immediately instead of queuing ThreadPool workers onWorkspaceState.trimLock.Issue6326WarmUpAndEvictionTeststrim-interleaving tests now holdTestAfterPinSnapshotuntil explicitreleaseTrim.Set()withtry/finallyrelease and bounded task draining instead of discarding a 10-secondManualResetEventSlim.Waittimeout. -
Forward transitive type-parameter bounds for imported substituted interface and base-class constraints (Fixes #6296).
ClrOverloadResolution.SatisfiesDeclaredConstraintsandTypeParameterForwardsDeclaredConstraintsnow evaluate constructed imported generic constraints through one unified canonical annotated projection pipeline (TryEvaluateGenericConstraintSymbolicallybacked byClrNullability.GetGenericParameterConstraintTypeSymbols,MemberLookup.GetClrRelationshipTypeSymbols,Binder.SameConstraintType, andConversion.IsVarianceArgumentCompatible(..., allowPlatformNilCheck: false)), while deferring receiver-dependent method constraints to receiver-aware validation (SatisfiesMethodConstraintsWithReceiver) and requiring both target and candidate exactness on CLR fallbacks. Transitive bounds such as[V IList[string], W V]callingApi.View[string, W], fixed generic carriers (Fixed[X] : List<string>->IList<string>), multi-instantiation interfaces in any declaration order, top-level reference covariance, and receiver-dependentHost[A].Need[List[A]]()/NeedBase[DerivedA]()compile and verify, while unsatisfied bounds, invariant-position projections (IList[V]forIList<IList<X>>), oblivious platform mismatches (Legacy[X]-> non-nullobject, non-nullIList[string]-> oblivious mutableIList<string!>), introducedInterfaceImplinner-nullability mismatches, crossed alternatives, and self-referential invariant guards remain rejected. -
Add opt-in
.NET 11Runtime Async emission (ADR-0232 Slice 1) (Fixes #6340; part of #5765). AddsCompilation.RuntimeAsync(defaultfalse),gsc /runtime-async[+|-](and--runtime-async[=on|off]), MSBuild SDK<GSharpRuntimeAsync>and<Features>runtime-async=on</Features>forwarding (<GSharpRuntimeAsync>taking precedence and both hashed into_GsharpCreateCoreCompileInputsCache), andRuntimeAsyncCapabilitiestarget-corlib probing (System.Runtime.CompilerServices.AsyncHelpers+MethodImplOptions.Async = 0x2000across reflection and handle-backed metadata without falling back to host runtime assemblies). ReportsGS0645when/runtime-async+targets an incapable corlib (such asnet10.0) andGS0646on manual@MethodImpl(MethodImplOptions.Async)(or raw bit0x2000). Eligible Slice 1 free,shared, and class instanceasync funcmethods returningTask,Task[T],ValueTask, orValueTask[T](and synthesized top-levelawaitentry points) emit directly withMethodImplAttributes.Async(0x2000), no<...>d__Nstate-machine struct, and no[AsyncStateMachine], lowering awaits to specializedAsyncHelpers.Awaitoverloads or by-valueAsyncHelpers.[Unsafe]AwaitAwaiter<TAwaiter>, driving<Main>$viaAsyncHelpers.HandleAsyncEntryPointwhile preserving authoredasync func MainTask-returning ABI, and recording("runtime-async", "on")in Portable PDBCompilationOptions. Ineligible and deferred Slice 2 shapes automatically fall back to ADR-0023 state machines, and default (RuntimeAsync == false) PE and PDB output remains bit-for-bit identical. -
Preserve operands of failed conversions in
SemanticModel(Fixes #6190).ConversionClassifier.BindConversionand its sibling conversion/argument-rejection paths now retain the unconverted bound operand onBoundErrorExpression.FailedOperands(using a syntaxless wrapper when the error would otherwise shadow the operand's syntax) soSemanticModel.GetSymbolInfoandSemanticModel.GetTypeInfokeep answering across failed implicit/explicit conversions, incompatible slice/by-ref/delegate-ref-kind/container-nullability/structural-projection/method-group conversions, and directGS0155conversion checks (reflocals/returns,throw, nullablelock,catch ... when, indirect compound assignment, andConvertToString) without changing diagnostics, lowering, or emitted IL. -
Enforce
CompilerFeatureRequiredAttributeon imported CLR types, constructors, and members withGS0644(Fixes #6331; part of #5765).gscnow readsSystem.Runtime.CompilerServices.CompilerFeatureRequiredAttributeacross bothMetadataLoadContextand handle-backed metadata (ADR-0209), ignoresIsOptional = true, allows features thatgscenforces (RefStructs,GSharp.NativeProtocols.v1, andGSharp.NativeStorage.v1), and reportsGS0644naming the symbol and required feature for unsupported features such as C# 15ClosedClasses,RequiredMembers, or unknown future features. Type-level enforcement covers type clauses, inheritance/interface lists, enclosing types, base/interface hierarchies (including generic base and interface type arguments),typeof,default,cast,is/as, generic type arguments, static receivers, and inferred member signatures without cascading duplicates; constructor-level enforcement rejects direct construction, object initializers, explicit: base(...), implicitbase()derivation, and genericnew()constraint satisfaction while still permitting type references and unmarked methods on C# 15 closed classes; member-level enforcement covers methods, generic/extension methods, method-group/delegate conversions, fields, constants, properties, separate getter/setter accessors, indexers, events and add/remove accessors, operators, conversions, property patterns,foreach/await for/awaitprotocol members, overrides, explicit/implicit/static-virtual interface implementations, and imported attributes. Compatibility note: code that directly constructs an imported C# 11+ type via a[CompilerFeatureRequired("RequiredMembers")]constructor (without[SetsRequiredMembers]) or constructs/derives from a C# 15 closed class now reportsGS0644(or failsnew()constraint satisfaction) instead of compiling unsoundly. -
Preserve array-element narrowing across runtime identity checks (Part of #5964). The shared storage-effect model now treats trusted
System.Object.ReferenceEqualscalls as pure.cs2gsuses the same rule when checking cross-project task envelopes; mutating calls still invalidate array contents, including local aliases erased toSystem.Array,object, interfaces, or non-value type parameters. -
Report
CS2GS-CROSS-PROJECT-RETURN-CONTRACTincs2gswhen a downstream task envelope cannot widen an independently emitted producer contract (Fixes #5964). When a consumer method, property, or indexer in a multi-project migration requires a nullableTaskorTask<T>return envelope (via[return: MaybeNull],[AllowNull], an explicit nullable return annotation, or a nullable return expression, conversion, or storage flow) while overriding or implementing an independently emitted non-nullable producer source contract,cs2gsnow reportsCS2GS-CROSS-PROJECT-RETURN-CONTRACTat translate time with the consumer declaration location, the blocking producer contract(s) and owning assembly name(s), and owner-annotation guidance ([return: MaybeNull]or a nullable return/property type on a non-asyncproducer; an annotatedasyncproducer still lowers to a non-nullable task envelope, so it needs a non-asyncnullable task contract), failing and short-circuiting the consumer'stranslatestage without mutating the producer's output. Same-project widenable contracts, owner-annotated non-asyncproducers, awaited nullable payloads (vs. nullable task envelopes),ValueTask/ValueTask<T>value types, open generic invariants, and external metadata are unaffected; whole-migration cross-project producer widening remains unimplemented. Element contents count as possibly null unless proven: parameters, unknown collections, non-array properties, virtual or interface results, custom constructors andAddmethods, and storage that a call can mutate or alias (bound per call to each helper's returned argument) are rejected, framework views are identified through the trusted effect image model, and static initializers that read later statics do not prove their members. Constructor checks follow C# evaluation order inside one statement, soAccept(_current = value, Read())is accepted andAccept(Read(), _current = value)is rejected. A static member is checked against every source method, accessor, constructor, field initializer, and other-type static initializer that can read it before its type initializer sets it. Arefforeach variable keeps the writes made to it. Element writes through a local alias apply to the aliased array, expression-bodied indexers return their storage, constructor reads ofrequiredmembers are checked, an automatic getter with a custom setter is proven through that setter, and each call of a block-bodied factory or computed getter returns a separate array, while an assignment through a property orrefreturn stays shared storage. Element writes through one call result and local-only alias chains inside a factory stay with that call, and deconstructed call results bind their returned arguments. Constructor and static-initializer checks follow every callback after its operands: local functions, lambdas, method-group receivers, user-defined operators and conversions, event accessors,foreachenumerators, and static delegate invocations. A compound property write runs its setter after the right-hand side, and a deconstruction writes its targets left to right. Earlier static initializers are checked against later static members, and source-derived constructors are checked against inheritedrequiredmembers. A chainedthis(...)orbase(...)constructor that assigns a member counts as its store, and object initializer callbacks before arequiredmember store are checked. One call-result query binds the actuals of a source callee or user-defined operator that returns its formal, compound writes store their operator result in every write index,Task<T>.Resultprojects its receiver payload, and metadata callees andusingdisposal follow the overrides and interface implementations of source values, including source subclasses and implementations of framework types, values that metadata calls return, and the elements of stored arrays. Returned-formal summaries are least fixed points over recursive calls, a chained constructor summary keeps its own read order, own static storage is matched per closed generic type, arrays of arrays alias the arrays that creations, collection expressions, spreads, and element writes insert, by-reference calls that cannot write keep the constructor state, and constant reads do not run type initializers. A setter or chained constructor uses one graph summary in constructors and object initializers, so a setter that stores and then reads is accepted; a required member store in an object initializer runs its own setter first, an overloaded equality operator is a call rather than a null test, and returned-formal summaries follow locals through the scope write index (including deconstruction) and bind indexer arguments. Deconstructing into a slot of an array of arrays inserts the array into its container. Increment and decrement writes store their operator result in every write index, and metadata property accessors follow callbacks into source receivers. Returned-formal summaries compose indexer accesses and read pattern variables by their pattern (a type pattern binds a non-null value, avarpattern binds its input); an unknown write counts only formals that convert to the local type. An implicit constructor of a type with arequiredmember checks the base constructor it runs. A trusted framework base constructor can reach source code only through framework virtual and interface slots of the new instance. A null test runs the effects of its other operand. A lifted user-defined operator returns null without its call when an operand is null. Returned-formal summaries and array aliases compose user-defined operator calls. Increments and decrements write throughreflocals, array aliases, and returned arrays. A metadata call runs a delegate value only through a parameter that can hold a delegate, and only when the trusted effect model covers the callee; otherwise the value is a possible callback. A delegate held by areadonlyor private static field resolves to the targets of its initializer and writes. A new delegate that such a framework call only stores, or that an indexed static field holds, does not run when it is created.System.EventArgs()runs no member of the new instance, and a creation does not dispatch to subclasses of its created type. Rectangular array initializers are checked at each element, returned-formal summaries reada ?? band assignments by their value, by-reference parameter scans repeat until their alias set is complete, and pattern variables alias the value that they match. A pattern variable starts with its matched input when its pattern matches null (varincluded), and otherwise starts non-null; later writes still apply, also in expression bodies. A conversion to a delegate type keeps a value a possible callback, and a value stored asobjectresolves its stored delegate targets. A method called on a receiver runs the receiver's delegate targets only when it is a delegate member that the framework effect model does not cover, such asDynamicInvoke;objectmembers such asToStringcheck only source overrides. A synthesized record member reads the record's fields and getters, and a primary constructor runs only its base call and instance initializers. Aforeacharray variable holds the element arrays of its sequence. A trustedSpan<T>,ReadOnlySpan<T>, orArraySegment<T>indexer reads an element of its receiver's contents, andSliceon a view is a view of the same storage. Aforeacharray variable aliases the arrays its sequence supplies, a metadata setter receives the assigned value as a possible callback, an own setter whose graph summary assigns a member stores it, and a partial property definition is not automatic storage. An array local written by a deconstruction holds the paired value's contents, and an array pattern variable holds its matched input's contents. A pattern that narrows a wider input proves array contents only from a resolvable origin. Conditional accessr?.M()yields what its non-null branch yields. A local array view reads the views written to it when every use reads it, and a view that is only read does not write the array it views; a view local with another use writes them. A conditional access instance stands for the receiver of its conditional access, sor?.M()binds and escapesrliker.M(). A write through a view includes a deconstruction target, and a value whose type has no element contract proves no array contents. Every write to a mutating view local escapes the arrays it views, view constructors and factories pick their source by formal ordinal,System.Array.SetValuewrites its receiver when an element type of the receiver, at any nesting level of a jagged array, can hold the checked element (an erased receiver can be any array),ReferenceEqualsruns no member of its arguments, a local function's returned values join its caller's returned-formal summary, and another closed construction of a member's own generic type stays conservative in initializer checks. A source member's body proves its returned array contents before its declared result type is consulted, and a declared type without an element type proves none. A view local or parameter and itsrefaliases share one set of written values, so a write through any of them escapes the arrays written to the others. A view creation or array-to-view conversion (includingArraySegment<T>) escapes its source array unless its consumer only reads it, directly or through a view local that is only read, so a boxed or field-held view counts as able to write the array. A view passed as a call argument or extension receiver counts as only read when the call keeps no copy of it: the bound parameter of a non-virtual source callee is only read, or a trusted framework call is pure and non-aliasing. A parameter that is returned, stored, or passed on keeps the view, and a virtual, interface, orexterncallee is unknown. -
Specify opt-in
.NET 11Runtime Async emission design (Fixes #6332; part of #5765; ADR-0232). Adds proposeddocs/adr/0232-runtime-async-emission.mdcovering the opt-in CLI/SDK switch (/runtime-async[+|-],<GSharpRuntimeAsync>,<Features>runtime-async=on</Features>), corlib capability probing (System.Runtime.CompilerServices.AsyncHelpersandMethodImplOptions.Async, noting thatRuntimeFeature.Asyncis absent from.NET 11.0.0), per-method eligibility and ADR-0023 state-machine fallbacks (keeping ADR-0174suspend funcdecoupled in Phase 1), shared lowering-pass reuse (ChannelOperationRewriter,AsyncExceptionHandlerRewriter,SpillSequenceSpiller,RefInitializationHoister), IL/Portable PDB/ILVerify contracts, and phased rollout gates. This documentation-only ADR does not yet add compiler support. -
Enforce generic container and magic-collection inner nullability invariance (
C[T]vsC[T?]) (Fixes #4321; part of #6264).Conversion.ClassifyCoreno longer erases inner reference nullability across invariant generic containers (List[T],Dictionary[K, V],Span[T],Box[T],IList[T],IEqualityComparer[T], nativeDerived[T] : Base[T]) or magic collections ([]T,[N]T,[,]T,map[K, V],chan[T]), closing both direct aliasing (C[T] <-> C[T?]) and the ADR-0186 two-hop platform bypass (C[T!] -> C[T?] -> C[T]), checked-cast andasinner-contract bypasses (cast[List[string]](IEnumerable[string?]),List[string] as List[string?],cast[[]object?]([]string),cast[[]IEnumerable[string?]]([]List[string])), declared-hierarchy platform bypasses, and unsound covariant/contravariant nullability narrowing (List[string?] -> IEnumerable[string],IEnumerable[[]string] -> IEnumerable[[]string?],sequence[string?] -> IEnumerable[string],IComparer[string] -> IComparer[string?]). Sound declaration-site variance (List[string] -> IEnumerable[string?],IEnumerable[string] as IEnumerable[string?],[]string -> IEnumerable[string?],IComparer[string?] -> IComparer[string],IComparer[string?] as IComparer[string]) and ADR-0186C[T!] -> C[T?]widening remain accepted, and CLR overload resolution ranks incompatible invariant container overloads below valid normal-form covariant competitors (sostring.Join(", ", stringSlice)binds cleanly toIEnumerable<string?>without letting expandedparams object?[]catch-all overloads displace mismatched normal-form overloads).cs2gspropagates matching container and array element nullability across target-typed array/collection initializers, inferred and explicit generic call type arguments (with substituted constraint validation), anonymous shapes, ref-aliased arrays, nested containers, andDocumentTranslationState. Generic method type inference over a nullable derived bound and a base bound with inner nullability (List[string?]andRows?whereRows : List[string?]) fixesTatList[string?]?in either argument order. Base and interface projection walks a complete finite metadata hierarchy at any depth, and aGS0154that differs only in inner nullability states it in the message and in theExpectedType/ActualTypepayload. A G# implicit operator whose result has the parameter's full nullability keeps an imported container argument applicable (an imported operator matched on erased types does not), constrained calls through a type parameter run that operator, andcs2gsgives generic local function calls the same sink-driven type arguments as other calls.cs2gsalso gives every arm of a conditional or switch expression and each construction viewed through a generic interface (List<string[]>intoIEnumerable<string?[]>) one sink-adjusted contract. A typed null arm such as(T?)nulltakes that contract as anullordefaultarm does, and a switch arm such asdefault(Source)that converts through a user-defined operator still runs the operator. Base and interface projection reads the interface metadata of each type one time, so semantic models for large files are not slower. Compatibility note: existing code that relies on implicit,as, orcast[...]conversions betweenC[T]andC[T?](for example[]Tto[]T?,List[T]toList[T?], or EF CoreInclude(e -> e.NullableCollection).ThenInclude(...)without!!) now reportsGS0154/GS0155/GS0637instead of silently aliasing mutable storage. A contravariant slot whose type argument comes from an oblivious receiver (IComparer[object!]) also rejects a non-null argument such asComparer[object].Default(GS0154); pass a nullable-accepting argument such asComparer[object?].Default. -
Bound language-server workspace warm-up concurrency and evict idle/LRU bound project state (Fixes #6326).
WorkspaceInitializer.Initializenow registers projects in deterministic path order, prioritizes projects with open documents (followed by their referenced projects), bounds the number of unopened projects warmed eagerly (WorkspaceState.MaxWarmUnopenedProjects, default4), and runs warm-ups through a fixed worker pool capped atmin(2, ProcessorCount)concurrent binds instead of spawning unbounded parallel tasks.ProjectStatetracks monotonic last-access timestamps, deterministic LRU sequence order, and activeCompilationLeasecounts;WorkspaceState.TrimIdleProjectsand cold-to-warm LRU budget enforcement evict cachedCompilation,ReferenceResolver(viaRetirableReferenceResolver), and analyzer state for idle or over-budget unopened projects while never evicting projects with open documents or active leases and keeping lightweight project metadata and syntax trees intact for transparent lazy re-hydration (including cross-assembly lookups).LspServernow implementsIDisposable, runs a weak-referenced periodic idle-eviction sweep timer (default 1 minute cadence, 5 minute idle threshold), and disposes all timers and workspace resources cleanly onShutdown()andDispose(). -
Prune stale
BoundBodyCacheentries across edits, share non-host reference images, and stop retaining raw disk bytes inSourceText(Fixes #6322, #6323).BoundBodyCachenow synchronizes cache mutations and prunes entries whoseFunctionSymbolis absent afterBinder.BindProgramcompletes, clears unreachable entries on full declaration rebinds inCompilation.BuildGlobalScope_Locked, and releasesforkBaseCompilation/forkBaseProgramafter publishingBoundProgram, so renamed, deleted, or signature-changed members and replaced syntax trees can be garbage collected while unchanged sibling members keep incremental cache hits.ReferenceResolvernow deduplicates immutable non-host reference assemblybyte[]images across resolvers via a bounded, thread-safe, weak-value cache keyed by canonical path, file length, and UTC last-write timestamp without memory-mapping or holding open file handles (ADR-0209).SourceText.LoadandSourceText.Fromnow compute and store the 32-byte SHA-256 checksum, BOM encoding kind, and encoding validity without retaining full rawbyte[]buffers for lossless encodings, reconstructing exact bytes on demand forRawBytesandEmbedAllSourceswhilePortablePdbEmitterreads the precomputed checksum directly. -
Reconcile
ProjectStatewith disk ontextDocument/didCloseand retire replaced/removedReferenceResolverandProjectStateinstances safely (Fixes #6324, #6325). Closing a document in the language server now reconciles its project syntax tree against disk (reloading on-disk content when it differs from the unsaved buffer, removing the tree and workspace mapping when the file does not exist on disk, dropping the stale cached compilation, clearing closed-file push diagnostics, and refreshing related open-document diagnostics).ProjectStatenow wraps itsReferenceResolverin a lock-free atomic ref-countedRetirableReferenceResolverpinned byCompilationLeaseacross all in-flight LSP requests, deferringReferenceResolver.Dispose()until active leases reach zero on reference/assembly-name reloads or project retirement;WorkspaceState.RemoveProject/AddProjectreplacement andLspServer.Shutdownretire removed projects,CodeActionComputertracks resolve-cache compilations weakly, andDocumentContentresolves workspace-owned projects without strongly pinning removedProjectStateinstances so removed projects, compilations, and resolvers become GC-collectible while open documents stay detached or re-associated. -
Avoid measuring process-wide allocations across the reused-resolver no-op branch in
gsc --bench-inprocess-bind(Fixes #6320).InProcessBindBench.ExecuteAndMeasureBindnow setsreferences.wallMs = 0andreferences.allocatedBytes = 0directly when reusing an existingReferenceResolverinstead of bracketing the no-op assignment with process-wideGC.GetTotalAllocatedBytes(precise: true), eliminating concurrent sampler/xUnit allocation noise that causedIssue6274InProcessBindBenchTests.InProcessBindBench_ReuseResolver_ReusesResolverOnSecondIterationto flake on CI. -
Rebind re-listed inherited interface slots to hiding intermediate members (Fixes #6290). When a derived class explicitly re-lists an interface already implemented by a base class (directly or through a derived interface) and an intermediate class hides the base implementation,
gscnow emits privatefinal virtual newslotforwarding bridges andMethodImplentries (or directMethodImplentries for derived overrides of hiding virtual slots) matching C# / CLR interface re-implementation semantics across methods, generic methods,async/ref/in/outsignatures, properties, indexers, events, default interface methods, generic hierarchies, and cross-assembly imported bases and interfaces. Virtual hiding members dispatch viacallvirtso downstream overrides are reached, non-openhiding members on intermediate classes remain non-virtual, non-public inherited members are skipped, explicit implementations on the derived class keep precedence, and classes that do not re-list the interface preserve the base mapping. -
Fix .NET 11 nightly regressions in
cs2gs-apps-nightlyforcode-exploderandgsharp-csharp(Fixes #6298, #6299).build/run-cs2gs-code-exploder.shnow runs the C# baselinedotnet restore,dotnet build, anddotnet testinside the isolatedcode-explodercheckout sodotnethonorscode-exploder's ownglobal.jsonSDK pin (10.0.301), and.github/workflows/cs2gs-apps-nightly.ymlinstalls the.NET 10.0.xSDK for thecode-exploderleg alongside.NET 11.0.100.SdkCompileRunner.TestMirroredProject(called byTestParityStage.RunMirroredTestProject) now runs single-targeted mirrored test assemblies directly viadotnet test <assembly.dll> --framework <tfm>instead ofdotnet test <project> --no-build, preventing outer .NET 11 MSBuild from leakingMSBuildSDKsPathand related SDK-resolver variables intotesthostwhere nesteddotnetinvocations under a.NET 10global.jsonpreviously hitMSB4216and timed out (Compiler.TestsandSdk.Tests). -
Add tracked in-process full-bind benchmark row for
src/Coreand document bind profile, targets, and host reuse guidance (Fixes #6274). Addsgsc --bench-inprocess-bind(src/Compiler/InProcessBindBench.gs) and--inprocess-bindcell support inbuild/compiler-bench.pyto track wall time, peak and live managed memory, allocations, post-dispose retention, and per-phase breakdowns (references,parse,declarations,bodies,dispose) for in-processGSharp.Corebinding over releases while failing closed on compiler errors or count drift. Records the measuredsrc/Corein-process bind profile (833 files, 176 references, 13,781 methods: 22.6 s coldTieredPGO=0/ 29.4 s coldTieredPGO=1/ 17.2 s warm reused-resolver, 1,296 MiB peak managed, 1,149 MiB live retained split across 493 MiBSyntaxTrees, 426 MiBBoundProgram, 138 MiBBoundGlobalScope, and 91 MiBReferenceResolver), maps overlap with#5131,#5141,#5167,#5134, and#5144, sets staged wall-time and live-memory reduction targets, and documents current in-process and planned cross-process host reuse contracts indocs/self-host-benchmark.md,docs/compiler-architecture-and-performance-study.md, andwebsite/docs/tooling/compiler-architecture.md. -
Add non-retiring incremental
Compilation.Fork,IncrementalReuseReport, warning-tolerant reuse, and member-level incremental rebinding (Fixes #6269, #6270). AddsCompilation.Fork(SyntaxTree, SyntaxTree)andCompilation.Fork(ImmutableArray[SyntaxTree], ImmutableArray[SyntaxTree])backed by thread-local read-only symbol overlays (SymbolMemberOverlay/SymbolMemberOverlayContext) and direct read-only body reuse from the baseBoundProgramso N sequential or concurrent candidate edits can share one base compilation without retiring or mutating it (leaving the base's diagnostics,SemanticModel, and emitted PE output byte-identical, and allowing forks to be disposed independently). ExposesCompilation.IncrementalReuse(IncrementalReuseReport,IncrementalReuseKind,IncrementalReuseMissReason) on bothForkandReplaceSyntaxTreesuccessors reportingBodyOnlyReuse,MemberLevelReuse, orFullRebind, exact miss reason/detail, and reused/rebound body counts. Extends incremental reuse to supportpartialclasses/structs/interfaces, multi-file edits, and files carrying declaration-level warnings (relocating warning spans rather than disqualifying reuse), and addsMemberLevelReusefor adding, removing, or changing signatures of ordinary instance/static methods and top-level functions (re-binding only changed declarations, edited trees, and dependent bodies — scoped to the owning type and its partial/nested parts forprivatemembers and via a lazy base-ownedIdentifierBodyIndexfor non-private members — with structural soundness guards falling back toFullRebindfor layout, hierarchy, override, interface, extension, operator, or external-initializer edits). On 836-filesrc/Core(13,882methods;26.4 sfull bind), body-only forks run in0.80–1.33 sand adding a private helper method runs in0.52–0.84 swith exact diagnostic parity against a fresh bind. -
Include matching extension methods alongside source instance methods and callable members in overload resolution (Fixes #6283). Member calls on source classes, structs, interfaces, generic interfaces, default interface methods, constrained type parameters, and function-typed fields/properties now fall back to matching source, cross-package, and imported CLR extension methods when no instance member is applicable (
c.M("a"),c.M[int32](1)), matching CLR receivers and the language specification while keeping applicable instance methods and callable members preferred over extensions without ambiguity. Wrong explicit type-argument counts across mixed instance/callable-member and generic-extension candidates reportGS0148with the generic extension's arity (c.M[int32, int32](1)-> requires 1), non-generic-only sets continue to reportGS0643, error recovery binds type and value arguments once without cascading, andSemanticModeland nilable-receiver diagnostics stay aligned with the chosen callee. -
Remove the 16-parameter cap from CLR expected-arity helpers, bind explicit-type CLR generic delegates and abstract/interface conversions by arity, and report GS0496 for ambiguous imported source generics (Fixes #6282, #6286, #6288, #6291). CLR expected-arity helpers (
TryFindImportedClassExpectedArity,TryFindQualifiedClrTypeExpectedArity,TryFindNestedClrTypeExpectedArity, and their type-clause/static-receiver siblings) now queryReferenceResolver's arity-insensitive type-name index and nested-type metadata directly in deterministic ascending order instead of stopping at 16 type parameters, so 17+-parameter CLR generics (Big<T1..T17>,Host.Big<T1..T17>) reportGS0148with their real arity rather thanGS0643/GS0149while preserving visibility and hiding rules. Single-argument calls against already-resolved CLR delegates (Action[int32](Nop),EventHandler[int32](H),Func[int32, string](Fmt), untyped lambdas, method groups, qualified and nested CLR generic delegates) and abstract/interface CLR types (Comparer[int32](nil),Comparer[int32](obj),IEnumerable[int32](xs)) now route throughconversions.BindConversionon the arity-selected CLR type instead of failing withGS0267or falling back to a non-generic namesake (System.Collections.Comparer), while zero-argument instantiations of generic abstract/interface CLR types (Comparer[int32]()) reportGS0386and matching-arity source types keep precedence over CLR imports. Ambiguous imported source generics (Q1.Range[T]andQ2.Range[T]alongsideSystem.Range, orQ1.Op[T]andQ2.Op[T]) now reportGS0496at matching arity before CLR fallback (with full type-argument and argument recovery) while wrong-arity calls (Range[int32, int32]()) continue to reportGS0148. -
Add
CompilationWithAnalyzers,DiagnosticSeverityOptions,ProjectAnalyzerConfiguration, and reusableAnalyzerAssemblyLoaderfor in-process analyzer execution (Fixes #6277; related: #5138). Adds Roslyn-styleCompilation.WithAnalyzers(...)/CompilationWithAnalyzers(GetAnalyzerDiagnostics,GetAllDiagnostics,FromAnalyzerPaths,FromProjectConfiguration) andCompilationWithAnalyzersOptionsinGSharp.Core.CodeAnalysis.Analyzersso library hosts can run a project's configured analyzers (such asGSA0007) against an in-memoryCompilationwith deterministic ordering and concurrent single-flight safety. Introduces sharedReportDiagnosticandDiagnosticSeverityOptions(supporting.editorconfigdotnet_diagnostic.<ID>.severitychains,/gsdiag:,/nowarn:,/warnaserror,/warnaserror+:,/warnaserror-:,IncludeHidden, and enabling disabled-by-default rules) used by bothgscandCompilationWithAnalyzers, plusProjectAnalyzerConfigurationfor reading/gsanalyzer:and severity switches from compiler response files (.rsp). Adds thread-safeAnalyzerAssemblyLoader(with process-wideAnalyzerAssemblyLoader.SharedbackingGSharpAnalyzerHost) that caches collectibleAssemblyLoadContextinstances and discovered type metadata by canonical path, file length, and UTC last-write timestamp while instantiating isolated analyzers and code-fix providers independently per load, loads from memory bytes so on-disk DLLs remain unlocked for rebuilds, automatically unloads stale contexts on file change, and releases contexts onClear()/Dispose(). -
Document and enforce the
Compilation/SemanticModelconcurrency contract and release retained state across compilations (Fixes #6273, #6275). Synchronizes lazy symbol and syntax publication on concurrent read-only queries (StructSymbolsubstituted member snapshots and synthesized data members,InterfaceSymbol.EnsureMembersResolved,DelegateTypeSymbol.EquivalentFunctionType,Symbol.ContainingType,TupleTypeSymbol.WithoutNames,SyntaxTree.GetParent/GetDocumentation,SyntaxNodespan/children publication,AssemblyTypeNames.Declares, andNullabilityOptions.EnteronSemanticModelimported-member and expected-type paths) so N concurrent threads can safely runGetSymbolInfo,GetTypeInfo,LookupSymbols,LookupMembers,GetMemberGroup,GetExpectedType,GetSpeculativeTypeInfo, andGetDiagnosticsagainst oneCompilationand itsSemanticModelinstances with results matching a serial run. MakesCompilationimplementIDisposable(addingCompilation(ReferenceResolver?, bool ownsReferences, ...SyntaxTree),Compilation.Dispose(), andCompilation.ClearProcessCaches()), converts all process-wide type-symbol interning caches (NullableTypeSymbol,PlatformTypeSymbol,SliceTypeSymbol,PointerTypeSymbol,ByRefTypeSymbol,SequenceTypeSymbol,AsyncSequenceTypeSymbol,ArrayTypeSymbol,RectangularArrayTypeSymbol,ChannelTypeSymbol,MapTypeSymbol,FunctionTypeSymbol,TupleTypeSymbol,FunctionPointerTypeSymbol,StructSymbol,InterfaceSymbol,EnumSymbol,DelegateTypeSymbol) plusClrTypeUtilities.MemberCache,ClrOperatorResolution, andStructValue.LayoutRuntimeto weak-keyed (ConditionalWeakTable/WeakTypeInternTable) storage so repeated compilations sharing oneReferenceResolverreclaim prior compilations, trees, and symbols with flat live memory, and documents the concurrency andReferenceResolver/MetadataLoadContextownership contract on the public API and inwebsite/docs/tooling/compiler-architecture.md. -
Filter nested-type lookup by arity before hiding, diagnose non-generic and generic-namesake type clauses accurately, and report GS0148/GS0643 on qualified/imported struct literals (Fixes #6289, #6280, #6285, #6287). Nested-type lookup across source and imported CLR class hierarchies now filters by generic arity before hiding (matching C# and documented in the language specification):
Derived.Item[int32]binds an accessible inheritedBase.Item[T]whenDeriveddeclares non-genericItem,Derived.Itembinds an inherited non-genericBase.ItemwhenDeriveddeclaresItem[T], and wrong type-argument counts reportGS0148with the reachable generic arity across type clauses, base clauses, static-member accesses, struct literals, and constructions. Non-generic nested and package-qualified type clauses (Outer[int32].Nested[int32],Host.Inner[int32],Host.Kind[int32],Q.Host.Inner[int32]) now reportGS0149instead ofGS0113while diagnosing every unresolved type argument, and type clauses whose type has a reachable generic namesake (Op[int32, int32]withOpandOp[T],Task[int32, int32],List[int32, string],Host.Twin[int32, int32],Q.Op[int32, int32]) now reportGS0148with that generic arity across base clauses, interface lists, annotations, constraints, aliases,typeof,default, andcastwhile keeping strict alias behavior (OpAlias[int32, int32]staysGS0149). Qualified, nested, imported-package, referenced-library, and CLR struct literals with invalid type arguments (Shelf.Pt[int32, int32]{X: 1},Q.OpPt[int32, int32]{X: 1},Pt[int32, int32]{X: 1},ValueTask[int32, int32]{},Guid[int32]{}) now reportGS0148orGS0643instead ofGS0157and recover type arguments, spread sources, and initializer expressions for diagnostics andSemanticModel. -
Attach structured
Diagnostic.Propertiespayloads to GS0158, GS0159, GS0154, GS0130, and GS0125 (Fixes #6272). Adds publicDiagnosticPropertyKeysconstants and populatesDiagnostic.Propertiesacross member, call, overload, constructor, indexer, and scope-lookup binding paths without changing message text:GS0158andGS0159recordMissingName,ReceiverSpanStart,ReceiverSpanLength,ReceiverType, andReceiverTypeId(including chained, static, CLR, write, and nullable receivers);GS0154recordsCalleeName,CalleeDisplay,CalleeSymbolId, deterministic sortedCandidateOverloads,ParameterName,ExpectedType,ActualType, and receiver metadata when receiver-qualified;GS0130andGS0125recordMissingName,LookupPosition,ScopeKind,EnclosingScope, andEnclosingScopeId.BodyLocalDeltarelocates span and lookup-position properties alongside diagnostic locations. -
Reject type arguments on enum conversions, named delegate constructions, and non-generic static-member receivers, and document the GS0149 / GS0643 position split (Fixes #6278, #6284, #6279, #6281). Top-level, aliased, and package-qualified enum conversions (
Color[int32](0),Q.Color[int32](0)) and named delegate constructions (D[int32](Id),Q.D[int32](Id)) no longer ignore explicit type arguments: they reportGS0643when no generic namesake is reachable andGS0148with the generic arity when one is (DelOp[int32, int32](Id)alongsideDelOp[T]). Type arguments on a non-generic static-member type receiver (Plain[int32].Make(),Plain[int32].Field = 1,String[int32].IsNullOrEmpty("a"),Host.Inner[int32].Make()) now reportGS0149instead of cascadingGS0125undefined-variable diagnostics, while wrong type-argument counts on generic static receivers or types with generic namesakes (Box[int32, int32].Make(),Op[int32, int32].Make(),Task[int32, int32].CompletedTask) reportGS0148. Both diagnostic references now document the position split explicitly:GS0149applies to type positions (type clauses,typeof,default,cast, base types, constraints, aliases, and static-member type receivers) andGS0643applies to call, construction, and conversion positions. -
Add
SyntaxTree.ParseExpressiondiagnostic/SourceTextoverloads and resolve member-access chain segments inSemanticModel(Fixes #6271, #6276).SyntaxTree.ParseExpressionaddsSourceTextandout diagnosticsoverloads matchingParseTokensso standalone expressions (such asa.B[int32](c).D) return exact spans and parse diagnostics even when the input is not a single expression, whileBinder.BindSpeculativeExpressionTypealiases standalone fragment trees to the host tree for import resolution.SemanticModel.GetBoundNodenow resolves unanchored inner and terminal segments of right-nested member-access chains (a.B.C(d).E, generic calls, static-qualified chains, indexed and!!-asserted segments, null-conditional chains, extension receivers with implicit conversions, method groups, tuple elements without receiver-symbol leaks, and prefixes before a failed tail) soGetBoundNode,GetSymbolInfo, andGetTypeInfoanswer for every segment, andGetSymbolInfohandles imported CLR fields and constant fields on expression nodes. -
Move default CI to .NET 11 with continuous .NET 10 smoke coverage and bump version base to 0.6 (Part of #5765).
version.jsonmoves from0.5to0.6,Gsharp.Runtime.Valuesunpins its assembly version so it moves withversion.json(0.6.0.0) alongsideFixedArrayAbi.ExpectedOwnerVersion(with a renewed#5244runtime proof), andglobal.jsonnow targets .NET SDK11.0.100, while shipped compiler/tool payloads (gsc,gsgen,gsfmt) and bundled runtime assemblies remain onnet10.0with<RollForward>Major</RollForward>on CLI tools so the SDK works out of the box on both .NET 10-only and .NET 11-only machines and compiles bothnet10.0andnet11.0targets. Also fixes .NET 11 compatibility in emit and SDK targets: covariant overrides now emitNewSlot+[PreserveBaseOverridesAttribute], unannotated empty structs emitClassLayout(Size=1)matching Roslyn (avoiding a .NET 11 RyuJIT crash inGenTreeFieldList::SoleFieldOrThis),_GsharpBuildHotReloadBaselineanchors to_GsharpFilterHotReloadWatchItems,e2etests/multitarget-e2e.shdropsnet8.0and validates bothnet10.0andnet11.0,build/run-ilverify.shverifies against the active SDK's BCL,r2r-compiler-smokeexercises pure .NET 11 withoutDOTNET_ROLL_FORWARD, and a dedicateddotnet10-smokeCI job verifies the packed SDK and ReadyToRun compiler on a pure .NET 10-only runner. -
Type arguments on a function, method or type that is not generic report GS0643 (Fixes #6203). A call or a construction that gives type arguments to a function, method, function value or type without type parameters (
Use[int32](x),c.M[int32](x),Console.WriteLine[int32](x),Plain[int32](),Pt[int32]{X: 1},StringBuilder[int32](),Host.Kind[int32](0)) now reports the new GS0643,'Use' is not generic and cannot be used with type arguments., as C# reports CS0308. Before, it reported GS0148 with "requires 0 type arguments". This replaces GS0148 for these callees in the #6186, #6201 and #6206 entries. GS0148 still reports a generic function, method or type that gets the wrong number of type arguments. When a non-generic type and a same-named generic type both exist, a construction whose type-argument count matches neither (Op[int32, int32]()withOpandOp[T],Task[int32, int32](nil)) now reports GS0148 with the arity of the generic type ("requires 1") instead of "requires 0", as C# reports CS0305. A type clause such asvar p Plain[int32]still reports GS0149. -
Speed up
gscandgsgenbinding,SemanticModelindexing, and bounded generator-host parsing (Part of #2189).SemanticModelnow partitions compilation declarations, imports, type clauses, partial parts, and function bodies bySyntaxTreeonce per(BoundProgram, BoundGlobalScope)generation instead of scanning every symbol per tree.BoundScope.TryLookupQualifiedSourceDeclarationandTryResolveExplicitSourceTypeAliasnow index type aliases by trailing leaf name (aliasCandidatesByLeafName) and store candidate buckets inImmutableArray, removing the remainingEnumerateTypeAliasesInChainfull-scope scans.Conversion.ContainsPlatformTypefast-paths leaf and single-child wrappers before allocating traversal state,ImportedTypeSymbol.Getadds an ephemeronConditionalWeakTabledirect-hit fast path,StructSymbolcaches shallow base-class hierarchies (depth<= 16, version-invalidated onSetBaseClass) and lazy per-name instance/static method indexes,AccessPathcaches its hash code and per-variable instance,BoundNode.ChildNodesavoids builder allocation for 0/1-child nodes,NativeProtocolSafety.ContainsDependencyreplaces chained LINQ walks with direct loops, and narrowing entry/exit alias maps store immutableIReadOnlyCollectionsnapshots (Array.Emptywhen empty) whileCaptureExternalCallableAliasesalways returns an ownedHashSet.GsgenTask,GsgenArgs, andGsgenProgramnow honorGSharpMaxWorkers/GSharpWorkerMemoryBudgetMiB(--workers:N,--worker-memory-mib:N) throughWorkerCoreLeaseandCompilationWorkBudgetfor bounded parallel source loading in input order. On frozen 824-fileGSharp.Coreinterleaved replays,gscmedian wall time drops from44.17 sto37.83 s(w=1,-14.3%) and36.48 s(w=4,-17.4%), andgsgendrops from8.24 sto7.40 s(w=1,-10.2%) and6.50 s(w=4,-21.1%) with raw SHA-256 byte-identical DLL, reference DLL, PDB, XML, and manifest outputs. -
Add retained SharpTUI REPL mode alongside Spectre.Console with live switching (Part of #3736).
Gsharp.Repl(gsi) now includes a retained-tree SharpTUI (SharpTui.Framework 0.1.1) interface as the default interactive UI while preserving the existing Spectre.Console interface. Users can select a backend at startup with--ui <sharptui|spectre>orGSI_UIand switch back and forth live mid-session with:ui [sharptui|spectre](or via the SharpTUI Settings tab) while keeping all evaluated cells and session symbols intact. SharpTUI mode provides six tabs (REPL, History, structured Variables, Diagnostics, Help, Settings), live session-chain semantic highlighting/diagnostics/completions/hover, editor formatting viaGSharpFormatter, session search (/),:show treeand:show ildumps, OSC 52 clipboard integration, andNO_COLOR/GSI_SCREEN_READER=1ASCII mode. -
Accept normalized native-slice calls in
deferand skip omitted@Conditionalcalls in loop-effect scans (Fixes #6252, #6242).StatementBinder.BindDeferStatementInBlocknow unwraps syntheticBoundBlockExpressionwrappers tagged withCallExpressionSyntax(such as native-slice receiver normalization forslice[T],readonly slice[T], andbytestringextension calls) beforeIsDeferableCallandHasByRefArgument, hoisting their prelude statements into the eager registration prefix and operand-effect list while still rejecting non-call block expressions ({ ... }, range slices) withGS0138and by-reference arguments withGS0460.RegionEffectScannerandStatementBinder.IsElidedConditionalCallInRegionnow shareKnownAttributes.IsConditionallyElidedwith binding and flow so omitted@Conditionalcalls (source, imported, extension, and scoped@DefineSymbol/@UndefineSymboloverrides acrosswhile,forbody/post,do-while, andfor-range loops) do not conservatively destroy loop narrowing withGS0158, while active calls and shadowed local callables still do. -
Align
docs/coverage-matrix.mdwith the coverage-matrix golden forNullCoalescingAssignmentExpression(Fixes #6244). Replaces the staleNullCoalescingAssignmentStatementrow indocs/coverage-matrix.mdwithNullCoalescingAssignmentExpressionso the checked-in coverage reference matchestest/Core.Tests/CoverageMatrix/coverage-matrix.golden.txt; no compiler behavior changes. -
Normalize SDK archive paths when probing scoped conditional-symbol capability in
cs2gs(Fixes #6256).SdkCompilerCapabilities.SupportsScopedConditionalSymbolsInPackagenow matches normalized archive entry paths (handling redundant separators such astools/compiler//GSharp.Core.dllemitted byGsharp.NET.Sdkpack targets as well as backslash separators) and resolves NuGet global-packages cache version directories case-insensitively, restoringcs2gs-apps-nightlytranslation ofConditionalAttributecalls while preservingCS2GS-CONDITIONAL-SYMBOLSdiagnostics for unsupported SDKs. -
Prefix bind: close remaining
later-overloadandKeepDeclarationsdiagnostic-finality gaps (Fixes #6229; ADR-0225 D6.8). Reports inside lambda arguments or contextual assignment RHS targets of enclosing calls whose signature or receiver uses a provisional expression, labeled and multi-assignment/index/field-assignment headers, indexer writes on incomplete hierarchies,KeepDeclarationstop-level-cut shadowing of non-package simple names and method groups inside member/function bodies, callee-level (GS0204) andref/parenthesized/checked/named-argument call-frame premises, and missing collection-initializer (GS0369), property-pattern (GS0173), and equality/inequality relational-pattern (GS0174) checks now classify asFutureDependentwhen later code can remove them. Fixed calls (includingbaseand interface/CLR calls recorded before argument binding), explicitly typed and implicit-voidfunction-literal bodies,nameofexpressions, outer interpolated-string types (while preserving interpolation holes),</>relational patterns, and package/local/qualified/top-level-sequential lookups stayFinal. -
Index assignment-narrowing proof sources in
cs2gsto avoid quadratic guarded-local rescans (Fixes #6254).CSharpToGSharpTranslator.ComputeGSharpAssignmentNarrowedLocalandGetGSharpAssignmentPrefixProofnow consult the existing per-scopeScopeWriteIndex(AssignmentsFor) andScopeGotoIndex(ExitingNullGuardsFor) with position-bounded binary search to skip symbols with no assignment or exiting null-guard proof sources in the enclosing scope and skip preceding statements that cannot introduce a proof whileproof == nil, eliminating O(N²)GetGSharpAssignmentNarrowingProofrescans on methods with many independent guarded reference-type locals (512guarded locals drop from555.3 MB/2,393 ms/2,628,612visits to28.4 MB/490 ms/0visits while preserving identical emitted output and scope-census counts). -
Emit direct capture-and-access lowering for non-nullable value-type null-conditional receivers (Fixes #6248).
EmitNullConditionalAccessandSpillSequenceSpiller.SpillNullConditionalAccessnow identify non-nullable value-type receivers (ReflectionMetadataEmitter.IsNonNullableValueType, coveringslice[T],readonly slice[T],bytestring,span[T], userstruct/enum/tuple values, primitives, andstruct-constrained type parameters) and emit a single receiver capture followed by an unconditionalWhenNotNullevaluation (wrapping non-nullable value results intoNullable<T>when needed) instead of probing withbrtrue— fixingILVerifyStackUnexpectedrejections onslice[T]?.Keep()/?[]and falsy zero-value branches on0?.ToString()/false?.ToString().BindIndexedWriteThroughChainalso usesReflectionMetadataEmitter.IsValueTypeSymbolfor result-slot allocation. -
Scoped conditional symbols and semantic inclusion (Fixes #6231, #6101, #6033, #6100). Add
@DefineSymbol,@UndefineSymbol, file-scoped overrides, intrinsic@defined("NAME")queries, and@Ifinclusion. Forward/define:,/d:, and SDKDefineConstantsthrough compiler and editor compilations. Preserve conditional-call state in cs2gs and reject unsupported destination SDKs. Inactive source still parses but does not bind or emit. Prefix later-type proofs ignore inactive declarations and statements, and recognize@definedas an intrinsic. Omitted calls retain function-pointer capture diagnostics. Void function-pointer declarations preserve following annotation owners. The published SDK pin remains unchanged. -
Emit
cast[*T]for pointer/function-pointer conversions and omit redundant receiver assertions incs2gsnull-conditional static-extension helpers (Fixes #6245, #6246).GSharpPrinternow printsConversionExpressiontargets forPointerTypeReference,FunctionPointerTypeReference,TupleTypeReference,NativeSliceTypeReference,ManagedReferenceTypeReference,ArrowTypeReference, and arrays of those elements using the unambiguouscast[Target](operand)intrinsic rather than*T(operand)(which parsed as a dereference and failed withGS0128on expressions such as(int*)0), and parenthesizescast[...](...)when used under unary*or->sogscdoes not reinterpret dereferences or arrow accesses as pointer-to-pointer casts.BuildNullConditionalStaticExtensionHelpernow checks whether the receiver is narrowed by itsif receiver != nilguard (a freshletcapture, statically non-null expression, or non-reassigned local/parameter excluding primary-constructor field reads) instead of emitting an unconditionalreceiver!!that triggeredGS0536. -
Elide unused
defercancellation shields and pack referenced bundled G# runtimes (Fixes #6249).SuspendingCallRewriternow unwrapsStatementBinder.ShieldCleanupblocks when the rewrittendefercleanup body does not reference its<defer$shield$N>local, so plain synchronousdeferemits a standardtry/finallywithout referencingGsharp.Runtime.Channelswhile suspendingdeferinsidescopepreserves its cancellation shield.Gsharp.NET.SdkaddsResolveReferencedGsharpRuntimesTaskand_GsharpGetBundledRuntimesForPack(with a zero-dependencynetstandard2.0ECMA-335AssemblyRefreader) to compute the transitive closure of SDK-bundled G# runtime assemblies (Gsharp.Extensions.dll,Gsharp.Runtime.Channels.dll,Gsharp.Runtime.Values.dll) referenced by$(TargetPath)and$(TargetRefPath)and pack them intolib/<tfm>/andref/<tfm>/(opt-out viaGsharpPackBundledRuntimes=false), and directgsc /out:runtime copying (CopyBundledRuntimesBeside) now also copiesGsharp.Extensions.dlland transitive bundled runtimes. -
Specify scoped conditional symbols and inclusion (Part of #6101; ADR-0230, ADR-0231). The accepted design defines file, declaration, and block symbol overrides, compiler flags, SDK/editor propagation, the collision-free
@defined("NAME")query, and semantic conditional inclusion through@If(...). It records a translation contract preserving direct calls and public metadata. These ADRs specify implementation requirements; this documentation-only change does not add compiler support. -
Bound
cs2gsreturn-contract graph collection and propagation to linear work (Fixes #6037).ObliviousNullabilityAnalyzer.ComputeReturnContractsnow caches immutable per-owner return-contract summaries (OwnerReturnSummaries) underScopedCompilationCache, skips re-solving clean upstream compilations whose declarations receive no downstream writes or contract edges, and replaces full-graphfixedReturnsandNullable/Promotedre-scan loops with deterministic queue worklists over reverse dependency edges (including projectedawaitDepthpaths). Reverse-ordered forwarding chains (N=128) drop from16,900to258node visits (130to1pass) andK=24dependency chains drop from300to24owner scans (69,600to5,568syntax visits and15,283to408node visits) while preserving identical emitted nullability, catalog isolation, and runtime behavior. -
Repository compiler uses published SDK 0.5.803. The bootstrap pin moves from 0.5.793 to the package published on nuget.org. Removed 42 redundant
!!assertions that the released compiler reports as GS0536 (src/Coreandsrc/LanguageServer). The sample PE baseline records the published extension assembly version; method bodies remain unchanged. The .NET SDK version and analyzer-testing dependency remain unchanged. -
SemanticModel.GetExpectedTypeanswers for imported, generic, and named-argument slots (Fixes #6223). Imported method, extension, and constructor slots now read parameter types through the ADR-0193 readers (MemberLookup.GetClrMethodParameterTypeSymbol) with constructed generic receiver and type-argument substitution, answering when every matching candidate agrees on both type and nullability (T,T?,T!). Named-argument slots (F(b: |)) resolve by parameter name across matching source and imported candidates (returningnullon unknown, duplicate, out-of-order positional, or disagreeing candidates). Generic function, method, extension, and constructor slots infer type arguments from explicit type arguments, receiver types, and arguments preceding the slot, returning the substituted parameter type when uniquely fixed andnullwhen unfixed or conflicting.CallCandidateRecorderrecords constructor candidate groups for both succeeded and failed source and imported constructor calls whenRecordMemberGroupsis enabled. -
Semantic model answers for chained member function-value calls and failed argument-layout calls (Fixes #6222, #6221). Calls through member function values (
BoundIndirectCallExpressioninBuildDelegateMemberInvocation,BindNamedDelegateInvokeCall, andBuildIndirectDelegateCall) retain theirCallExpressionSyntaxanchor and receiver-chain traversal (SemanticModel.ReceiverOf), so calls in the middle of an accessor chain (c.G(x).ToString(),c.Inner.G(x).ToString(),o.Inner.Fp().ToString(),h.Inner.Fs[i](x).ToString(),o.Inner.Callback(x).ToString(),StaticHolder.SD(x).ToString(),StaticHolder.Fs[i](x).ToString()) answer their member symbol and result type while keeping intermediate receiver and static-qualifier queries accurate;TryBindClrDelegateMemberInvocation/TryBindClrStaticDelegateMemberInvocationmarkCalleeIdentifierand record failed callees, andSemanticModel.GetSymbolInfounwrapsBoundNullConditionalAccessExpressionrather than surfacing its synthetic capture variable. Calls whose argument list failsTryAnalyzeCallArgumentLayout(GS0245duplicate named arguments) continue binding arguments and resolving callees/candidate sets under diagnostic truncation (including queuedliteralTargetDiagnostics), deferred span scope cleanup (BindCallArgumentsForLayoutRecovery), narrowing rollback, and preserving nested completedBoundErrorExpressionresults, keeping argument, callee, andGetMemberGroupanswers without changing diagnostics. -
Emit reified generic CLR indexer calls (Fixes #6234). Indexers on imported generic types now use their selected accessor and constructed receiver type instead of legacy non-generic
IList/IDictionarydispatch. GenericImmutableArray[T]indexing produces valid IL without a runtime crash, and mutable struct indexers retain their original receiver storage. -
Narrow switch arm bodies and switch-expression arm results from
whenguards (Fixes #5643).StatementBinder.BindSwitchArmHeadernow classifies thewhenguard withComputeConditionNarrowingInOrderafter applying the guard's own side-effects to the pattern frame and outer narrowings, merging the guard's when-true facts intoSwitchArmHeader.Framewhile keepingPatternFrameseparate forReapplySwitchArmHeaderEffects. Switch-expression arm results and switch-statement bodies observewhen s != nil,s != nil && s.Length > 0,s is Derived d,s?.Length != nil,readonlyfield guards, and backward-gotore-narrowings without retaining invalidated facts or leaking facts to sibling arms;cs2gshonors switchwhen-guard narrowing for locals, conditional accesses, qualified andthis/unqualifiedreadonlyfields, multi-label sections, and delayed compound captures while preserving required!!assertions on mutated, nullablevarcatch-all, and unguarded paths. -
Prefix bind: a later source type that hides an imported type (Fixes #6215, ADR-0225 D6.8). With
PrefixRemainder.Nothing, a diagnostic that a later source type can change by hiding an imported type is nowFutureDependentwith the new reasonlater-type. The test is opt-in: a diagnostic staysFinalonly in a statement of a function body that uses keyword types, locals, parameters and their members; any other diagnostic getslater-type. A host that does not expect later types to hide imported ones can treatlater-typeas final. -
Key
ReturnSourceIsNullablevisited state byrequirePromotionincs2gs(Fixes #6038).ObliviousNullabilityAnalyzer.ReturnSourceIsNullablenow includesrequirePromotionin its visited-set key(Symbol, Path, Depth, RequirePromotion)so an earlier narrowed (requirePromotion: true) traversal cannot suppress a later unnarrowed (requirePromotion: false) full-contract traversal of the same projected source acrossif, ternary,switch, coalescing, tuple-source, and cross-owner branches. -
Prefix bind: successive cuts in a member body of a script reuse the declarations (Part of #6178, ADR-0225 D6.6).
Compilation.BindPrefix(..., previous)now reuses the global scope for a file with top-level statements when the two prefix trees share their text, the declarations are kept with both cuts in a member, no function suspends or infers its return type, and neither text has ayield, and re-points the globals that the statements declare. On the samples kept as scripts (314 cuts in function bodies, both remainders), 77 of the 125 chained cuts whose prefix keeps top-level statements reused the declarations, with 0 differences from a bind from scratch over all 314 cuts. -
Repository compiler uses published SDK 0.5.793 (Fixes #6226). The bootstrap pin moves from 0.5.767 to the package published on nuget.org. The repository builds without source changes. The sample PE baseline records the published extension assembly version; method bodies remain unchanged. The .NET SDK version and analyzer-testing dependency remain unchanged. This separate pin update requires a clean-clone build and passing CI, including the self-host fixpoint check.
-
Prefix bind: diagnostics that a later better overload or a later member can remove are future-dependent (Fixes #6179). A call that resolves before the cut of
Compilation.BindPrefixcan resolve to a later, better candidate. WithPrefixRemainder.Nothing, a diagnostic whose location contains such a call, or a name of a local whose inferred type such a call gives, is nowFutureDependentwith the new reasonlater-overload(ADR-0225 D6.8). An exact non-generic match, a function value, a constructor, and a member of an imported or closed source type stay final.GS0116(not indexable, noGetEnumerator) andGS0164(noDeconstruct) now have thelater-memberpremise of an unknown member. A later source type that hides an imported type is tracked in #6215. Complete programs report the same diagnostics as before. -
SemanticModel.GetSpeculativeStatementDiagnostics(Fixes #6176, ADR-0229). The new member binds a statement as if it were inserted at a position of the model's text and returns aSpeculativeStatementResult: the classified diagnostics located in the statement, the symbols that it declares, the bound tree and the statement's span. For a prefix tree it isCompilation.BindPrefixof the text with the statement inserted, with the same remainder; for a complete tree, every diagnostic is final. The statement sees the flow state at the position. It costs a bind of the text (about 5 ms at p50 on the samples). -
Semantic model: member-access names, imported constructors, and callees of calls whose arguments do not analyse (Fixes #6217, #6177 item 1, #6197, #6199). The name node of a member access now answers
GetSymbolInfoandGetTypeInfoas its identifier token does, at the end and in the middle of a chain (FirstinDescriptors.Firstand inDescriptors.First.Id), and an inner accessor of a chain answers as its terminal. The call of an imported constructor (StringBuilder(16),List[int32](4)) answers the newImportedConstructorSymbol(SymbolKind.ImportedConstructor) with the chosenConstructorInfo. The callee of a call through a function value whose named arguments do not analyse (f(v: x, v: x),c.G(v: x, v: x)) answers its variable or member. The callee ofc.G(x).ToString()already answered onmain; tests now pin it. Diagnostics do not change. -
Diagnostic.Phaseand a cache forSemanticModel.LookupMembers(Part of #6177, ADR-0223 D7).Diagnostic.Phase(DiagnosticPhase.Parse,Declaration,Body,Emit, orUnknownfor a diagnostic that a host or an analyzer creates) names the pipeline that reported a diagnostic. A semantic model caches the extension members of a receiver type, so repeatedLookupMembersqueries skip the scan of the imported extension methods: on the samples, a query of a receiver type that the model already answered takes 0.075 ms instead of 20 ms at p50. -
Call type-argument and oblivious member-value diagnostics and semantic-model preservation (Fixes #6202, #6201, #6200, #6198). Mixed generic/non-generic overload sets now report
GS0148against the generic candidate(s) when no candidate matches the supplied type-argument count (Mixed[int32, int32](1)). Imported CLR static, instance, extension, and constructor calls with non-matching type arguments reportGS0148instead ofGS0159/GS0130while keeping genuine missing-memberGS0159and valid generic extensions ("abc".Contains[char]('b')). Member and named-delegateInvokecalls with an unresolved type argument (c.M[Nope](x),c.G[Nope](x),n.Invoke[Nope](x)) no longer emit a cascadingGS0159and retain argument and receiver answers inSemanticModel. Calling an@Obliviousmember function value through a receiver (c.G(x, 2),c.G?(x, 2)) unwrapsPlatformTypeSymbolbefore choosing the invocation branch so wrong argument counts reportGS0144and preserve the callee inSemanticModel. -
Retain bound operands across failed
if/switchexpressions,&x/*x, relational patterns, and native-slice indexers forSemanticModel(Fixes #6204, #6205).SemanticModel.GetSymbolInfoandGetTypeInfounwrap captured native-slice index blocks (CapturedIndexArgument) so index expressions answer their own symbol and type in failed operator, compound-assignment, and write expressions (s[x] + c,s[x] += c,s[x] = c,s[r] + c) instead of the temporary receiver capture orBoundErrorExpression.BindIfExpression,BindIfLetExpression,BindSwitchExpression,BindAddressOfExpression,BindDereferenceExpression,BindBinaryOperation,BindConstantPattern, andConversionClassifier.BindConversionretain bound operands, statements, and patterns on failure viaBoundErrorExpressionwithout changing diagnostics or emitted IL. -
Track dynamic control flow when re-seating
ByRefTypeSymbol(var p = &x) locals insideasyncfunctions and async iterators via per-site operand component hoisting and a hoisted slot tag inRefInitializationHoister, keeping non-crossing re-seated locals as nativeMoveNextlocals so unreachable branches (if false { p = &y }), conditional/guard/short-circuit re-seats, and loops never overwrite active pointer targets lexically. (Fixes #6182) -
Bind bare indexed callable calls (
fns[i](x)) as index-then-call (Fixes #6206). When an unqualifiedName[...](...)orName[...]?(...)call parses with aTypeArgumentListunder ADR-0020 andNameresolves to a non-callable variable, field, property, or static/inherited value whose bracket items reshape to index expressions (fns[i](x),fns[jobs[i]](x),matrix[i, j](x),fns[i]?(x)), the binder now resolves it as index-then-call and anchors the reshaped identifier tokens for the semantic model, while preserving generic calls, constructors, Color Color shadows, and #6186GS0148diagnostics on non-generic functions and callable variables. -
Record
emit.method-bodies.parallel-batchesandlowering.emit-lambdas.parallel-batchesdeterministically from scheduled batch workers (Fixes #6207).CompilationWorkBudget.LastScheduledWorkersrecords the worker count scheduled for the most recently joined batch (0for empty,1for sequential,workersfor parallel) separately from the runtime-overlap peakLastObservedWorkers;FunctionEmitterandReflectionMetadataEmitternow increment*.parallel-batcheswheneverLastScheduledWorkers > 1so fast parallel batches no longer under-report0under thread-pool contention while*.observed-workerscontinues to reportLastObservedWorkers. -
Preserve same-condition stable-path narrowing across comparisons, casts, arguments, and nested operators in
cs2gs(Fixes #5954).IsGSharpFlowNarrowedFieldOrPropertyInSameConditionnow climbs through comparisons, arithmetic, casts, arguments, patterns, switch arms, conditional expressions, and nested&&/||operands while checking evaluation-order invalidation, sibling condition effects, closure/by-reference roots, and stable-link separation;GSharpExpressionIsStaticallyNonNullandTranslateCasthonor that narrowing so redundant!!assertions causingGS0536are omitted without dropping required runtime checks on invalidated or unstable paths. -
Format prefix
++and--expressions without spuriousGSF0001round-trip rejections (Fixes #5957).GSharpFormatterrecovers lowered increment/decrement AST parents for++and--tokens during trivia binding, distinguishes prefix from postfix increment/decrement by operator/operand position so prefix operators stay spaced on the left and tight on the right, and compares increment/decrement AST nodes by semantic role (Target,OperatorToken,Value,ReturnsPreviousValue) rather than synthetic zero-width literal source order. -
Index conditional preprocessor state once per syntax tree in
cs2gs(Fixes #6034).TranslationContext.IsPreprocessorSymbolDefinedbuilds an ordered per-syntax-tree index ofCSharpParseOptions.PreprocessorSymbolNamesand active#define/#undefdirectives (in a single directive-bearing traversal whenContainsDirectivesis set), replacing repeatedDescendantTriviaprefix traversals inIsElidedInvocationwhile preserving parse-option symbols, inactive#ifbranches, multiple[Conditional]attributes (OR semantics), overridden-method conditions, and elided argument-effect exclusions. -
Type arguments on a non-generic call, and the operands of a failed operator expression (Fixes #6186, #6187). A call that gives type arguments to a function, method, extension function, function-typed field or property, or function value without type parameters (
Use[int32](x)) now reports GS0148, as C# reports CS0308, instead of ignoring the type arguments. Each type argument is bound first, so an undefined type name (Use[Nope](x)) also reports GS0113. When a binary, unary, conditional or compound-assignment operator expression fails to bind, the semantic model now answers the symbol and type of each operand that bound (thexofUse(x)inUse(x) + Use(x, x)), and so do the target and the value of a compound assignment that has no operator. The diagnostics of these operator expressions do not change. -
Semantic model: the callee of a call through a function value (Fixes #6189). The callee of a call through a local, a parameter, a field or a property of function or delegate type now answers
GetSymbolInfoandGetTypeInfowhen the call fails to bind, as it does when the call binds: wrong argument count, or a nullable value called without?(...). Before,finf(x, 2)answered nothing. The callee of a member function value called through a receiver (c.G(x),c.G?(x), a CLR delegate fieldc.D(x)) now answers its field or property whether the call binds or not. The call and the arguments answer as before, and diagnostics do not change. An argument whose conversion fails still answers nothing (#6190). -
Keep short member chains together in wrapped expressions (Fixes #6180). The formatter groups each logical, additive, coalescing, and pattern operand inside its enclosing line or argument group. A long expression can wrap between operands without splitting short chains such as
!from.ClrType.IsValueType. Long chains and indentation-sensitive chains still wrap to the existing 120-column limit. Fit checks consume the pending render stack lazily instead of copying its unvisited suffix for every operand. Repository source adopts the corrected canonical whitespace. -
Artifact handoff manifest verification in CI (Fixes #6181).
build/artifact-manifest.shwrites a deterministic SHA-256 and byte-size manifest (artifact-manifest.sha256with an end-of-manifest entry count marker) whennuget-packagesandtest-build-outputsare archived, and verifies every download immediately across all six ReadyToRun smoke platforms, desktop MSBuild smoke, test shards, and release publishing jobs (upgradingactions/upload-artifacttov7andactions/download-artifacttov8with enforced digest verification).e2etests/r2r-compiler-e2e.shandbuild/release-publish.pyalso verify the manifest when present while preserving the six-RID package inventory requirement. -
Use the packaged Visual Studio Marketplace publisher (Fixes #6167). Release publishing uses the existing
Microsoft.VSSDK.BuildToolspackage pin instead of the hosted Visual Studio installation. Keep its publisher, binding configuration, and dependency files together. Check the MSAL assembly version before publishing. Windows CI initializes the packaged authentication client without credentials and rejects a mismatched assembly configuration. Marketplace version checks and duplicate-publish behavior remain unchanged. -
Top-level by-ref-like (
ref struct) bindings in entry-point locals (Fixes #6169; ADR-0228). Top-levelSpan[T],ReadOnlySpan[T],span[T],readonly span[T], and user-declaredref structbindings in executable compilations now live in entry-point local slots on<Main>$using the#3215non-hoisted storage path, without emitting<Program>static fields. Library compilations (GS0219/GS0285), accesses from declared functions or lambdas (GS9004), values live acrossawait/suspension or captured bygo(GS0219), heap escapes (GS0219), and cross-submission REPL persistence remain rejected. -
Body-local delta check with analyzer time budgets (Fixes #6183; ADR-0227 follow-up). When
DeltaOptions.AnalyzerOptionssetsTimeBudgetMilliseconds, the body-local delta check no longer always binds the whole compilation. The baseline records the time of each analyzer, and the check runs the body-local analyzers on the edited body when each analyzer's baseline time plus its time on the new body is not more than half the budget. Otherwise it keeps the full bind. The diagnostics are the same as the full bind's. The language server's full gate for data-defined fixes now uses the body-local check when its analyzers are body-local and fast. -
Body-local checks for the nullability-funnel analyzer (Fixes #6184; ADR-0227 follow-up).
NullabilityFunnelAnalyzer(GSA0007) now declaresAnalyzerScope.MemberBodythroughAnalysisContext.ConfigureScope, so the body-local diagnostic-delta check can run it on the edited body instead of binding the whole compilation. Its diagnostics do not change. -
Select the placeholder of a fix for clients without snippet edits (Fixes #6185; ADR-0227 follow-up). When a client declares
window.showDocument.supportbut gets no snippet edits, a fix with placeholders now carries the commandgsharp.selectPlaceholder. The client runs the command after it applies the edit, and the language server sendswindow/showDocumentwith the first placeholder (such asdefault /* TODO: value */) selected. Other clients keep the current behavior. -
Bind-order-independent call-effect summaries, body-local analyzers and plain placeholders (Fixes #6162, #6164, #6165; ADR-0227 follow-ups). A call-effect summary whose effects depend on whether the root of its traversal takes a sequence is now cached once for each answer, so flow narrowing (and the GS0158 and definite-assignment diagnostics that follow from it) no longer depends on the order in which members are bound. An analyzer can declare
AnalysisContext.ConfigureScope(AnalyzerScope.MemberBody)when it registers only bound-node and bound-body actions that read one body; when every analyzer ofDeltaOptions.Analyzersdoes, the body-local delta check runs them on the edited body and keeps their earlier results for the other bodies, and any other analyzer keeps the full-bind check. For a client without snippet edits, the language server replaces a placeholder that does not bind with a target-typeddefault /* TODO: text */when that binds, and gates the edit that the client gets. -
Repository compiler uses published SDK 0.5.767 (Part of #6166). The bootstrap pin moves from 0.5.698 to the package published on nuget.org. Remove only
!!assertions that the released compiler reports as redundant, preserving required runtime checks. One generic-inference test fixture uses bareTto retain its unconstrained domain under the released nullable-kind rule. The sample PE baseline records the published extension assembly version; method bodies remain unchanged. The .NET SDK version and analyzer-testing dependency remain unchanged. This separate pin update requires a clean-clone build and passing CI, including the self-host fixpoint check. -
Prefix-bind reuse and library-host queries (Part of #6079; ADR-0225 D6.6, D6.7). A new
Compilation.BindPrefixoverload takes thePrefixBindResultof the previous cut and reuses its declarations and the bodies that did not change, with the same classified diagnostics, scope and open constructs as a bind from scratch. On the samples with their top-level statements moved into a function, a chained check costs about half; a file with top-level statements reuses nothing yet.SemanticModel.GetExpectedType(position)gives the type that an argument slot, a typed initializer, areturnor an assignment expects.SyntaxTree.ParseExpressionandSyntaxTree.ParseStatementparse a fragment on its own.GetDeclaredSymbolnow answers for parameter and local declarations, andGetSymbolInfoof a source constructor call gives the choseninit. -
Prefix-bind finality of overload, argument, operator and conversion diagnostics (Fixes #6078; ADR-0225 D6.5). With
PrefixRemainder.Nothing,Compilation.BindPrefixnow reports an overload-resolution or argument failure (GS0144,GS0151,GS0154,GS0266and related reports) asFutureDependent:later-declarationfor a simple-name callee,later-memberfor a member callee. A call of a local or a parameter of a function type staysFinal. A conversion diagnostic of a function-literal or untyped argument gets the premise of its call. An undefined operator (GS0128,GS0129) islater-member, because a later receiver-formoperatorcan declare it, and a missing conversion or a switch-expression arm mismatch that involves a type of this compilation or an imported type islater-declaration, because a laterfunc operator implicitcan declare it (after a later type that hides the imported one).gotolabels of function literals, lambdas, rich anonymous methods, static initializer blocks and top-level statements, and the missing-arm, exhaustiveness and arm-type checks of an open switch expression, are now future-dependent when later text can still supply them. A diagnostic of an expression that ends at the cut isrest-of-statement, because a postfix continuation such as.Lengthcan change the expression. WithKeepDeclarationsthese reports stay final, as before, except for simple-name callees in the top-level statements or in a function literal of the open member. -
Verify C#
paramsmethod-group conversions (List<T>, arrays,IEnumerable<T>) throughcs2gswith strict IL verification and confirm unknown method-group consumers preserve non-null element contracts. (Fixes #6001) -
Gate
CSharpTypeMapper.NormalizeAnonymousProjectedStoragewidening on oblivious (NullableAnnotation.None) reference elements and type arguments, reconcile same-shape anonymous storage across mixed nullable/oblivious contexts inMergeAnonymousShapeContractsandMergeAnonymousNullability(unwrappingNullable<T>wrappers), and project element nullability throughApplyMappedArrayElementShapeandEnumerable/Queryableelement-returning calls so#nullable enablenon-null array, tuple, and generic type arguments—including enclosing type arguments on nested types such asDictionary[Alias, string].ValueCollection—are preserved without spuriousGS0159errors while keeping oblivious and explicitT?element contracts widened. (Fixes #6159) -
Answer
GetSymbolInfo,GetTypeInfoandGetBoundNodefor expressions inside a function literal body as in a function body (in an expression-bodied literal such as() -> c.N, the expression answers), and for the arguments and the receiver of a call that fails to bind (wrong argument count, no applicable overload, a missing function or constructor, or GS0159 on a receiver that may be nil). The arguments the binder bound keep their symbols and types, as the receiver of a failed member access does (#6127). Diagnostics do not change. The GS0156Convert to 'T'fix now also applies inside a function literal body. (Fixes #6149, #6150, #6151) -
Published 0.5.767 documentation (Part of #6166). The default 0.5 snapshot uses the release tag, with matching installation instructions and independently verified downloads. Released native-feature guidance keeps stable fragment links and uses function-local span examples. Scrollable Markdown tables receive keyboard focus without adding tab stops to non-scrolling tables. The 0.4 and 0.3 snapshots and historical editor captures retain their original provenance.
-
Lower C#
[InterpolatedStringHandler]conversions and handler-typed call arguments uniformly incs2gsacross both source and imported callees and handler types, preserving single-evaluation receiver and forwarded-argument capture,ref/inhandler passing,out boolandbool-append short-circuiting, call-effect invalidation, and assignment-narrowing semantics while leaving ordinary string interpolations native. (Fixes #5965)
0.5.767 (November 21, 2026)
This snapshot is grounded in v0.5.767, commit 30dcc01a948ce5f876e73f715461a6896bc950d3, published November 21, 2026 at 20:36:46 UTC. It includes the compiler, runtime and tooling changes recorded below, including nullable type-parameter restrictions and the code-fix service. The following entries preserve the tag's complete release history.
-
Body-local delta check, snippet edits and the Transformations package (Fixes #6128, #6129, #6130; ADR-0227 follow-ups).
DeltaOptions.BodyLocalBind(default on) letsCodeFixService.ComputeDeltabind only the edited function body when an edit stays inside one body and keeps every declaration, and falls back to the full check whenever it cannot show the same result; on a project it is one to two orders of magnitude cheaper. When the client declaresworkspace.workspaceEdit.snippetEditSupportand appliesdocumentChanges, the language server sends a fix with placeholders asSnippetTextEdits with one tab stop per placeholder.GSharp.CodeAnalysis.Transformationsis now packed as a NuGet package with its JSON schema. A delta snapshot made byCompilation.WithReplacedSyntaxTree(s)without explicit references now reuses the compilation's reference resolver. -
Data-defined transformation programs (Part of #6119; ADR-0227 D6). The new assembly
GSharp.CodeAnalysis.Transformationsreads aTransformationProgramfrom JSON (schema:transformation-program.schema.json): a diagnostic trigger, a tree pattern anchored at the diagnostic with named captures, guards from a closed set of syntax and semantic predicates, and replace/delete/insert edits with${capture}templates. Unknown properties, predicates and operations are rejected at load time, and a program'sVersionis the SHA-256 of its canonical JSON.ProgramFixProviderinterprets programs as a data-defined code-fix provider; the language server runs the full delta gate on data-defined fixes. The assembly is packed as a NuGet package since #6130. -
Compiler suggestions on diagnostics (Part of #6119; ADR-0227 D2 option b).
Diagnostic.Suggestionsholds the fixes that the compiler already knows at the report site, asDiagnosticSuggestion(message, equivalence key, applicability, text changes). GS0273 suggestsnilfornull, and GS0302 suggests:for the deprecated->switch arm.CodeFixServiceoffers each suggestion as a fix before the providers' fixes. Suggestions do not take part in diagnostic equality. -
Numeric-conversion and cross-file code fixes (Part of #6119; ADR-0227 phase 2). GS0156 between two numeric types (including
nint,nuintandchar) getsConvert to 'T', which wraps a simple operand inchecked(cast[T](expr)), so an out-of-range value throws instead of wrapping; compound assignments and tuple elements get no fix.CodeFixContext.RegisterMultiDocumentFixandMultiDocumentEditorlet a fix edit several trees of the compilation; thelet→varfix now edits a field declared in another file of a partial type. -
FixAll for code fixes (Part of #6119; ADR-0227 D3).
CodeFixService.FixAllapplies every fix with an equivalence key (or the first fix of each diagnostic) atFixAllScope.Document,ProjectorSolutionscope, like Roslyn's batch fixer: each round computes the fixes against one snapshot and keeps the fixes whose changes do not overlap or touch.FixAllOptionssets the minimum applicability (machine-applicable by default), the number of rounds and an optional delta gate.FixAllResultlists applied and dropped fixes with the reason, the changed documents and the new compilations. The language server offerssource.fixAll.gsharpwhen the client asks for it. -
Language-server code actions use the code-fix service (Part of #6119; ADR-0227 D7).
textDocument/codeActionreturns the Core and analyzer-assembly fixes for the diagnostics in range (syntax, declaration, body and, when a provider fixes them, analyzer diagnostics), withdiagnostics,isPreferredandcontext.onlyfiltering. Each fix passes the syntax stage of the delta gate. The server now declaresresolveProviderand handlescodeAction/resolve, records the client's document version, and emits versioneddocumentChangeswhen the client supports them. The ADR-0099 nullability fixes moved to Core with the same titles and edits. -
Built-in code fixes for common C#-isms (Part of #6119; ADR-0227 D8).
CodeFixRegistry.CreateDefault()now has providers fornull→nil(GS0273),new T(...)→T(...)for a reference type (GS0125),let→varon a reassigned variable (GS0127),or/and→||/&&andnot→!(GS0125, GS0130), and the ADR-0099 nullability fixes (GS0158, GS0154/0155/0156). Compiler diagnostics now keep theirDescriptorand a newDiagnostic.MessageArguments, so fixes no longer parse message text;GetDiagnostics()results do not change. -
Diagnostic-delta gate for code fixes (Part of #6119; ADR-0227 D4).
CodeFixService.ComputeDeltaparses each changed document, stops when the parse adds a syntax diagnostic, and otherwise binds a snapshot compilation (Compilation.WithReplacedSyntaxTrees) under the request's own work budget. It compares the diagnostics of the whole compilation before and after the complete edit set by document, ID, severity, message and mapped span, after the host's severity filter.DeltaPolicynames the gate rules:NoNewDiagnostics(the default),RemovesTargetNoNewErrors,NetImprovementandPhaseAware(for fixes of parse errors only). The host's compilation does not change. -
Code-fix API and span editor (Part of #6119; ADR-0227).
GSharp.CoreaddsTextChange,SourceText.WithChanges,SyntaxEditor,SyntaxNode.DescendantTokensandSyntaxNode.FindToken, and theGSharp.Core.CodeAnalysis.CodeFixesnamespace:CodeFixwith an equivalence key and anApplicability,GSharpCodeFixProvider,CodeFixRegistryandCodeFixService.GSharpAnalyzerHost.LoadCodeFixProvidersloads@GSharpCodeFixProvidertypes from analyzer assemblies. A provider that throws reports GS9308 and gives no fix. -
Preserve P/Invoke return marshalling overrides (#6072). Emit return-target
MarshalAsdescriptors forDllImportand bothLibraryImportmethods. Preserve other return attributes, diagnose unsupported return forms, and keep unannotated boolean defaults unchanged.
Breaking Changes
- Source nullable type parameters require a known kind (Fixes #6040, #6043, #6057, #6060; ADR-0224). Source
T?annotations and operators that create nullable results or binding-header storage reportGS0641unless constraints prove reference kind or nonnullable value kind. Diagnostics point to the annotation or source operator, including theletkeyword in nullable binding headers. Useclass/class?, a sufficient reference-class bound,struct, orunmanagedfor the API's actual domain.notnull, interface-only bounds, and a dependent parameter's bareclassbound are insufficient. Use ordinary unconstrainedTwhen callers supply a complete nullable argument, such asId[int32?]. Mixed APIs can require separate reference/value contracts. Imported CLR nullable annotations and the repository's published SDK pin are unchanged. This restriction replaces the draft return adapter and unimplemented companion proposal; it introduces no new nullable ABI.
Bug Fixes
-
Keep constructor call parentheses on zero-argument generic collection initializers in
cs2gswhen the initializer is empty or begins with an identifier key (Dictionary[K, V](){ key: value }), preventinggscfrom misparsing the brace as a struct literal (GS0158or silent property writes). (Fixes #6011) -
Narrow nullable receivers and stable intermediate
?.chain members when a conditional-access result is compared withnil(!= nil,nil !=,== nilelse/early-exit branches, conditional expressions,&&/||,is not nil/non-nil patterns, method calls, and?[]indexers), while preserving side-effect invalidation when a getter, call, or index mutates the receiver. (Fixes #6042) -
Substitute constructed interface type arguments through
base[Interface[Args]].Membercalls, parameters, generic interface method type arguments, default interface properties, value-type (struct) receiver boxing, async/lambda forwarders, and imported C# default interface methods, while rejecting mismatched interface type arguments withGS0338. (Fixes #6045) -
Allow writable
ref this,out this, and&thisin non-constructor struct instance methods and property accessors (preservingldarg.0receiver identity, rejecting constructors with unassignedthisviaGS0239, rejecting classthisand captured lambdathisviaGS9005), and emitref this/out thisincs2gsfor writable struct receiver calls andthis refextensions. (Fixes #6064) -
Preserve symbolic element types and declaration-site nullability across imported generic constructor parameter conversions and
paramsarray expansion, acceptingnilat nullable generic constructor slots and matching symbolicparamselements while preserving invariant slice and generic-argument rejection. (Fixes #6059, #6061) -
Settle nested conditional capturing local-function values as ordinary function values that shadow same-signature outer and forward-declared siblings, while preserving distinct outer callable overloads and keeping capture-free local functions delegate-free. (Fixes #6112)
-
Bind the body of a
for … inorawait forloop whose collection cannot be iterated (an unresolved collection, or a type that is not enumerable), with error-typed loop variables. The body's own errors are now reported, and the semantic model answers its declarations and type clauses. (Fixes #6140) -
Parse nested indexers followed by member access (
samples[jobs[slot]].Key) as indexers instead of generic type names unless an inner type argument is unambiguously type-shaped, and reshape index-shaped nested generic static receivers (Box[List[int32]].Create()) in the binder. (Fixes #6071) -
Normalize
nintandnuintoptional parameter default values toint32anduint32CLR Constant metadata, rejecting out-of-range defaults with GS0265 and converting omitted call-site arguments to native-width integers. (Fixes #6073) -
Report targetless method groups (
GS0582) and inapplicable nullable-receiver member reads (GS0158) instead of discarding them toBoundErrorExpressionacross operators, indexers, switches, and assignments, avoiding silent?-typed locals andGS9998crashes in emit. (Fixes #6077) -
Reify synthesized anonymous object types over referenced generic type parameters from generic local functions, methods, classes, and nested generic scopes. Preserve deterministic parameter ordering, same-shape deduplication,
data objectvalue semantics, and rich anonymous object enclosing-scope mappings. (Fixes #6109) -
Convert capturing forward-recursive local functions to function values and compatible delegates. Preserve callback identity and shared capture cells across direct calls, escaped callbacks, and loop iterations. (Fixes #6105)
-
Report
GS0325at the declaration for bodyless top-level functions, extension functions, receiver-clause operators, and conversion operators without@DllImportor@LibraryImport, and skip body binding whenBodyis absent sogscexits with diagnostics instead ofGS9998or emitting an empty method. (Fixes #6116) -
Allow overloaded explicit interface indexers with distinct parameter signatures on the same interface while still reporting
GS0495for duplicate signatures, and align metadata-only explicit property accessor names with emitted runtime accessors. (Fixes #6125) -
Preserve
refandincontracts across primitive/value-type extension receivers, non-identifierinoperands (in this,in x.Value,in xs[0]), and sourceref readonlyparameter declarations and calls incs2gswithout copying storage operands. (Fixes #6063, #6052, #6047) -
Preserve non-null delegate field contracts for nullable-result callables and bridge genuinely nullable delegate receivers on unconditional invocations, propagate oblivious nullable storage into implicit collection-initializer
Addparameters, and propagate inferred nullable task payloads through synchronousGetAwaiter().GetResult()reads incs2gs. (Fixes #6051, #6046, #6035) -
Replace recursive closure-chain traversal and full callable-state copies in
StatementBinder.AssignedRootsCollectorwith an explicit heap work stack and immutable persistent state. Deep closure-call chains no longer overflow the compiler host stack or allocate quadratically, while preserving callable provenance, argument-dependent effects, cycles, and captured-write invalidation. (Fixes #6111) -
Lower open generic
T?anddefault(T?)incs2gsto bareTanddefault(T)when type-parameter constraints do not prove a reference or value kind under ADR-0224, while preservingT?for provenclass/class?/struct/unmanaged/concrete-reference bounds and preserving runtime semantics across callers, overrides, generic interface property bridges, async awaited forwarding, and??=without throwing assertions. (Fixes #6113) -
Keep the SDK reference-assembly pack regression independent of installed Android workloads. Retain four inner builds and exact effective-framework path checks. (Fixes #6032)
-
Preserve symbolic receiver types in imported method labels for hover, signature help, and member completion. Show source-defined arguments instead of erased
objectplaceholders. Keep fixed-array lengths, tuple names, and declared return nullability. Keep declared signatures separate from call-result narrowing. (Fixes #5492) -
Set
MALLOC_MMAP_THRESHOLD_=131072for mirroredcs2gsdotnet testruns. With this fixed glibc threshold, freed native blocks of 128 KB or more return to the OS. Under hosted-runner limits, the self-migratedCs2Gs.Teststesthost peaks at 4.9 GB instead of 15.3 GB. Build environments do not change. (Fixes #6096) -
Preserve non-null assignment facts from ordinary extension-call receivers, including imported extensions. Receiver-side
??=no longer causes a false GS0158 after the call. Keep later assignments and by-reference writes invalidating those facts. (Fixes #6107) -
Preserve function values for capturing
letliterals that call earlier local functions. Keep forward references, outer/local overloads, and capture-free functions directly callable without allocating extra delegates. Bind capture-free functions as methods, including generic async and nested recursive helpers; bind closure values afresh without leaking speculative diagnostics or capture state. Reconcile nested capturing overloads and validate the final method host before publication. Revalidate source-level capture proofs after symbol-role changes to avoid repeated nested binding. Journal speculative retry-cache writes instead of copying growing caches. Keep shadowed address-of locals and nested functions from changing the enclosing closure's value representation. Separate capture-free method eligibility from required forward signatures; use shared run-eligibility decisions for inner function values and ignore qualified member names while preserving applicable outer callable overloads, including optional and variadic parameters. End forward regions at the last applicable overload and compare semantic identifier names, including escaped spellings. (Fixes #6082) -
Reject constructor initializer targets other than
basewith GS0642 instead of silently calling a base constructor. Useconvenience init() { init(args) }for same-class chaining. (Fixes #6074) -
Cover stored
Func[T]factories passed to imported generic methods with dependent constraints. Runtime regression tests preserve delegate invocation counts and results for the symbolic applicability correction in #6058. (Fixes #6088) -
Match imported data types by CLR declaration and semantic type arguments when converting method groups. A forwarding lambda in another scope no longer causes GS0218 for a compatible shared callback. (Fixes #6090)
-
Resolve calls to parameters and locals named
closethrough ordinary callable lookup, including nested callbacks. Keep unshadowed retired-builtin diagnostics. (Fixes #6089) -
Accept nullable managed-reference resources in
using letandawait using let, including conditional initializers. Dispose non-nil resources once and skip nil resources. (Fixes #6087) -
Bind bare address-of arguments to managed
ref,out, andinparameters in unsafe shared methods, including P/Invoke calls. Preserve storage-type checks and generic forwarding. (Fixes #6086) -
Initialize repository version metadata before G# build preparation when NBGV targets are imported, including projects that disable generated version sources. Preserve cold restore-and-publish evaluations before those imports exist. Build Extensions without a bundled self-reference and reuse its graph output for SDK packing. Unchanged builds retain identical metadata and skip compilation. Keep stage-2 certification's exact SDK target inventory current. (Fixes #5116)
-
Admit conversion operators whose owning class appears through a nullable reference type. Preserve nullable operand and return contracts. Reject same-type conversions and duplicate signatures that differ only by reference-nullability annotations. Translator acceptance remains gated on a released compiler SDK pin. (Fixes #6024)
-
Include accessible static members of constructed imported types in language-server completion, including trailing dots and unfinished member names. Keep instance members and constructors out of type-qualified suggestions. (Fixes #6019)
-
Preserve explicitly nullable reference type-parameter storage passed as a complete inferred method type argument in
cs2gs. Do not add a throwing assertion when the unconstrained argument does not reach the result. Keep concrete reference inference, fixed storage, authored forgiveness, synthesized explicit type arguments, constraints, and the broader oblivious generic-store bridge policy unchanged. (Part of #4612; prerequisite for #6044) -
Reject ref-struct type arguments in ordinary generic constructor calls with GS0219, as in type declarations. Check symbolic arguments before erasure, including source constructors and open generic owners. Preserve imported parameters that allow ref structs. (Fixes #6015)
-
Preserve the inferred platform reference type in
x ?? nil. Oblivious imported references retain their null values and evaluation order. (Fixes #5565) -
Symbolic imported-call arguments (Fixes #6055, #6056). Constructor and method overload selection uses source type conversions when CLR erasure surrogates differ or falsely agree. Enum-valued dictionary properties bind matching copy constructors; incompatible invariant enum-to-integer generics are rejected instead of emitting invalid IL. Genuine generic identities retain their overload rank, while unrelated implicit operators do not block structural projections.
-
Fewer cascading parse diagnostics (Oats). The parser reports
GS0005once for each token where it stops, sofunc f( int32 {gives oneGS0005, not two. The binder does not reportGS0113"Type ''" for a type name token that the parser synthesized. -
Public entry-point and internal-error diagnostics for library hosts (Oats, ADR-0223).
Compilation.GetMissingEntryPointDiagnostics()(GS0634) andCompilation.CreateInternalErrorDiagnostic(Exception)(GS9998) are public, so a host can report them asgscdoes. ADR-0223 proposes packaging, hermetic reference sets, an explicit runtime directory, and a thread-safety contract. -
Gsharp.Compilerpackage for library hosts (Oats, ADR-0223 D2). A new NuGet package,Gsharp.Compiler, containsGSharp.Core.dllwith its XML documentation and PDB. It has the same version asGsharp.NET.Sdkand comes from the same build. Its dependencies includeSystem.Reflection.MetadataLoadContext, so a host does not add it by hand. The G# runtime assemblies are underruntimes/gsharp/. The SDK now ships one copy ofGsharp.Extensions.dllandGsharp.Runtime.Channels.dll: before,tools/compiler/,tools/gsgen/, andtools/formatter/had the bootstrap SDK's copies. (Fixes #6067) -
Hermetic reference sets for library hosts (Oats, ADR-0223 D3).
ReferenceResolver.ForReferencePack(targetFramework, packRoot)builds a resolver overMicrosoft.NETCore.App.Ref/<version>/ref/<tfm>and the bundled G# runtimes. It does not use the assemblies that the host process has loaded.ReferenceResolver.CaptureHostAssemblies()andReferenceResolver.WithRuntimeReferences(referencePaths, hostSnapshot)are public, so a host can capture the host assemblies once, asgscdoes. The documentation ofDefault()andWithRuntimeReferencesstates that their result depends on the host process. (Fixes #6065) -
Thread-safe shared
ReferenceResolveracross concurrent compilations (Oats, ADR-0223 D5).Compilationpasses its consumer assembly name explicitly into binding and emit instead of mutatingReferenceResolver.CurrentAssemblyName.ReferenceResolverkeys semantic aggregates and visibility-scoped type resolution by consumer assembly name, so interleaved or concurrent compilations with differentAssemblyNamevalues isolateInternalsVisibleToaccess and share one resolver safely. (Fixes #6070, Fixes #6068) -
Explicit bundled runtime directory for library hosts (Oats, ADR-0223 D4).
ReferenceResolver.Default(runtimeDirectory),ReferenceResolver.ForReferencePack(targetFramework, packRoot, runtimeDirectory), andReferenceResolver.ResolveDriverReferencePaths(referencePaths, runtimeDirectory)take the folder of the bundled G# runtime assemblies. The search order is the argument, then the folder beside the application, thenGSHARP_SDK_TOOLS_DIR. The internal process-wideReferenceResolver.SdkToolsDirectoryis removed.gscandgsikeep their search order. A library host that sets onlyGSHARP_SDK_TOOLS_DIRnow gets the files beside the application first.ForReferencePackhas a third optional parameter; it is not released yet. (Fixes #6066) -
Bind an incomplete program (Oats, ADR-0225, part of #6075).
Compilation.BindPrefix(tree, cut, options)binds a tree as if its text ended atcut. The parser closes each delimiter that is open at the cut, so the host writes no seal. Each diagnostic isFinal,FutureDependent(a later declaration, the rest of an open body or the remaining members of an open type can remove it) orArtifact(the cut caused it), with a reason. The result also has the scope and the open constructs at the cut.PrefixRemainder.KeepDeclarationskeeps the declarations after the cut for a fill-in edit. Diagnostics of complete programs do not change. -
One diagnostic for a property initializer (Oats).
prop X T = valuereports the newGS0640once at the=token. Before, the=started a field declaration and causedGS0113(Type ''),GS0288, andGS0005. ThePropertyDeclgrammar still has no initializer. -
No GS0573 after an unresolved
catchtype (Oats). Acatchclause whose type does not resolve reports onlyGS0113. It no longer counts ascatch (System.Exception)in the unreachable-clause check, and later clauses do not shadow it. -
No GS9002 for a redeclared inline
outlocal (Oats). A redeclaredout let nameorout var nameat an imported call reports onlyGS0102. The by-reference argument check skips error arguments, which already have a diagnostic. -
Generic tuple reference returns (Fixes #6039). Generic substitution preserves source tuple types inside nullable and nested generic containers. Reference aliases retain their original storage and nullability contracts.
-
Assignment-narrowed conditional indexing in
cs2gs(Fixes #5936). Non-null assignments, null-coalescing assignments, and branch joins use ordinary indexing with nullable result casts. Nullable writes, control-flow entries, escaped closures, exception filters, disposal exits, and mutable capture boundaries end assignment facts. Nullable declaration initializers and erased C# suppressions retain conditional indexing. Non-null contracts and casts retain runtime guards, and platform assignments follow G#'s distinct plain-assignment and??=rules. Analysis memoizes recursive queries. Chained stores, condition roots, and null-coalescing values retain evaluation-order invalidation and runtime null guards. Nullable nested stores retain their result types. Conditional and switch??=arms use G#'s non-null proof without adding throwing assertions to null-preserving contracts. Coalescing result classification includes valid incoming facts; compound-assignment results do not inherit their operands' runtime proofs. Indirect reference stores remain separate from direct local assignments. Annotation-only inputs and stable receiver paths use the shared assignment proof. Branch joins validate loop-carried provenance before exporting facts. Initializer mutations follow evaluation order and half-open effect boundaries, including contextual conversions and enclosing compound calls. Overloaded null comparisons retain C# operand typing and do not establish nil guards; lifted, string, compiler-recognized managed-handle, and retargeted analyzer comparisons retain native behavior. Lowering and effect analysis use the same classification. Managed-reference expression-tree callbacks retain their projected contracts. Suppressed null literals retain operator dispatch and nil guards. Optional RHS operands do not export skipped-path assignment facts. Declaration-style for headers and expression-statement arguments share mutation analysis, including conversions, later effects, and one-time header invalidation. Params-array null tests retain runtime identity checks for explicit null arrays from external CLR callers. Elided partial and excluded conditional calls export no argument facts or effects, including loop clauses. Custom-handler holes retain possible invalidation without exporting optional assignment facts. Hoisted field captures retain their pre-call effect boundary. Evaluated prefixes within statements, expression bodies, and completed conditions share ordered mutation analysis. Constructor effects precede initializer reads, while one-time loop-header reads precede body effects. Plain-assignment results retain nullable storage contracts and bridge non-null sinks once. Erasednameofoperands and dropped closure, reference-alias, or loop writes do not invalidate facts; contextual conversions still do. Prefix reads do not inherit plain-assignment facts before condition completion. Lowered loop incrementors account for intervening body and continue-path effects. Each lowered continue site retains its own prefix and guard facts; shared incrementors join post-cleanup paths. Native for-post expressions retain their separate binding boundary. Unbraced loop bodies retain their root-condition facts. Invalidation skips absent incoming facts and preserves indexed guard-query scaling. -
Keep
cs2gsbuilds valid after writable shared-storage ref arguments (Part of #6036). Emit the required null assertion when G# drops an unrelated local's narrowed state; ref arguments to separate locals remain unaffected. -
Keep
cs2gsnarrowing in step with gsc after writable member-reference calls (Fixes #6036). A call that receives a writable member reference (Interlocked.Increment(ref ctx.Counter)) now ends the narrowing of every reassigned local and parameter. This applies after a null guard and after an assignment, including through a loop's back edge, so the translator emits the required!!. Areforinargument that C# proves non-null, but gsc does not narrow (for example, after a guard through a user-defined==), now carries@SuppressDiagnostic("GS0612"), as a dropped!already does. -
Run nested
cs2gsSDK commands (build,msbuild,test, andrestore) from the repository root so generated projects outside the checkout still use itsglobal.jsonSDK pin. Relative work and project paths still resolve from the caller's directory. Keep external builds without a repository root unchanged.Gsharp.NET.Sdknow resolvesgsharp.generated.runsettingsandgsharp.trimmer.xmlfrom the project directory, not the process working directory. (Fixes #6029) -
Retain erased-array writes and nested anonymous storage contracts (#5326). Treat unrecoverable
System.Arrayelements as unknown writes. Preserve disjoint element proofs before argument conversion erases them. Reuse anonymous constructor contracts for member reads and project native managed-reference and slice elements recursively. Validate stable local results before publishing binder and slice-resolution outputs. -
Keep anonymous evidence and metadata fallback isolated in cs2gs (#5326). Partition merge results by their compilation and catalog/model analysis domain. Retain original untrusted references when snapshot metadata is invalid, so default-reference loads report Roslyn diagnostics without poisoning later loads.
-
Retain scoped anonymous input spellings in cs2gs (#5326). Include recursively rendered aliases and qualifiers in merge-cache input identity. Preserve structural nullability contracts, canonical output deduplication, and evidence grouping.
-
Invalidate external descendant facts at every explicit callee in G# (#5326). Root replacement now drops readonly member narrowings. Generic constructors and event accessors enter the shared call-effect inventory. Canonicalize equivalent native and qualified managed-reference and slice identities in anonymous output while retaining scope-correct incoming contracts.
-
Keep anonymous merge inputs and cached local occupancy distinct in cs2gs (#5326). Key anonymous merges by their incoming physical contracts without changing evidence grouping. Replaying a cached synthesized name now also reserves it in the current body, preventing later deconstruction collisions during retranslation.
-
Preserve semantic allocation paths and physical contracts in cs2gs (#5326). Keep nested tuple temporaries distinct while replaying stable names. Apply nested-type boundaries to replacement helper inventories and reserve names against their emitted owners. Include managed-reference elements and all physical type children in anonymous declaration contracts.
-
Use effective constructor and naming facts in cs2gs (#5326). Preserve array initializer identity, record-struct constructor values, and argument evaluation order when a supplied model replaces a body. Preallocate lifted helpers from effective bodies in model-isolated naming domains and reuse stable source-site names across document orders.
-
Retain output ownership and apply speculative declaration facts (#5326). Keep anonymous declarations across collected contexts and normal/special models without retaining source compilations. Distinguish emitted nullable contracts deterministically. Use replacement-body iterator, suspension, constructor-folding, and partial-type member-usage facts before emitting signatures and storage.
-
Keep catalog declaration ownership and speculative inventories coherent in cs2gs (#5326). Reuse canonical equivalent catalog versions across distinct list instances so anonymous classes are declared once. Retain cancellation and special-model inputs in producer/signature visitors. Overlay speculative method bodies in semantic inventories and body translation, replacing original effects while preserving unaffected declarations.
-
Consume the effective supplied semantic model in cs2gs analyses (#5326). Carry exact owner/tree model provenance through ref-storage, null-flow, tuple, anonymous-shape, and related query builders instead of isolating caches while reading normal models. Preserve normal-peer binding and lazy tuple analysis; unscoped cache inspection now uses the same default analysis domain as normal queries.
-
Keep semantic-model and assembly-image boundaries complete in cs2gs (#5326). Isolate accessibility-aware supplied models across effect, projection, and catalog-dependent caches while normal peers retain shared indexes. Restore implicit root tree-scope fallback without overriding selected producer owners. Preserve original untrusted multi-module references instead of snapshotting only their manifests. Reuse library taint analysis for equivalent bound source classifications without mixing catalog versions.
-
Isolate catalog-dependent semantic state across translation contexts (#5326). Scope linked managed-reference storage, frozen contracts, taint/source classification, and anonymous-shape evidence to the captured catalog version instead of a compilation-wide mutable union. Publish completed reconciliation batches. Preserve supplied accessibility-aware semantic models across nested tree switches without leaking them into normal peers. Keep the loaded-image path-replacement witness portable by renaming mapped files aside before replacement on Windows.
-
Bind effect trust and catalogs to immutable provenance (#5326). Do not trust loaded assemblies through replaceable
Assembly.Locationfiles. Require captured load images or exact canonical compiler framework bindings. Retain the original one-argumentUseSemanticModelForCLR overload. Capture one shared immutable catalog version per translation context, so caller list changes cannot mix old ownership/effect indexes with live projection inputs; new contexts observe new versions. -
Use selected execution and ownership contracts in call effects (#5326). Keep immediate LINQ callbacks immediate when their result type is an enumerable type argument. Share deferred-method decisions across region analysis, bound summaries, and translation. Carry selected owners through projection and initializer queries, retain owned projection-consumer contexts, and isolate corrupt file references without suppressing Roslyn diagnostics. Snapshot tests exercise actual file inputs, shared immutable images, and continued healthy reads. Preserve the five-argument
TranslationContextconstructor ABI for compiled consumers while retaining cancellation support. -
Preserve actual reference images and semantic owners in call effects (#5326). Do not rebind arbitrary Roslyn images through supplied file paths. Carry selected method and caller-callback compilation ownership across shared syntax trees. Share immutable ownership indexes across document contexts with cancellation-safe publication and an active-model fast path.
-
Specify the released
Gsharp.NET.Sdk0.5.698instead of0.5.460-g21e3f30fa3for repository builds. Remove diagnosed redundant null assertions, use explicit byte conversions in nullable-metadata checks, declare the common compilation type for reassignment, and match readonly-reference call modifiers. Keep required runtime null checks and the .NET SDK policy unchanged. (Fixes #6028) -
Renew the independently witnessed, explicitly approved finite runtime certificate for the new compiler output. Retain the old certificate and the same complete two
AsSpandiagnostics. Full ILVerify still reports two known upstream errors; this is not strict-clean verification. Keep rejection controls and upstream tracking open. (Part of #5244) -
Keep the repository's unchanged .NET SDK policy in the hot-reload E2E sample. Watch subprocesses no longer select SDK 11 on multi-SDK hosts. Check SDK selection before starting watch; retain all runtime assertions and wait thresholds. (Fixes #5976)
-
Check imported generic
class,struct, andnew()constraints before reading type-bound constraints. Missing type-bound dependencies no longer bypass known special flags. The older unreadable type-bound fallback remains unchanged pending ADR-0209's post-stage-7 follow-up (#5176). (Fixes #6023) -
Document the twelve acknowledged imported-attribute support gaps, including partial marker readers and the distinction from source attributes. This changes documentation only; compiler behavior is unchanged. (Fixes #5177)
-
Clarify ADR-0209's existing public-copy preference for well-known types, nonpublic fallback, and searched/dependency module partition. Consumer-specific access remains compilation-owned. This changes documentation only. (Fixes #5204)
-
Construct expanded List and span variadic carriers over source-declared elements and generic type parameters. Preserve symbolic element types through ordinary constructor emission, including nullable elements and nested collections. Normal-form arguments retain their carrier identity. (Fixes #6010)
-
Follow widened
cs2gsfield, property, and call-result values into call arguments and reduced extension receivers. Discover forwarding through the existing candidate-filtered read analysis and retain the all-reads-safe fixed point. Collect reads from every canonical linked-source declaration before pruning. Keep fixed contracts, effectful dereferences, and incompatible params carriers pinned. (Fixes #5556) -
Reject release packages whose embedded nuspec ID or version differs from the filename. Reuse package metadata verification before publishing. (Fixes #5550)
-
Preserve nullable scalar storage in oblivious
cs2gsjagged-array allocations. Reuse depth-aware storage contracts for allocations, declarations, aliases, and element reads. Keep nullable array references separate from nullable elements. Range slices keep the array depth; scalar indices consume an element position. Preserve allocation, copy, and row-assignment order. (Fixes #6006) -
Pack expanded collection-params arguments in source extension calls. Preserve whole-carrier identity, generic inference, fixed arguments, and receiver evaluation order. Function values retain their physical signatures. (Fixes #6002)
-
Convert variadic method groups to delegates using their physical parameter signatures. Preserve carrier identity, overload selection, and receiver evaluation. Function values do not gain variadic expansion. (Fixes #6003)
-
Preserve nullable writable storage in flat
cs2gsdeconstruction declarations. Materialize typed locals when tuple inference loses their contract. Reuse ordinary inferred-local nullability, live default-origin analysis, and ref-storage contracts. Preserve nested nullable positions and retain native bindings when inference already matches. Keep required read assertions and evaluate the source once. (Fixes #5994) -
Preserve null forwarded into expanded
cs2gsparams elements for count-only consumers and source forwarders that share element widening. Reuse the null-argument fixed point for declarations, calls, and suppression bridges, including explicit packing through same-run emitted reference assemblies. Check normal-form arguments through their actual constructed collection views. Keep element reads, unknown escapes, generic slots, and incompatible normal-form collections pinned. The authored literal-null policy is unchanged. (Part of #5581) -
Initialize captured switch-pattern variables before evaluating
whenguards. Immediate and escaping guard closures now retain the matched values in both switch forms, including after false guards. Pattern bindings remain read-only. (Fixes #5998) -
Avoid redundant null assertions on inferred deconstruction locals from non-null positional properties. Reuse the emitted declaration's nullability decision. Keep nullable and changed locals guarded. (Fixes #5597)
-
Propagate nullable constructor parameters through guarded readonly field storage in
cs2gs. Keep semantic guard proofs separate from target narrowing across calls. Preserve required assertions or reuse existing captured locals when calls invalidate member narrowing. Keep unsafe handoffs, mutable fields, changed receivers, and deferred reads pinned. (Fixes #5585) -
Omit author-written null assertions in
cs2gswhen an unwidened oblivious source declaration already emits a non-null G# value. Apply the same decision to plain reads, pattern captures, and inferred deconstruction destinations. Keep required nullable, analyzer-mapped, and unknown-value assertions, including bridges into non-null stores. (Fixes #5609) -
Record pattern variables' emitted storage before translating their consumers. Deconstruction stores into non-null switch subpattern locals retain required assertions. Nullable pattern locals still store null without assertions. (Fixes #5605)
-
Allow up to 30 minutes for NuGet SDK indexing and 10 minutes for the VS Code Marketplace post-upload query. Polls stop when the expected version appears. (Fixes #5619)
-
Correct release documentation: the recorded rehearsal accepted duplicate symbol packages with 201 Created; duplicate NuGet packages returned 409 Conflict. This changes documentation only. (Fixes #5620)
-
Show child-process status in hot-reload E2E failures with verbose
dotnet watchoutput. This diagnostic-only change does not resolve the intermittent startup failure. (Part of #5976) -
Use declared storage nullability for writable ref arguments — Passing a nullable-declared variable after a non-null assignment no longer reports a false GS0612 warning. Writable ref matching uses the declared storage contract, while narrowed reads can still prove input safety. Passing non-null storage to a nullable writable parameter still warns, and ref writes invalidate earlier read proofs. (#5949)
-
Reuse raw
cs2gsalias terminals across live projection boundaries with provably separate initializer provenance. Keep shared-terminal boundaries, projected values, and scoped assignment checks live. Bound boundary scans by alias length. Shared-component walks, positive replay, and whole-pipeline switch allocations remain residual work. (Part of #5962) -
Accept declared aliases for qualified nested named types with generic arguments on each segment. Preserve constructed outer identity and existing type binding rules. (Fixes #5983)
-
Omit redundant outer-array assertions in cs2gs nested initializers (Fixes #5978). Array-element bridges use emitted value nullability, so nullable inner elements do not force
!!on non-null outer storage. Required nullable-value assertions remain. -
Print bounded primary SDK failure logs in the Oahu and Code Exploder nightly console without adding them to retained reports. Keep gate results unchanged; the Oahu build failure remains unresolved. (Part of #5977)
-
Schedule source declaration headers and base-member continuations iteratively. Deep acyclic attribute dependencies compile on small-stack workers. Validate complete source contracts and retain late diagnostics. Preserve recursive attribute contracts, source contexts, inheritance-cycle diagnostics, and deterministic emission. (Fixes #5975)
-
Match forwarded handler constructor arguments without treating an
out boolgate as a bool value. Match forwarded ref kinds and reject readonly addresses for writable constructor slots. Capture managed call addresses in source order, preserving null, bounds, and array-type checks. Fixed shared-field addresses still evaluate type initialization before subsequent synchronous arguments. Adapt forwarded values and readonly references to selected constructor parameter types without repeating evaluations. Canonical managed-reference captures preserve chosen storage across suspension. References consumed without suspension preserve address effects at their definitions inside async methods. Overloaded handlers preserve constructor gating and emit valid IL. (Fixes #5966) -
Reduce
cs2gsscalar-alias allocations by sharing immutable syntax facts and invalidating only dependent promoted-local answers. Share scope, write, closure, and guard censuses while retaining live projection bindings and dynamic flow checks. Stop write-index receiver traversal at known reference boundaries, preserving value-type ancestors without retaining every distinct reference-field prefix. Whole-pipeline allocation bounds cover chains and switch fan-out. Live alias walks remain repeated, and whole-pipeline switch fan-out allocation remains superlinear. (Part of #5962) -
Keep call effects on one canonical, completely published graph (#5326). Include selected imported operators, prefer actual project-reference symbols, and snapshot reachable project metadata before compilation. Preserve unreadable references for Roslyn diagnostics. Validate runtime manifest schemas before adding trust, and publish immutable deferred/comparer indexes only after successful scans. Closed source overrides retain their precise effects.
-
Resolve callback implementations and owned operands in call effects (#5326). Include contextual operators and conversions, inherited imported methods, and synthesized record formatting. Treat externally supplied comparers and open collection dispatch as unknown. Share positive framework method models between the compiler and translator. Preserve known construction and default-comparer proofs, and isolate reference-pack root enumeration failures.
-
Share raw
cs2gsinitializer-chain terminals when no live projection boundary is present. Keep terminal projection and assignment checks live. Scalar-chain alias work then scales linearly. Nonempty-boundary walks and whole-pipeline switch allocations remain residual work. (Part of #5962) -
Infer inline
outlocals from substituted generic function parameters, preserving closed reference and value types and caller type parameters. (Fixes #5971) -
Require complete callback proofs for storage effects (#5326). Include direct formatting, open imported callbacks, handwritten enumeration, and private imported comparers. Limit deferred-factory models to verified framework images and each function's own yields. Skip unreadable reference-pack manifests without trusting partial results. Reuse verified runtime image hashes across queries, and synchronize active cancellation tests without timing races.
-
Accept return-target attributes on delegates and emit them on
Invokereturn parameters. Preserve type and parameter attributes. Reject unsupported delegate returnMarshalAswithGS0360instead of omitting required marshalling metadata. (Fixes #5967) -
Keep call-effect ownership and cache lifetimes sound (#5326). Treat unmodeled external dispatch and formatting as unknown writes. Follow source-project operations, event accessors, deconstruction stores, property initializers, actual buffers, and enumerated callbacks. Share immutable reference snapshots per project load and immutable indexes per compilation. Completed pure callback summaries do not consume the recursion budget. Check deferred-factory shapes before framework image verification.
-
Operation-based
cs2gsstorage effects (#5326). Follow implicit accessors, constructor chains, interface slots, formatting, buffers, deferred callbacks, and comparer contracts. Cache completed context-sensitive summaries and observe cancellation. Bind immutable reference images for effect trust without restricting host reference visibility. -
Verify call-effect trust and share storage effects with
cs2gs(#5326). Framework models require installed framework image fingerprints, not matching metadata identities or arbitrary host dependencies. Resolver-local membership and cached discovery cover unregistered host comparers without process-history leaks. Typed call effects now cover translated ordinary statements, condition operands, and loops while retaining disjoint-write and pure-callback precision. -
Callback-aware call-effect summaries (#5326). Include interpolated-string handlers, imported getters, deferred LINQ comparers, recursive tuple formatting, and set/ordering callbacks. Resolve package-qualified storage types conservatively, inspect private imported comparers, and cache call summaries and comparer-factory indexes per compilation.
cs2gsshares the verified imported-assembly identity rule and restores required assertions after unmodeled imported loop calls. -
Share local default-value and deconstruction reachability through sparse alias dependencies and finite tuple-index summaries, including reassigned locals, split aliases, loop-carried cycles and tuple-unboxing cycles. (Fixes #5633)
-
Preserve source
[return: MaybeNull]reference-return contracts incs2gs, including forwarded task envelopes and inherited migrated signatures, without asserting nullable values. Share declared-contract and storage-flow queries across declarations, receivers, assignments, and source-reference boundaries. Keep explicit nullable delegate results, inferred storage, task envelopes, and awaited results distinct. Compose stored task contracts and preserve property, argument, assignment-result, awaited-deconstruction, and eligible source-contract flows. Apply source-owner contracts consistently to storage, owned delegates, and awaited values. Retain bound delegate returns and attributedInvokecontracts. Share reverse reference transfers and stored-tuple deconstruction writes. Preserve inferred contracts at each await depth, including referenced producers. Keep task payload flow across guarded assignments and arguments without widening guarded envelopes. Respect effective speculative bodies,AllowNullwrite contracts, and narrowed producer results. Preserve payload contracts through coalescing and null-warning suppression. (Fixes #5951) -
Keep
cs2gstask contracts consistent across transitive source catalogs, tuple reassignments, and ordinary indexer reads. Preserve each tuple and contract edge's binding owner. Separate substituted argument evidence from open generic declarations. Honor fixed async result contracts before following nullable bodies. Share ref-alias and ref-return storage contracts without confusing task envelopes with their results. Preserve generic task-envelope storage independently from substitutable payloads. Keep output transfers directional and nullable tuple stores assertion-free. (Fixes #5951) -
Bind source attribute declarations before validating applications, including delegate attributes,
@Attributesugar, and recursive attribute dependencies. Read generic attribute contracts from their definitions without losing constructed application types. Delay derived member binding until source base members are complete. ReportGS0639instead of exhausting the stack on excessive declaration dependencies. (Fixes #5968) -
Preserve nullable tuple leaves in generic indexer writes in
cs2gs, instead of inserting runtime null assertions. (Part of #5948) -
Preserve promoted-local null-guard narrowing in
cs2gs(Fixes #5645). Nullable-oblivious translations omit redundant!!assertions on guarded immutable-local receiver and argument reads. Mutable receivers, intervening escaped-closure calls, and mutable capture boundaries retain required assertions. Promoted nullable tuple destinations accept values changed through ref aliases without asserting the yielded value. Destination projection preserves intermediate assignment contracts before following assignment results into nullable arrays. -
Preserve imported nullable tuple leaf contracts during generic identity and hierarchy conversions. Resolve CLR nullable members on symbolic optional tuples; a nil tuple's
ToString()returns an empty string. (Fixes #5956) -
Reuse inferred generic call arguments during implicit static dispatch, so deeply nested calls bind in linear work. (Fixes #5652)
-
Nullable conditional-index results on non-null receivers in
cs2gs(Fixes #5706). Guard-narrowed receivers use ordinary indexing with nullable result casts. Merely statically non-null receivers retain a single-evaluation runtime guard, including null-preserving reference casts and non-nullable contracts that still receive null. Nullable member containers retain native conditional indexing; nullable elements alone do not make a container nullable. Complete continuations retain nullable result types and inner null checks, and named constants do not imply type-test narrowing. Void callbacks and nested index continuations use guarded statement-only blocks without nullable results. Only captures that remain read-only in their declaring scope inherit guards across lambda boundaries. This avoidsGS0300without changing overload selection or evaluating indices twice. -
Compile SDK packaging image checks without unreachable-code warnings (Fixes #5938). The
GsharpAssertImagesinline task preserves failure results for missing or invalid images without emittingCS0162. -
Report deconstruction store bridges in
cs2gs(Fixes #5942). Deconstruction assertions use the generic-store reporting funnel, including array elements, collection indexers, generic members, locals, parameter assignments, and conversion inputs. Diagnostics identify the assigned target without changing emitted G#. -
Preserve nullable-value receivers in
cs2gs(Fixes #5935). Calls toNullable<T>members and extensions keep the nullable receiver instead of unwrapping it with!!. Conditional-index locals can callGetValueOrDefault, and null receivers retain theirToString,Equals, andGetHashCodebehavior. -
Audit translator non-null assertions in both source trees (Fixes #5940). The store-bridge inventory classifies current G# pattern receivers and conversion caches separately from the pinned C# baseline. CI also audits the G# checkout when
CS2GS_TEST_SOURCE_ROOTselects the C# archive. -
Preserved null-guard narrowing for immutable foreach deconstruction and read-only closure captures in
cs2gs(Fixes #5869).CSharpToGSharpTranslator(IsGSharpFlowNarrowedLocal,IsGSharpFlowNarrowedLocalInScope,IsSynthesizedQueryLambdaBody,IsPrimaryConstructorFieldRead,IsEmittedReadOnlyCapture,TryResolveClosureEffectiveTarget,NearestFunctionBoundary,IsGSharpSwitchNarrowedLocal,ForgiveNullableReferenceValue,IndexArgumentValueNeedsNullForgiveness, andIsUnguardedForwardOfTaintedValueAsRuntimeLambdaResult) evaluates G# smart-cast flow narrowing when Roslyn reportsNullableFlowState.Nonein jump-free oblivious scopes and walks enclosing scopes across in-place lambdas, anonymous methods, synthesized LINQ query-clause lambdas, and local functions for read-only G# bindings (including deconstructedforeachleaves, primary-constructor parameters in field/property initializers, and immutableletlocals/parameters) while retaining required!!assertions on mutablevarcaptures, single-identifierforrange variables, field-backed primary-constructor reads in member bodies, query-clause reassignments, and local functions hoisted before the guard. -
Lazy, once-only list-pattern element evaluation (Fixes #5807). Compound element patterns cache each indexer result when a consuming subpattern first needs it. Synchronous and awaited
and,or,not, property, and nested list patterns reuse that value across branches. Discards and empty non-nullable value-type patterns do not read the indexer, including when short-circuiting skips a consuming branch. -
Automatic
P0issue filing oncs2gs-apps-nightlyjob/step timeouts andcs2gstranslation performance restoration (Fixes #5931)..github/workflows/cs2gs-apps-nightly.yml,build/cs2gs-apps-leg.py(leg_result,job_timed_out_note, and--timed-out/--jobs), andbuild/cs2gs-apps-gate-issues.py(timed_out_legs,job_timed_out, andcancelled_legs) add explicit step-leveltimeout --kill-after=1mguards on theapp,gsharp-csharp (translate), andgsharp-csharp (validate)execution steps and inspectjobs.jsonelapsed durations (completed_at - started_at) so a leg or upstream job cancelled at its timeout limit is reportedstatus: "red"with a stable timeout fingerprint (translate-timeout,validate-timeout, orleg-timeout) and automatically files or updates aP0issue onmainfor banked applications while keeping short manual workflow cancellationsincomplete. InCs2Gs.Translator,TranslationContext.GetSemanticModelcaches RoslynSemanticModelinstances per(Compilation, SyntaxTree),CSharpToGSharpTranslatorcaches per-compilationRefStorageCaches,RepositorySharedDocumentPathsCache(skipping cross-repository ref-storage reconciliation when a compilation contains no shared documents),ScopeReservationMapperCaches, andDisambiguateAgainstMigratedProducerDeconstructfast-path guards,CSharpTypeMappercaches source simple-name/declared-type/identity-critical-delegate censuses per compilation and imported/synthesized namespace scans perSemanticModel, andObliviousNullabilityAnalyzerindexesTaintResultedges by target, pre-filters cross-compilationCanRemapToCompilationandTryResolveTupleElementSourceprobes, cachesEfEntities, and checksIsTupleContractFixedonly afterShouldPromoteToNullableReferenceCandidatesucceeds. -
Mutable tuple member assignments, compound assignments, and alias invalidation (Fixes #5897).
ExpressionBinder(BindTupleElementAssignment,BindTupleCompoundAssignment, andTryBuildNullCoalescingReadWrite),StatementBinder.Conditionals(TryCreateMultiAssignmentTargetPlanandPrepareMultiAssignmentStorage),SideEffectSpiller, andSpillSequenceSpillerbind and lower simple, compound, increment/decrement, null-coalescing, and multi-assignment writes to named, ordinal (ItemN), and zero-based (.N) tuple elements across simple, nested, andRest-chained (arity >= 8) tuple receivers without requiring a reflectedTupleTypeSymbol.ClrType, while rejecting read-only (GS0127) and temporary (GS0499) tuple receivers and invalidating flow narrowing on aliased tuple roots and element references inStatementBinder.Narrowing. -
cs2gs preserves nullable tuple leaves in collection initializers and whole-tuple ref aliases (Fixes #5868, Fixes #5880). Collection, dictionary-indexer, and array initializers retain direct and forwarded null evidence at each tuple leaf. Whole-tuple ref aliases share leaf contracts with their referents, including nested tuples, ref parameters, and ref returns. Explicit non-null contracts remain unchanged.
-
cs2gsnotnullgeneric constraint translation and dependent/source constraint preservation in anonymous projected storage (Fixes #5910).CSharpToGSharpTranslator.MapTypeParametertranslates C#where T : notnullconstraints to G#[T notnull]so generic declarations forwardnotnullto constrained targets such asConcurrentDictionary[K, V]andReadOnlyDictionary[K, V]withoutGS0580,CSharpToGSharpTranslator.NullableTypeArgumentViolatesTranslatedConstraintsincludesHasNotNullConstraint(preservingDictionary[TKey, TValue]'s reference-nullable key view) so oblivious container storage does not widennotnull-constrained type arguments toT?, andCSharpTypeMapper.TypeParameterForbidsNullableReferenceArgumenthonors source-declared constraint lowering and dependent type-parameter bounds (where TOperation : TBase) when normalizing anonymous projected storage. -
Addressable tuple elements for managed references (Fixes #5858). Ref locals, explicit address-of, and
ref/out/inarguments can use named, nested, and long tuple elements. Ref returns inherit the tuple receiver's storage lifetime, including both arms of conditional projections. Explicit references retain original readonly and boxed receiver storage, including block-wrapped reads, selected conditional arms, and nullable reference declarations. Read-only receivers remain read-only, and replacing a tuple invalidates facts on its element aliases.cs2gsshares nullable storage with scalar and tuple-valued ref aliases and explicit ref arguments, including conditional and target-typed constructor arguments, ref indexers, copied array elements, container-valued copies and returns, tuple-projected arrays, suppressed projections, and containers inside aliased tuples. Fixed ref-return contracts constrain leaf promotion. Output arguments propagate writes without freezing caller declarations, and array-valued leaves retain their nullable spelling. -
Type-test narrowing on imported readonly fields and get-only auto-properties (Fixes #5814).
ExpressionBinder(BindAccessorStepCore,BindTypeParameterInstanceMemberAccess,TryBindInheritedClrInstanceMemberByBareName,BindBaseClassPropertyRead, andTryBindBaseClrFieldRead) applies active member-path narrowings toBoundClrPropertyAccessExpressionreads while preservingEffectiveDeclaredTypeacross lowering, expression trees, andMethodBodyEmitter.EmitClrPropertyAccess, so method calls,deferreceiver captures, and member reads on narrowed importedinitonlyfields and get-only auto-properties resolve and emit against the narrowed type. -
Call-effect summaries for by-reference narrowing (Fixes #5326).
CallEffectSummary(BindingServices) andStatementBinder(CallEffectsMayOverwriteRoot,RegionCallsMayOverwriteRoot,GetFunctionEffectSummaryCore,AnalyzeImportedMethodEffects,ScanCalleeSyntaxNode, andAssignedRootsCollector.MayWriteStorageOf) compute transitive storage-write summaries across source callees, virtual/interface overrides, generic substitutions, imported container/buffer operations, equality/comparer/ToStringcallbacks, and reflection/unsafe calls, invalidating narrowedref/outparameters andreflocal aliases when a call can overwrite their aliased storage while preserving narrowing across calls whose effects cannot reach the guarded root. -
By-ref suppression bridges for reassigned
varlocals, array elements, and generic receivers with declared type arguments incs2gs(Fixes #5701).CSharpToGSharpTranslator(SlotTypeIsDeclared,TryGetEnclosingArrayElementStore,UnboundValueSlotIsDeclared,LocalSlotIsDeclared,LocalReceiverTypeArgumentsAreDeclared,OutLocalReceiverTypeArgumentsAreDeclared,ProjectDeclaredReceiverSlot,ResolveReceiverTypeArgument,CallReceiverSlotIsDeclared,PromoteInferredDelegateArrayElementType, andForgiveInitializerElementValue) bridges dropped by-ref suppressions (Volatile.Read(ref full!)) stored into reassignedvarlocals whose emitted storage is non-null, array elements and array/collection initializers whose emitted element type is non-null, and type-parameter members, indexers, and parameters of receivers with declared type arguments (includingout varreceiver bindings and partially inferred delegate-tuple array elements), while leaving nullable and inferred slots unasserted. -
Self-migration shard planning rejects incomplete-stage duration maps (Fixes #5884).
build/generate-selfmig-shard-matrix.py(load_costs,companion_run_is_complete,select_costs, and--check-costs),build/derive-selfmig-app-durations.py,build/run-cs2gs-selfmig-gate.sh, and.github/workflows/cs2gs-apps-nightly.ymlselect duration artifacts from successful runs and reject duration maps containing non-positive (0.0-second dependency-blocked) durations, incomplete or skipped stage evidence inrun.merged.json/stats.json, or missing baseline corpus entries before falling back to the checked-inbuild/selfmig-shard-costs.jsonseed map. -
Directional
GS0612by-ref nullability for value-tuple leaves and one-wayouttuple flow incs2gs(Fixes #5905).ByRefStorageMatching(AreSameStorageTypeandClassifyNestedNullability) classifies direct and nested value-tuple (TupleTypeSymbol, includingNullable<ValueTuple>wrappers) leaf nullability differences directionally throughstorageNullableandparameterNullablewhile keeping shared container positions ([]T,List[T]) invariant undernestedMismatch, andObliviousNullabilityAnalyzer(CollectTupleArgumentFlows,CollectRefTupleStorage,EnumerateTupleContainerSources,AddTupleContractPair, andSlotCrossesSharedContainer) excludesoutparameters from caller-to-parameter value flow and distinguishes inlineNullable<ValueTuple>wrappers from shared container slots so whole-tuple, projected-tuple, and nullable-tupleoutcalls with wider nullable caller leaves compile without falseGS0612warnings or frozen leaf contracts. -
ADR-0213 L1 call-argument and chained-call overload resolution for by-reference narrowing in loops (Fixes #5662).
StatementBinder.NarrowingLoops(ResolvedCallArgumentsRunUserConversion,SourceCallRunsUserConversion,ClrReceiverCallRunsUserConversion,TryResolveClrCandidate, andInstanceMethodAppliesToCallStep) andOverloadResolver.TryResolveLoopCallParametersresolve loop call candidates and chained call steps through the binder's own source (OverloadResolver) and imported CLR (ClrOverloadResolution.ResolveandMemberLookup.GetClrMethodParameterConversionTargetTypeSymbol) overload resolution on each receiver alternative instead of requiring every same-named overload and same-named extension method to be conversion-free, preservingrefandoutnarrowing facts across conversion-free calls such asConsole.WriteLine("ab"),Console.WriteLine(n),Math.Max(n, 1),Keep(dt),Use(ys, 1),s.Trim().Length, and instance calls that share a name with an extension method when an instance method applies. -
Preserved pre-conversion null-coalescing RHS types for assignment narrowing (Fixes #5907).
ExpressionBinder.GetAssignedValueTypeunwraps the implicit target-type conversion wrapper added around a target-typed??expression (including when nested as an ordinary ordefer/usingcleanup block expression's trailing value) before recordingBoundAssignmentExpression.AssignedValueType, while keeping explicitcast[T?](...)conversions (including block-wrapped operands) and platform-typed (T!)??results nullable. Reassignments of nullable locals such asnamed = named.TupleUnderlyingType ?? namedandmodel = model ?? owner.GetSemanticModel(...)therefore retain their non-null??result type inStatementBinder.ApplyAssignmentNarrowingand no longer report falseGS0158orGS0154diagnostics on subsequent uses, restoringtools/cs2gs/Cs2Gs.Translatorand its 9 dependent apps in thecs2gs-apps-nightlygsharp-csharpgate. -
Nullable<T>member resolution and tuple fallback conversions on imported and symbolic nullable tuples (Fixes #5030).ExpressionBinder(NarrowedTypeMayHaveMember,ImportedExtensionMayApply,TryBindNullableInstanceMember,TryBindSymbolicNullableInstanceCall, andRelaxLenientPlatformTarget),ClrOverloadResolution.GetEffectiveExtensionReceiverClrType,MemberLookup.TryProjectErasedClrType, andTupleTypeSymbol.BuildClrTypeproject symbolic tuple receivers whose element nullability suppressesTupleTypeSymbol.ClrType(including value-nullable tuple elements) onto theirSystem.ValueTupleCLR backing during narrowed-member and extension-applicability probes and admitValue,HasValue, andGetValueOrDefault(including stated-to-platform array and interface element tuple fallbacks) on guarded and unguarded nullable tuples across single-dimensional, rectangular, nested, andRest-chained tuple shapes. -
Projected generic, member,
await, callback, and subpattern slot chains forvarpattern captures incs2gs(Fixes #5656).CSharpToGSharpTranslator(ComputeNilableOnlyInEmittedGSharp,GSharpExpressionIsStaticallyNonNull,TryGetVarCaptureStaticNonNull,SubpatternMemberCarriesNilableOnlyAtSlotChain,ExpressionCarriesNilableOnlyAtSlotChain,InvocationInfersNilableOnlyForMethodTypeParameter, andDeclaredValueIsStaticallyNonNull) resolves whether avarpattern capture's input or property subpattern member carries a G#-onlyT?value through generic calls, generic fields/properties/indexers,await, receiver-dependent methods, callbacks, and inferred locals instead of leaving captures whose scrutinee mentions aT?-only value undecided, eliminating redundant throwing!!assertions when the scrutinee's emitted type is non-null (Lookup(Volatile.Read(ref full!).Count)) and bridgingis varand target-aware nullable slots when the scrutinee's emitted type isT?(Task.FromResult(Volatile.Read(ref cache!)).Result). -
Preserved imported array override contracts, optional callable member defaults, and inherited collection initializers (Fixes #5865, Fixes #5892, Fixes #5909). Imported override returns require matching stated nullability in mutable array elements and invariant generic arguments, including arrays inside tuples and
TaskorValueTaskresults. Oblivious native positions remain compatible. Calls through source fields and properties use the same optional-argument binding as local function values. Source subclasses can initialize inherited imported collections, including reordered generic dictionary and list bases. -
Projected imported override tuple contracts through reordered, variance-compatible, and wrapped generic return types in cs2gs (Fixes #5912, Fixes #5913). Return declarations and constructor type arguments retain the imported contract's nullable tuple leaves through covariant base and interface templates, including variance-compatible constructed views and wrapped tuple templates, without tainting unrelated positions.
-
Parameter declaration repointing on body-only edits and unmodified
didOpentree reuse in the language server (Fixes #5904).ProjectState.UpdateFilereuses the cachedSyntaxTreeandCompilationwhen an in-memory editor buffer (rawBytes == nil) matches an existing valid disk tree's text, while still refreshing encoding provenance when a disk tree carriedGS0628orGS0632or when disk bytes change.ParameterSymbol.RepointDeclarations,VariableSymbol.RepointDeclaration,FunctionSymbol.RepointDeclaration,ConstructorSymbol.RepointDeclaration,PropertySymbol.RepointDeclaration,StructSymbol.RepointDeclaration,DelegateTypeSymbol.RepointDeclaration,IncrementalGlobalScopeReuse, andSemanticModel.EnumerateDeclaredSymbolsrepoint function, method, constructor, indexer, primary-constructor, and delegate parameter declarations to the updatedSyntaxTreeon body-only edits soSemanticModel.LookupSymbolsandtextDocument/hoverresolve parameters acrossFieldAssignmentExpressionSyntaxreceivers,: base(...)constructor-initializer interpolation holes, and lambda bodies, retiring all remaining#5899,#5900, and#5904reviewed failure expectations inWaikikiHoverAuditTests. -
Whole-tuple array-element assignment leaf promotion in
cs2gs(Fixes #5901).ObliviousNullabilityAnalyzer(CollectTupleFlows,CollectTupleReturnFlows,CollectTupleGetterFlows,CollectDeclarationTupleFlow,CollectNestedTupleValueFlow,CollectTupleValueFlow,TryResolveTupleStorageSource,TryResolveTupleContainerSource,ResolveAssignable,RefArrayStorage,GetArrayStorageOwner,TupleContractPositionAcceptsNil, andProjectTupleContractPosition),CSharpToGSharpTranslator(GetArrayElementType,PromoteElementTypeForNullElements,ResolveArrayStorageSink,ResolveValueSink,DirectValueSink,GetFixedElementDestinationType,GetTargetTupleElementContract,TupleElementYieldsNilableBeyondItsCSharpType,TranslateCallArgument,TryTranslateStaticInitializedAutoProperty, andTranslateLocalDeclaration), andCSharpTypeMapper.PromoteTupleTypeArgumentsroute array-element tuple writes (items[0] = (null, 0)) into the shared tuple-position evidence and contract graph across direct and suppressed null literals, nested tuples, conditional/switch/null-coalescing tuple expressions, forwarded tuple variables/parameters/calls, jagged/rectangular/tuple-projected array element accesses, and shared array aliases (including returns, getters, property initializers, and tuple-contained arrays) while preserving and bridging fixed non-nullable contracts. -
Headless language-server hover regression audit over pinned Waikiki (Fixes #5026).
WaikikiHoverAuditTests(test/LanguageServer.Tests/WaikikiHoverAuditTests.gs),build/waikiki-hover-audit.py,build/test-waikiki-hover-audit.py, and.github/workflows/waikiki-hover-audit-nightly.ymladd a shared headless hover regression audit and compiler-symbol oracle covering fast in-repository PR checks (routed viabuild/ci-selection.py) and scheduled/manual full-corpus sweeps overDavidObando/Waikikiatec66d0bfaa39583cd11c66095f2748342dc9e8f6(8 projects, 68 authored plus 13gsgen-generated.gsfiles, 45,829 physical source tokens, and 68,039 start/interior hover checks), including#5024/#5025cold-open and incremental body-only edit lifecycle verification,#5035/#5036indexed-member and receiver-provenance checks,#5277synthetic-token hit-testing leak checks, issue-linked known-failure ratcheting (#5899,#5900,#5904), and scrubbed Markdown/JSON/CSV artifact reporting. -
Preserved captured-local narrowing across negated and compound pattern conditions in loops (Fixes #5890).
RegionEffectScanner(IsPureBooleanForm,BuildPath,ArgumentForm,RecordConversion,RecordArmConversion,IsOperatorForm,RecordTypeTests,TryNarrowPatternSubject,Compose, andVisitNode),RegionTypeTest.DeclaredInRegion,StatementBinder.TestedType, andCSharpToGSharpTranslator(LoopConditionLowersOutOfHeaderandFallbackPatternBinderLosesHeaderNarrowing) classifyistests and boolean combinators (!,&&,||,==,!=) over pure boolean operands asSystem.Boolean, narrow conjunctive (and) pattern subjects for right-hand subpatterns (propagating an unknown subject when a bare type-or-constant candidate intervenes), skip constant-pattern recording on property-suffixed type patterns (C { ... }), recognize region-declared constants inTestedTypeafter type resolution, and aligncs2gsloop-exit narrowing over built-in value-type header pattern casts while still invalidating captured-local narrowing when a pattern can invokeobject.Equals, a user property getter, or a list pattern accessor. -
decimalanddecimal?optional parameter defaults ingscandcs2gs(Fixes #5871).ConversionClassifier.TryNormalizeClrConstantnormalizesTypeCode.Decimaloptional parameter defaults (including widened integral andcharconstants) forParameterMetadataEmitter'sDecimalConstantAttributeemission,ConstantExpressionEvaluator.TryGetDecimalConstantAttributeValueandConversionClassifier/ImportedTypeSymbol/ClrNullabilitydecode importedDecimalConstantAttributedefaults acrossdecimal,decimal?,object, and positional record parameters,FunctionTypeSymbol.DefaultValuesEqualandSynthesizedRefDelegateCache.BuildKeycompare fulldecimal.GetBitsrepresentations (preserving scale and signed zero), andCSharpToGSharpTranslator.MapConstantValueemits themsuffix for materializeddecimaldefaults. -
Language server hover resolution for imported member accesses shadowed by enclosing members, parenthesized arrow function type clauses, generic CLR types and constructors, property-setter assignment targets, struct-literal member initializers, generic type parameters, and nested or namespace-qualified CLR types (Fixes #5899, Fixes #5900).
HoverComputer.TryResolveGSharpMemberandMemberTokenResolver.IsMemberOrInitializerTokenprevent member-access RHS tokens, field-assignment targets, and initializer member names from falling back to implicit-thislookup on the enclosing type, andSemanticLookup.FindTokenAtno longer maps a caret on the dropped outer parentheses of a parenthesized type clause ((() -> T)?) onto the adjacent token (#5899).SemanticLookup.ResolveImportedClrType,MemberTokenResolver, andSemanticLookup.SemanticModelresolve generic CLR type and constructor references acrossCallExpressionSyntax,GenericNameExpressionSyntax,IndexExpressionSyntax,StructLiteralExpressionSyntax, andTypeClauseSyntax, property-setter assignment targets inFieldAssignmentExpressionSyntax,MemberFieldAssignmentExpressionSyntax, and implicit-thisinherited CLR property writes,StructLiteralExpressionSyntaxmember initializers, generic type-parameter declarations and in-scope uses, and nested or namespace-qualified CLR types inAccessorExpressionSyntax(#5900). -
User-defined lambda return conversions for nullable delegate initializers and sinks,
Addparameter nullability resolution for constructible collection expressions incs2gs, constrained generic type arguments on anonymous-type projected properties,SyncMap[K, V]/ConcurrentDictionary[K, V]unconstrained type-parameter key forwarding, andvsce packageflag logging in thevsixworkflow job (Fixes #5883, Fixes #4573, Fixes #5607, Fixes #5894, Fixes #5895).ConversionClassifier(RequiresRuntimeDelegateReturnValidation,ClassifyConvertedDelegate,CanConvertFunctionLiteralReturnWithUserDefinedImplicitConversion, andTryGetEligibleRuntimeDelegateFunctionLiteral),LambdaBinder.TryGetFunctionLiteral,ExpressionBinder(BindAssignmentRhs,BindBinaryOperation,TryBindTargetTypedNullCoalesce,MakeSymbolicArgumentConversionClassifier,MakeStructuralProjectionArgumentCheck, andTryGetCollectionSpreadElementType), andOverloadResolver.IsValueReturnDiscardedToVoidDelegaterebind and classify expression- and block-bodied function literals against nullable and non-nullable delegate targets when the lambda's return type converts to the target delegate's return type via a user-defined implicit conversion (Card -> Node), while preserving explicit non-delegate conversions (cast[object](...)) (#5883).CSharpToGSharpTranslator(TranslateCollectionExpression,CoerceCollectionElement,GetCollectionAddParameter,IsCollectionAddParameterApplicable,IsBetterCollectionAddConversionTarget,GetCollectionProjectionElementType,SlotProvesNonNull, andCollectionAddParameterRejectsNull) resolves the applicable single-parameterAddoverload's parameter symbol and translated write contract by declaring-type hierarchy and conversion-target specificity on constructible collection targets so non-nullableAdd(T)parameters bridge nullable, subtype, multi-overload, user-converted, and widened-array elements with!!while preserving[AllowNull]/ declaration-widenedAddcontracts, null-accepting user-defined conversions,null-literaldefault(T)lowering, and owner-substituted...spreadelements (#4573).ClrOverloadResolution.IsMapReferenceKeyViewextends theDictionary[K, V]unconstrained type-parameter key forwarding rule toConcurrentDictionary[K, V]andRepositoryMirror.CopyFilerewritesclass SyncMap[K, V any]toclass SyncMap[K notnull, V any]when mirroringSync.gs(#5894).CSharpTypeMapper.NormalizeAnonymousProjectedStoragepreserves non-nullable reference type arguments when the target type parameter forbids nullable reference arguments (notnull, non-nullableclass, or non-nullable type constraints such asOperationBuilder<TOperation> where TOperation : MigrationOperation) (#5895)..github/workflows/build.yml(Package VSIXstep in thevsixjob) logs the resolvedtag-kindand expandedvsce packageflags before invokingnpx vsce package(#5607). -
Nilable-receiver
GS0158member-access diagnostic and retirement of legacy--nullability=enabledmode (Fixes #4366, Fixes #4372). When a member read, write, compound assignment, or event subscription on a stated-nullable (T?) or unnarrowed type-parameter receiver fails only because the receiver may be nil while the underlying type exposes the member,ExpressionBinderandDiagnosticBag.ReportUnableToFindMember(TextLocation, string, string)now reportGS0158with an explicit receiver-may-be-nil message naming the remedies (?.,!!, or narrowing withif letor a nil check) while keepingCannot find member X.when the underlying type does not declare the member (#4366).NullabilityMode.Enabled, the/nullability:enabled(--nullability=enabled) CLI switch,GSHARP_NULLABILITY=enabled,NullabilityOptions.PlatformTypesEnabled, and the legacy mode branches inClrNullabilityandNullableFlagsBuilderare retired now thatplatform-typesis the sole imported-nullability mode alongside--nullability=oblivious(#4372). -
cs2gs preserves entry-type state and readable underscore locals (Fixes #5875, Fixes #5877). Entry classes and structs with fields, constants, properties, or constructors retain their declarations. Referenced C# locals and parameters named
_use collision-checkedunderscorenames; true discards remain_. Named calls use the owning compilation's names, including constructed generic parameters. Positional-record property names remain unchanged. Partial methods use their implementation's parameter names. -
Reserved
yieldkeyword (SyntaxKind.YieldKeyword), collision-checkedunderscoreparameter renaming and__q{N}/__underscoresynthetic family retirement incs2gs, and defaultOptimizationLevel.Releasecompilation inCSharpFixture(Fixes #4304, Fixes #4307, Fixes #4794, Fixes #4872).SyntaxKind.YieldKeyword,SyntaxFacts.GetKeywordKind,SyntaxFacts.GetText, andParser.ParseStatementCorenow treatyieldas a reserved keyword rather than a contextual identifier, removingLooksLikeYieldTupleLiteraland theyield [bracket lookahead carve-out soyield (x) + y,yield (x).Foo(),yield (x)[i], andyield [3]T{...}parse unambiguously asYieldStatementSyntaxwhile escaped$yieldremains available for identifiers (#4872).CSharpToGSharpTranslator(MapParameterNameandTranslateIdentifierName) andEmittedNameAllocatorrename a single referenced C# parameter literally spelled_tounderscore(disambiguating tounderscore_2,underscore_3, etc. whenunderscoreis already occupied in the enclosing scope), andbuild/cs2gs-counters.shmoves__underscorealongside__q(#4304 / ADR-0185) to the retired synthetic-identifier families (#4307).CSharpFixturenow defaultsCSharpCompilationOptionstoOptimizationLevel.Release(while keepingoptimizationLevelconfigurable) so Roslyn block ref-return fixture helpers emit direct field-address returns that pass strictILVerifywithoutReturnPtrToStackfalse positives (#4794). -
Dispatch-preserving record
Deconstructcontract, extension, pointer-output, nested-pattern, and cross-project metadata lowering incs2gs(Fixes #5844).EmittedNameAllocatorandCSharpToGSharpTranslatorpropagate recordDeconstructrenames and tuple/scalar adapters across source interface contracts, abstract base contracts, selected extension overloads, and metadata-backed consumers of migrated producers; synthesize intermediate CLR slot bridges (<Record>DeconstructBridge) when source records implement imported interfaceDeconstructcontracts or override imported recordDeconstructslots; transport multi-output pointer and function-pointerDeconstructcomponents throughnuinttuple carriers with target-pointer casts at declaration, assignment,foreach, and positional-pattern consumers; and share root type guards, nested member receiver caches, and path-keyed deconstruction caches across positional and property pattern decisions. -
Preserved address-of safety through async spilling and constrained tuple receiver storage (Part of #4383). Address reconstruction retains unmanaged/read-only flags and fixed-buffer escape provenance across rewriters, argument captures, and async lowering, including direct-indexed fixed buffers whose pointer or
nintaddress is spilled across a laterawait. Inline-await and awaiting-index fixed-buffer decays from movable, state-machine, or temporaryMoveNext-frame storage reportGS0638. Direct-indexed fixed-buffer assignment, compound-assignment, and multi-assignment temporaries use GC-trackedByReflocal slots instead of unmanagedT*slots so synchronous collections during index or RHS evaluation update interior pointers. Constrained calls on block-backed tuple elements use the shared receiver-addressability query, preserve stored value/reference receivers, keep narrowed type-parameter receivers on their plannedT-typed spill slots, and no longer fail withGS9998orStackUnexpected. -
cs2gs preserves C# pattern-evaluation and designation-binding order for closure-assigned and by-reference subjects (Fixes #5837).
CSharpToGSharpTranslator(PatternScrutineeMayChangeDuringMatch,UsesNativeBooleanPatternTest,IsPatternQualifiesForNativeVariables,TryTranslateIfLetResidualPattern,TranslateRecursivePatternTest,MaterializeFallbackPatternBindings,HoistLoopConditionClauseCore,TryBuildNestedNegatedGuardHoist, andTranslateSwitchPattern) keeps a closure-assigned or by-reference local or parameter subject in place across subpattern evaluations and binds whole-value designations after subpattern matching completes, while capturing root type conversions at the type-test point and rejecting value-equality or ambiguous-constant residual patterns inif letguards. -
Preserved addressable block-wrapped tuple storage during fixed-buffer decay (Part of #4383). Receiver emission uses the same physical-addressability query as spill planning, including blocks yielding direct or nested tuple elements. These local-storage buffers compile without
GS9998, retain writes to the original tuple, and evaluate block prefixes once. -
Preserved boxed-tuple storage boundaries and legal readonly receiver addresses (Part of #4383). Tuple-element storage classification retains reference-backed roots instead of treating them as stack temporaries. Receiver emission and spill planning share a context-aware addressability query across user/CLR fields, tuple elements, blocks, and conditional chains. Static readonly value fields outside their declaring
.cctoruse defensive copies, preserving ILVerify and existing sample PE baselines without unused field-read spill slots. -
Classified fixed-buffer pointers by physical storage after capture and state-machine lowering (Part of #4383). Captured locals and parameters, including nested and async function literals, require
fixedwhen their buffers move to heap fields. Unpinned pointer escapes reportGS0638; promoted buffers no longer receive the prematureGS0507rejection. Unboxed block, tuple, and temporary value-storage chains remain legal without pinning. Receiver addressing and spill planning preserve these accepted value locations. -
Preserved rich-object method diagnostics and synthesized adapters across repeated binding and selected complete inherited interface contracts for structural adapters (Part of #4345, Part of #4346). Reusable rich-object plans retain declaration diagnostics. Methods with synthesis side effects bind again in the current synthesis registry. Adapter method selection filters class overrides through effective member lookup. Interface selection coalesces identical dispatch slots and hierarchical redeclarations only when full contracts agree, including return types, ref-kinds, and nullability. Unrelated interfaces and distinct constructed owners retain independent slots and report
GS0606ambiguity instead of selecting an arbitrary implementation. Hierarchical redeclarations select the derived slot regardless of traversal order. Imported parameter matching compares effective ref-safety contracts instead of attribute spelling. -
Centralized structural-adaptation obligation/contract normalization and source-retention validation, reusable rich-object declaration plans,
GS0638movable fixed-size buffer pointer decay diagnostics, in-type zero initialization for private closed-generic struct fields, mirroredpackages.lock.jsonrestore handling, and ADR-0210 explicit array-copy status alignment (Fixes #4345, Fixes #4346, Fixes #4347, Fixes #4348, Fixes #4383, Fixes #4746, Fixes #4851, Fixes #5208).Binder(BindStructuralAdaptation,TryValidateStructuralAdaptationSource,BindImportedAdapterInterfaceSlots,MethodContractsMatch,PropertyContractsMatch,EventContractsMatch, andImportedMethodContractsMatch) centralizesadapt[I](source)source-retention validation ahead of target obligation enumeration and normalizes user and imported interface method, property, indexer, event, and owner-substituted generic-constraint contracts across generic and inherited sources (#4345, #4347, #4348).RichAnonymousObjectPlanandBinder.BindRichAnonymousObjectFromPlanseparate cached rich-object declaration plans from per-call bound capture expressions and generic substitutions (#4346).ExpressionBinder(BindFixedBufferPointerandBindAddressOfExpression) andStatementBinder.IsFixedVariablereportGS0638(MovableFixedBufferRequiresFixed) when a fixed-size buffer field on a movable receiver decays to a pointer or has its element address taken outside afixedstatement initializer while keeping direct element indexing (holder.H.Name[0]) and unboxed value-location buffers legal (#4383).MagicCollectionZeroValue.TrySynthesizeStructFieldDefaults,BoundStructLiteralExpression.ValidateInitializerWrites, andReflectionMetadataEmitter'sStructLetFieldCtorHandlesretain and initialize non-public closed-generic struct fields requiring default initialization through an in-type constructor sovar outer Outer[Inner]passesILVerify(#4746).SdkCompileRunner.BuildMirroredBuildArgumentsandGSharpProjectTransformer.PruneSuppressedProjectsFromLockFilepass-p:RestoreForceEvaluate=trueand-p:RestoreLockedMode=falseduring mirrored builds and prune suppressedProjectReferenceentries from mirroredpackages.lock.jsonfiles (#4851).docs/adr/0210-explicit-same-type-array-copy-operations.mdaligns the trailing#5325status note with the implementedArray.Copy/Clonerules (#5208). -
Type-level nullability metadata emission and import on
TypeDefbase types,InterfaceImplrows,GenericParamConstraintrows, andGenericParamrows (class?,notnull), website transitive dependency-audit remediation, heap-data stress tests across GC compaction and concurrency, and GitHub REST API asset download inbuild/install-netcoredbg.sh(Fixes #4996, Fixes #5341, Fixes #5397, Fixes #5886).CustomAttributeEncoder(EmitNullableAttributeOnType,EmitNullableAttributeOnInterfaceImpl,EmitNullableAttributeOnGenericParamConstraint,EmitNullableAttributeOnGenericParam, andShouldEmitRelationshipNullable),TypeDefEmitter,ReflectionMetadataEmitter,PendingGenericParameter, andClrInterfaceClosurenow emit[Nullable]and[TupleElementNames]attributes onTypeDef(base-type arguments),InterfaceImpl,GenericParamConstraint, andGenericParammetadata rows, whileParser.Members,TypeParameterSyntax,TypeParameterSymbol,DeclarationBinder.Functions,BaseCallForwarderRewriter, andGSharpFormatterparse, bind, remap, and format[T class?]and[T notnull]generic constraints.ClrNullability(GetBaseTypeSymbol,GetInterfaceTypeSymbols,GetGenericParameterConstraintTypeSymbols,GetGenericParameterTypeSymbol,HasNotNullConstraint, andNormalizeRelationshipFlags),ClrSignatureMetadata,MemberLookup(GetClrReceiverProjectedReturnTypeSymbolandGetClrReceiverProjectedParameterPointeeTypeSymbol),Binder(SatisfiesConstraint,SatisfiesNotNullConstraint,TypeParameterForwardsUserDeclaredConstraints,DescribeConstraint,DescribeClrConstraint,ApplyImportedGenericConstraints, andAdapterGenericConstraintsMatch), andClrOverloadResolution(SatisfiesDeclaredConstraints,TypeParameterForwardsDeclaredConstraints, andSatisfiesAnnotatedClrTypeConstraint) read and enforce relationship and constraint nullability acrosscsc- andgsc-compiled assemblies.website/package.jsonandwebsite/package-lock.jsonpin compatible transitive overrides forfast-uri(3.1.9),qs(6.16.2),serialize-javascript(7.1.3), andtinypool(2.1.2).Issue5397HeapDataStressTestsexercisesmanaged[T],readonly managed[T],slice[T],readonly slice[T], andbytestringacross forced compacting GCs, concurrent multi-threaded reader/writer access on shared locations, reslicing, reallocation, and lifetime boundaries.build/install-netcoredbg.shdownloads the pinnednetcoredbg3.2.0-1092release asset via the GitHub REST API asset endpoint (Accept: application/octet-stream, with optionalGITHUB_TOKENbearer auth and direct release-download fallback) while preserving SHA-256 verification (#5886). -
Constant patterns preserve explicit boxing, and constant initializers support decimal metadata and reference nulls. An explicit
cast[object]orcast[object?]in a floating-point pattern keepsobject.Equalssemantics, including after anawaitspill (#5805). Imported decimal constants, includingdecimal.MaxValueanddecimal.MinValue, fold fromDecimalConstantAttributewithout executing field initializers. Decimal emission retains scale and signed zero (#5823). Reference-typeconstfields and locals acceptniland reference defaults; non-null, non-string reference initializers remain rejected (#5825). -
Disjoint default toolchain archive snapshots (#4856). Stage-2 verification rejects caller archives that collide with the default snapshot path. Same-path reuse requires an explicit controller-owned, read-only snapshot and an approved SHA-256 hash.
-
Canonical cs2gs fixture markers and complete stage-2 archive error boundaries (#4896, #4856). The staged-feed fixture uses the shared repository marker. Archive readers convert encryption, unsupported compression, malformed UTF-8, and optional codec failures into controlled certification errors and failure reports.
-
Staged-only SDK discovery for configured cs2gs source roots (#4896). Shared package discovery now consults the writable
LocalPackageFeedas well as the source.nugsfeed. Exact-version lookup, SDK and analyzer-verifier version resolution, compilation, and live test-project setup can reuse packages that remain only in the staging feed. Existing build-output and source-feed precedence remain unchanged. -
Shared archive-path collision rejection in stage-2 certification (#4856, #4885). Tar and ZIP consumers validate canonical member trees before payload hashing or extraction. They reject duplicate and normalized paths, case-folded and Unicode-equivalent aliases, and file/directory prefix collisions. Package cache rejection preserves existing extracted files. Valid archives retain their payload hash encoding.
-
Original caller permissions and controlled truncated-archive failures in stage-2 certification (#4885, #4856). Migrated caller identity now binds original permission bits, including the root, separately from normalized snapshot permissions. Caller
chmodchanges no longer pass verification. Shared archive-error handling includes gzip/tar EOF and ZIP decompression failures, returning controlled errors and writing certification failure reports. -
Empty-directory preservation in migrated stage-2 snapshots (#4885). Migrated-tree manifests now record directory entries, including empty directories. Snapshot freezing preserves them in both stage trees, so directory-dependent MSBuild conditions retain their behavior. Caller and immutable-snapshot verification reject directory additions, removals, and renames. Regular-file manifest schemas and toolchain identities remain unchanged.
-
Read-only cs2gs source-root SDK package staging (#4896).
GsharpTestProjectRunner.LocalPackageFeedselects a writable feed beside the running test assembly whenCS2GS_TEST_SOURCE_ROOTnames a source tree. Package staging, SDK compilation, and generated test-project NuGet configuration use the same decision. SDK fallback no longer creates.nugsin the source checkout, including the immutable stage-2 source tree. -
Reference-tuple (
System.Tuple<...>) reader agreement inTypeSymbol.FromClrType, reproducible stage-2 toolchain archive and pre-migrated tree verification inbuild/selfhost-stage2.py, and unbuiltCS2GS_TEST_SOURCE_ROOTpackage fallback inGsharpTestProjectRunner(Fixes #4401, Part of #4856, Part of #4885, Fixes #4896).TypeSymbol.TryCollectTupleElements,TypeSymbol.SpliceTupleRest,NullabilityImportRule.ClassifyArgument, andBinder.GetClrSlotAlignedArgumentsnow reserveTupleTypeSymbolandTRestsplicing exclusively forSystem.ValueTuple<...>while keepingSystem.Tuple<...>as a referenceImportedTypeSymbolacross bothFromClrType/ClrNullabilityandMemberLookup.MapOpenClrTypeToSymbolic, removing thesystem-tuple#4401allowlist entry fromReaderAgreementAllowlist(#4401).build/selfhost-stage2.pyadds controller-verified.NET SDKarchive extraction (--dotnet-archive,--dotnet-archive-sha256,--verify-dotnet-archive), configurable host/manifest trust pins (--dotnet-host-sha256,--dotnet-root-manifest-sha256,--allow-system-dotnet-manifest), and pre-migrated tree snapshot freezing (--migrated-tree,--freeze-migrated-tree,freeze_migrated_tree, andverify_migrated_caller_unchanged). Snapshot freezing rejects overlapping caller and destination roots before any writes, including symbolic-link aliases. CI workflow wiring remains deferred (#4856, #4885).GsharpTestProjectRunner(ResolveLocalPackage,FindLocalPackageVersion, andCandidatePackageRoots) andCs2Gs.Testssource-inspection tests (Adr0151IfLetExpressionTranslationTests,Issue4545ManagedArrayProjectionSelfMigrationTests,Issue4645NoRootWorkspaceTests,Issue4801GeneratedValidationSourcesTests,Issue5402SourceVersionTests, andIssue914NumericCoercionTranslationTests) fall back to the running G# checkout's builtout/bin/<Config>/nupkgsand compiler artifacts whenCS2GS_TEST_SOURCE_ROOTpoints to an unbuiltcs2gs/csharp-0.4source checkout, anddocs/self-migration-cutover.mdupdates the source-root documentation accordingly (#4896). The fallback regression test fails if its required SDK packages are absent instead of silently passing. -
Readable synthetic names for mutable switch-pattern captures, loop-condition pattern hoists, and captured method-group receivers (
pattern,scrutinee,receiver), WebKit search-dialog theme-token stabilization, managed-reference array projection invocation short-circuiting, CFG state tracking for local-function delegate storage, per-target-framework test-name parity comparisons, G#-tree compatibility forIssue4704/Issue4779/Issue4681/Issue4612tests, C#-formatToString()overrides on synthesized anonymousdata classes, productionPackageContentHashverification in stage-2 cache tests, andnetstandard2.0SDK task implicit runtime reference exclusion (MSB3277) (Fixes #4303, Fixes #4305, Fixes #4306, Fixes #4438, Fixes #4572, Fixes #4586, Fixes #4691, Fixes #4848, Fixes #4879, Fixes #4881, Fixes #5073).CSharpToGSharpTranslator(NewMutableSwitchPatternCaptureName,TranslateLoopIsPatternCondition, andAllocateCapturedReceiverName) replaces__pattern{N},__scrutinee{N}, and method-group receiver__spill{N}temporaries with collision-checkedpattern,scrutinee, andreceiverlocals and retires__patternand__scrutineeinbuild/cs2gs-counters.sh.website/tests/browser/site.spec.tsfactors theme-token readiness intoexpectThemeTokensAppliedand awaits it before the search-dialog accessibility scan.TranslateInvocationCore,TryGetManagedReferenceArrayProjectedMethod, andMethodMayRequireManagedReferenceArrayProjectionshort-circuit non-generic invocations without populatingManagedReferenceArrayProjectedMethodByCall.NonLocalDelegateMayReferenceAnonymousFunction,ApplyDelegateReachingOperation, andDelegateAssignmentValueAnonymousFunctionCounttrackIMethodSymbollocal functions across field overwrites and event unsubscriptions.CSharpTestOracle,TrxParser, andTestNameParity.Comparepartition discovery and TRX outcomes by target framework when present.Issue4704ForwardedWarningIdTests,Issue4779NullableReflectionArgumentsSelfMigrationTests,Issue4770NullableClassifierCoalescingTests,Issue4681ChannelsNullPassThroughTests, andIssue4612StoreBridgeInventoryTestssupport the committed.gssource tree.CSharpTypeMapper.GetOrCreateAnonymousDataClassShapeemits anoverride func ToString() stringformatting{ Name = value }without the generated type name.build/selfhost-stage2.py(--verify-package-content) andbuild/test-selfhost-stage2.pydrive the builtAdr0198.PackageContentHashhelper across signed and replaced archives.Gsharp.NET.Sdk.gsproj,Gsharp.Templates.gsproj,Gsharp.NET.Sdk.Compiler.gsproj,Gsharp.NET.Sdk.props, andGsharp.NET.Core.Sdk.targetsexcludenet10.0runtime helper assemblies fromnetstandard2.0compilations. -
Byte-based emitted assembly loading in test fixtures, persistent pointer-escape narrowing invalidation across unknown callables, release tag-vs-NBGV version verification, source-referenced C# project loading in
SelfMigratedCompilerSource, MSBuild-evaluated stage-2 runtime-producer closure and locked-package test-output asset provenance checks,Issue3119.CrossConstantstest-asset relocation, retirement ofbuild/verify-migration-run.py, static delegate caching on capture-free<lambda_host_*>classes, andGS0637impossibleasconversion diagnostics (Fixes #4349, Fixes #4605, Fixes #4639, Fixes #4745, Fixes #4882, Fixes #4884, Fixes #4888, Fixes #4898, Fixes #4908, Fixes #4945).EmittedOracleand emitted-assembly test helpers acrosstest/Compiler.Tests,test/Core.Tests,test/Interpreter.Tests, andtools/cs2gs/Cs2Gs.Testsnow load emitted.dllbinaries from bytes or streams (EmittedFixture.Load,EmittedFixture.LoadTogether,Assembly.Load(File.ReadAllBytes(...)), andLoadFromStream) rather than file paths (LoadFromAssemblyPath,LoadFrom, andLoadFile) so temporary workspaces can be deleted cleanly during teardown without swallowed cleanup exceptions (#4349).BinderContext(RecordPointerEscapedArgumentandRecordPointerEscapedName),ConversionClassifier,ExpressionBinder.Operators, andOverloadResolverrecord bound address-of operands passed or converted to pointer-typed (*T/PointerTypeSymbol) targets as persistent pointer-escaped variable names so subsequent unknown callable invocations invalidate narrowing on the pointee local (#4605)..github/workflows/build.yml(Show Nerdbank.GitVersioning version) now checks thatv$(dotnet tool run nbgv get-version -v SimpleVersion)matches$GITHUB_REF_NAMEonrefs/tags/*runs before any pack or publish job starts (#4639).SelfMigratedCompilerSource.LoadOrCreateAsyncnow loads external C# source roots throughCSharpProjectLoader.LoadProjectWithReferencesAsyncso referenced projects bind against live source rather than stale output reference assemblies (#4745).build/selfhost-stage2.py(Controller.project_reference_closureandvalidate_vstest_extensions) evaluates transitiveProjectReferenceitems viadotnet msbuild -getItem:ProjectReference(#4882) and verifies that every file in a certified test output directory whose relative path exists in any locked package matches that locked package payload's SHA-256 hash (#4884).test-assets/Issue3119.CrossConstantsis relocated totest/Interpreter.Tests/TestAssets/Issue3119.CrossConstantswithtest-assets/removed (#4888), and the supersededbuild/verify-migration-run.pyverifier is retired (#4898).SlotPlanner(LambdaCollector),ClosureEmitter(SynthesizeClosures,RegisterClosureSymbols, andEmitClosureTypeDefs), andMethodBodyEmitter.Closures(EmitFunctionLiteralandEmitFunctionLiteralToNamedDelegate) synthesize a static<>9__cacheddelegate field on capture-free<lambda_host_*>classes and lazily cache the constructed delegate instance across repeated evaluations (#4908).ExpressionBinder.BindAsExpressionandCanPossiblyConvertViaAsnow reportGS0637(CannotConvertViaAs, pointing tocast[T](x)when an explicit conversion exists) when the operand's static type can never convert to theastarget type via a reference, boxing, unboxing, wrapping, or null conversion (#4945). -
Flow-aware
GS0612by-ref nullability checks, per-behaviorManagedReferenceTranslationTestssplit, in-memoryDriverReferenceLoadContextassembly loading and CRLF test normalization on Windows, host-fallbackDefaultInterpolatedStringHandlerresolution under user-only/reference:sets, conditional/cross-documentRepositoryVerbatimSourcesand mirror fidelity rules, relocated stage-2 test root and binary discovery viaCS2GS_TEST_SOURCE_ROOT, rebalancedCs2Gs.TestsCI shards, and CI stage-2 compiler PE fixpoint verification (Fixes #4454, Fixes #4571, Fixes #4635, Fixes #4636, Fixes #4867, Fixes #4873, Fixes #4895, Fixes #4897, Fixes #4925).BinderContext(NonNullByRefVariablesandHasNonNullByRefValue),StatementBinder(IsNonNullByRefInitializer,CollectNonNullOutCallVariables, andCallPreservesNonNullByRefVariable),ExpressionBinder.CheckByRefArgumentStorage, andConversionClassifier.AddressedLeafStorageTypenow suppressGS0612when areforinargument addresses aT?-declared variable whose current value is proven non-null by flow narrowing or a non-null initializer/assignment and the parameter is non-nullref Torin T, while continuing to reportGS0612onref T?/out T?writes into non-nullable storage and maybe-nullT?arguments passed toref T/in T(#4454).tools/cs2gs/Cs2Gs.Tests/ManagedReferenceTranslationTests.gsis split into five per-behavior test classes (ManagedReferenceTranslationTests,ManagedReferenceGenericStorageTranslationTests,ManagedReferenceCollectionExpressionTranslationTests,ManagedReferenceLambdaCallbackTranslationTests, andManagedReferencePatternTranslationTests) (#4571).DriverReferenceLoadContext(ReferenceResolver.gs),EmittedOracle,CSharpFixture, andCore.Testsreference-loading tests now load assemblies from in-memory byte streams instead ofLoadFromAssemblyPath, disposeMetadataLoadContextResolverinstances before temporary-directory cleanup, and normalize CRLF process output and lexer newline assertions on Windows (#4635).DefaultInterpolatedStringHandlerShape.TryResolvenow accepts the host-fallbackDefaultInterpolatedStringHandlerwhenSystem.Objectitself resolves from the host fallback (such as/reference:Gsharp.Extensions.dllwithout an explicit BCL reference closure) while still rejecting host-fallback leakage when an explicit BCL closure omits the handler (#4636).RepositoryVerbatimSources(ComputeCopyAndTranslate,CollectReferencedFiles,EvaluateItemElement, andCollectFileBasedAppHelpers),RepositoryMirror,RepositoryOrphanSourceTranslator,RepositorySolutionGenerator, andSdkPinpreserve both.csand.gscounterparts for conditional or target-scoped<None Include="...cs" />items, apply cross-document<Compile Remove>/<None Remove>acrossDirectory.Build.props/.targetsand canonical<Import>chains, keep file-baseddotnet runC# helpers (build/selfhost/PeBodyMutations.cs), skipexcludedScopepaths during SDK rebinding, suppress stray.slnxgeneration for template payloads and excluded.slnfiles, and rewrite$(IntermediateOutputPath)to$(OutputPath)on<DocumentationFile>when rebinding bootstrap projects (#4867, #4897).RepositoryRootMarker.Locateand tests inCore.TestsandCompiler.TestshonorCS2GS_TEST_SOURCE_ROOTandAppContext.BaseDirectorywhen running from relocated stage-2 output trees (#4873).build/generate-ci-test-matrix.pysplitsCs2Gs.Testsintoissue41-44,issue5, andmanaged-refshards and.github/workflows/build.ymlrestorestimeout-minutes: 60on thetestsjob (#4895).build/selfhost-fixpoint.pyand thefixpointjob in.github/workflows/build.ymlverify MVID-normalized PE equality between stage-2 and stage-3 builds ofGSharp.Core.dllandgsc.dll, andCONTRIBUTING.mdupdates the pin-move policy accordingly (#4925). -
Imported tuple overrides preserve nullable leaf contracts, and named delegates preserve nullable return metadata (Fixes #4756, Fixes #4795, Fixes #4763). Imported
TaskandValueTasktuple implementations support nullable reference and value leaves, including long tuples and open generic contracts. An oblivious base return permits a nullable tuple leaf, but an explicitly non-null base return rejects a nullable override withGS0185. The same check covers nullable tuple storage, by-reference returns, and explicit non-asyncTaskorValueTaskresults. Writablerefreturns require compatibility in both directions; ordinary andref readonlyreturns can strengthen the nullable contract. Covariant task subclasses use their annotated task-base result, while non-generic task contracts have no result position. The check reads receiver-projected metadata and compares semantic positions without erasing their nullability. Focused Roslyn-fixture, ILVerify, runtime-dispatch, andNullabilityInfoContexttests also protect the existing named-delegateInvokereturn metadata correction. -
Nullable storage for guarded
refaliases incs2gsandgsc(Fixes #4726, closes the remaining verification for #4719). Shared storage components connect variables, fields, array elements, aliases, ref arguments, and ref-returning methods, properties, and indexers. Fixed contracts and promoted array positions agree across linked source projects, including projects without local ref aliases. Fixed contracts take precedence. Constructed storage and reduced extension calls retain their nullable type arguments. Ref arguments constrain storage invariantly; out arguments retain directional output flow and exclude actual discard symbols. Array declarations and constructions consume component decisions at every nested depth, with cycle-safe queries and shared array-owner normalization. Null writes through array or ref aliases reach scalar return contracts across ref-returned arrays, ref parameters, and subarray aliases. Generated storage and existing null-write evidence still widen array elements without changing unrelated array-write decisions. Alias components attach the smaller member list to the larger. The translator emits matching storage types without!!. The compiler checks and infers a ref-local type from declared storage, not a smart-cast value read, and preserves alias-write invalidation. Runtime parity tests also verify cast-null and default tuple leaves in nested iterators without widening an unrelated outer iterator. -
Post-cut-over tidy, strict self-migration corpus/baseline equality enforcement, Portable PDB
.snupkgzeroed-IDPdbChecksumcalculation, transitive failed-dependency attribution incs2gs, native statement-formif letguards (&&) and value-position??=emission incs2gs, single-pass deeply nested tuple conversion classification,CustomAttributevalue-blob metadata drift digests, redundant!!elision on coalesces with platform-typed element reads, andGS0636jump-into-nested-block diagnostics (Fixes #4900, Fixes #4901, Fixes #4926, Fixes #4933, Fixes #4972, Fixes #4979, Fixes #5476, Fixes #5515, Fixes #5567, Fixes #5588).build/verify-migration-run.py(expected_apps) andbuild/check-selfmig-stage-floor.py(evaluate) now enforce total app-set equality between the discovered C# corpus andtools/cs2gs/selfmig-baseline.json, failing closed when any app in a migration run is absent from the baseline.ReflectionMetadataEmitter.BuildPortablePdbAndDebugDirectorynow computes the PEPdbChecksumSHA-256 digest insidePortablePdbBuilder'sidProvidercallback while the 20-byte#Pdbstream ID is still zeroed, matching the Portable PDB specification and NuGet Gallery's.snupkgsymbol package validator.CompileStage.ActiveCompileReferencePathsexpandsProjectReferencechains transitively so direct and transitive dependents of a failed referenced project becomedependency-blockedwithout locationless (gsFile: null) consumer artifacts.IfLetStatementandGSharpPrinter.RenderIfLetnow carry and print an optional&& <guard>expression andCSharpToGSharpTranslator.TryBuildIfLetGuardemits statement-formif let name = receiver && guarddirectly (including when anelsebranch is present).CSharpToGSharpTranslator.TranslateAssignmentAsExpressionand the nullability/flow analyzers now emit native G#(x ??= y)in value position instead of lowering to anifblock expression.Conversion(ClassifyCore,TryClassifyPlatformTypeArgumentMismatch,TryProjectPlatformArgumentsToSupertype,TryGetConstructedGenericArguments, andAreCrossContextIdenticalTupleElements) andTupleTypeSymbol(WithoutNamesandHasNilElement) now classify tuple-to-tuple andTupleTypeSymbol-to-System.ValueTupleconversions in a single pass per nesting level so deeply nested tuple literals passed to imported generic constructors bind in linear time.MetadataTableDigest.SummariseTablesnow includes aCustomAttributetable summary over parent token, constructor identity, and complete value-blob bytes.CSharpToGSharpTranslator.ReadsPlatformTypedImportTopLevelconsultsObliviousPositionsOfand recurses through??so coalesces whose right operand is a platform-typed element read omit redundant outer!!assertions (GS0536).StatementBinder(BindGotoStatement,DefineUserLabel,FinalizeUserLabels, andGetEnclosingBlockExpressions),LambdaBinder(FinalizeNestedFrameLabels), andBindernow reportGS0636(GotoIntoNestedBlock) at thegotostatement when jumping into a nested block from outside that block and suppress the cascadingGS0100diagnostic on the enclosing function or lambda. -
Internal ADR/issue citation removal from compiler diagnostics and
cs2gs --help,gsfmtspace before:in?:conditionals, non-nil branchy RHS underlying typing in??=, per-resolver UTF-8 literal member caching, bounded post-inference liveness diagnostic suppression indexing, streaming UTF-8 literal lexer scalar encoding, source-local Git mirror URL rewrites (insteadOf/pushInsteadOf) incs2gs, function-literal overload resolution against importedrefdelegate parameters, and declared-read recovery for narrowed nullable/optional values and cleanup branch blocks (Fixes #4953, Fixes #4981, Fixes #4984, Fixes #5383, Fixes #5384, Fixes #5385, Fixes #5411, Fixes #5560, Fixes #5631, Fixes #5636).DiagnosticDescriptors,DeclarationBinder.Attributes, andCs2Gs.Cli(Program,ValidateCommand, andCaptureTestOracleCommand) no longer cite internalADR-...records,issue #...numbers, or"nightly mode"in user-visible diagnostic messages and CLI--helpoutput (#4953).GSharpFormatter.NeedsSpaceBeforeColonnow includesConditionalExpressionSyntaxandConditionalRefArgumentExpressionSyntaxsogsfmtformats ternary conditionals asc ? a : bwith spaces on both sides of?and:(#4981).ExpressionBinder(BindNullCoalescingAssignmentExpression,BindNullCoalescingAssignmentStatement,TryRewriteNonNilRhsToUnderlying, andRhsArmsProveNonNil) now checks and rewrites target-typed conditional,if,if let,switch, block, and??right-hand sides ofx ??= yto the target's underlying non-nullable typeTwhen every completing arm proves non-nil while keepingT?when any arm may benil(#4984).ClrSpanTypes(TryResolveUtf8LiteralandTryResolveUtf8Type) andReferenceResolver.GetOrResolveUtf8LiteralMemberscache the resolvedReadOnlySpan<byte>,RuntimeHelpers.CreateSpan<byte>, andSlice(int32, int32)lookup perReferenceResolverinstance while preservingMetadataLoadContextisolation and missing-member diagnostics (#5383).DiagnosticBag(SuppressDuplicateDiagnostics,SuppressDuplicateDiagnosticsIn, andDuplicateSuppressionFrame) lazily indexes existing diagnostics byEquivalenceCompareronce per bag rather than copying the diagnostic list per root inRefStructAsyncLivenessAnalyzer.AnalyzeProgram, while preserving one-to-one multiplicity consumption, newly added diagnostics between roots, andfinally-based restoration (#5384).Lexer.ReadUtf8Stringnow streams decoded UTF-16 code units and pending high-surrogate provenance directly into the UTF-8 byte builder without allocating per-character strings, aStringBuilder, or aList[TextSpan](#5385).RepositoryGitMetadata.Preparecopies source-local (local,worktree, and included)url.<base>.insteadOfandurl.<base>.pushInsteadOfrewrite rules into the migrated Git mirror alongside rawremote.<name>.urlandremote.<name>.pushurlvalues without copying global config, credentials, credential helpers, or hooks (#5411).ExpressionBinder.TryResolveDelegateTargetFromCandidatesandResolveDeferredArrowLambdaArgumentsskiprefandoutparameters when resolving plain-value lambda targets soCalls.Ref(() -> 1, 1)selectsRef(object, long)with the natural delegate type instead of reportingGS0160(#5560).ConversionClassifier(ConversionNeedsNarrowedSource,TryRecoverDeclaredMemberRead, andDecideNarrowedConversion) andLambdaBinder.ReturnConversionRewriterrecover the declared read of a narrowed nullable reference or optional value (for both member paths and local variables, and across block expressions includingdefer/usingcleanup result locals) whenever the target or common branch type accepts the declared type without representation change (#5631, #5636). -
Same-compilation custom attribute named member arguments, qualified generic construction receiver extension resolution, deterministic
cs2gslifted local-function suffixes across partial documents, analyzer target-type filtering,gsfmt-clean polish output, partial-run baseline stale-gap filtering, and pinnedinstall-netcoredbg.shverification (Fixes #4610, Fixes #4638, Fixes #4650, Fixes #4667, Fixes #4683, Fixes #4798, Fixes #4815, Fixes #4858, Fixes #4883, Fixes #4887, Fixes #4894).DeclarationBinder.BindAttributeandCustomAttributeEncoder(EmitUserBoundAttribute,ValidateUserNamedAttributeMembers,TryResolveUserNamedMember, andWriteUserCustomAttributeNamedArg) now resolve, validate, and encode named property (0x54) and field (0x53) arguments on same-compilation custom attributes (StructSymbol), excluding indexers and reportingGS0613,GS0614,GS0615, orGS0245on invalid targets instead ofGS0466.ExpressionBinder.BindAccessorExpressionresolves package-qualified same-compilation source type constructions before imported CLR reflection fallbacks so chained extension calls on constructed generic values (ReceiveResult[T](value, ok).ToTuple()) bind to the source type rather than an imported homonym.LiftedLocalFunctionNameAllocator.TryBeginPreallocationandCSharpToGSharpTranslator(EnsurePartialAggregateLiftedLocalFunctionsAllocated,GetLiftedHelperScopeMapper,RegisterSynthesizedPropertyBackingField,CollectOwnedExtensions, andVisitAggregateCore) preallocate lifted local-function names and lowered property backing fields (scoped per owning aggregate and reserving primary-constructor parameters and document-scope imports across all partial parts) in canonical(FilePath, SpanStart)order across partial declarations.CSharpTypeMapper.IsAnalyzerTargetTypeskips<...>and[CompilerGenerated]types when enumeratingGSharp.Coreanalyzer target types.NullAssertionPolishPass.Stripformats modified.gsfiles withGSharpFormatter.Formatso polished migration output remainsgsfmt-clean.GapLedger.ClassifyandCs2Gs.Cli.Programfilter stale baseline gap checks to the stages actually executed per app and restrict partial-runUNVERIFIEDchecks to passing apps.ImportedAssemblySemanticsandImportedTypeSymbolcomments now document the all-classGSharp.TypeSemanticsmarker policy,docs/cs2gs-coverage-matrix.md.actualis removed with*.actualadded to.gitignore,build/test-cs2gs-apps-gate-issues.pycovers unreadable binary result files, andbuild/install-netcoredbg.shpins the3.2.0-1092release tarball with SHA-256 verification and makesGITHUB_PATHoptional outside CI. -
LSP
"params": nullshutdown handling,??=target flow narrowing,gsfmtnested block-expression line breaks, exact overload declaration mapping inSemanticLookup, linear-time pattern-switch header lowering, substituted generic method signatures inSemanticModeland hover, ARM64 host platform detection inverify-ci-test-partition.py,GS0127/GS0499readonly receiver member names on??=, and bareResponseFilePathhandling inBuildTask(Fixes #4686, Fixes #4978, Fixes #4983, Fixes #4997, Fixes #4998, Fixes #5002, Fixes #5008, Fixes #5022, Fixes #5047).LspJson.CreateFormatter(LspJsonFormatter) now strips top-level"params": nullbefore delegating toSystemTextJsonFormatter.Deserializewhen StreamJsonRpc rejects a null-params JSON-RPC request, soshutdownandexitrequests carrying"params": nullreceive{"result": null}and exit cleanly.ExpressionBinder(BindNullCoalescingAssignmentOperands,BindNullCoalescingAssignmentStatement,BindNullCoalescingAssignmentExpression,ProvesNestedNonNil, andTryBuildNullCoalescingReadWrite) andStatementBinder(ApplyAssignmentNarrowing,ApplySubExpressionNarrowingEffectsCore,ProcessBranchStatement,CollectConditionNonNullAssignments,NestedAssignmentPreservesNarrowing, andDischargesNullableWidening) now record the pre-conversion RHS type (including nested non-nil assignments across temporary storage and throwingneverfallbacks while rejecting unchecked platform values) on??=variable writes and narrow nullable reference targets afterx ??= vin both statement and expression positions whenvproves non-nil, while preserving reference-type-only narrowing and closure/goto invalidation.GSharpFormatter(IsLineContainerandIsLineItem) now treatsBlockExpressionSyntaxas a line container and its trailing expression as a line item so a nested{ ... }block stays on its own line after a preceding statement.SemanticLookup(BuildModelUncached,MapStructDeclaration, andMapParameters) now pairs each field, property, indexer, event, method, and surviving parameter declaration token directly with the symbol whose declaration is that syntax node instead of keying by member name or negative parameter offsets.BoundTreeRewriter.RewritePatternSwitchStatementWithDiscriminantandLowerer.RewritePatternSwitchStatementnow reuse the already-rewritten discriminant when falling back from constant-pattern switch folding, eliminating the $O(2^d)$ duplicate rewrite on nested switch headers.SemanticModel(GetSymbolInfo,ReferencedSourceSymbol,ReferencedCallSymbol,CreateSubstitutedSourceMember, andSubstituteGroupMember) now substitutes constructed generic receiver, static-owner, and base-call type arguments intoFunctionSymbolsignatures (including receiver-independent signatures, attached attributes, and receiver ref-safety flags) while preservingDeclarationfor go-to-definition and reference lookup.build/verify-ci-test-partition.pynow defaults/Platform:ARM64when runningdotnet vstestonarm64/aarch64hosts.ExpressionBinder.TryBuildNullCoalescingReadWriteandBindEventLikeCompoundAssignmentnow report the readonly variable/field or target member name inGS0127andGS0499instead ofSyntaxNode.ToString()'s ASCII tree dump.BuildTask.Executenow skipsDirectory.CreateDirectorywhenPath.GetDirectoryName(ResponseFilePath)is empty so a bare response filename like"first.rsp"succeeds. -
Expression-bodied function literals convert their result to the target delegate's return type, and
cs2gsbridges expression-bodied lambda results at declared non-null delegate slots (Fixes #5686).LambdaBinder.BindLambdaExpressionnow sets the return type of a target-typed function literal toplaceholderReturnTypewhenever the target delegate's return type is fixed (placeholderReturnType != TypeSymbol.Error && placeholderReturnType != TypeSymbol.Void) and no speculative natural-type fallback or expression-tree target applies, soEmitTrailingExpressionconverts the trailing body expression against the target delegate's return type and reportsGS0155when aT?result flows into a non-nullTdelegate return, matching the block-bodiedreturnform.ExpressionBinder.TryResolveDelegateTargetFromCandidates,ResolveDeferredArrowLambdaArguments,TryMapDeferredLambdaTargetsSymbolic,RebindFunctionLiteralDelegateArguments,ConversionClassifier.RequiresRuntimeDelegateReturnValidation, andMemberLookup(TryGetDelegateFunctionTypeFromSymbolandTryGetExpressionTreeDelegateTypeFromSymbol) preserve parameter-level and generic-argument nullability (T?andT!) and keepExpression<TDelegate>and inferred method-type-parameter returns on body-driven return inference, andExpressionBinder.TryBindLambdaExpressionWithTargetType,ConversionClassifier.BindConversion,StatementBinder, andDeclarationBinderthread the target delegate type into parenthesized,checked/unchecked, nullable-delegate, field-initializer, and tuple-element function literals while preserving outer lambda parameter scopes. Incs2gs,CSharpToGSharpTranslator.TranslateLambda,FindResultLambda,FindContextualValueTarget,ComposedValueOperands,GSharpExpressionIsStaticallyNonNull,RecordClassSynthesizedToStringIsNilableInGSharp,ForgiveNullableReferenceValueCore,TryBridgeTupleValue, andSlotTypeIsDeclared(LambdaHasExplicitDelegateCast,MemberSlotIsDeclared,LambdaFeedsDeclaredCollectionElement,ParameterSlotIsDeclared,LocalSlotIsDeclared, andReceiverTypeArgumentsAreDeclared) now route expression-bodied lambda results (includingchecked/uncheckedwrappers, conditional-access and same-compilation record-classToString()results, async and local tuple values, and nested expression and expression-tree delegate lambdas) throughForgiveNullableReferenceValuewhen the lambda's delegate slot is declared, emitting!!for values such asFunc<Dictionary<string, int>> read = () => Volatile.Read(ref full!);. -
Synthesized-import homonym alias pinning (
GS0547fail-safe), field-wise struct local definite-assignment initialization, transparent wrapper unwrapping onreftargets, expandedparams T[]result-free generic method null-forwarding, partial-run report verdicts,CS2GS_TEST_SOURCE_ROOTsupport inCore.Testsrepo-root helpers, in-treeGsharp.Runtime.*reference shadowing validation, and bounded child-process reads inAdr0151IfLetExpressionEmitTests(Fixes #4602, Fixes #4709, Fixes #4728, Fixes #4857, Fixes #4868, Fixes #4889, Fixes #4910, Fixes #4987).CSharpTypeMapper(TrackBarePrintedMetadataType,HasCompetingBarePrintedMetadataType, andCollectSynthesizedImportHomonymAliases) andCSharpToGSharpTranslatornow record bare-printed top-level metadata types, qualify or alias subsequent competing homonyms, and emitimport Name = Namespace.Namewhen a synthesized import introduces a homonym in the final import set.CSharpToGSharpTranslator.TranslateLocalDeclaration(RequiresStructFieldWiseDefaultInitializerandSyntaxNodeWritesMemberOfSymbol) emits= default(S)for uninitialized struct locals that are assigned through their fields before being passed byref.TranslateRefExpression,TranslateRefLocalDeclaration,GetRefAliasTargets, andWritesThroughStorageunwrap parentheses and postfix!suppressions onrefoperands throughUnwrapParenthesesAndSuppressions.IsObliviousImportedInferredTypeParameterTargetandIsImportedObliviousNullableTargetunwrapGetParamsElementTypefor expandedparams T[]arguments so unconstrained result-free generic methods omit runtime!!bridges while constrainedwhere T : classtargets keep them.RunResult.RequestedStages,MigrationPipeline,ReportModel, andHtmlReportWriterpersist the requested stage scope inrun.jsonand render stopped-early (--translate-only/--stop-after) runs as partial/unverified (isGreen: false) rather than green.CorePublicApiSnapshotTests.LocateRepoRootand siblingLocateRepoRoothelpers inCore.TestshonorCS2GS_TEST_SOURCE_ROOT.build/gsharp.build.props,build/gsharp.build.targets(_GsharpValidateInTreeRuntimeReferences),Compiler.gsproj,Repl.gsproj,LanguageServer.gsproj, and test projects opt out of duplicate SDK_ExplicitReferenceruntime copies and treatMSB3243as an error.Adr0151IfLetExpressionEmitTests.CompileAndRunreads stdout and stderr concurrently withReadToEndAsync()before boundedWaitForExitand kills the process tree on timeout. -
Condition-operand call invalidation for explicit-layout member paths, CRLF line-comment formatting in
gsfmt, canceled CI selector plan handling, async operand-temporaryGS0219source locations, unboxeddata structandinline structGetHashCode/ToStringdispatch, source-anchored base copy-constructor rejection, and in-repoTMPDIRC# fixture isolation (Fixes #5843, Fixes #5114, Fixes #5248, Fixes #5335, Fixes #5373, Fixes #5386, Fixes #5429, Fixes #5433).StatementBinder(OperandKillsStableMemberPath,HasSeparateMemberPathLinks,ClearOperandFacts, andClearAssignedRootsForConditionOperand) andStructSymbol(FieldsandPropertiescontainment anchoring) now drop member-path narrowing facts across calls in condition operands whenever any link of the path is declared in a source or imported type withLayoutKind.Explicit(or unknown layout), preventing overlapping mutable fields in explicit-layout types from invalidating aletlink without reportingGS0158.Lexer.ReadSingleLineCommentnow consumes\r\nas a single line terminator andGSharpFormatter.FormatCoretreats canonical CRLF inputs as unchanged (returning the originalSourceTexton no-op range formatting) sogsfmt --checkandgsfmt --diffdo not insert blank lines after//comments or reject CRLF checkouts of canonical files.build/ci-selection.py(check_results) now handles empty or malformedPLANvalues fail-closed with an explicit cancellation or missing-plan error instead of raisingJSONDecodeError.AsyncBoundTreeQueries.FindFirstAwaitSyntax,RefStructAsyncLivenessAnalyzer.ReportIfUnsafe,Lowerer.LowerAwaitForRange, andConversionClassifier.TryBuildDisposeAsyncCallpreserve syntax locations on loweredawait,await for, andawait usingsuspensions soGS0219diagnostics on synthesized operand temporaries carry source locations.StructSymbol(DataGetHashCode,DataToString,GetDeclaredInstanceMethods, andTryGetMethod),ReflectionMetadataEmitter,DataStructSynthesizer, andUserTokenResolverexpose synthesizedGetHashCode()andToString()methods ondata structandinline structvalue types so direct calls emitcallon the receiver address without boxing while explicit conversions toobjectretain boxing.DataStructSynthesizer.TryResolveBaseCopyConstructorTokenwraps missing base copy-constructor errors inEmitDiagnosticException.Wrap(structSym.Declaration, ...), andDefaultInterfaceMethodsEmitTests.WriteIsolatedCsProjectisolates temporary C# test fixtures intest/Compiler.Tests/Emitfrom ancestor repositoryDirectory.Build.props,Directory.Build.targets, and.editorconfigfiles whenTMPDIRis inside the checkout. -
Synthesized by-reference delegates for arrow lambdas without an explicit delegate target, CLR overload resolution ref-kind ranking, and
GS0154Nullable<V>storage diagnostics for imported constructors, conditional-ref arguments, and extension methods (Fixes #4415, Fixes #4418, Fixes #4464).BoundScope.TryGetSynthesizedRefDelegateForLiteral,StatementBinder.BindOrdinaryVariableDeclaration,ExpressionBinder(BindBlockExpressionParts,BindTupleLiteralExpression),OverloadResolver(BindIndirectCallExpression,TryBindFunctionTypeArguments,TryBindNamedDelegateArguments,BindConstructorCallExpression), andLambdaBinder(CreateErasedFunctionLiteralAdapter,ErasedFunctionLiteralAdapterRewriter) now infer and materialize synthesizedSynthesizedRefDelegateCachedelegate types for arrow lambdas within,ref, oroutparameters in untargeted variable declarations, block expressions, tuple elements, and direct invocations while preserving target-typed parameter inference against delegate and(in ...)function-type parameters.ClrOverloadResolution.IsBetterOmittedByRefPassingMode,ExpressionBinder.MakeSymbolicArgumentConversionClassifier,MemberLookup.TryResolveClrIndexer, andOverloadResolver.ValidateRefArgumentsrank by-value parameters ahead ofinandref/outparameters for modifierless arguments and classify mismatched explicitin/ref/outmodifiers and readonly storage against writableref/outparameters asDelegateRefKindMismatchduring overload resolution while still reportingGS9002,GS9009, orGS0235when a single candidate remains.ExpressionBinder.TryReportValueNullableByRefArgument,TryReportClrConstructorByRefArgumentStorageMismatch,TryReportClrConstructorInlineOutTypeMismatch, andDeclarationBinder.BindBaseConstructorCallunwrapBoundConditionalAddressExpressionviaByRefStorageMatching.TryGetStorageType, probe imported extension methods, and prioritizeNullable<V>vsVpointee mismatches across constructor and base-constructor candidates to reportGS0154with theNullable<V>runtime-type explanation. -
A write of a
varfield keeps the narrowing facts on stable member paths (Part of #5786; ADR-0208 R21). Since #5796, a write of a source auto property that runs no user code keeps the facts on member paths. A field write still removed every member-path fact, soif b.Pet !is Dog { return "" }; b.Other = 1; return b.Pet.Bark()reported GS0159, andif owner != nil { this.owner.A = true; this.owner.B = true }withvarfields reported GS0158. A link of a stable path is aletfield, which only a constructor can write. SoAssignedRootsCollectornow treats aBoundFieldAssignmentExpressionof a field that is notletlike an auto-property write. A constructor write of aletfield, an index, indirect or imported write, a write whose location can hold the storage of a by-reference root (R20), a write of a member of an imported type or of a type with explicit layout (fields can overlap), a write of an interface field, and a loop or backward-jump region still remove the facts. A separate write through a by-reference value receiver, such asthis.count = 4in a struct method, keeps the member-path and[MemberNotNull]facts of that receiver, and removes the member facts of every other root, which can name overlapping storage. The first read or write of an interfacesharedfield now counts as user code when the interface declares a field initializer that is not a literal, the same test as for a struct or class (ADR-0208 R11, #5520). A[MemberNotNull]fact on a bare field (#5830) is a fact on a member ofthisand uses the same decision: a write of anothervarfield keeps it, a write of the same field through any receiver removes it, and a write that can replace a structthis(R20) now removes it too. An increment or a compound assignment of a named member (owner.N++,owner.N += 2) uses the same classification as a plain write. A write in an operand of a condition (&&,||,?:) uses the same overlap rule as a statement, so a write that can overlap aletlink of an explicit-layout type removes the fact on the earlier operand. The tests for bare-name write receivers from #5804 (compound assignments, increments, index and rectangular writes,[MemberNotNull]receivers and negative controls) are included. -
Nested pointer array generic-call look-ahead, short-circuit nullable function-pointer narrowing, function-pointer
T -> T?lifting and display, null-conditionalfn?()function-pointer calls,o is T ? a : bconditional parsing, defaultSystem.Linq.Expressionsreference resolution,SymbolPrinterimported/member symbol formatting, andNullable<T>.GetValueOrDefault()for user structs/enums andstruct-constrained type parameters (Fixes #4944, Fixes #4949, Fixes #4950, Fixes #4951, Fixes #4970, Fixes #4975, Fixes #4992, Fixes #5001).Parser.TryScanTypeClauseCorenow enablespointerAllowedafter an array or slice prefix so generic calls such asList[[]*int32]()scan as generic instantiations rather than indexers.SmartCastStability.TryClassifyNilGuardLeafremoves the obsoletereferenceNullableOnlyparameter so short-circuit&&/||and statement nil guards share value-type nullable and function-pointer narrowing uniformly.Conversion.ClassifyCoreadmits implicitT -> T?widening forFunctionPointerTypeSymbol, andNullableTypeSymbol.ComputeDisplayNameandSymbolDisplay.FormatTypeparenthesize nullable function pointers as(unmanaged[CC] (…) -> R)?and(*func(…) R)?.OverloadResolver(BindCallExpressionAfterArgumentsandBindNullConditionalIndirectCallExpression) andExpressionBinder(TryBindUserCallableMemberInvocation,TryBindClrDelegateMemberInvocation, andTryBindClrStaticDelegateMemberInvocation) support null-conditional invocationfn?()on nullable function pointers.Parser(ParseOptionalTrailingTypeQuestionTokenandShouldLeaveQuestionTokenForConditional) leaves?for an enclosing ternary conditional wheno is T ? a : boro !is T ? a : bis followed by a conditional arm and matching:.ReferenceResolver.WellKnownBclAssemblyNamesincludesSystem.Linq.ExpressionssoExpression[Func[T]]resolves in top-level signatures without requiring an earlier expression-tree load.SymbolPrinter.WriteToandSymbolDisplay.ToDisplayPartsformatImportedFunctionSymbol,ImportedClassSymbol,FieldSymbol,PropertySymbol, andEventSymbolwithout throwing.ExpressionBinder(TryBindSymbolicNullableInstanceCallandGetImportedExtensionProbeReceivers) andImportedMemberRefFactory.TryNormalizeToSymbolicContainerbind and emitNullable<T>.GetValueOrDefault()andNullable<T>.GetValueOrDefault(T)over same-compilation structs, enums, andstruct-constrained type parameters, including after smart-cast guards. -
Nested
foreachtuple deconstruction arity preservation and managed-reference array projections across collection spreads, extensionGetEnumerator, non-tuple positional patterns, expression-tree query operators, andforeach/query reference conversions incs2gs(Fixes #4566, Fixes #4569, Fixes #4575, Fixes #4576, Fixes #4581, Fixes #4583).CSharpToGSharpTranslator.TranslateForEachVariable(CollectForEachVariableTargets,CollectForEachTupleArgumentTarget, andCollectForEachDesignationTargets) now preserves the outer tuple arity inForTupleInStatementandawait foreachdeconstructions by allocating collision-safe structural carrier names (AllocateDeconstructionTempName) for nested tuple designations and emitting nestedlet (...) = <carrier>prelude statements at the start of the loop body.GetManagedReferenceArrayProjectedCollectionType,GetCollectionProjectionElementType,GetProjectedSpreadElementType, andGetCollectionAddParameterTypenow resolve constructible collection element types acrossAddcontracts andSpan<T>/ReadOnlySpan<T>or enumerable spread elements ([..widened]), andTranslateLocalDeclarationpreserves projected collection local types on explicitly typed declarations.GetProjectedForEachElementTypeandForEachMatchesProjectedCollection(TryGetProjectedForEachEnumeratorElementType) now project extension-basedGetEnumeratorandGetAsyncEnumeratorcalls (ReducedFrom) and theirCurrentproperty through the projected collection receiver.RegisterProjectedNativePatternBindings,FindProjectedPatternBindingType, andPatternMatchesProjectedInput(GetProjectedPositionalSubpatternTypeandGetProjectedPatternMemberType) now project non-tuple positional record andDeconstructpattern slots throughTryGetPositionalMembersandTryResolvePositionalSlot.ResolveRangeVariableElementTypeSymbol(TryGetQueryOperatorRangeType) now unwrapsSystem.Linq.Expressions.Expression<TDelegate>parameters and projects instance and extension query operators onto projected query sources.GetProjectedBindingTypenow resolves constructed generic base types and interfaces from the projected source's receiver hierarchy (GetReceiverTypeHierarchyand array interface conversions) across implicit reference and boxing conversions. -
Explicit-layout auto-property diagnostics (
GS0347),BoundGlobalScope.Referencesretention inBinder.BindProgram, source nominal generic delegate conversions, variadic slice element types (...[]T), type-inferredconstmembers insharedand type bodies, generic constructor lambda parameter substitution, anddata classPrintMembersinheritance across abstract base slots and imported non-data intermediaries (Fixes #5834, Fixes #4729, Fixes #4730, Fixes #4836, Fixes #4837, Fixes #4838, Fixes #4876, Fixes #4877).StructLayoutBinder(ValidateAndAttachandValidateExplicitLayoutAutoProperties) now reportsGS0347on instance auto-properties and unannotated instance fields declared on@StructLayout(LayoutKind.Explicit)classes and structs while keeping static auto-properties and computed properties valid.BoundGlobalScope.ReferencesandBinder.CreateParentScoperetain theReferenceResolverused to bind the global scope whenBinder.BindProgram(globalScope)is called without an explicitreferencesargument, so imported generic class constructors closed over tuple type arguments bind in method bodies.Conversion(IsClassLikeReferenceType,IsSealedReferenceType, andAreSameConstructedDelegateIdentity) andMethodBodyEmitter.IsReferenceCompatibleclassifyDelegateTypeSymbolas a sealed nominal reference shape with tuple-element-name identity across constructions.VariadicCarriers.IsCarrierTypetreats 1D non-collection-element slice types (...[]T) as the element type of a slice-of-slices variadic ([][]T) while preserving explicit jagged array carriers (...[][]T) and collection-element array carriers (...[]List[T]).FieldDeclarationSyntax.Type,Parser.ParseFieldDeclaration,DeclarationBinder.Structs, andDeclarationBinder.Interfacesallow omitting the type clause on initializedconstfield declarations (const Name = expr) insideshared { }and type bodies, inferring the constant's type from its initializer.OverloadResolver.BindExplicitConstructorCallExpressionsubstitutes the constructed class's type arguments into the constructor parameter type before target-typing lambda arguments.StructSymbol.GetUnimplementedAbstractMethodsincludesGetDeclaredInstanceMethods()so a deriveddata class's synthesizedPrintMembers(StringBuilder) boolsatisfies an inherited abstractPrintMembersslot, andDataPrintMembersModel.GetBasewalks the imported CLR base chain to select the nearest compatible virtualPrintMembers(StringBuilder)slot whenever an imported record or data class is present in the hierarchy. -
[MemberNotNull]bare-field narrowing invalidation across other-receiver field writes and calls, static explicit-interface clauses targeting imported CLR interfaces, symbolic method type-argument inference on constructed generic static calls, and collection-initializerT?element nullability checks (Fixes #5830, Fixes #4625, Fixes #4627, Fixes #4690).StatementBinder.AssignedRootsCollector(VisitFieldAssignmentExpression,VisitPropertyAssignmentExpression,RecordWritableReference,AssignsRoot, andMayMutateImplicitMembers),DropsOnMemberMutation,NarrowFieldIfNullable, andDecideRegionKillnow record field and property writes by member symbol regardless of receiver expression, restrict[MemberNotNull]post-conditions tothisreceivers, and invalidate implicit member narrowings across calls and member writes so writing or clearing the same field through another reference (other._name = nilorother.Clear()) removes the bare-field narrowing and reportsGS0158.DeclarationBinder(ResolveExplicitInterfaceClauses,ResolveExplicitClrInterfaceImplementations,VerifyExplicitInterfaceClauseResolution, andTryFindClrStaticVirtual*Implementation),TypeMemberModel,ExplicitInterfaceMetadataNaming,InterfaceImplEmitter,MemberDefEmitter, andTypeDefEmitternow resolve and emit static explicit-interface methods, properties, and events targeting imported CLR interfaces (shared { func (IS) Z() ... }), preferring explicit implementations over implicit name matches while excluding them from ordinary static lookup.ExpressionBinder.TryBindSymbolicImportedStaticCall,ImportedClassSymbol.TryResolveStaticMethodOverload, andMemberLookup(GetClrOpenParameterTypeSymbolandMergeSymbolicAndClosedMethodTypeArgs) now infer and substitute method type arguments on static generic methods of constructed generic receivers (ImmutableArray[Base].CastUp(derivedItems)).ConversionClassifier.BindClrParameterConversionsnow projects receiver generic parameters forNullableTypeSymbolarguments in synthesized collection-initializerAddcalls (List[string]{ maybe }), reportingGS0155when aT?element is supplied to a non-nullableTcollection literal. -
Throwing
switch-expression arms andnever-typed control-flow branches no longer emit unreachable result stores or branches afterthrow(Fixes #5806).MethodBodyEmitter(EmitSwitchExpression,EmitPatternSwitchStatement,EmitConditional,EmitStatement,EmitExpressionCore, andEmitConversion) andSpillSequenceSpiller(SpillSwitch,SpillSwitchWithGuardedAwait,SpillSwitchWithPatternAwait,AppendSpilledSwitchExpressionArmResult,SpillConditional, andSpillNullCoalesce) now omit the resultstloc,pop,ret, and merge-targetbrafter anyTypeSymbol.Neverexpression, preventing ILLink (Mono.Cecil.Cil.CodeWriter.ComputeMaxStack) from under-computing.maxstackon trimmed methods and NativeAOTilcbodies. -
Nested partial types in
gsgenstubs and implementing-part headers,ILocalReferenceOperationvsIParameterReferenceOperationdiscrimination incs2gsanalyzer mode, array-storage element widening across all array creation forms forout/refT?arguments, and#4287receiver-diagnostic and expression-tree follow-ups (Fixes #4471, Fixes #4475, Fixes #4491, Fixes #4492).GsStubRenderer,GsToCSharpTypeSpeller,GeneratedDocTranslator.SpellDataTypeParts,ImplementingPartHeaders.FindDeclaringPart, andCSharpToGSharpTranslator.TranslateGeneratedRegexDefinitionnow project nested user types and partial-method definitions in the C# generator stub, preservedatamodifiers and copy declaring-part headers across enclosing-to-nested type chains (SemanticAbstractTypeKey), and translate nested[GeneratedRegex]definitions to G# declaring parts unless nested inside an interface.RoslynAnalyzerApiMap.OperationKindDispatchandCSharpToGSharpTranslator(GuardOperationHandlerandMapPatternTypeSyntax) now guardOperationKind.LocalReferenceandOperationKind.ParameterReferenceregistrations and discriminateILocalReferenceOperationandIParameterReferenceOperationpattern tests onBoundVariableExpression.Variable(LocalVariableSymbol and not ParameterSymbolvsParameterSymbol).CSharpToGSharpTranslator(IsWidenedArrayElementStorage,PromoteIfUsedAsNullable,PromoteElementTypeForNullElements, andTranslateArrayCreation) now decidesout/refT?element widening on the array storage symbol and applies it across declarations and all array creation, initializer, and collection-expression forms.ExpressionBinder.TryReportStatedNullableReceiverCallrolls back speculative delegate-member diagnostics before reportingGS0159on a statedT?receiver,RoslynAnalyzerApiMap.GSharpNullableCapableTypesincludesMicrosoft.CodeAnalysis.INamedTypeSymbol, andCSharpToGSharpTranslator.ReceiverIsNullableReferenceFieldOrPropertyasserts nullable reference local and parameter receivers inside expression-tree lambdas. -
Raw-pointer and function-pointer
data struct,data class, andinline structsynthesized members, andGsharp.NET.SdkPrepareForILLinkpreservation for Android NativeAOT and trimmed publishes (Fixes #5818, Fixes #5819).DataStructSynthesizer,ConversionEmitter.EmitBoxIfNeeded,MethodBodyEmitter.Operators,MethodBodyEmitter.MemberAccess,DataPrintMembersModel.GetPrintableMembers, andClrOverloadResolution.SatisfiesGenericConstraintsnow compare raw pointer (PointerTypeSymbol) and function pointer (FunctionPointerTypeSymbol) fields withceq, convert them withconv.itoSystem.IntPtr(nint) forHashCode.Combine/HashCode.Add/EqualityComparer<nint>.Default.GetHashCodeand boxing, emitldind.i/stind.ifor indirect pointer loads andDeconstructoutstores, skip pointer and function-pointer members inPrintMembers, and reject pointer, function-pointer, and by-ref type arguments during generic constraint checks without throwingGS9998.Gsharp.NET.Core.Sdk.targetsnow runs_GsharpPrepareForILLinkbeforePrepareForILLinkwhenPublishTrimmedorPublishAotis enabled, writinggsharp.trimmer.xml(<assembly fullname="System.Runtime" preserve="all" />) into@(TrimmerRootDescriptor)and registering enabled bundled SDK runtime helpers (Gsharp.Extensions,Gsharp.Runtime.Channels, andGsharp.Runtime.Values) in@(TrimmerRootAssembly)withRootMode="All". -
Behavior fix: a value-type write that can replace the storage of a struct
thisor arefroot removes the narrowing facts on its member paths (Fixes #5827; part of #5786; ADR-0208 R20). Since #5796, a write of a source auto property that runs no user code keeps the facts on member paths. A structthiscan name the backing field of an auto property: insideclass Holder { prop Tok Token { get; set; } },Tok.Restore(this, ...)runsRestoreon that field. Soh.Tok = freshinRestorereplacedthis.owner, and gsc acceptedthis.owner.Aafter it, which threwNullReferenceException.AssignedRootsCollectornow records each member, index and indirect write, andMayWriteStorageOfremoves the facts on the member paths of a by-reference root (a structthis, arefparameter, areflocal) whenStatementBinder.StorageWriteMayOverwriteRootfinds that the written location can hold the storage of that root: the same type, a value type other than a primitive, an enum or a pointer (a containing struct, a tuple, a generic struct orNullable<T>), or a reference of an overlapping type. A scalar or reference write, such asthis.owner.A = true, keeps the facts. ADR-0208 now records the #5796 relaxation and this rule as row R20. -
A
constlocal in a staticinitblock no longer fails with GS9998 (Fixes #5797). The slot planner gives aconstlocal no IL slot, so the emitter inlines each read of it from theconstbindings of the method body. Each body emitter recorded these bindings with a separate call, and the type initializer of a class or struct without an initialization plan did not. A read of aconstlocal of ashared { init { ... } }block that the binder does not fold, such asd.ToString(),e.Length, or"${d}", failed with "Variable 'd' has no local slot or parameter index in the current method." Before #5800 gave a block with a capturing function literal an initialization plan, a function literal that captured the local failed the same way.MethodBodyEmitSession.PlanandPlanIndependentnow record theconstbindings of each region they plan, so each method body has them. For example,const d int32 = 300andS = d.ToString()give300. -
Optional null-default parameter lifting on symbolic receivers, nested and by-ref imported
T?method type-argument inference, range-slice return nullability when returning the receiver's own type, and imported CLR operator return/operand nullability regression tests (Fixes #4403, Fixes #4429, Fixes #4473, Fixes #4487).MemberLookup's symbolic parameter readers (GetClrMethodParameterTypeSymbol,GetIndexerParameterTypeSymbol, andGetClrOpenParameterPointeeTypeSymbol) now shareClrNullability.HasOptionalNullDefaultandNullabilityImportRule.ApplyNullDefaultLiftwithClrNullability.GetParameterTypeSymbol, lifting optional null-default parameters (T value = default) toT?when substituted with a reference type (and unwrappingByRefTypeSymbolpointees while preserving non-nullable collection zero-value obligations on brace/spread literals inMagicCollectionZeroValue.TrySynthesizePrimaryArgument), leaving value-type and unconstrained in-scope type-parameter substitutions unchanged, and removing the#4403optional-null-defaultexcusal fromReaderAgreementAllowlist.MemberLookup.UnifyForMethodTypeArgsandClrNullability.GetParameterDeclaredState(parameter, position)now track the pre-order[Nullable]flag index against the open declaration layout (ClrNullability.GetOpenParameterDefinition, including across delegate and expression-treeInvokeslots viaDelegateArgLayout) across by-ref parameters (ref T?,in T?), arrays (params T?[]in both expanded and normal forms, andT?[]), tuples, and constructed generic parameter types (IEnumerable<T?>,IList<T?>, and constructed generic receivers) and applyNullabilityImportRule.InferOpenSlotArgumentat each method type-parameter leaf so a reference-typedX?argument infersT := X.ExpressionBinder(BindSpanLikeSlice,BindRangeIndexerSlice, andBindRangeValueSlice) now reads range-slice results directly throughMemberLookup.GetClrMethodReturnTypeSymbolandMemberLookup.GetClrPropertyTypeSymbolwithoutSliceResultType's identity shortcut so a slice member returning the receiver's own type preserves[Nullable(2)](T?) and[NullableContext(0)](T!), andAdr0193FunnelMergeTests/Adr0186NullabilitySwitchTestscover imported CLR unary and binary operators with nullable reference returns. -
Definite-assignment diagnostics for unassigned
outparameter reads (GS0239), bare inherited CLR event subscriptions (+=/-=), importedprotectedinstance member access through derived-class receivers, and friend-assemblyprotected internal(FamORAssem) visibility (Fixes #4417, Fixes #4434, Fixes #4463, Fixes #4467).DefiniteAssignmentAnalyzernow seedsoutparameters into the use-tracked set (AnalyzeWithCaptured) and reportsGS0239inCheckTrackedUsewhenever anoutparameter is read before definite assignment on any value-read path (including explicit and implicitinarguments, operator operands, member and index receivers, compound assignments, closures, and partial branch joins).ExpressionBinder.BindBareEventOrCompoundAssignmentnow resolves bareEvent += handlerandEvent -= handlersubscriptions inside a class deriving from an imported CLR base type againstGetInheritedClrBaseType, applying the sameIsCallableClrEventAccessor/ResolveNonPublicClrEventaccessibility rules asthis.Event += handler.ExpressionBinder.IsFamilyAccessibleClrMember(backed byAccessibilityChecker.IsReceiverWithinClass) now governs importedprotectedinstance method calls, delegate-member invocations, method groups, property and field reads/writes/compound writes, and indexers so access succeeds through a receiver typed as the deriving class or a subclass and reportsGS0379through the imported base class or a sibling subclass.ClrMemberVisibility.IsVisible(along withMemberLookup,ImportedClassSymbol,ImportedTypeSymbol, andExpressionBinder.Literals) now admitsIsFamilyOrAssembly(protected internal) members and constructors whenInternalsVisibleTogrants internal access while keepingIsFamilyAndAssembly(private protected) hidden from non-derived types. -
Omitted imported
inandref readonlyoptional arguments use correctly typed readonly temporaries, and nullable optional parameters preservedefault(T)values (Fixes #5714). Methods, constructors, base initializers, and indexers retain enum, nullable, decimal, date, boxed, and generic defaults withoutGS9998.T? = default(T)retains a present zero for primitive, enum, and decimal values, including metadata round-trips;default(T?)stays missing. Non-simple struct defaults, including open value-type parameters, that cannot round-trip as present nullable values reportGS0265instead of silently becomingnil, matching C#'s metadata restriction. -
Deferred struct method calls preserve receiver storage (Fixes #5707).
defer host.counter.Bump()anddefer items[index].Bump()now mutate the original field or element. The reference owner, array, and indices are captured eagerly, before the arguments. Locals, by-reference parameters and aliases, and mutable global/static fields retain their storage; reference-type and rvalue receivers still evaluate eagerly. -
Goroutine calls preserve global value-type receiver storage and reject by-reference arguments (Fixes #5708).
go global.Bump(), nested global fields, and static struct receivers mutate live storage instead of a work-item copy. Value arguments and reference-type receivers still capture their values eagerly. Calls withref,out, orinarguments, including implicitin, report GS0460, matchingdefer. -
Goroutine calls reject by-ref-like operands with
GS0219and preserve live global writes in argument blocks (Fixes #5836).StatementBinder(CaptureGoOperand,CaptureCallReceiver,CaptureCallReceiverCore,HoistArgumentBlock, andBindGoStatement),ClosureCaptureLegalityChecker,GoCapturedVariableCollector, andClosureEmitterspill by-ref-like (ref struct)goreceivers and arguments into capture-checked temporaries so they reportGS0219instead of evaluating late in the child goroutine or forcing subsequent operands into the child, evaluate unmanaged pointer address inputs on the spawning goroutine without retaining later arguments, and keep global variables out of work-item snapshot fields so argument blocks and child expressions mutate live global storage. -
Speculative lambda return values reuse nested function literals, expression-bodied interpolated strings target-type to
IFormattable/FormattableString, and sequential retried returns roll back operand-local deltas in linear time (Fixes #5578, Fixes #5604).StatementBinder.BindReturnStatementandBindDeferredTargetTypedReturnnow retry target-typedreturnvalues (?:,switch,if,if let, block,??, andIFormattable/FormattableStringinterpolations) that contain function literals by caching innerLambdaBinder.BindLambdaExpressionandBindFunctionLiteralExpressionresults (BinderContext.RetriedFunctionLiterals) and reusing local, pattern, parameter, type-parameter, and direct-call local-function symbols declared inside the retried value (BinderContext.RetriedValueVariables,RetriedTypeParameters,RetriedLocalFunctions), so nested speculative literals bind in linear time and fall back to their natural function type when the outer return fails the delegate target.Binder(BindLambdaBodyExpressionForLambdas) andStatementBinder.BindFormattableReturnValuetarget-type expression-bodied interpolated-string lambdas (() -> "x${1}") toIFormattableandFormattableStringwhile preserving the naturalstringfallback inLambdaBinder.DeferredReturnState.StatementBinder.CaptureSpeculativeBindState,CaptureSpeculativeAfterTarget,RestoreSpeculativeBindState, andLambdaBinder.DeferredReturnState.CaptureDelta/TruncateToreplace full-collection snapshots of narrowing frames, labels, jumps, finally blocks, and held returns with watermarked undo logs and copy-on-write narrowing frames so sequential retried returns bind in $O(R)$ time. -
cs2gsoblivious container flow for metadata overrides/implementations, generic-call return aliases, deconstructed tuple call results, multi-assignment tuple deconstructions, and inherited CLR collection indexers (Fixes #5566, Fixes #5584).CSharpToGSharpTranslator.SignatureKeyandDeclaredPositionsnow key source members of an override or interface-implementation group that includes a metadata member on their shared source group representative while leaving metadata declarations unpromoted,AddAliasedSourcePositionspropagates required container positions backward through generic method return type-parameter bindings into argument storage,DeconstructedBindingHasObliviousContainerElementsrecognizes implicitly typed deconstruction bindings whose tuple element is non-null at top level with nested nullable positions,TryLowerNativeMultiAssignmentroutes tuple-literal elements throughTranslateValueWithNullForgiveness(TupleElementSlotProvesNonNull/StoreTargetProvesNonNull), andExpressionBinder(BindIndexAgainstTarget,BindIndexAssignmentAgainstTarget,BindRectangularIndexAgainstTarget,BindSystemIndexAccess,BindSystemIndexAssignment,BindRangeSlice,BindRangeValueSlice, andTryBindMultiIndexUserAssignment) resolves inherited CLR indexers and slices throughGetInheritedClrBaseTypewhen a user class declares no matching indexer of its own. -
Chained member reads in
GSA0005, generic partial-method header copying ingsgen, statement-scoped#pragma warning disable GSA####translation incs2gs, and namespace-alias type resolution inside same-named nested classes (Fixes #4395, Fixes #4439, Fixes #4447, Fixes #4455).RewriterClonePreservationAnalyzer.CollectReads,BaseClassCycleUnsafeWalkAnalyzer.GetBaseClassAccess, andCSharpToGSharpTranslator.TryTranslateAnalyzerMemberAccessnow extract a member access's identifier viaRightPart.GetFirstToken()rather thanGetLastToken()so G#'s right-nestedAccessorExpressionSyntaxchains (rewritten.Candidates.Length) record the member read off the receiver.ImplementingPartHeaders(FindDeclaringPart,ParameterNameMismatch, andHeaderIdentifiers) now matches generic partial methods by method type-parameter arity, reportsGS9208when a generated implementation renames a method type parameter, and excludes method and enclosing-type type-parameter names fromHeaderIdentifiersbefore selecting alias imports.CSharpToGSharpTranslator(TranslateBlockandCSharpToGSharpTranslator.PragmaSuppressions) now translates statement-scoped#pragma warning disable GSA####/#pragma warning restore GSA####regions inside method bodies into@SuppressDiagnostic("GSA####") { ... }blocks (or@SuppressDiagnostic("GSA####")on local declarations whose variables remain in scope after the region) and reportsCS2GS-PRAGMA-DROPPEDwhen aGSA####pragma region cannot be mapped to a declaration or statement range.Binder(TryResolveUserNestedTypeChain,TryResolveOuterPrefixWithArity,LookupType, andTryResolveDottedClrType) now expands leading import aliases viaBoundScope.ExpandQualifiedTypeNameand resolves source-type aliases by package-qualified identity (TryLookupQualifiedSourceType) so namespace aliases inside same-named nested classes resolve to the aliased namespace's type rather than the enclosing nested class. -
Static
initblock interpolated-string lowering, narrowed-expression assignment invalidation across indexed writes, immutablePartialTypeMerger.NormalizeNestedTypes, and readableGS0611parameter mismatch diagnostics (Fixes #5801, Fixes #4985, Fixes #4399, Fixes #4424).InterpolatedStringHandlerLowerer.RewriteFieldInitializersandLowernow rewriteStructSymbol.StaticInitializerStatementsandBoundProgram.InitializersbeforeInitializationPlanner.Prepare, preventingGS9998(Bound expression kind 'InterpolatedStringExpression' is not yet supported by the emitter) when ashared { init { ... } }orshared class { init { ... } }block contains an interpolated string.ExpressionBinder.BindNativeSliceIndex,BindNativeSliceAssignment,BindNativeSliceCompoundAssignment, andBindIndexedAssignmentToVariableCoreevaluate and apply sub-expression narrowing effects (StatementBinder.ApplySubExpressionNarrowingEffects) on native-slice index expressions before binding the right-hand side, completing in-expression assignment invalidation across narrowed regions (if,if-expression,&&,||,?:,switch, and indexed writes).PartialTypeMerger.NormalizeNestedTypesandMergePartialNestedTypesreturnStructDeclarationSyntax.WithMemberListscopies instead of mutatingnode.NestedTypesin place on the parsedSyntaxTree, andPartialMethodMerger.ValidateConsistencyformats parameter source spans (FormatParameterText) instead of internal token-kind comparison keys inGS0611diagnostics. -
SpillSequenceSpillerlowersawaitexpressions inside pattern values acrossisexpressions,switchstatements, andswitchexpressions (Fixes #5696).AsyncBoundTreeQueries.HasAwait(BoundPattern)andSpillSequenceSpiller(SpillIs,RewritePatternSwitchStatement,SpillSwitchWithPatternAwait, andEmitSpilledPatternTest) now walk and spillBoundPatterntrees (BoundConstantPattern,BoundRelationalPattern,BoundTypePattern,BoundPropertyPattern,BoundListPattern,BoundSlicePattern,BoundBinaryPattern, andBoundNotPattern), evaluating the pattern subject once before pattern value expressions and preserving short-circuit evaluation forand,or,not, type/property/list sub-patterns, and earlierswitcharms instead of leaving an unloweredBoundAwaitExpressionfor the emitter (GS9998). -
while letandguard letsupport&& guardclauses with left-to-right short-circuiting bindings, filter-in-finally ILVerify checks verify method tails via shadow-patched PE images, and non-overridable auto-property writes preserve member-path narrowings while bare-member write receivers narrow (Fixes #4968, Fixes #5115, Fixes #5786).Parser.ParseIfLetHeader,StatementBinder.BindWhileLetStatementCore,BindGuardLetStatementInBlock, andRegionEffectScannernow accept an optional&& guardafterwhile letandguard letbindings (retiringGS0625), evaluatewhile letbindings left to right so later initializers and the guard short-circuit on the firstnilor closed channel receive (<-ch) and observe earlier bindings narrowed, and propagate guard narrowings and when-true pattern variables into thewhile letbody and the block remainder afterguard let.IlVerifyFilterInFinallyRule,IlVerifier, andIlVerifyRunnernow validate filter-region stack heights and re-verify a shadow-patched PE image (seeding the filter-entry stack in place while preserving the exactisinst/castclasstarget type) whenever a filter-in-finally start underflow is waived, rejecting invalid IL after a fatal verifier underflow.ExpressionBinder(BindNameExpression,BindFieldAssignmentExpression,BindIndexAssignmentExpression, andBindRectangularIndexAssignment) now applies member-path narrowing to bare field and property write receivers, andStatementBinder.SyntaxMayMutateMemberPathsandAssignedRootsCollector.VisitExpressionpreserve member-path narrowings across source auto-property writes whose setter runs no user code and cannot dispatch to an override while preserving R12ref/outalias invalidation (ADR-0208 R14). -
Capture boxing across field initializers, base-constructor arguments, and static
initblocks, language server $O(\log N)$FindTokenAttoken index and loose-fileServerCompilationmemoization, andByteStringliteral-cache enumeration warm-up (Fixes #5800, Fixes #5089, Fixes #4656, Fixes #4659, Fixes #4716, Fixes #4765, Fixes #4849, Fixes #4862, Fixes #4930).InitializationPlanner(RequestFinder.VisitExpression,Prepare,InstancePlan) now includes static and instance field initializers, base-constructor arguments, interface static field initializers, and staticinitblocks that contain capturingBoundFunctionLiteralExpressions inprogram.Initializers(lowering synthesized field-initializer assignment statements viaLowerer.Lower) andCaptureBoxingRewritershares non-parameterBoxedVariablecells and rewrittenBoundFunctionLiteralExpressioninstances across shared instance field initializers so closures inside field initializers,: base(...)arguments, andshared { init { ... } }blocks share captured local/parameter cells instead of snapshotting values.SemanticLookup.FindTokenAtnow indexes disjoint leaf tokens and enclosingInterpolatedStringTokens separately perSyntaxTree(TreeTokenIndex) so both ordinary and multi-hole interpolated-string token lookups run in $O(\log N)$ time without backward scans across preceding hole tokens,SemanticLookup.SemanticModelindexes member-access and field-assignment nodes by token span (accessorsByTokenSpan,fieldAssignmentsByTokenSpan), andServerCompilation.Creatememoizes single-tree compilations (used acrossSemanticTokensComputer,InlayHintComputer,HoverComputer, andLspServer.TryGetCompilation) so loose-file semantic tokens, inlay hints, and hover on large files (src/Core/CodeAnalysis/Binding/Binder.gs) shareSemanticLookup.ModelCacheand complete in a few seconds.ByteStringRuntimeTests.WarmLiteralFactoriesAndValueIterationAllocateNoByteBuffersnow runs a 100-iteration warm-up ofByteString.FromLiteralandByteString.Enumeratorbefore measuringGC.GetAllocatedBytesForCurrentThread()across 10,000 iterations. -
Behavior fix: sub-expression narrowing and enclosing
catch ... whenfilter effects apply between sequentially evaluated operands of the same expression (Fixes #5637, fixes #5238; ADR-0208 R9, R10, R14, R15, R18).StatementBinder.ApplySubExpressionNarrowingEffects(together withApplyConditionEffectsAndHeaderAliases,EnclosingFilterWrites,CaptureNarrowingBindSnapshot/RestoreNarrowingBindSnapshot,JoinBranchNarrowingSnapshots/IntersectNarrowingWithSnapshot,VerifyCallArgumentsAfterConversions, andBinderContext.TryGetNarrowedAccessPath) now applies the narrowing and callable-alias effects of each bound sub-expression—including calls, computed or overridable property getters/setters, implicit argument conversions, deferred target-dependent block arguments, method-group receivers, assignments,ref/outwrites, and writes from enclosingcatch ... whenfilters when a sub-expression may run code or an innertry—before subsequent operands of the same expression or condition are bound (across binary and short-circuit logical operators,isand property/list pattern sub-tests, conditional/if/if-let/switch expressions with mutually exclusive arm state joins,switchstatements, call receivers and arguments, constructor arguments, indexers, range bounds, tuple/array/map/collection/object/struct/with/anonymous-class initializers, interpolated string holes, assignments, and multi-assignment RHS values). Incs2gs,CSharpToGSharpTranslator.SymbolIsWrittenBetweenalso accounts for enclosingcatch ... whenfilter writes triggered by earlier calls ortrystatements in the protected block so translated reads after such calls retain!!. -
Constant floating-point to integer conversions are host-independent, and an out-of-range constant conversion is error GS0635 (Fixes #5767; ADR-0219).
ConstantExpressionEvaluatorused the JIT of the runtime that hosts gsc to fold a conversion such asint8(300.5). The result changed in .NET 11, so the same source compiled to44on a .NET 10 host and to127on a .NET 11 host.ConstantExpressionEvaluator.TryConvertFloatingConstantnow truncates a value in range toward zero, saturates a value out of range at the nearest bound of the type, and converts NaN to0.ConversionClassifierreports GS0635 (C# CS0221) for a constantfloat32orfloat64value that is NaN or out of range for an integer type,char, or an enum of one of these types (including a sibling or cross-typeconstfield that the const fixpoint folds later), unless an explicitunchecked(...)expression orunchecked { }block contains the conversion. Each conversion of a constant operand uses the folded value, including aNullable<T>target and aconstlocal that a lambda captures (also in a field initializer or a base-constructor argument) or that lives across anawaitor ayield, solet a = unchecked(int8(300.5)),unchecked(cast[int8?](300.5)), anExpression[Func[int8]]body, an async function, andconst a int8 = unchecked(int8(300.5))all give127. Acheckedconversion out of range in aconstinitializer reports GS0635 only, not also GS0376.BinderContext.IsUncheckedContextdistinguishes an explicituncheckedcontext from the default context. A conversion of a variable is unchanged. -
switch-expression andswitch-statementwhenguards containingawait,cs2gstuple-contract parameter synchronization across inherited/interface/delegate declarations, and post-cut-over build script cleanup (Fixes #4751, Fixes #4906, Fixes #5363).SpillSequenceSpiller(SpillSwitchWithGuardedAwaitandRewritePatternSwitchStatementWithGuardedAwait) now lowersBoundSwitchExpressionandBoundPatternSwitchStatementnodes whosewhenguards containawaitinto sequential guard-free boolean pattern-match checks and statement-level spilled guards so a false guard falls through to the next arm after suspension while preserving single discriminant evaluation, pattern variable bindings acrossawait, andRefStructAsyncLivenessAnalyzerspan-temporary, pattern-bound ref-struct, and pattern-operand (InterestingLocalCollector.VisitPattern,CollectPatternBindings,ReadAndAwaitCollector, andProcessSwitchBackward) checks. InCs2Gs.Translator,ObliviousNullabilityAnalyzer(CollectTupleContractEdges,CollectDelegateReturnContractEdges, andAddTupleContractPair) andCSharpToGSharpTranslator.TryGetIndexReceiverGenericTupleconnect tuple-bearing parameters acrossOverriddenMethod,AllInterfaces(methods and indexers),OverriddenProperty, andDelegateInvokeMethod(including void-returning delegates and generic method type-parameter substitutions) alongsideCanPromoteTuplePosition/FixedTupleContracts, keeping annotated and imported metadata contracts fixed while synchronizing oblivious source-owned contracts. Inbuild/,migrate-emitted-oracle.pyis removed,verify-migration-run.pyfalls back tobuild/selfmig-common.shsoCorpusDerivationTestsexecutes without skipping on the G# tree, and remaining.cscomment citations incs2gs-counters.sh,test-cs2gs-counters.sh, andrun-ilverify.shnow name.gs. -
Composite literals route value-struct source
letfield stores through synthesized constructors, constructed source generic event overrides substitute base type arguments, imported CLR function-pointer members and parameters bind directly, and type-qualified nested interfaces resolve static members (Fixes #5372, Fixes #5378, Fixes #5381, Fixes #5387).BoundStructLiteralExpression.CanWriteInitializerFieldadmits sourcelet(FieldAttributes.InitOnly) fields ondata structliterals alongsidestructliterals, andReflectionMetadataEmitter(CollectReadOnlyLiteralFields,EmitPlannedStructLetFieldConstructors),UserTokenResolver(TryResolveStructLetFieldCtorToken), andMethodBodyEmitter(EmitStructLiteral,EmitFieldAssignment) route post-construction value-structletfield stores through synthesized assembly-scoped.ctorhelpers with unique arities so constructor-first lexical evaluation order is preserved in place,InitOnlyfields remaininitonlyin metadata, and emitted assemblies pass strictILVerify.DeclarationBinder.BindStructEventsandPropertyOverrideTypeConforms(with recursiveBinder.SubstituteTypeinBuildBaseTypeArgumentSubstitution) substitute constructed base type arguments across single- and multi-level generic inheritance chains when validatingoverride eventdeclarations and wireOverriddenMethodon event accessors.ExpressionBinder.TryBindClrDelegateMemberInvocationandTryBindClrStaticDelegateMemberInvocationdispatch imported instance and static function-pointer fields and properties throughOverloadResolver.BindFunctionPointerInvocation, whileExpressionBinder.MakeSymbolicArgumentConversionClassifier,Conversion.ClassifyNonStructural(HaveIdenticalTypeArgumentContracts), andConversionClassifier.NeedsBindClrParameterConversionclassifyFunctionPointerTypeSymbolarguments against CLRIsFunctionPointerparameters by ABI and contract-preserving signature instead of theirnintruntime erasure.ExpressionBinder.TryResolveNestedTypeChainUnderReceiver,BindUserTypeStaticAccessorStepCore,BindInterfaceStaticAccessorStepCore,TryResolveConstructedGenericTypeReceiver, andBindConstructedGenericStaticFieldWriteresolve nestedInterfaceSymbols (including package-qualified generic outer types) in static member reads, writes, compound assignments, and calls (Outer.Nested.Value,Pkg.Outer[int32].Nested.Count). -
Struct literals and structural projections clone cached field-initializer bound subtrees per use site, and
CaptureBoxingRewriterrewrites captured variables insidecatch (...) whenexception filters (Fixes #5785, Fixes #5380).ExpressionBinder.BindStructLiteralExpressionandConversionClassifier.TryGetStructuralProjectionFieldInitializernow clone cachedStructSymbol.InstanceFieldInitializerssubtrees throughBoundTreeRewriter.Cloneso repeated struct literals or structural projections in the same method body never shareBoundStructLiteralExpression,BoundDefaultExpression, orBoundIndexExpressioninstances across emit slot dictionaries inMethodBodyPlanner.CollectLocalsAndLabels. InCaptureBoxingRewriter.BoxingRewriter.RewriteTryStatement, eachBoundCatchClause.Filterexpression is now rewritten throughRewriteExpression(and seeded ahead of the filter when the catch variable itself is boxed, withMoveNextBodyRewriter.InnerRewriter.RewriteTryStatementandHoistedFieldRewriter.RewriteTryStatementinitializing hoisted catch fields before the filter expression when awhenfilter is present), preventingGS9998(Variable '...' has no local slot or parameter index in the current method) when a local,using letvariable, parameter, or catch variable is both captured by a closure and read by an exception filter. -
Source-element function, delegate, and channel
objectupcasts, importedFunc/Action-to-arrow conversions, source-enum span overload identity, and C# by-value overintie-breaking for imported overloads (Fixes #5251, Fixes #5529, Fixes #5539, Fixes #5559).Conversion.ClassifyCoreandMethodBodyEmitter.IsReferenceCompatiblenow routeobject(andSystem.Delegate) reference widenings throughConversion.IsReferenceLikeTargetwhile keepingboxemission forTypeParameterSymbol, so(Item) -> Item, namedDelegateTypeSymbolvalues, andchan[Item]over source elements upcast toobjectand covariant containers (IReadOnlyList[object]).Conversion.TryClassifyConstructedImportedReferenceConversion,AreTypeArgumentsEquivalent, andDeclarationBinder.TypeSignaturesEquivalentconsultTryGetNaturalDelegateShape/TryGetNaturalFunctionShape(excluding by-reference and pointer slots) so importedSystem.Func[...]andSystem.Action[...]over source elements convert to identity or variance-compatible arrowFunctionTypeSymboltargets and rank as identity against their natural arrow counterparts while keeping explicit-cast diagnostics (GS0156) for contravariant/covariant downcasts (including CLR-backed targets) and rejecting value-type variance (GS0155).Binder(BindTypeClauseandConstructIfGeneric),ExpressionBinder.Literals,ExpressionBinder.Calls(EraseEnumElementArrayForClosedConstruction), andExpressionBinder.Operators(CollectErasureSurrogates) project sourceEnumSymbolelements ofSystem.Span[T],System.ReadOnlySpan[T], andspan[T]/readonly span[T]with theint32ride-through and includeint32in the erasure-surrogate set,ConversionClassifier.IsSameSymbolicTypecompares open definitions withClrTypeUtilities.AreSame, andClrOverloadResolution/ExpressionBinder.IsErasedArgumentApplicabilityMismatchvalidateUserDefinedImplicitconversions on non-erased slots so source-enum and source-struct spans preserve element identity across overload resolution, constructors, andMemoryExtensions.ClrOverloadResolution.IsBetterOmittedByRefPassingModeandOverloadResolver.IsBetterOmittedInPassingModeapply C# §12.6.4.3's by-value overintie-breaker across all omitted-inarguments when conversions alone do not separate candidates. -
Regression coverage for
cs2gsself-migrated Core compilation (Fixes #5791). Tests exercise nullable annotation targets and recursive expression-tree translation after redundant assertions are removed. The compiler's shared prebind rollback preserves argument narrowing for unqualified static calls. -
cs2gsglobal tool runs outside the G# source tree, VS Codegsharp.generateAssetsselects runnableExe/WinExeprojects with<AssemblyName>and${workspaceFolder}-relative task paths, andbuild/ci-projects.pycloses temporary.slnffiles before invokingdotnet(Fixes #4956, Fixes #5009, Fixes #5085).GsharpTestProjectRunner.TryFindRepoRootandSdkCompileRunnernow allow runningcs2gs migrateandcs2gs validateoutside a G# repository checkout without settingCS2GS_TEST_SOURCE_ROOTor creating a.nugsdirectory, resolvinggsc.dll,gsgen.dll, and the defaultGsharp.NET.Sdkversion from the installed tool's package metadata and the NuGet global-packages cache (GscInvoker.ResolvePackagedCompiler,SdkCompileRunner.ResolveExternalPackageVersion), andIlVerifyRunner/IlVerifyStagefall back to a global or--tool-pathilverifyexecutable when no local tool manifest definesilverifyand report a missing verifier asILVERIFY-UNAVAILABLE(tool-setup-error) instead of acil-emitfailure. Insrc/vscode-gsharp,gsharp.generateAssetsandGSharpDebugConfigurationProviderfilter workspace.gsprojcandidates to runnable non-testExe/WinExeprojects (findRunnableProjects, prompting viashowQuickPickwhen multiple runnable projects exist), honor<AssemblyName>and<TargetFramework>(parseProjectMetadata), and emit${workspaceFolder}-relative project paths in.vscode/tasks.json(computeWorkspaceTaskPath). Inbuild/ci-projects.py,run()closes the temporary.ci-projects-*.slnffile (delete=False) before spawningdotnetand unlinks it in afinallyblock so Windows does not reject reopening the solution filter withPermissionError. -
gscresolves source-declaredDeconstructinstance and extension methods across deconstruction statements andfor (a, b) inloops (Fixes #5693).StatementBinder.BindTupleDeconstructionStatementandBindForTupleLoopPreludenow callTryBindDeconstruct(TryBindSourceInstanceDeconstruct-> imported instanceTryBindImportedDeconstruct->TryBindSourceExtensionDeconstruct-> imported extensionTryBindImportedDeconstruct), resolving accessible sourceDeconstructinstance methods onStructSymbol,InterfaceSymbol, and constrainedTypeParameterSymbolreceivers (substituting generic receiver type arguments throughOverloadResolver.TryBuildReceiverSubstitution, deduplicating and binding default interface methods to their constructed declaringInterfaceSymbol, and resolving inherited interface slot owners inMethodBodyEmitter.EmitUserInstanceCallfor constrained calls) ahead of imported instanceDeconstructmethods, and resolving in-scope source extensionDeconstructfunctions (BoundScope.TryLookupExtensionFunctions, including generic receiver inference, constraint checking,TypeSymbol.IsByRefLikerejection, andOverloadResolver.CompareExtensionReceiverConversionsranking) ahead of imported extensions while propagating function-localIsScopedescape scope (including declaration-levelFunctionSymbol.HasUnscopedRef,InterfaceSymbol.SubstituteMethodattribute/receiver-contract preservation, importedRefCapabilities.HasUnscopedRef/RefCapabilities.IsReadOnlyMethod, andRefCapabilities.RequiresReadOnlyReceiverDefensiveCopy) to by-ref-like deconstruction outputs. EmittedBoundUserInstanceCallExpressionandBoundCallExpressionnodes integrate withAssignedRootsCollectorandLoopPreludeRunsUserCode(andCSharpToGSharpTranslator.DeconstructingForEachRunsUserCodedistinguishes implicit positional record deconstruction from explicit/extensionDeconstructcalls) so user-declaredDeconstructcalls invalidate narrowed mutable globals and loop-region by-reference parameters. -
Language server shared-field and shared-interface property navigation, forward-
gotoconstructed base-type joins, andcs2gslocal/conditional null-argument pinning (Fixes #5043, Fixes #5053, Fixes #5509, Fixes #5579).DefinitionComputer.FindFieldTokennow resolvesFieldSymbol.Declarationdirectly and searchesStructDeclarationSyntax.SharedBlock.FieldsandInterfaceDeclarationSyntax.StaticFields(alongsideSemanticLookupmapping interface and struct static/const fields and interface static/private methods) so go-to-definition navigates to sourcesharedfield declarations.SemanticModel.ReferencedSymbol,ReferencedSourceSymbol, andGetSymbolInfonow map property-accessor calls (FunctionSymbol.AssociatedSymbol is PropertySymbol, withPropertySymbol.WithSignaturefor constructed generic interface receivers) back to the sourcePropertySymbolso plain and constructed shared-interface property reads (IData.Name,IData[int32?].Name) resolve their symbol, hover, and definition. Forward-gotolabel joins (StatementBinder.ApplyIncomingJumpJoin/NarrowingState.JoinTypes/Conversion.ProvesNominalReference/ ADR-0208 R6) preserve constructed generic source base types ((Parent[int32], Child)joining toParent[int32]), andObliviousNullabilityAnalyzer.ClassifyNullArgumentReadpins parameters whose reads flow through local aliases (var copy = node;) or conditional arms (b ? node : node) into non-widenable slots instead of emitting throwing!!assertions. -
gscruns on a .NET 11 host with explicit references (Fixes #5768). .NET 11 adds the virtualType.GetNullableUnderlyingType(), andNullable.GetUnderlyingTypecalls it. The base implementation throwsNotSupportedExceptionfor the MetadataLoadContext types of imported assemblies, so gsc failed with GS9998 for each program.NullableLifting.GetValueTypeNullableUnderlyingClrnow uses only metadata (theSystem.Nullable`1generic type definition). The member lookup, constant evaluator, and custom attribute encoder use it instead ofNullable.GetUnderlyingType. On .NET 10,Nullable.GetUnderlyingTypegavenullfor an importedNullable<T>. The metadata test gives the correct type argument. -
String interpolation preserves enclosing
unsafecontext for pointer member access, nominal interface static struct initializers resolve reservedDeclaredFieldDefs, package-qualified source constructions preserve trailing member/index/invocation chains, and declaredtypealiases resolve same-compilation source types (Fixes #5110, Fixes #5195, Fixes #5357, Fixes #5358, Fixes #5528).Parser.ParseInterpolatedStringExpressionnow transfersunsafeDepthto the interpolation hole probe and inner parsers so bare pointer member accesses ("${ptr->object:G}") parse as dereference member accesses insideunsafecontexts while keeping lambda head parsing unchanged.MethodBodyEmitter.EmitStructLiteral(together withEmitFieldAccess,EmitFieldAssignment,ResolveFieldAddressHandle, andEmitPropertyPatternMember) resolves value-struct literal field tokens throughUserTokenResolver.ResolveFieldToken/MetadataTokenCache.DeclaredFieldDefsso nominal interface.cctorand default method bodies emitted ahead of aggregateFieldDefrows can initialize and access same-compilation structs without throwingGS9998.ExpressionBinder.TryResolveQualifiedSourceTypeHeadandBindQualifiedSourceTypeRemainder(withTryResolveConstructedGenericTypeReceiver) preserve package-qualified source constructions across trailing member accesses, indexers, and indirect invocations.Binder.BindGlobalScopebindsTypeAliasDeclarationSyntaxafter same-compilation delegate, interface, enum, and struct/class shells are registered (deferring interface, enum, and enum-member attribute binding inDeclarationBinder.BindPendingShellAttributesuntil after aliases resolve), andBoundScope(GetDeclaredTypeSymbols,TryRedeclareTypeAlias,GetAliasDeclaringPackages) preserves alias declaring-package identity acrossBindProgramwithout duplicating aliased declarations or returning imported semantic aggregateStructSymbols inGetDeclaredStructs. -
Definite assignment models pattern evaluation and short-circuiting across
switchandispatterns, valueswitchexpressions recognize irrefutable combinator arms as catch-alls, and async lowering reconstructs native-slice element field stores across suspensions (Fixes #5011, Fixes #5012, Fixes #5016).DefiniteAssignmentAnalyzer.ProcessPatternnow computes the matched and failed assignment/alias states forBoundConstantPattern,BoundRelationalPattern,BoundNotPattern,BoundBinaryPattern(and/or),BoundTypePattern,BoundPropertyPattern,BoundListPattern, andBoundSlicePatternacrossBoundSwitchExpression,BoundPatternSwitchStatement(merging dispatch andfallthrougharm entries and post-switch pointer aliases), andBoundIsExpression(both inProcessExpressionandClassifyConditionAssignments), preserving unconditional constant/relational and non-nullable value-type property pattern evaluation while keeping short-circuited binary, nullable/reference property, and list subpatterns conditional on the failure path.ExpressionBinder.BindSwitchExpression,ExhaustivenessAnalyzer,StatementBinder.SwitchHandlesAllValues, andControlFlowGraphnow shareBoundSwitchExpressionArm.MatchesAllInputs/IsCatchAll(BoundPatternSwitchArm.IsCatchAll) so unguarded irrefutable combinator patterns (case 1 or _:,case _ and _:,case not not _:) satisfy the catch-all requirement without reportingGS0176orGS0100(including when followed byfallthrough), while guarded wildcard alternatives remain conditional. For async, channel-suspending, andgoreceiver native-slice stores (#5012),SideEffectSpiller,RefInitializationHoister, andStatementBinder.CaptureGoReceiverCorenow reconstruct nativeslice[T]element receivers (IsNativeSliceElementOperand,SpillNativeSliceElementOperand,CaptureGoNativeSliceElementOperand) from hoisted slice-owner and index locals instead of borrowing areflocal across suspension, andAsyncIteratorRewriterhoistsSpillLocalsalongside user locals. -
Native-interface and class-constrained type-parameter property writes on tuple-element and expression receivers, auto-dereferencing of static and inherited CLR
ref-returning properties, and base-first nested-type member binding (Fixes #5029, Fixes #5032, Fixes #5075).ExpressionBinder.BindMemberFieldAssignmentExpression,BindFieldAssignmentExpression,TryBindInterfaceCompoundAssignment,ExpressionBinder.Async, andExpressionBinder.Literalsnow resolve nativeInterfaceSymbolandStructSymbol/imported class constraints onTypeParameterSymbolreceivers (including generic interface type-argument substitution and compound assignments) for non-variable expression receivers such as tuple elements (items[0].Item1.Value = "v"), preserving in-place value-type storage and reference-type receiver snapshots.ExpressionBinder.Access.MemberLookupandExpressionBinder.TryBindInheritedClrInstanceMemberByBareNamenow wrap static and inherited CLR property reads inConversionClassifier.AutoDereferenceRefReturnand unwrapIsByRef/ByRefTypeSymbolinResolveStaticMemberTypeFromSymbolicReceiverso static CLRref-returning tuple properties (External.Slot.Item1) resolve tuple members and preserve borrowed-location safety.DeclarationBinder.BindStructBaseAndInterfacesinvokesEnsureBaseStructBodyBoundas soon as a base class is installed on aStructSymbol,BindStructEventsvalidates event overrides throughPropertyOverrideTypeConforms, andDetectClassInheritanceCyclesincludes nested class definitions so nested derived classes declared before their nested base classes bind method, property, indexer, and event overrides regardless of source order. -
ReferenceResolver.TryGetMemberLookupTypetoleratesArgumentExceptionand metadata-load failures during type projection, andif-expressions,?:ternaries, and&&/||operands narrow value-type nullables and[NotNullWhen]bool calls across!,&&, and||(Fixes #4928, Fixes #4969).ReferenceResolver.TryGetMemberLookupType,ExpressionBinder.TryNormalizeSliceArrayReceiverForLambdaInference,NullableLifting.TryConstructNullable, andReferenceResolver.FindTypeForComparisonnow route reference-set type projection throughReferenceResolver.TryMapClrTypeToReferences/ReferenceResolver.IsProjectionFailure, catchingArgumentExceptionandClrTypeUtilities.IsMetadataLoadFailurealongsideInvalidOperationExceptionso projection failures on downlevel or partially unloadable reference sets reportGS0546instead of escaping binding asGS9998.ExpressionBinder.ClassifyTypeTestNarrowingandExpressionBinder.ClassifyConditionalNarrowingnow passreferenceNullableOnly: falsetoSmartCastStability.TryClassifyNilGuardLeaf(unwrapped on read viaExpressionBinder.BuildNarrowedRead) and composeStatementBinder.TryClassifyBoolCallNarrowingLeaf([NotNullWhen],[MaybeNullWhen], and receiver-scoped[MemberNotNullWhen]) across!,&&, and||while filtering left-operand narrowings through right-operand mutation effects (ClearAssignedRoots), aligningif-expressions,?:conditional expressions, and&&/||short-circuit operand narrowing withif-statements. -
Behavior fix: condition and pattern narrowing effects apply in evaluation order across
&&/||operands,if-expressions, conditional expressions, loop headers, andif letbindings and guards (Fixes #5545, ADR-0208 R18, R19).StatementBinder.BindShortCircuitBinaryOperands,BindConditionWithEffects,BindInitializerWithEffects,BindConditionalExpressionBranches,BindIfLetBranches, andComputeConditionNarrowingInOrdernow apply each operand's, condition's, and initializer's narrowing and callable-alias effects before binding the next operand, guard, or branch (withconditionKillJournalrestoring then-branch removals for sibling else-branches,BindDeferrableConditionalpreserving deferred argument effects for subsequent arguments while restoring argument-entry state on contextual re-binds,CaptureCallArgumentPrebindRollbackrestoring pre-bind narrowing/alias state before static orusing staticcalls re-bind their arguments, andAddressedLeafStorageType/ConditionalStorageTypesMatchvalidating physical storage types inBindConditionalAddressFromGeneral), andClearOperandFactsinvalidates facts proven by earlier operands of&&and||when a later operand can clear them (if x != nil && Check(h)andif x is D && Check(h)). Type tests after an effectful left operand (Check(h) && x is CatandCheck(h) && x is int32, corpus rowsw18andw19) now bindxat its post-effect declared type instead of emitting a stalecastclassorNullable<T>unwrap, andif-expressions, conditional expressions, and&&/||operands shareTestMayRemoveItsOperandFactso patterns whose own property getters orEqualscalls can clear the tested path narrow neither branch. -
Attributes with
Nullable<T>constructor parameters reportGS0585(CS0181), baredefaultin logical&&/||and equality operators target-types or reportsGS0362, barereturnin iterator bodies terminates enumeration per ADR-0040, andselfhost-pack-stage1.pydisablesGeneratePackageOnBuildduring explicit pack (Fixes #5771, Fixes #5019, Fixes #5044, Fixes #5052).DeclarationBinder.IsScalarAttributeParameterTypenow rejects value-typeNullableTypeSymbolparameters (T?and[]T?), andDeclarationBinder.BindAttributetogether withCustomAttributeEncoder(TryResolveImportedAttributeConstructor,TryMapAttributeConstructorArguments,ResolveAttributeConstructor,TryGetAttributeParameterWriteType, andClassifyAttributeArgumentConversion) keeps applicableNullable<T>constructor candidates in overload ranking so a more-specificNullable<T>overload wins ahead ofobjectand then rejects any winning constructor whose parameters are not valid ECMA-335 II.23.3 custom-attribute parameter types withGS0585instead of silently falling back toobjector emitting a broken.ctor(System.Object)reference that throwsMissingMethodExceptionat runtime.ExpressionBinder.BindBinaryOperation(MaterializeBareDefault) target-types baredefaultoperands in logical&&/||tobooland in==/!=to a concrete sibling operand type, andReportUnresolvedBareDefaultsdiagnoses remaining untyped baredefaultoperands in unary, binary,is,throw, andswitchexpressions withGS0362instead of letting an unresolvedTypeSymbol.Errornode reach emission asGS9998.StatementBinder.BindReturnStatement(IsIteratorFunction) andBodyFacts.YieldDetector(together withLowerer.RewriteReturnStatementpreservingYieldStatementSyntax) now recognize sync and async iterator bodies (IteratorDetection.ContainsYieldandAsyncIteratorDetection, includingyield break-only iterator bodies) so a barereturnterminates enumeration (yield break) without reportingGS0123. Inbuild/selfhost-pack-stage1.py,pack()now passes-p:GeneratePackageOnBuild=falsetodotnet packsoPackGsharpBuildTask'sBuilddependency does not re-enterPackwithMSB4006. -
Imported CLR generic inference and constraint checking preserve contravariant array bounds, multi-interface variance, and tuple element promotions (Fixes #5020, Fixes #5021).
Conversion.IsVarianceArgumentCompatibleandConversion.ProvesNominalReference(reused byClrOverloadResolution.AreVarianceCompatibleArgumentsandMemberLookup.SatisfiesSymbolicInferenceBounds) now admit one-dimensional and jagged SZ-array reference covariance inside variant generic type-argument slots while preserving outer reference and annotated-element nullability (GetElementPositions), keeping standalone slice-to-slice conversions explicit-only (#2516), and preserving fixed-array length checks (#3962,#4024).ClrOverloadResolution.UnifyForInferencecomposesClrInferenceBoundKind(Lower,Upper,Exact) through nested generic variance and retains candidate bounds inClrInferenceBoundsuntilTryFixClrInferenceBound(so invariant bounds refine upper bounds while lower and upper bounds fix to their common target),IsInferenceBoundPromotionandMemberLookup.UnifyForMethodTypeArgspropagate element-wiseValueTuplepromotions and unwrap outerPlatformTypeSymbolwrappers before structural generic projection (withConversionClassifierreadingrejectionTargetTypethroughMemberLookup.GetClrMethodParameterConversionTargetTypeSymbol),CollectExtensionReceiverConstructorEquationsconsults selected multi-interface constraint choices before defaulting tuple element equations, andClrTypeUtilities.IsAssignableByNamechecks declaration-site generic interface variance acrossSafeGetInterfacesand cross-context reference arrays. -
cs2gsmirrors ADR-0213 L1 loop-entry by-reference fact removals for conversion calls, deconstructed loop variables, and call-collection loop variables, and mirrors R7 (f) loop-exit condition narrowing (Fixes #5692, fixes #5697, ADR-0213):CSharpToGSharpTranslator.NodeMayWriteReferenceStoragenow marks a loop whose region emits a conversion callT(x)orcast[T](x)(LoopRegionLosesByReferenceNarrowing,NodeEmitsTypeConversionCall), invokes an unresolved bare or conditional-receiver member call (NodeIsUnresolvedRegionCall), or uses a loop variable thatgsc'sRegionEffectScannerleaves without an origin (ForEachUntypedLoopVariableIsUsed: a deconstructingforeach (var (a, b) in items)or an untypedforeach (var part in call())whose collection expression has no region receiver path inResolveExpressionRegionReceiverTypes), so by-reference reads inside or after the loop receive!!instead of failing withGS0158.CSharpToGSharpTranslator.ComputeBooleanFlowRegionsnow includes the statements after awhile,for, ordo ... whileloop in thefalseflow region of the loop condition whenCanNarrowAfterLoopExitholds, andClosureAssignedLocalLosesNarrowing/SymbolIsWrittenBetweenevaluate an exited loop's condition after its body andforincrementor (GetExitedConditionLoop,ExitedConditionTriggersEnclosingFilterWrite), omitting redundant!!assertions (GS0536) on reads after loops such asdo { ... } while (s == null); return s.Length;.
-
Statement-position
??=snapshots receiver and CLR indexer argument variables when the right-hand side can reassign them, andClrTypeUtilities.IsSameAsdistinguishes open generic parameters and function pointers (Fixes #5000, Fixes #5018).ExpressionBinder.BindNullCoalescingAssignmentStatementandTryBuildNullCoalescingReadWritenow consultStatementBinder.CreateExpressionVariableMutationChecker(backed byAssignedRootsCollectorandStatementKillsPath, includingin/ref/outexternal-storage aliases across calls and unseeded callable-alias walks) so a statement-position??=captures a variable-backed reference receiver or CLR indexer argument before the nil test whenever the right-hand side (or a later indexer argument) can reassign that variable, and spills the right-hand side before a value-type field write when the right-hand side can reassign the struct receiver variable, keeping emitted IL byte-identical for ordinary??=statements (samples/NullCoalescingAssignment.gs). InClrTypeUtilities,IsSameAs(AreSame,ClrTypeInspector.IsSameAs,IsSameAsCore, and method-scoped signature hiding inClrTypeUtilities.IsHiddenByExistingandMemberLookup.IsMethodHiddenByExisting/HasSameSignature) now compares open generic parameters byGenericParameterPositionand declaring method or type definition identity (matchingModule.ModuleVersionId+MetadataTokenbefore signature fallback across runtime reflection, inherited declarations, constructed generic types, andMetadataLoadContext), comparesIsFunctionPointertypes structurally, and requires non-nullFullNamevalues at the fallback comparison instead of equating distinct open generic parameters or constructed open types whoseFullNameisnull. -
Omitted optional generic delegate arguments use their substituted parameter type, synthesized
dataand auto-property members carryCompilerGeneratedAttribute(and explicit constructors emit PDB sequence points), and mergedpartialtypes retain XML documentation summaries (Fixes #5760, Fixes #5761, Fixes #5762).OverloadResolver(CreateOptionalUserDefaultArgument,BindCallExpression,BindExtensionFunctionCall, andBindUserInstanceCall) skips omitted optional argument slots during generic type inference, rebuilds synthesized default arguments against the substituted parameter typeexpectedType, and guardsparameterSyntax[i]location lookups when an optional argument is omitted, preventingGS9998invariant crashes on calls such asAccept[string]()overfunc Accept[T](callback(() -> T)? = nil).DataStructSynthesizer.StampSynthesizedandMemberDefEmitter.StampAccessornow emitCompilerGeneratedAttributeon synthesizeddatamethods (Equals,GetHashCode,ToString,PrintMembers,op_Equality,op_Inequality,Deconstruct,<Clone>$,get_EqualityContract, and copy constructors) and auto-property accessors while keeping implicit default constructors and primary constructors unmarked, andConstructorBodyEmitter.EmitClassConstructorWithBodyBodyBytes/TryEmitInitializationrecord entry and exit sequence points in Portable PDBs for explicitinit(...)constructors (withPortablePdbEmitter.EncodeSequencePointsemitting multi-documentInitialDocumentheaders and document-switch records when field initializers span partial-type files).PartialTypeMerger.MergeStructGroupandMergeInterfaceGroup(together withInterfaceDeclarationSyntax.DocumentationSource,Binder.AttachDocumentation, andIncrementalGlobalScopeReuse.TryMapStruct) preserve the documented part'sDocumentationSourceacross same-file and multi-filepartialclass, struct, and interface declarations so/doc:emits their<summary>entries. -
Evaluation-order condition lift restore and block/cleanup callable-alias and fact restore after a call (Fixes #5498, fixes #5502; ADR-0208 row R15).
StatementBinder.RestoreEarlyExitLiftsWrittenOnlyByConditionnow checks the evaluation-order condition flow state (ComputeConditionNarrowingInOrder, withFilterBoolCallNarrowingAfterEffectsfor non-by-reference[NotNullWhen]calls) instead of scanning only top-level||operands (RunsEscapedClosureAfterTest), so an early-exit condition that writes a root throughout/refand then runs a call after the non-null proof inside a compound operand (if !TryGet(out x) || x == nil || Wrapper(h) || (x == nil && stop) { return 0 }orif !(TryGet(out x) && x != nil && !Wrapper(h)) { return 0 }) no longer restores the fact and reportsGS0158, while a test evaluated after the call (if !TryGet(out x) || Wrapper(h) || x == nil { return 0 }orif !(TryGet(out x) && !Wrapper(h) && x != nil) { return 0 }) still restores it. InAssignedRootsCollector,MarkRunsEscapedClosureand post-operand call/accessor/constructor evaluation now invalidate closure-assigned callable aliases inCallableAliasStatein evaluation order, andApplyCallableAliasExitState,RemoveHeaderAffectedAliases, andAliasesAfterconsultDefinitelyExternalFunctionValuesinstead of stripping closure-assigned aliases across the whole statement, so a bare block ({ Wrapper(h); action = callback }) orfinallyblock (finally { { Touch(); x = "abc" } }andfinally { Wrapper(h); action = callback }) preserves facts and external callable aliases established after a call while still removing those followed by a call. -
gscwrites the correct shared framework version toruntimeconfig.jsonfor all .NET target frameworks (Part of #5765). For/target:exe,ResolveFrameworkMonikernow gets theMicrosoft.NETCore.Appversion from the target framework. Previously, it knew onlynet8.0,net9.0, andnet10.0, and used10.0.0for all other values. Thus,/targetframework:net11.0loaded the .NET 10 runtime. Platform suffixes (net11.0-windows) andnetcoreappX.Yare also supported. Target frameworks that are not .NETCoreApp continue to use10.0.0. -
cs2gsblocks consumers depending on invalid required referenced producers without duplicating producer gaps and ignores stray__pycache__/*.pycbytecode files in repository mirrors (Fixes #4767, Fixes #4893).CSharpProjectLoader(CreateWorkspace,PartitionWorkspaceLoadDiagnostics, andResolveWorkspaceDiagnosticOwnerPath, withDeclaredProjectItems.WorkspaceConfigurationandMigrationPipeline.LoadEvaluatedProjectReferencesAsync) now passes the selectedConfiguration(context.Options.Config) unconditionally when opening projects and evaluating compile-reference graphs inRunAsyncandValidateAsync(withValidationManifest.HydraterestoringProjectReferencesandEvaluatedProjectReferencePaths), and attributesMSBuildWorkspaceload-failure diagnostics to their owning project instead of attaching sibling load failures to the root consumer.TranslateStagerecords evaluated active compileProjectReferencepaths onStageExecutionContext.EvaluatedProjectReferencePaths(including repository-layout--no-via-sdkruns usingRepositoryLoadedProjects) and tracks referenced-project workspace-load, unsupported-construct, formatter, round-trip, and.resxfailures (both inline under--no-via-sdkand across SDK/repository project references, including.resxand formatter validation inIsUnselectedReferencedProjectValid), failing dependent consumers withStageOutcome.DependencyBlocked()(failureCategory = "dependency-blocked"and zero consumer-owned triage artifacts) when the consumer has no own-project translation diagnostics.CompileStage(HasInvalidProjectReference,IsReferencedProjectDiagnostic,MatchExactEmittedFile,IsOwnedByReferencedCompileInputs,IsOwnedByReferencedDirectory, andBuildFailureOutcome) consults the evaluated active compile-reference graph (ActiveCompileReferencePaths) while retaining declaredProjectReferencesfor project emission, checks referenced compile inputs, producer manifests (ProjectEmittedGsPaths), MSBuild[project]diagnostic suffixes, and more-specific nested-project directory ownership before falling back to basename-onlyMatchEmittedFilematching (while preserving exact own-file attribution), and returnsStageOutcome.DependencyBlocked()instead ofStageOutcome.Passed()when all compile diagnostics map to referenced sibling files, andCompileStage,IlVerifyStage(IlVerifyMissingAssembly), andTestParityStagefail closed when a required output assembly is missing. InRepositoryFileInventory,HasExcludedDirectoryandIsPythonBytecodePathnow exclude__pycache__directories and*.pyc/*.pyobytecode files from source enumeration andRepositoryMirror.ValidateCompleteddestination completeness checks, andbuild/selfmig-app-table.py/build/test-check-selfmig-stage-floor.pysuppress bytecode writes when loadingcheck-selfmig-stage-floor.pyby file path. -
Targetless throw-expression lambdas materialize
voidreturn types, andnever-typed values no longer reach inferred CLR signatures (Fixes #4994, Fixes #5003).TypeSymbol.MaterializeNeverFunctionReturnsnormalizes anyneverfunction return slot (including nested function returns and tuple elements) tovoidwhen a targetless expression is materialized for an untyped variable, deconstruction, anonymous-object member, direct invocation, non-delegate conversion target, or discarded statement, while keeping#2716target-typed delegate adaptation intact (ConversionClassifiernow also propagates target conversions into block, conditional, and switch expressions and nested adapter returns, andLambdaBinder.InferLambdaReturnTypeinfersvoidfor targetlessasync () -> throw ...lambdas). In generic and composite inference,ClrOverloadResolution.NeverArgumentTypeandMemberLookup.UnifyForMethodTypeArgsskipneverarguments so concrete sibling arguments still infer type parameters whilenever-only generic calls and composites reportGS0151,GS0159,GS0155, orGS0124at bind time instead of crashing in emit withGS9998, and named-argument,defer/go, struct-literal,select, and side-effect spills avoid allocatingnever-typed temporary locals. -
Derived positional
data classdeclarations reuse inherited base properties without duplicate storage, andcs2gspreservesvoidreturn semantics for block-bodied statement lambdas ending in a value-capable tail (Fixes #4874, Fixes #4977).TypeMemberModel.ResolveInheritedDataPositionalProperty/TryGetInheritedDataPositionalProperty,StructSymbol.InheritedPositionalProperties, andDeclarationBinder.BindStructProperties(along with base-first nested-type binding inBindNestedTypeBodies/EnsureBaseStructBodyBound) now skip synthesizing a duplicate auto-property and backing field when a deriveddata classprimary-constructor parameter is not replaced by an explicit property declaration and matches an accessible inherited base property (checking getter accessibility, friend-assembly visibility,PositionalTypeSatisfiedByInheritedGetter, andMemberLookup.GetClrPropertyTypeSymbolruntime type equivalence), whileTypeMemberModel.GetDataDeconstructionMembers,ReflectionMetadataEmitter.TryGetPrimaryCtorTargetField,DataStructSynthesizer.EmitDataStructDeconstruct,BoundStructLiteralExpression.GetPrimaryMember,ExpressionBinder.Literals,PatternBinder,AccessibilityChecker,StructuralProjectionPlan,UserTokenResolver, andManagedReferenceSafetyAnalyzershare the canonical inherited property across synthesizedDeconstruct, property patterns, spreads, and record literals without re-initializing base storage or emitting duplicatePrintMembersentries. Incs2gs,ExpressionStatementandAssignmentStatementnow recordIsVoid,CSharpToGSharpTranslator.TranslateLambdaappends a trailing barereturnwhen a C#void(or non-genericasyncTask/ValueTask) block lambda ends in a value-capable tail (a non-void expression statement, a non-void assignment or increment/decrement statement, a nested plain block, or anif … else …/if let … else …chain ending in a value-capable branch), andGSharpPrinter.RenderIfprintselse if letchains so translated statement lambdas remainvoidand preserveActionvsFuncoverload resolution. -
The loop and backward-jump region walker exempts resolved R16 stable getters and non-hideable fields and auto properties from rule W5 (Fixes #5549, ADR-0213):
StatementBinder.RunsUserCodeOnMemberRead(DecideRegionKillandRegionRunsCodeinStatementBinder.NarrowingLoops.gs) now exempts a member or index read in a loop or backward-jump span from W5 when its receiver resolves at the region's entry scope without a type test on the receiver inside the region (HasTypeTestOnReceiver,HasEntryMemberTypeTest) and the resolved member is either on the ADR-0208 R16/R17 stable imported accessor list (IsStableClrAccessor, such asstring.Length,StringBuilder.Length,Array.Length,List<T>.Count, andNullable<T>.HasValue) or a field, tuple element, enum member, array/sliceLength, or auto property (!SourcePropertyRunsUserCode) of a type that cannot have a subclass (a value type or a class that is neitheropennorsealed, or a sealed CLR type).- Corpus rows
t09_5231_string_length_in_a_loop_R16_loop_is_stricter,q5c_imported_getter_closure_root, anda09_5629_loop_continue_in_an_int_case_keeps_the_fact_R19are now accepted, whileq5d_hidden_field_getter(a type test in the region narrowing the receiver to a subtype with a hiding getter), fields or auto properties onopenorsealedclasses, and unlisted imported getters (Lazy<T>.Value) remain rejected.
-
Synthesized default constructor calls keep by-reference parameter narrowings,
TestMayRemoveItsOperandFactwalks onlyisExpr.Pattern, andif/if init;/if letconditions carry true/false callable-alias states into their branches (Fixes #5562, fixes #5606; ADR-0208):AssignedRootsCollector.VisitExpressionno longer setsMayMutateReferenceStorageunconditionally onBoundConstructorCallExpression, leaving by-reference storage invalidation tosourceConstructionRunsUserCode(SelectedConstructor != nil || ConstructionRunsUserCode(StructType), withConstructionRunsUserCodealso checkingDeclaresInstanceFieldInitializerandImportedBaseType != nilacross the base-class chain and treating an unexhausted chain as running user code) so a synthesized default constructor call (Mixed()) on a type with no user constructor, no imported base class, no instance field initializer, and no staticinitblock preservesref/outparameter narrowings just likeMixed{}(and C#new Mixed()translated bycs2gscompiles without a!!assertion).StatementBinder.TestMayRemoveItsOperandFactnow passesisExpr.PatterntoEffectsMayRemoveFactOfso only effects evaluated after the operand read are walked.StatementBinder.AliasesAtTests,BindIfStatement,BindIfLetStatement(IfLetBindingSupport.BindHeader), andAssignedRootsCollector(VisitExpression,VisitBinaryExpression,VisitPropertyPattern,VisitConstantPattern,VisitListPattern,VisitBaseClassCallExpression,VisitForRangeStatement,VisitAwaitForRangeStatement,VisitCondition,VisitIfStatement,VisitConditionalExpression,VisitConditionalAddressExpression, and goto-loweredIfLetStatementSyntaxblocks inVisitBlockStatement) snapshot external-callable aliases before binding each header/clause, evaluate convertedif letinitializers, invalidate closure-assigned callable state across user-code sites, apply enclosingcatch ... whenfilter invalidation (RemoveCollectorFilterAffectedAliases) inAliasesAfterandRemoveHeaderAffectedAliases, and carry the condition'sWhenTrueandWhenFalseexternal-callable alias states into thethenandelsebranches, preserving aliases gained in the condition on every path reaching the branch.
-
Retire the slice-L0
.loopscomparison report, thenarrowing.loop-rebindscounter, and dead loop/jump narrowing helpers (Fixes #5319; Part of #5196, ADR-0213 slice L3).NarrowingComparison,StatementBinder.NarrowingLoops, andStatementBinder.Loopsno longer maintain or flush the temporary.loopscomparison report (LoopsEnabled,ReportLoopKill,ReportLoopSummary,ReportSpan,ReportLoopExitGain,TryRegisterSpanFunction,FindBangSitesAfter,CollectBangSites, andReportBackwardJumpSpan), whileGetEnclosingBackwardJumpSpancountsnarrowing.spansdirectly alongside the remaining ADR-0213 §15CompilationMeasurementscounters. Removes the retirednarrowing.loop-rebindscounter assertions and unreferenced narrowing/jump helpers (StatementBinder.HasActiveNarrowings,IsRepresentationPreservingJoin,RemoveByRoots,ClrPropertyReadRunsUserCode,BindLabeledForRange, andNarrowingJumpState.ActiveFinallyClauses/ActiveCleanupStatements), and updates ADR-0069, ADR-0208's probe corpus, ADR-0213 (§20c), the language specification, and the control-flow tour for the completed L0–L3 region lower-bound rules. No change togscoutput or theGSharp.Corepublic API. -
Expression-tree lambdas lower smart-cast narrowed reads to
Expression.Convert, andnetstandard2.0/ downlevel compilations synthesizedataandinline structmetadata without host-only runtime references (Fixes #4974, Fixes #4993).ExpressionTreeRestrictionValidator.VisitUnaryExpressionnow admits synthesized value-type-nullable smart-cast unwraps (BoundUnaryExpression.IsNarrowingUnwrap, preserved acrossBoundTreeRewriter.RewriteUnaryExpressionduring capture boxing) while still reportingGS0473on explicit user!!assertions, andExpressionTreeLowererlowersIsNarrowingUnwrapnodes and type-test narrowedBoundVariableExpression,BoundFieldAccessExpression, andBoundPropertyAccessExpressionreads (WrapNarrowingConversionIfNeeded) toExpression.Convert(operand, typeof(T))whenever the narrowed type differs in runtime type from the declared storage type. For downlevel target frameworks such asnetstandard2.0,EmbeddedAttributeSourceandWellKnownReferencesnow embed[CompilerGenerated, Embedded]internal definitions ofSystem.Runtime.CompilerServices.IsReadOnlyAttributeandSystem.Runtime.CompilerServices.IsExternalInit(reusing source-declared class or structIsExternalInitand attributeIsReadOnlyAttributepolyfills viaIsFrameworkTypeDeclaration/FindSourceTypeor referenced polyfills when present, pre-scanningTypeClauseSyntax.FunctionParameterRefKindTokens,TypeClauseSyntax.ReadOnlyManagedModifier, andFunctionLiteralExpressionSyntax.ReturnReadOnlyModifier, and preserving imported interface and base-overridemodreqtokens acrossMethodInfoHelpers,TypeDefEmitter,FunctionEmitter,MemberDefEmitter,InterfaceImplEmitter, andUserTokenResolver) instead of leaking hostSystem.Private.CoreLib/System.RuntimeAssemblyRefs oninline struct,inparameters,ref readonlyreturns, andinitproperty setters, andDataStructSynthesizer.EmitDataStructGetHashCodefalls back toEqualityComparer[T].Default.GetHashCodewith a deterministic* -1521134295polynomial combine whenSystem.HashCodeis absent from the target reference set. -
Binderconsolidation behindSubmissionBindingandBindingServices.BodyBindingOptionscompletes ADR-0212 (Fixes #5139, fixes #5140, fixes #5312; ADR-0212 slice S8):- Incremental body-binding options (
BodyBindingOptions(Cache, DirtyTrees)) now live onBindingServices(propagated acrossBoundScope.CreateIndependentBodyScope), removingBoundBodyCacheanddirtyTreesparameters and per-body cache closures fromBinder.gs. - Interactive-submission binding and helpers now live under
src/Core/CodeAnalysis/Binding/Submissions/(SubmissionBinding,Binder.Submissions.gs,ExpressionBinder.Submissions.gs,OverloadResolver.Submissions.gs,BoundScope.Submissions.gs,SubmissionImports.gs, andSubmissionGlobalTypeProjection.gs), reached through theSubmissionBindingdoor whenBoundScope.SubmissionImportsis present, soBinder.gscarries zero submission or body-cache logic (ADR-0212 §11.3 Gate 3). No change togscoutput or theGSharp.Corepublic API.
- Incremental body-binding options (
-
Behavior fix: implicit interface property, indexer, and event implementations that are neither
opennoroverrideemitMethodAttributes.Finalin both implementation and reference assemblies (Fixes #5638; ADR-0208).MemberDefEmitter.EmitPropertyGetter,EmitPropertySetter,EmitEventAddAccessor,EmitEventRemoveAccessor, andEmitEventRaiseAccessor(together withDeclarationBinder.SynthesizePositionalInterfacePropertiesandFindClrInterfacePropertyImplementationOrField) now stampMethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.Finalwhen an implicit interface implementation is neitheropennoroverride, matchingFunctionEmitterfor methods and computed accessors as well as C#. Derived classes in other assemblies can no longer override a non-openinterface property, indexer, or event (GS0184in G#,CS0506in C#), keeping ADR-0208 R14 narrowing across non-openauto-property reads sound. -
Behavior fix: string interpolation with a non-primitive, non-
stringhole removes narrowed mutable-global and member-path facts (Fixes #5739, ADR-0208 R11, R12, R15).AssignedRootsCollector.VisitExpressionnow callsMarkMayMutateGlobalRoots(writesReferenceStorage: false)instead of onlyMarkRunsEscapedClosure()when aBoundInterpolatedStringExpressioncontains a hole whose type is neitherstringnor a built-in value type (TypeSymbol.IsLegalPointeeType), because formatting the hole calls itsToString()method and can run user code that mutates globals or fields. Previously, a narrowed mutable global or stable member path remained narrowed across"$b"in straight-line statements,ifconditions,deferarguments, and loop headers/bodies, compiling withoutGS0158and throwingNullReferenceExceptionat runtime. Built-in primitive andstringholes as well asref/outparameter narrowings (under ADR-0208 amendment A3) remain preserved. -
Narrowing joins
breakstates with the header-false state at loop exit (Fixes #5460, ADR-0213 table 9).BindBreakStatementnow records the current narrowing state (with activefinally/using/deferand non-indexedfor ... in/await forenumerator-disposal cleanup regions, and after applying the effects of any already-evaluated prefix operands along the bound-tree path to thebreakwhenbreakappears inside an expression) on the target loop'sbreaklabel viaNarrowingFlow.RecordBreak(skippingswitchandselectframes onLoopStackso an unlabeledbreakinside aswitchorselectarm does not record onto an enclosing loop, and resolving labeledbreak nameto the named loop), andRecordLoopExitFactscomputes the loop exit state as the n-aryNarrowingState.Joinover all reachablebreakstates targeting that loop (afterApplyExitedFinallyEffects) and the loop's header-false state when the header exit is reachable (orNarrowingState.Unreachablewhen the header is unconditional, such aswhile true,for { },for init; ; post, ordo { ... } while true). Loops such aswhile s == nil { if c { s = Fix(); break }; s = "ok" },while true { if c { s = "ok"; break }; s = "other"; break }, and three-branch subtypebreakjoins (g1_with_break) now retain their narrowed type after the loop, while abreakpath that leaves the variable potentiallynildrops the fact. -
SemanticModel.GetMemberGroupcoversbasecalls, constrained staticT.M(...)calls, and unfinished calls;LookupMembersincludes private interface helpers inside their interface; imported aggregate methods carryFunctionSymbol.ImportedMember(Fixes #5444, ADR-0212):BindBaseClassCallandBindBaseInterfaceCallExpressionnow open aCallCandidateRecorderframe and stampBoundBaseClassCallExpression/BoundBaseInterfaceCallExpression, andSemanticModel.GetMemberGroupsubstitutes a constructed generic base's type arguments sobase.M(...)andbase[T].M(...)return the full overload group.BindTypeParameterStaticAccessorStepopens its own recording frame and records both source-interface (TypeMemberModel.GetMethods) and imported-CLR-interface static-virtual candidates, so standalone and nestedT.Parse(...)calls expose their full overload group at the constraint type.CallCandidateRecorder.Stampretains candidate sets onBoundErrorExpressionwhen a call fails or is unfinished (sb.Append(,Pick(), andSemanticModelindexes those failed calls soGetMemberGroupandSignatureHelpComputerreturn all candidate overloads on incomplete invocations.TypeMemberModel.EnumerateMembersyields an interface's ownPrivateMethodsandStaticPrivateMethods, andSemanticModel.LookupMembersoffers them when the query position is inside that declaring interface while excluding them on derived interfaces and type parameters.FunctionSymboladdsprop ImportedMember MethodInfo?(populated byImportedTypeSymbol.BuildMethodSymboland preserved throughSubstituteSourceMember), allowingBoundSemanticsandMemberTokenResolverto resolve methods of imported records and G# data types for cross-assembly Go to Definition. No change togscoutput.
-
cs2gselides C# 14partialindexer definitions onto their implementing declarations and excludes build-output namespace splits from repository mirror completeness (Fixes #4781, Fixes #4804).DeclarationVisitor.TranslateIndexernow skips the defining declaration of a C# 14 partial indexer (symbol.IsPartialDefinition, reporting an untranslated generated implementation viaReportGeneratedPartialImplementation) and reconciles definition-side optional parameter default values, parameter attributes (ReconcilePartialIndexerParameters), member/accessor attributes (MapPropertyAttributes), and scalar/tuple-leaf nullability contracts (ObliviousNullabilityAnalyzer.CollectOverrideContractEdges,CollectTupleContractEdges, andPartialCounterpart) onto the single emitted implementingprop this[...]declaration. InCs2Gs.Pipeline,TranslateStageandRepositoryMirror.ValidateCompletednow filterRepositoryFileInventory.HasExcludedDirectorypaths when recording and comparingRepositoryAdditionalFiles, so multi-namespace build-generated compilation inputs underout/obj/orobj/retain their split.gsunits inValidationManifestforcs2gs validatereplay without failing repository completeness while keeping authored.csnamespace splits fail-closed. -
Escaped nested CLR type names resolve in constructed generic owners, and unclosed generic-enclosing nested types are rejected at bind time (Fixes #4754, Fixes #4774).
Binder.BindQualifiedTypeNameandExpressionBinder.GetTypeClauseSegmentNamesnow readSyntaxToken.ValueTextfor dotted qualifier segments (Outer[string].$delegate[int32],$event[string].$delegate[int32], andtypeof(Outer[_].$delegate[_])) so ADR-0170$-escaped nested type names match their unescaped CLR metadata names while preserving outer and inner generic arguments.BinderContext.HasUnclosedEnclosingTypeParameters(enforced acrossTryLookupSourceType,Binder.TryResolveUserNestedTypeChain,Binder.BindQualifiedTypeName,ExpressionBinder.BindStructLiteralExpression,ExpressionBinder.TryResolveUserNestedTypeExpressionCore,ExpressionBinder.TryResolveNestedTypeChainUnderReceiver, andExpressionBinder.TryResolveQualifiedSourceTypeHead, withInterfaceSymbolreifying and preserving enclosing generic arguments acrossConversion,DeclarationBinder,BoundScope,SignatureEncoder,UserTokenResolver,CustomAttributeEncoder,ExplicitInterfaceMetadataNaming,NullableFlagsBuilder, andReflectionMetadataEmitter, andTryResolveBareOpenGenericDeclaredType/TryResolveBareOpenGenericDeclaredQualifiedType/TryResolveOpenGenericDeclaredType/TryResolveOpenGenericDeclaredNestedTyperetaining open definition lookup fortypeof(Inner),typeof(PlainInner),typeof(Outer.Inner), andtypeof(Inner[_])) recursively validates enclosing type arguments against the active type-parameter scope and rejects nested source types whose enclosing generic type parameters are neither supplied by an outer construction (Outer[string].Inner) nor in lexical scope inside the generic owner (Outer[T]), reporting a compile-time diagnostic instead of emitting an unclosed nested type that fails at runtime withBadImageFormatException. -
The loop and backward-jump region walker resolves bare default-interface, inherited-CLR, and static-import property accessors and classifies conversion sites with
ConversionsRunUserCodefor every fact (Fixes #5470, Fixes #5657, ADR-0213).StatementBinder.TryResolveBareFallbackMembernow reusesExpressionBinder.TryResolveInterfaceInstancePropertyByBareName,ExpressionBinder.TryResolveInheritedClrInstanceMemberByBareName, and static-import / submission member resolution (afterExpressionBinder.ResolvesBareMethodGroupandMemberLookup.FindLexicalMemberOwnerprecedence) when a bare name in a loop or backward-jump span is not a variable of the entry scope, so bare property and field accesses (P,P = 1) inside a default interface method, a class deriving from an imported CLR base, or a file with a static type import have the same narrowing effect as qualified accesses (includingIsStableClrGetterunder ADR-0208 R16 and source/CLR static type-initializer checks under R11, along withBareStaticOwnerInitializeson implicit static-field writes).ResolveRegionWritesnow uses the recordedRegionConversionorigins andConversionsRunUserCode(including channel capacity conversions, structural projections, and tuple element conversions, and treatingnameof(...)as a purestringform and non-empty map literals as constructions) for all facts instead of marking every conversion candidate as running user code, keeping narrowed mutable globals, closure-assigned locals, and member-bearing paths across conversion-free declarations (let n = 1), assignments, conditions, and returns while continuing to reject sites that can run a conversion operator or structural projection. -
Narrowing preserves locals that shadow names written by an enclosing
catchfilter and restores statement-level removals in athen-branch for the siblingelse-branch (Fixes #5239, fixes #5654).StatementBinder.CollectEnclosingFilterWritesandStatementBinder.FilterWritesVariablenow pair eachcatch ... whenfilter's written names with its owningtrystatement's protected block and skip variables whose declaration (AliasChain(variable)'sDeclaringSyntax) lies inside that protected block across handler entry, statement invalidation, join-exit lifts, callable-alias updates, and ADR-0213 W8 loop-region decisions (DecideRegionKill), so an inner local that shadows a name written by an outer filter keeps its narrowing.StatementBinder.InvalidateNarrowingsForAssignedVariables,InvalidateNarrowingsForEnclosingFilters,ApplyTryFinallyFallthroughNarrowings,ApplyIncomingJumpJoin, andApplySpanLabelLowerBoundnow record statement-level removals inconditionKillJournalalongside condition removals (replacing the separatelaterArmStatementKillslist inBindAfterLaterArmTests), soRestoreThenBranchConditionKillsrestores facts removed by statements in thethen-branch ofif/elseorif let(or inside a block expression of a condition in that branch) while binding the siblingelse-branch, andCSharpToGSharpTranslator.IsInThenBranchOfElseReadmirrors that rule so reads in theelse-branch stay bare. -
Imported
Task/ValueTaskand member tuple element names survive symbolic receiver/method projection and synthesizedDeconstructemission, and imported genericdata struct/record structcomposite literals preserve symbolic type arguments (Fixes #4772, Fixes #4799).MemberLookup's symbolic signature readers (GetIndexerParameterTypeSymbol,GetClrPropertyTypeSymbol,GetClrFieldTypeSymbol,GetClrMemberValueTypeSymbol,GetClrEventHandlerTypeSymbol,GetClrMethodReturnTypeSymbol,GetClrMethodParameterTypeSymbol,GetClrOpenMethodReturnTypeSymbol,GetClrOpenParameterPointeeTypeSymbol,ApplyEventDeclarationNullability,ResolveCallReturnTypeFromSymbolicTypeArgs, andResolveByRefParameterPointeeFromSymbolicTypeArgs) now applyTupleElementNamesReader.ApplyNamesguided by the open declaration layout (layoutType), preserving both declaration-site tuple element labels onTask[(...)]/ValueTask[(...)]/ member signatures and caller-supplied tuple element labels at open generic parameter positions whileTupleElementNamesReader.TryFlattenValueTupleandBinder.SubstituteTypeflattenSystem.ValueTuple(including 8+-elementTRestchains) from retained symbolicTypeArgumentsand keepSystem.Tuplereference-tuple identity intact;DataStructSynthesizer.StampSynthesizedandCustomAttributeEncoder.EmitNullableAttributeOnEventalso stamp[TupleElementNamesAttribute]on synthesizedDeconstruct/inline structparameter rows andEventDefrows. InExpressionBinder.Literals,BindStructLiteralExpressionno longer collapses an imported genericdata struct/record structliteral with symbolic or lossy type arguments (RowStruct[(Required string, Code int32)]{...},RowStruct[string?]{...}) to its unconstructed semantic aggregate, routing it throughBindImportedTypeLiteralExpressionwith the constructedImportedTypeSymbolsowith,.copy(...), and member reads preserve the generic construction. -
Type aliases have a dedicated
TypeAliasSymbol(SymbolKind.TypeAlias),SemanticModel.LookupSymbolslists them under their own names, and completion no longer enumeratesTypeAliasDeclarationSyntaxfrom syntax (Fixes #5333, ADR-0212).DeclarationBinder.BindTypeAliasDeclarationnow produces aTypeAliasSymbol(GSharp.Core.CodeAnalysis.Symbols.TypeAliasSymbol,SymbolKind.TypeAlias, added to theGSharp.Corepublic API) declared at the alias identifier with its resolvedTargetTypeSymbol, package, attributes, and documentation, retained onBoundGlobalScope.DeclaredTypeAliasesand re-pointed across body-only edits inIncrementalGlobalScopeReuse.TryRepointBodyOnlyEdit.SemanticModel.GetDeclaredSymbolandGetSymbolInfonow answer theTypeAliasSymbolfor aTypeAliasDeclarationSyntaxand its identifier token,SemanticModel.LookupSymbolslists and resolves type aliases under their own names in globals-tier source order (preferring the current file's package and boundImportSymbol.Targetimports when same-named types or aliases exist across packages, retaining the symbol when multiple imported candidates share the same targetTypeSymbol), andCompletionComputer.ComputeCompletionsobtains type aliases directly fromLookupSymbolswith the syntax-levelTypeAliasDeclarationSyntaxenumeration removed. -
Behavior fix: the eagerly evaluated receiver and arguments of a
defercall apply their narrowing effects to the statements that follow (Fixes #5640; ADR-0208).StatementBinder.BindBlockStatementspreviously invalidated narrowing facts at adeferstatement from syntax alone without passingdefer_.PrefixStatementstoInvalidateNarrowingsForAssignedVariablesorUpdateExternalCallableAliases. A call, a computed getter, an overridable auto-property read, aref/outargument, or a callable-alias reassignment in adeferoperand left narrowed globals, closure-assigned locals, and by-reference parameters narrowed for the statements following thedefer(NullReferenceExceptionat runtime), while adeferwith no mutating operands dropped member-path and by-reference narrowings from the deferred call's syntax before the block exited.BindBlockStatementsnow appliesInvalidateNarrowingsForAssignedVariables,UpdateExternalCallableAliases, andShadowAfterStatementto the captured prefix block (defer_.PrefixStatements) before binding the remaining statements of the block, without counting the deferred call itself as executed until block exit. -
Dependent generic constraints substitute sibling and owner type arguments before validation, and generic named-delegate constructions enforce type-parameter constraints (Fixes #4744, Fixes #4762).
Binder.SatisfiesConstraintnow substitutes resolved sibling, owner, and self-referential type arguments intoInterfaceConstraint,ClrInterfaceConstraint, andClassConstraintviaSubstituteConstraintType(keeping platform wrappers on mapped arguments and retaining symbolic type arguments inBinder.SubstituteTypewhenTypeSymbol.ContainsSourceArrayShapeholds),Binder.SatisfiesClassConstraint(SatisfiesImportedClassConstraint),Binder.SameConstructedInterface,Binder.SatisfiesClrInterfaceConstraintReflectively, andBinder.SourceSymbolImplementsImportedInterfacetraverse annotated imported base and interface relationships viaMemberLookup.GetClrRelationshipTypeSymbols(TryFindMatchingClrRelationship) and verify closed generic type arguments across source, symbolic-imported, closed-CLR,NullabilityAnnotatedTypeSymbol,map/Dictionary,sequence/IEnumerable,async sequence/IAsyncEnumerable,chan/Channel, naturalFunctionTypeSymbol/Action/Func, rectangular-array, rank-1 non-SZ array (IsSZArray), nullable-struct, and multi-segment tuple (GetClrSlotAlignedArguments) representations while preserving nested reference and platform nullability contracts (SameConstraintType) and directional reference-only variance (IsConstraintArgumentCompatible/Conversion.IsImplicitReferenceVariantSlot),Binder.ImplementsInterfaceandBinder.IsReferenceTypeForConstraintpropagate interface and non-universal reference class bounds alongEnumerateForwardedParameterChain(withTypeDefEmitter.EmitGenericParamRowsstampingReferenceTypeConstrainton dependent bounds proven reference-typed by a non-universal class bound),BoundScope.TryUnifyAndCheckConstraintsunifies receiver-referenced constraints mentioning additional extension type parameters, andOverloadResolver.BuildTypeArgumentVectorseeds fixed owner type parameters during explicit-type-argument candidate filtering. InBinder.BindNonNullableTypeClause,Binder.BindAndConstructUserGenericSegment, andOverloadResolver.TryConstructConversionTarget, genericDelegateTypeSymbolconstructions now validate closed type arguments (GS0152) and unforwarded open type parameters (GS0580) throughCheckUserGenericTypeClauseConstraints, matching generic class and interface type clauses instead of emitting assemblies that fail at runtime withSystem.TypeLoadException. -
Explicit
GetEnumerator()/GetAsyncEnumerator()onsequence[T]over imported elements and implicit conversions from source-declaredIEnumerable[T]/IAsyncEnumerable[T]implementers tosequence[T]/async sequence[T]bind, verify, and execute (Fixes #4760, Fixes #4761).SequenceTypeSymbol.MakeClrTypeandAsyncSequenceTypeSymbol.MakeClrType(andMemberLookup.TryProjectErasedClrType) now constructIEnumerable<T>/IAsyncEnumerable<T>in the element type's referenceMetadataLoadContextviaMapTypeSymbol.TryMakeSingleArgumentClrTypeInReferenceContextinstead of closing the hosttypeof(IEnumerable<>)over a reference-context type to produce aTypeBuilderInstantiation,MemberLookup.GetProjectionReceiverImportedTypeprojects closedSequenceTypeSymbolandAsyncSequenceTypeSymbolreceivers (TryGetClosedSequenceProjectionView),Binder.BindReturnTypeClauseunwraps an obliviousPlatformTypeSymbolwrapper before rewritingasync func ... sequence[T]toAsyncSequenceTypeSymbol, andClrTypeUtilities.FindMetadataDefinition/ClrNullability/ImportedMemberRefFactoryresolve syntheticTypeBuilder.GetMethodmembers throughMapConstructedGenericMethod/FindTokenlessMetadataDefinitionand open-definition attribute providers without readingMemberInfo.MetadataTokenon tokenless members or accepting ambiguous fallback overloads. InConversion,IsValueTypeAssignableToInterface,ClassifyCore(fromClass), andTryProjectPlatformArgumentsToSupertypenow match source-declaredstruct,class, inherited base-class, andinterfaceimplementations ofIEnumerable[T]/IAsyncEnumerable[T]againstsequence[U]/async sequence[U]throughIsRepresentationPreservingImplicit(while preserving the CLR-assignability fallback for metadata-backedStructSymbols and recognizingInterfaceSymbolto symbolic sequence alias upcasts inMethodBodyEmitter.IsReferenceCompatible), admitting exact and covariant reference-element conversions while rejecting incompatible element types and sync/async mismatches withGS0155. -
SemanticModel.GetMemberGroupincludes calls dispatched through extension methods (Fixes #5480, ADR-0212):CallCandidateRecordernow records the source extension function candidates and the receiver-filtered imported CLR extension method candidates (Binder.FilterImportedExtensionMethods) when the call binder resolves an extension call.SemanticModel.GetMemberGroupreturns, deduplicates, and orders extension groups (source extension functions by file path then start position; imported extension methods as openImportedFunctionSymbols by holder class in reference order then metadata token).- Hover overload counts and signature help in the language server now report the extension overloads for the receiver on extension calls, and
Adr0212MemberConformanceTestsverifies extension call member groups acrosssamples/andsrc/LanguageServer/. No change togscoutput.
-
cs2gsroutes unbound nested-delegatetypeofoperands through their allocated lifted top-level names and widens owner-private orprotectednested types referenced by lifted delegates (Fixes #4758, Fixes #4759).DeclarationVisitor.MapTypeOfOperandnow maps an unbound source-declared nested delegate (CSharpTypeMapper.IsLiftedNestedDelegate, including unqualifiedtypeof(Callback<>), qualifiedtypeof(Owner.Callback<>), and multi-aritytypeof(Callback<,>)) toCSharpTypeMapper.LiftedNestedDelegateNamewith_arity placeholders (Owner_Callback[_]), diagnoses unboundtypeofover nested source delegates inside generic containing types (Outer<>.Callback<>,Outer<>.Plain) as unsupported so generic arities are never silently erased, preserves imported unbound nested delegate spellings (ImportedOuter[_].Callback[_]), and resolvesusingaliases viaGetAliasInfoinRenderUnboundTypeSimpleName(typeof(Collections.List[_])).DeclarationVisitor.MapVisibilitynow widensprivatenested types and members toVisibility.Internaland widensprotectednested types and members toVisibility.Default(public) when their enclosing chain is externally visible orVisibility.Internalotherwise whenCSharpToGSharpTranslator.IsReferencedByLiftedDelegatefinds them referenced by a lifted top-level delegate's signature, generic constraints, or attributes, avoiding runtimeTypeLoadException: Access is deniedwhile preserving cross-assembly derived-type access. -
Disambiguate
CompilationinAdr0212ImportedRecordMemberTestsfor the next compiler pin (Fixes #5726).test/Core.Tests/CodeAnalysis/Adr0212ImportedRecordMemberTests.gsnow aliasesGSharp.Core.CodeAnalysis.Compilation.CompilationasGsCompilationalongsideGsSyntaxTreesotest/Core.Testscompiles with zeroGS0547cross-import homonym diagnostics under both the pinned0.5.460compiler and the currentmaincompiler after#5668. -
SemanticModel.LookupSymbolsscopes booleanispattern variables to the binder's flow regions, including after an early exit (Fixes #5334, Fixes #5466, ADR-0212).PatternVariables.BindInScopeandStatementBinder.ApplyEarlyExitPatternVariablesnow record the syntax regions in which the binder declares aPatternVariableSymbol(when-true/when-false branches ofifand conditional expressions, short-circuit&&and||operands, loop bodies,if let/switch/catchguards, and the rest of the enclosing block after an unconditional early exit), andSemanticModel.RegionOfconsults those regions instead of scopingis-pattern variables to the enclosing statement.LookupSymbolsandGetSpeculativeTypeInfono longer offer a when-true variable in theelsebranch or on the false side of||, and now resolve negated pattern variables (if !(x is T v) { return }andif x is not T v { continue }) after an early exit, removing theNotPatternSyntaxskip inAdr0212SpeculativeTypeInfoTests. -
Behavior fix: structural
==and!=on data and inline structs (and==/!=relational patterns) count theirEqualscall in flow-narrowing invalidation (Fixes #5710, ADR-0208 R19).AssignedRootsCollector.VisitBinaryExpressionnow recordsMarkMayMutateGlobalRoots(writesReferenceStorage: false)whenStatementBinder.BinaryEqualityRunsUserCodeidentifies a non-nullBoundBinaryExpression(==or!=, includingBoundRelationalPattern.Testforis ==andis !=) that emitsObject.Equals(object, object)on adataorinlinetype (StructSymbolwithIsDataorIsInline, or itsNullable<T>form) or acomparabletype parameter. Previously,AssignedRootsCollector.VisitBinaryExpressionrecorded only the operand effects, so a field'sEqualsoverride that cleared a narrowed mutable global or closure-assigned local left the narrowing active and threwNullReferenceExceptionat runtime. Primitive/enum/reference-identity comparisons,nil/ null-default comparisons, andref/outparameter narrowings (under ADR-0208 amendment A3) remain preserved. -
gscruns value-structlet(initonly) and private field initializers in the owning struct constructor and preserves enclosingunsafecontext across deferred field initializers and rich anonymous objects (Fixes #4742, Fixes #4753).StructSymbol.NeedsSynthesizedValueStructDefaultCtornow includes value structs whoseInstanceFieldInitializerscontain alet(IsReadOnly) field even when that field ispublicwhileStructSymbol.UsesOwningZeroInitializerConstructorpreserves zero-only initialization for bare declarations (var s S),InitializationPlanner.RequestFinderchecksHasDeclaredPrimaryConstructorwhen scanning struct literals for constructor-owned initialization, andConstructorBodyEmitterlowersfieldInitBodythroughLowerer.Lower(..., classSym)inEmitClassConstructorWithBaseInitializerBodyBytesandEmitClassConstructorWithBodyBodyBytes, ensuring nested struct field initializers (public var Nested Inner = Inner{}) executeinitonlyand private stores insideInner's own constructor rather than emitting invalidInitOnly/FieldAccessstfldinstructions in the outer constructor. InDeclarationBinderandBinder,CreateFieldInitializerAccessibilityContext,CollectRichAnonymousObjectDeclarations(afterPartialTypeMerger.MergeStructs),SynthesizeAnonymousClassDeclaration, andCreateRichBindingMethodpreserve the enclosingunsafecontext so raw-pointer array allocations ([0]*int32) in field initializers and rich anonymous objects bind*TasPointerTypeSymbolinstead ofByRefTypeSymbol(GS9998: TypeLoadException). -
Symbolic CLR interface signature matching projects open slot signatures into G# symbols and compares them via
ConformanceSignaturesEquivalent, accepting asyncTask<T>/ValueTask<T>, tuple, function/delegate, pointer, nestedNullable<V>, andmap/sequencepositions (Fixes #4626).MemberLookup.ParameterTypeMatchesSubstitutedandReturnTypeMatchesSubstitutednow project each open CLR signature position throughMemberLookup.MapOpenClrTypeToSymbolicWithoutNullability(substituting both the interface's symbolic type arguments and the method's own generic parameters, then unwrappingTask/ValueTaskreturns viaAsyncReturnTypeNormalizer.TryUnwrapTaskReturnType) and compare the projected symbol against the candidate withDeclarationBinder.ConformanceSignaturesEquivalent, replacing the hand-written structural comparators (ParameterTypeMatchesSubstituted,ClrParamTypeMatchesGenericMethodParam, andTryGetSymbolicConstructedGenericShape).DeclarationBinder.TypeSignaturesEquivalent(under conformance matching) andTypeSymbol.AreRuntimeEquivalentIgnoringReferenceNullabilitynow also matchMapTypeSymbolagainstDictionary<K, V>, naturalFunctionTypeSymbolshapes againstSystem.Action/System.Func, and cross-context constructedImportedTypeSymboldefinitions while rejecting value-nullable (int32?vsint32), fixed-array ([N]Tvs[]T), rank-1 non-vector array (T[*]vs[]T), nominalSystem.TuplevsValueTuple, erased-object(List[object]vsList[Shape]), and nominal-delegate mismatches. -
OutputType=WinExeprojects now retain their entry point. The SDK passes/target:winexetogsc. Windows apphost and NativeAOT builds use the GUI subsystem.Exekeeps the console subsystem. Fixes #5730. -
Imported user-defined conversions with nullable value parameters and returns bind and execute with their declared contracts (Fixes #4737).
ClrOperatorResolution.TryResolveConversionForTypesandClrOperatorResolution.HasImplicitConversionnow probeNullableLifting.GetEffectiveClrType(targetType)alongsidetargetType.ClrType, wrap a non-nullable, non-by-ref-like value operand toNullable<S>(NullableLifting.TryMakeNullableClrType) when the only applicable conversion operator acceptsS?, and gate underlying-source (sourceType.ClrType) fallback probes onBoundClrConversionCallExpression.CanLiftTo(targetType).BoundClrConversionCallExpressionwraps a non-nullable value operand in aBoundConversionExpressiontoS?when the resolved operator takesNullable<S>and recognizes lifted conversions whose operator already returns a nullable value type (S -> T?lifted toS? -> T?),ExpressionTreeLowerer.BuildUserDefinedConversionExpressionwraps a non-liftedT -> T?return conversion aroundExpression.Convert(..., method)and preserves the symbolic declaring owner when materializing the conversionMethodInfo(BuildConversionMethodInfoConstant, together with symbolicNullable<T>token emission inImportedMemberRefFactory.GetTypeOfToken), andMethodBodyEmitteravoids re-wrapping a result that is alreadyNullable<T>(ReturnsValueTypeNullable) and selects the declaring generic owner by closedDeclaringTypeor projected operator signature when both source and target instantiate the same generic definition (SymbolicConversionOwner/SymbolicOperatorMatchesOwner). Also enables runtime and ILVerify assertions on the three#4737controls inIssue4719CastNullTupleLeafTests. -
Smart-cast flow-narrowing documentation in
ADR-0069, the language reference, and the Tour matches the compiler (Fixes #5165).docs/adr/0069-smart-cast-flow-narrowing.md,website/docs/ref/spec.md, andwebsite/docs/tour/control-flow.mdnow document that bare top-levelletandvarbindings do not narrow onis/!istype tests (Issue700SmartCastBinderTests.If_IsTest_OnGlobalVariable_DoesNotNarrow, ADR-0208 rowe20), while a read-only top-levelletnarrows as aswitchdiscriminator or stable member-path root and top-level globals narrow on nil guards,[NotNullWhen]predicates, and non-null assignments until invalidated by a write, a call or other operation that can run user code (ADR-0208 rows R11, R14, R16, R17, R19), or a suspension point (row R13). The Tour replaces the stale claim that fields and properties never narrow with the stable member-path and invalidation rules (ADR-0069#1180, ADR-0208 R14/R16–R19), the language specification updates the closure-capture rule to reflect that read-only plain variables retain their narrowing inside a closure body while closure-assigned variables lose narrowing across declared calls, getters, and constructors (with calls through a callable value using the separate external-callable alias classificationAnalyzeCallableVariable; ADR-0069#2442, ADR-0208 R15), restores the ADR-0069 / ADR-0208 / ADR-0213 links inRef:, and documents the early-exit and branch-exit join lift rules (ApplyEarlyExitNarrowingsandApplyJoinExitNarrowings, ADR-0069#4216and ADR-0208 rows R1–R5) and loop entry/exit rules (ADR-0213 slice L1 and §20b). -
Restructure the
src/Coreparenthesized-assertion receivers and callable-memberfunctionTypenarrowing sites for the next compiler pin (Fixes #5674, fixes #5695).StatementBinder.StripNullableValue,StatementBinder.StripReferenceNullability, andStatementBinder.NarrowingState.StripNullabilitynow unwrapNullableTypeSymbolandPlatformTypeSymbolthrough type patterns instead of(x as T)!!.UnderlyingType, returning the committedsrc/Core)!!.count from 11 to 8 (below the<= 9ceiling ofIssue3422RedundantNullForgivenessTranslationTests.CoreMigration_RedundantAssertionInventoryDoesNotRegress).ExpressionBinder.TryBindUserCallableMemberInvocationsplits the indexed-delegate fallback guard (!MemberLookup.TryGetDelegateFunctionTypeFromSymbol(indexedType, out functionType)) into its ownifstatement and drops the 12 downstreamfunctionType!!assertions so both the pinned0.5.460compiler and the currentmaincompiler narrowfunctionTypetoFunctionTypeSymboland compilesrc/Corewith zeroGS0536diagnostics. -
SemanticModel.GetSpeculativeTypeInfoincludes in-scope local functions (Fixes #5469).SemanticModel.GetSpeculativeTypeInfopreviously filteredLookupSymbols(position)toVariableSymbol, omitting direct-call local functions (FunctionSymbolwithLocalDeclaration != nil, covering generic local functions,ref-returning local functions, and mutually recursive non-generic local function groups).GetSpeculativeTypeInfonow collects all in-scope localFunctionSymboloverloads (from the start of each consecutive local-function declaration group through the end of its enclosing block, grouped by lexical block depth from outermost to innermost when the nearest declaration of that name is not a variable or parameter) along with the type parameters of any enclosing generic local functions (SemanticModel.EnclosingLocalFunctionTypeParameters), and passes them toBinder.BindSpeculativeExpressionType, which declares each lexical depth in its own childBoundScopewithBoundScope.TryDeclareFunctionand seedsBinderContext.CurrentTypeParameters. -
Inherited generic properties, indexers, events, and fields from a referenced assembly preserve their receiver-substituted symbolic type (Fixes #5590).
MemberLookup.FindOpenIndexerDefinitionandMemberLookup.GetClrEventHandlerTypeSymbolnow includeBindingFlags.NonPublicwhen locating the open generic member definition on an imported declaring type,MemberLookup.GetClrMemberDeclaringTypeSymbolandMemberLookup.GetClrFieldReferenceContainerproject derivedStructSymbolreceivers throughGetProjectionReceiverImportedType,MemberLookup.MapOpenClrTypeToSymbolicmaps symbolicSystem.ValueTupleinstantiations toTupleTypeSymbol, andUserTokenResolver.TryGetSymbolicSubstitutedPropertyReturnandTryGetSymbolicSubstitutedInstanceMethodReturnrecover the member's generic declaring owner across imported base-class hierarchies. Previously, aprotectedgeneric property (protected prop Input TInputonBase[TInput]in a referenced assembly, inherited byclass Owner : Base[Big]) missed its open definition inFindOpenIndexerDefinitionand fell back to the erasedBase<object>property, typingInputasobjectwhile emittingBase<Big>::get_Input()and causingif Input is Big valueto emitisinston an unboxed struct (NullReferenceExceptionon CoreCLR and exit code 139 in NativeAOTilc). -
Named compile-time constants and constant expressions over
constfields are accepted as optional parameter defaults (Fixes #5586, Fixes #5034).ConversionClassifier.TryExtractConstantDefaultandExpressionBinder.TryGetConstantIntegerValuenow evaluate compile-time constant expressions (including qualifiedTokens.SizeandWidget.Prefix, unqualified and static-importedSize, and unary/binary constant expressions overconstfields) throughConstantExpressionEvaluator, andDeclarationBinder.BindPendingConstInitializersfoldsconstfield initializers across all structs, classes, and interfaces beforeBindPendingParameterDefaultValuesand top-level function parameter defaults run (withPushStaticMemberScopeactive for member parameter defaults). Non-conststatic fields (shared { var ... }andshared { let ... }) continue to reportGS0265. -
SemanticModel.LookupMemberslists the members of a type-parameter receiver (Fixes #5488, ADR-0212).LookupMembers(position, type, name)now returns the members of each constraint of aTypeParameterSymbol(includingT?andT!wrappers) in constraint order alongBinder.EnumerateForwardedParameterChain— source interfaces, imported CLR interfaces, source and imported base-class constraints (instance members, inherited imported base members, and default interface methods), and transitive dependent type-parameter constraints ([A I, B A]) — followed by the public instance members ofobjectwhen no constraint is a class, and extension members in scope. Duplicate members reached through multiple constraints are listed once, and imported member types are projected through the ADR-0193 readers at each constraint. Member completion and hover in the language server now offer and resolve members on constrained type-parameter receivers, andAdr0212MemberConformanceTestsno longer skipsTypeParameterSymbolreceivers. No change togscoutput. -
GetEnclosingSymbolandLookupSymbolsuse the real block extents of a mergedsharedblock (Fixes #5465. Part of #5340).PartialTypeMergernow records each part'ssharedblock extent on the mergedSharedBlockSyntax, andSemanticModel.FindInnermostNodeenters a mergedsharedblock only when the position lies in one of its recorded extents in the tree. -
Behavior fix:
go f(args)evaluates the function value, the receiver, and every argument on the spawning goroutine, once and in source order, before the child starts (Fixes #5591; ADR-0174 D5). Before this fix, the child evaluated the call's operands after the spawner had continued.go Record(this.count)followed bycount++passed the incremented value, and a side-effecting argument ran after the statements that followed thego. Ingo Work(source?.Token ?? CancellationToken.None), the child readsourcelate and called.Tokenon a copy of the?.capture local that the spawner had not yet assigned, so it threwNullReferenceExceptionwhensourcewas notnil. A call to a suspending function in an argument emitted invalid IL.StatementBinder.BindGoStatementnow evaluates each operand into a read-only local declared before the work item is queued, through the call rebuild thatdeferalready used. A value-type receiver is still storage: ingo holder.counter.Bump(),go box.Value.Bump(),go holder.pair.Item1.Bump(), andgo items[index].Bump()the spawner evaluates and probes the location before evaluating arguments, and the child mutates that storage; an opaque ref-returning receiver is rejected withGS9011instead of mutating a copy. By-reference arguments, byref-like values, and operands that read a variable that no closure may capture keep their previous evaluation, and an explicitawaitin an argument (including inside an implicitly awaited suspending call) still reportsGS0576. The same defect inasync letinitializers is also fixed: the locals that?.and type patterns declare there now belong to the child. -
Early-exit guard lifts,
guard letlifts,switchlifts, andif/ bare-block exit joins remain active in functions with usergotostatements or labels (Fixes #5301, Part of #5130, ADR-0208 R6, ADR-0213 §3d). Removes the function-wideFunctionContainsUserGotoOrLabelsuppressions inStatementBinder.ApplyEarlyExitNarrowings,ApplyIfJoinNarrowings,StatementBinder.NarrowingExits(JoinExitsEnabled), andBindGuardLetStatementInBlocknow that ADR-0213 slice L2 (#5318) binds backward-jump spans underLower(S, span)atspan.FirstStatementand at participant labels (preventing falseGS0536warnings on!!inside backward-gotospans, probeq2) and joins forwardgotos into a loop body into the loop's entry stateSunder rule J6 (probeq6). Forward jumps into labels continue to join atDefineUserLabel(JoinForwardJumpsAtLabel),ApplyIfJoinNarrowingsandApplyJoinExitNarrowingsunwrap labeledifstatements (L: if ...),ApplyEarlyExitNarrowingsskips liftingelseFramewhen an explicitelsebranch contains a user label, andProcessBranchStatement,ClassifyIfConditionNarrowing,ComputeConditionNarrowingInOrder, andClearAssignedRootsAndUpdateAliasesclear running branch state and callable aliases across user labels in conditions or statements so agotointo a condition or branch cannot lift a bypassed fact or alias. -
Backward-jump spans apply the ADR-0213 region lower bound at entry and participant labels, and remove the external classification of a function value reassigned in the span (Fixes #5318, Fixes #5671; ADR-0213 sections 11, 13, 16 R8, 20 L2).
StatementBindernow binds the first statement and every participant label of a backward-jump span (BackwardJumpSpans) underLower(S, span)through the sharedApplyRegionLowerBoundCorepath used by loops, joins pending forwardgotos targeting labels inside a loop or span into the region's entry stateS(rule J6), records forwardgotojump states inNarrowingFlow, and deletesGotoNarrowingSnapshot.gsand the optimistic post-hoc backward-gotonarrowing tracker (BackwardGoto*,TrackBackwardGotoNarrowingUse, proof generations, andReportUnsafeBackwardGotoNarrowings). BecauseApplyRegionLowerBoundCorealso reducesexternalCallableAliaseswhenexternalCallableAliases.Count > 0, a function value initialized from an external callback (var g = cb) and reassigned inside a backward-gotospan (g = h) loses its external classification across the span even when no narrowing fact is in force before the label, reportingGS0158instead of throwingNullReferenceExceptionon the second iteration. -
Source-qualified constructor and callable overloads compare canonical type definitions, and argument ref-kinds participate in constructor applicability (Fixes #4739, Fixes #4740).
BoundScope.SigTypesEquivalentandDeclarationBinder.TypeSignaturesEquivalentnow compare user-defined aggregates (StructSymbol,InterfaceSymbol,EnumSymbol,DelegateTypeSymbol) by canonicalDefinitionidentity plus effective enclosing and constructed type arguments, and compareImportedTypeSymbols by open generic definition (ClrTypeUtilities.AreSame) andConstructedTypeArgumentsinstead of falling back tox.Name == y.Name, so overloads over same-compilation homonyms across packages or containers (init(x Foo.X)vsinit(x Bar.X),Foo.Box[int32]vsBar.Box[int32],List[Foo.X]vsList[Bar.X],OuterA.InnervsOuterB.Inner) no longer collide asGS0264. InOverloadResolver,IsRefKindApplicableandIsConvertibilityApplicablenow filter user and constructor candidates by call-site argument passing mode (ref,out,in,&, vs by-value) before ranking,TryCloseGenericExplicitConstructorTypebindsref/out/inconstructor arguments throughbindRefArgumentExpression,DeclarationBinderroutes: base(ref/out/in ...)arguments throughBindRefArgumentExpression, andBindExplicitConstructorCallExpression/BindConstructorChainingExpressionreportGS0235on ref-kind mismatches instead of treating value/ref constructor families as ambiguous (GS0266) or emitting invalid IL. -
The language server no longer references
GSharp.Core.CodeAnalysis.Bindingtypes (BoundGlobalScope,BoundProgram), emptying the ADR-0212 binding reference gate allowance list (Fixes #5474, Fixes #5311).SemanticLookup.BuildModelUncached,SemanticLookup.WarmUp, andHoverComputer.CountOverloadsnow resolve top-level declarations, overloads, type aliases, imports, and packages throughCompilation.GetSemanticModel(tree)(GetDeclaredSymbol,LookupSymbols) over per-tree syntax buckets, andBoundSemantics.GetModelandSemanticLookup.BuildModelUncachedwarm up declaration and body binding viaCompilation.GetDiagnostics()instead ofCompilation.BoundProgram.GSharp.LanguageServer.dllnow carries zeroTypeRefrows intoGSharp.Core.CodeAnalysis.Binding, andBindingReferenceGateTestsenforces an empty allowance list. -
gscpreserves null across typed-null and platform delegate conversions, bindsstruct- andunmanaged-constrainedT?unwrap and boxing conversions, and unwraps widened value-type null-coalescing results before numeric conversion (Fixes #5487, Fixes #4723, Fixes #4735).ConversionClassifier.BindConversionCorenow admits explicitS? -> Tunwrapping conversions (Conversion.HasExplicitNullableValueUnwrap, including[T struct]and[T unmanaged]type parameters,T(value)) while keeping implicit non-numericS? -> Srejected withGS0155, andConversion.ClassifyCoreclassifies lifted boxingT? -> U?(T? -> object?,T? -> ValueType?, and constraint-proven interface targets) asConversion.Implicitacross all value-typeNullable<T>shapes (NullableLifting.IsAnyValueTypeNullable, including[T struct]and[T unmanaged]type parameters).MethodBodyEmitter.EmitConversionreuses the source delegate whenConversion.ReusesFunctionValueDelegateholds for an imported delegate converted to a structural function type, andMethodBodyEmitter.EmitNullGuardedDelegateToDelegateAdaptationpops and replaces always-null delegate sources (default(...)/nil) withldnullwithout emitting an unverifiableldvirtftn/newobjsequence while null-guardingPlatformTypeSymbol(T!) and conditional delegate sources.MethodBodyEmitter.EmitBinaryalso preserves runtime-equivalent nullable tuple wrappers across reference-nullability differences and unwraps and converts or boxes (with interface merge casts) the non-null branch of??when the coalesced result type widens or boxes the leftNullable<T>operand, ensuringint32(Count(present) ?? ...)overuint64?/uint32?produces verifiable IL and accurate values under JIT and NativeAOT. -
Async compound assignments to hoisted local and static struct fields compile and mutate in place, and struct literals in earlier field initializers retain the target struct's declared field defaults (Fixes #5594, Fixes #5596).
MoveNextBodyRewriter.InnerRewriter.RewriteFieldAssignmentExpressionandHoistedFieldRewriter.RewriteFieldAssignmentExpressionnow delegate expression-receiver and interface-static field writes toBoundTreeRewriter.RewriteFieldAssignmentExpression, which rewritesReceiverExpressionwhile preserving shared receiver identity across compound-assignment reads and writes (RewriteWithSharedReceiver),SpillSequenceSpiller.SpillFieldAssignmentspills expression-receiver field assignments withpreserveReceiverStorage: true, andSideEffectSpiller.IsInPlaceStorageWriteReceiverrecognizes addressable source static fields (Receiver == nil && !Field.IsConst). Previously,result.Size += valueon a local struct or data struct retained across anawaitleftReceiverExpressionas the unrewritten localBoundVariableExpressionand failed emission withGS9998("No slot populated for VariableExpression receiver"). InDeclarationBinder,EnsureStructFieldInitializerBoundnow binds each omitted target field's deferred initializer on demand and publishes it intoInstanceFieldInitializersimmediately whenExpressionBinder.BindStructLiteralExpressionorConversionClassifierconstructs a struct literal, andBindPendingFieldInitializersdrains all instance field initializers beforesharedstatic field initializers, so an inline field initializer on a type declared before the struct (var Value Report = Report{}), asharedfield initializer, or mutually dependent struct literals with overridden fields retain all declared field defaults regardless of declaration order. -
Behavior fix: imported user-defined conversions from a nullable value type to a non-nullable value type are rejected at compile time instead of emitting invalid IL (Fixes #5587, Fixes #5777).
ClrOperatorResolution.TryResolveConversionForTypespreviously fell back tosourceType?.ClrType(NullableTypeSymbol's underlying value type) even when the target type could not be nullable-lifted (!BoundClrConversionCallExpression.CanLiftTo(targetType)), andBoundClrConversionCallExpression.CanApplyImplicitClrConversiontreated an unlifted operator taking the underlying value type as returning the non-nullable target type. As a result, assigning afloat64?value to a non-nullable imported struct property declaringop_Implicit(float64)(such asStyle{FontSize: Button.FontSize}in asharedinitializer or() -> Text{FontSize: size}on aninitproperty in a lambda) compiled without diagnostics and emitted an unliftedcall op_Implicit(float64)withSystem.Nullable<float64>on the evaluation stack (InvalidProgramExceptionat runtime).ClrOperatorResolution.TryResolveConversionForTypesandBoundClrConversionCallExpression.CanApplyImplicitClrConversionnow requireCanLiftTo(andCanLiftImplicitlyTofor implicit conversions) before resolving an underlying-value operator on a nullable value-type source (validating symbolically substituted parameter types for open generic conversion operators), reportingGS0155(orGS0154at call arguments) just like same-compilation conversion operators while preserving lifted conversions to nullable targets (Length?), open generic nullable-parameter operators (Box[T](T?)), and non-null-asserted reads (Button.FontSize!!,size!!). -
cs2gspre-declares an inlineoutvariable asvar x T?when the local is promoted toT?and the callee'soutparameter does not already supplyT?(Fixes #4598).TranslateOutVarDesignationnow emits avar x T?declaration ahead of the enclosing statement and passesout xwhenShouldPromoteToNullableReference(local)widens theoutvariable and the callee'soutparameter is not already promoted in the same compilation (for exampleDictionary<int, Node>.TryGetValue(1, out Node value)followed byvalue = Unwrap(maybe)), instead of emittingout var value, which took the callee's non-nullTtype and failedGS0155on the nullable assignment. Also removes the#4598!assertions inCSharpToGSharpTranslator.Statements.gs. -
Behavior fix: a
==or!=relational pattern uses the operator of the binary expression (Fixes #5688). Before this fix,EmitRelationalPatternemittedceqfors is == "abc",case == "abc":, andp is == P(1, "a"), so astringpattern compared references and a data-struct pattern compared struct bits, and the program gave incorrect results without a diagnostic.PatternBinder.BindRelationalEqualityPatternnow binds the operationinput op valuethroughExpressionBinder.BindBinaryOperation, the operator decision of the binary expression, and the emitter evaluates the input and then the value once before the operation. Astring, data struct, enum, floating-point, or nullable input therefore matches as the expressioninput == valuedoes, and a==or!=pattern on astring?, a struct with a user-definedoperator ==, a CLR type withop_Equality(DateTime,DateTime?), or a tuple now compiles instead of reportingGS0174. The value keeps its own type, as the right operand of the expression does, sox is == niland a useroperator ==with a different right operand type behave asx == nilandm == 5; a baredefaultvalue takes the input type. An input type without an equality operator still reportsGS0174, and a value of an incompatible type reportsGS0129(before this fix,GS0155). The narrowing analysis treats== valueand!= valueas operator candidates, as it treatsinput == value. -
Behavior fix: an omitted value-type
T?argument with a non-null constant default reaches the callee as that non-null value (Fixes #5589). Before this fix, a call that omitteddirection Direction? = Direction.LeftToRight,x int32? = 5, or any otherT?parameter with a constant default pushed a bareTinto theNullable<T>slot. The JIT then threwInvalidProgramException, and NativeAOT reported that the method "will always throw". Imported C#decimal?defaults passed an unverifiable value, and importedDateTime?defaults from[DateTimeConstant]passednil. G# functions, methods, constructors, base-constructor initializers, indexers, extension functions, generic members, named-argument calls, and expression-tree lambdas now buildnew Nullable<T>(value)for each omitted argument. This includes imported C# methods withint?,decimal?,DateTime?, and enum?defaults. The parameter metadata does not change: it keeps the underlying constant, as C# does, so C# callers of G# methods get the same defaults. -
cs2gsmaterializes non-constant struct and nullable-struct default arguments at folded nullable-group and delegate call sites (Fixes #4642).TranslateOperationDefaultArgumentnow falls back toBuildOptionalParameterDefault(parameter, mappedType, callSyntax)whenargumentOperation.Value.ConstantValuehas no value, emittingdefault(T)for non-nullable value-type defaults (TimeSpan = default,CancellationToken = default, user structs, andstruct-constrained type parameters) andnilfor nullable value-type defaults (TimeSpan? = default) without reportingUnsupported. -
cs2gs asserts a dropped by-ref suppression at every non-null slot, not only at a member-access receiver (Fixes #5627, found in #5608).
Volatile.Read(ref cache!)drops the by-ref!, so G# infers the result from the declaredDictionary?storage and the result isT?. Since #4287 only a receiver such asVolatile.Read(ref cache!).CountbecameVolatile.Read(&cache)!!.Count. An argument (Take(Volatile.Read(ref cache!)), GS0154), a return (GS0155), an assignment or an explicitly typed initializer, and a receiver composed by a conditional, a switch expression or??(GS0582) did not compile. Each of these bridges now asks one query,YieldsValueNilableBeyondItsCSharpType, and adds!!where the emitted value isT?and the slot is non-null with a type that the program text writes (a field, a property, an explicitly typed local, a parameter that G# does not infer, or a method or fixed-delegate lambda result). A slot that accepts nil keeps the null as C# does, and so does a slot that G# types from the value: avaror deconstructed local (also through a tuple literal or a later assignment), the result of a lambda whose type G# infers, and an inferred generic parameter. When the cache is null, the!!throwsNullReferenceExceptionat the slot. C# passes, returns or stores the null and throws at the first dereference, so a program that dereferences the value prints the same output. -
Bound method groups over
asyncextension functions convert toTask- andValueTask-returning delegate types (Fixes #4699).ExpressionBinder.BindExtensionMethodGroupOrErrornow computes a single non-generic extension method group's natural return type throughMethodGroupObservableReturnType(Task,Task[T],ValueTask, orValueTask[T]) instead of the unwrapped declared return type (voidorT), which previously rejectedlet f async () -> int32 = "four".LengthAsyncandlet f () -> ValueTask = "later".ValueDelayAsyncwithGS0155.ExpressionBinder.ProjectMethodGroupReturnClrType,ExpressionBinder.TryGetSymbolicUserMethodGroupType, andOverloadResolver.ResolveUserMethodGroupReturnalso widen async and suspending method-group return types (classified on the candidate's declared return type viaAsyncIteratorDetection.IsAsyncIteratorReturnType) and close receiver-bound generic candidates during CLR and user generic call inference (Task.Run("nine".LengthAsync),Task.Run(Payload(77).DelayIdentityAsync)),LambdaBinder.CreateUserMethodGroupAdapterwraps and converts extension method groups with non-reference-constrained type-parameter receivers, andMethodBodyEmitter.TryEmitClosedExtensionMethodGroupemitsMethodSpechandles for generic extension method groups and supports named-delegate and symbolic imported-delegate targets (Func[Task[Payload]]). -
cs2gsprojects nullable managed-reference array substitutions through nested types of generic outer types and inherited generic base types (Fixes #4548, Fixes #4549).BuildConstructionpreserves the mappedContainingTypequalifier when constructing a nested type of a generic outer type (Outer[managed[int32]?].Inner(...),Outer[managed[int32]?].Mid.Deep(...),Outer[managed[int32]?].GenericInner[string](...)), andResolveValueSinktreats C# discard assignments (_ = ...) as sinkless so discard-assigned constructions do not reject containing-type projection as fixed destination storage.GetProjectedBaseType,GetEffectiveBaseType, andGetReceiverTypeHierarchynow project a source-declared derived type's generic base type (class Derived : Base[managed[int32]?]) and resolve inherited members across single- and multi-level derived receivers (new Derived().Add(source[0]),new SubDerived().Add(source[0]),new GenericDerived<ManagedRef<int>>().Add(source[0])) when all base-type conversions remain compatible, while reportingUnsupportedwhen a fixed base destination cannot adopt the projected type. -
cs2gs asserts a by-reference read around a
foreachwhose iteration gsc runs through an enumerator (Fixes #5650; ADR-0208 R11, ADR-0213 table T5). gsc iterates a single-dimensional array and astringby index and every other collection (aList<T>, anIEnumerable<T>, a dictionary, a span, a multi-dimensional array,await foreach) throughGetEnumerator,MoveNextandCurrent, which can run user code, so it removes the narrowing fact of aref,inoroutparameter or areflocal at the loop, for a read in the body and after it. A typed loop variable with a user-defined, tuple or nullable-unwrapping conversion and a deconstruction that callsDeconstructcount too, and so does any loop whose body holds aforeach(unless its condition is the literalfalse), because gsc scans a loop's region without types. C# keeps the fact, soforeach (var item in items) total += item; return s.Length + total;was translated to a bares.Length, which gsc rejected with GS0158. The read is nows!!.Length. A read in the loop's collection or in aforinitializer runs before the loop's region and stays bare, and so does a read in anelsebranch after a loop in thethenbranch. -
Missing or mismatched implementations of imported static-abstract interface members are diagnosed at compile time, and static-virtual slots bind to public static members inherited from G# base classes (Fixes #4618, Fixes #4620).
DeclarationBinder.VerifyClrStaticVirtualImplementationsnow verifies static-virtual method, property, and event slots across the imported CLR interface closure (EnumerateClrInterfaceClosure), reportingGS0331for missing or signature-mismatched static-abstract methods and events,GS0332when an instance method is declared for a static-virtual slot, andGS0397for missing static-abstract properties or accessors (missing static property,getter,setter) while continuing to accept defaulted static-virtual slots and slots satisfied by an imported base class (ImportedBaseImplementsClrInterface). InDeclarationBinderandInterfaceImplEmitter, static-virtual method, property, and event resolution now walks the implementing class's G# base-class hierarchy (GetHierarchy(), with generic base type-argument substitution viaSubstituteStaticMethodForOwnerandSubstituteMemberType) for accessiblepublicstatic members, andInterfaceImplEmitter.PlanInheritedStaticVirtualBridges/EmitInheritedStaticVirtualBridgessynthesizes private static forwarding bridges on the derived class soMethodImplrows bind inherited static members withoutTypeLoadException. -
Capture-free direct-call local functions inside generic types emit top-level
MethodDefs and promote enclosing type parameters across calls, method groups, and function pointers (Fixes #4655).ClosureEmitter.SynthesizeClosuresnow excludes every capture-free direct-call local function (FunctionSymbol.LocalDeclaration != nil, covering non-generic mutual-recursion groups andref-returning local functions alongside generic local functions) from the<lambda_host_*>display-class branch when the lexical owner is generic, soReflectionMetadataEmitterplans and emits itsMethodDefon<Program>instead of failing withGS9998("Call to function '...' has no emitted MethodDef").UserTokenResolver.BuildMethodSpecForGenericCall,UserTokenResolver.BuildMethodSpecForGenericMethodGroup,MethodBodyEmitter.EmitMethodGroupTarget,MethodBodyEmitter.EmitFunctionPointerFromMethod,LambdaEnclosingTypeParameterCollector, andLambdaBinder.FindEnclosingTypeParameterReferencealso handle promoted enclosing type parameters and owner-access checks (GS0586) on non-generic direct-call local functions. -
Behavior fix: a relational pattern on a nullable value-type input compares the present value and does not match
nil(Fixes #5681). Before this fix,n is > 0,case > 0,n is 1 or > 5, and{ P: > 0 }over anint32?,int64?,float64?,decimal?,char?, or enumE?input compiled without a diagnostic, butEmitRelationalPatterncompared the twoNullable<T>structs withcgt,clt, orceq, so the pattern gave incorrect results. A relational pattern on a value-typeT?input now has the result of the lifted operator:PatternBinder.BindRelationalPatterncompares the underlyingTvalues when the pattern value converts toT, and the emitter testsHasValuefirst. Anilinput does not match<,<=,>,>=, or==with a non-nil value,not > 0and!= 3match it, and aT?pattern value (n is == m,n is == nil) uses lifted equality and ordering. A relational pattern on a user enumE?input now compiles instead of reportingGS0174. A relational pattern on adecimalinput now calls thedecimalcomparison operators; before this fix it compared the structs withcgt,clt, orceq. -
Re-listing a generic CLR interface closed over a G# type over an imported base compiles without spurious
GS0187, and explicit implementations of symbolic base-interface slots no longer emit erasedInterfaceImplrows (Fixes #4613, Fixes #4615).DeclarationBinder.VerifySymbolicClrGenericInterfacenow checksImportedBaseImplementsClrInterface, andDeclarationBinder.ClrTypeImplementsInterfaceprojects generic interfaces throughMemberLookup.EnumerateConstructedTypeArgumentsThroughHierarchyinstead of returningfalsewhenever the interface or imported base carries a symbolic type argument (class Shapes : Collection[Shape], IList[Shape]). Mismatched or unimplemented interface contracts still reportGS0187(orGS0493on an explicit interface clause). InReflectionMetadataEmitter.EmitInterfaceImplRows, explicit interface slots on symbolic generic interfaces now resolve their declaring owner throughMemberLookup.GetClrMemberDeclaringTypeSymboland deduplicate throughClrInterfaceClosureinstead of comparing the open definition against the erased closedDeclaringTypeand falling through to emit an extra<object>InterfaceImplrow (TypeLoadExceptiononfunc (IF[Shape]) F(x Shape)underclass W2 : IF2[Shape]). -
try/finallycleanup narrowing preserves facts re-established after earlier mutations and keeps post-tryexternal callable aliases across exceptional-only paths (Fixes #4608, Fixes #4609).StatementBinder.ProcessBranchStatementnow applies statement mutations and updates callable-alias state in execution order before recording normal-exit non-null facts, instead of running a whole-subtree mutation pass afterProcessBranchStatementinComputeCleanupFallthroughNonNull, andComputeConditionNarrowingInOrderinvalidates left-operand condition facts against right-operand mutations in evaluation order (if x != nil && (x = nil) == nil). A nestedtry { x = nil } finally { x = "safe" }orifbranch inside afinallyblock that clearsxbefore unconditionally reassigning a non-null value now preserves thefinally-established narrowing at normal fallthrough andgototarget joins instead of reporting a spuriousGS0158. InAssignedRootsCollector, callable alias tracking now evolves both normal-exit (normalCallableState) and all-entry (allEntryCallableState) states in a single pass, so atrywith afinallyblock collects conservative all-entryfinallymutation effects without exponential re-walks on nestedtry/finallychains while exporting the normal-exit callable alias state (or all-entry state whenfinallyexits via an escaping jump). -
gscreports GS0634 for an executable without an entry point (Fixes #5623). AnOutputType=Exeproject with noMainfunction and no top-level statements compiled without a diagnostic, and the program failed at start withMissingMethodException: Entry point not found.gsc /target:exe /out:now reports error GS0634, as C# reports CS5001, when no other error stops the output. When a function differs fromMainonly in case, such as Go-stylefunc main(), the diagnostic is on that function and asks "Did you mean 'Main'?". SDK change:Microsoft.NET.Test.Sdkmakes a test project an executable but generates its entry point only for C#, Visual Basic and F#, soGsharp.NET.Sdknow generates the same emptyAutoGeneratedProgram.Main(obj/<project>.AutoGeneratedProgram.gs) for a G# test project whenIsTestProject,GenerateProgramFileandOutputType=Exehold. Set<GenerateProgramFile>false</GenerateProgramFile>in a test project that declares its own entry point, as in C#. Library builds, the in-memorygscmode without/out:, the REPL and the language server do not report GS0634. -
cs2gsresolves the element target of a conditional or switch expression passed as an expandedparamsargument (Fixes #4448).FindContextualValueTargetnow resolves the expandedparamselement target viaTryGetExpandedParamsElementTarget(including through null-preserving reference casts) before consultingResolveValueSink, which otherwise returns the variadic parameter's array carrier type (T[]orstring?[]) rather than the element type (Torstring?).TryGetExpandedParamsElementTargetalso determines expanded form from the bound call'sIArgumentOperation(ArgumentKind.ParamArrayorArgumentKind.ParamCollection) matched by parameter name (including reduced extension calls),GetArgumentParameterresolvesparamsindexer parameters onIPropertySymbol, andIsInferredGenericParameterTarget/SinkInfersTypeFromValueunwrap supportedparamscollection element type parameters viaGetParamsElementTypeonly for expandedparamsarguments whose type parameter is unconstrained, not fixed to a non-nullable type by another argument or reduced-extension receiver in an invariant or contravariant position (OtherArgumentFixesTypeParameterToNonNull), and not explicitly supplied at the enclosing call (ValueFeedsExplicitTypeArguments). Previously, a nullable arm of a conditional or switch expression passed as an expandedparamsargument toM(params string?[] values),M(params object?[] values), a reduced extension orparamsindexer, a taint-widenedM(params string[] values),M<T>(params ReadOnlySpan<T> values), orM<string?>(params T[] values)could receive a spurious!!and throwNullReferenceExceptionat run time when the arm evaluated tonull; an arm targeting a non-nullparamselement, a constrained or invariantly/contravariantly fixed genericparamselement, explicitM<string>(...), or a normal-formparamscarrier keeps its!!. -
cs2gskeeps the native form of a constant pattern where only that form narrows the tested local (Fixes #5626). cs2gs loweredcurrent is "a"tocurrent == "a", which gsc does not narrow, but still readcurrentas narrowed, soreturn current.Lengthreported GS0158. A booleanistest over astring?local now keeps its native form (current is "a",current is not "a",current is "a" and not "b") when only that form narrows where C# relies on it, the pattern has only constant, relational and type tests, and each constant is a literal (gsc reads a name in a booleanispattern as a type first, so a named constant keeps the lowered test). One model of gsc's native pattern narrowing decides both the emitted form and the narrowing that cs2gs assumes for it. The same model also covers a switchcaseand a switch-expression arm, so their reads need no!!; it follows gsc for anandpattern (the right side's type wins), for a type test (SmartCastStability.IsTypeTestNarrowing), for a subject that is not a bare local (switch (s!)) and for a section that agoto caseenters (no narrowing). The narrowing of a lowered test mirrors gsc's separate nil-guard and type-test classification of&&,||and!, and a local counts as closure-assigned when a closure assigns any local of the same name in the function, as gsc records it. Tests that their lowered form already narrows (is null,is not null,is not null and not "a") are unchanged. A test of a nullable value (n is 1for anint32?,c is not Color.Green) also stays lowered, because the native narrowing changes the G# type of later reads (overload resolution,HasValue). A native constant or relational test in an&&or||operand is parenthesized, because gsc parses the pattern value as a full expression. -
User indexer
inparameters emit readonly-by-reference metadata and pass arguments by readonly reference, whilerefandoutindexer parameters reportGS0633(Fixes #4421; ADR-0060 §15).DeclarationBindernow bindsinon struct, class, and interface indexer parameters intoParameterSymbol.RefKind(RefKind.In) and rejectsrefandouton indexer parameters withGS0633, matching C#CS0631.MemberDefEmitter,InterfaceImplEmitter, andUserTokenResolverencodeinindexer parameters asmodreq(IsReadOnlyAttribute) T&inPropertyDefandget_Item/set_Itemsignatures withParameterAttributes.Inand[IsReadOnlyAttribute], andExpressionBinderpasses both explicitidx[in x]and omitted-inidx[x]/idx[rvalue]arguments by readonly reference across single- and multi-parameter indexer reads, writes, and compound assignments. Previouslyprop this[in i int32]silently dropped theinmodifier and emitted a by-valueint32parameter. -
Constructing and referencing a nested type under a closed generic enclosing type preserves the enclosing type arguments across
cs2gsandgsc(Fixes #4750).CSharpToGSharpTranslator.BuildConstruction(along with pattern and control-flow value-type narrowing casts) now retainsNamedTypeReference.ContainingTypewhen emitting a construction expression (new Outer<int>.Inner()->Outer[int32].Inner()instead of bareInner()). Ingsc,Conversion.AreSameConstructedStructIdentity,Conversion.DerivesFromConstructed,Binder.InferTypeArguments,ExpressionBinder.BindUserTypeStaticCallCore,ExpressionBinder.TryBindNestedTypeConstructorCall,OverloadResolver,UserTokenResolver.GetGenericTypeArguments,ClosureEmitter.ConstructedTypeCollector, andBaseCallForwarderRewriternow includeStructSymbol.EnclosingTypeArgumentsalongsideTypeArguments(preservingStructSymbol.DeclaredTypeParametersacross emission-scoped nested generic reification). Previously,new Outer<int>.Inner()lost its enclosingOuter[int32]qualifier incs2gsandgscaccepted open or mismatched enclosing instantiations (Outer[T].InnerorOuter[string].Inner->Outer[int32].Inner) without a diagnostic, emitting unverifiableOuter`1+Inner<!0>IL (ILVerify: StackUnexpected). -
cs2gsreports dropped explicit-eventaddandremoveaccessor attributes (Fixes #4523; ADR-0184).TranslateExplicitEventnow routes explicit-event declarations throughMapPropertyAttributesso attributes onaddandremoveaccessors emit the source-located non-fatalCS2GS-ACCESSOR-ATTRIBUTE-DROPPEDwarning to stderr andtranslate.logwhile preserving member-level event attributes. -
Member access through a constructor-call or composite-literal receiver preserves symbolic and nullable type arguments (Fixes #4355).
TryBindQualifiedClrConstructorCallnow requires at least one qualifier segment so unqualified constructor receivers (Box[List[int32]?]().Value) bind through the standard call binder instead of the qualified-type path, andTryBindQualifiedClrStructLiteralnow binds trailing member accesses on qualified composite literals (Ns.Box[List[int32]?]{}.Value). Nested CLR type construction and composite literals (Outer.Inner[List[int32]?](),GenericOuter[List[int32]?].Inner(),GenericOuter[List[int32]?].Inner{}) now resolve type arguments throughTryResolveClrConstructionTypeArgsand combine enclosing and nested symbolic type arguments on the constructedImportedTypeSymbol, andImportedTypeSymbol.NormalizeSemanticAggregateretains constructedImportedTypeSymbolinstances that carry symbolic type arguments (Box[Rec[List[int32]?]]().Value.Value) instead of replacing them with an unparameterized CLR-keyed semantic aggregate. -
A loop that stores a closure in a function value removes that value's external classification, also when no narrowing is in force at the loop (Fixes #5461; ADR-0213 section 13). A function value that starts from a parameter or a named function (
var g () -> void = cb) is external: a call of it cannot reach a local that a closure assigns. A loop removes that classification at its entry when its body or header assigns the value, but only did so when a narrowing fact was in force at the loop. Otherwise, infor ... { if x != nil { g(); total += x.Value }; g = h }wherehsetsx = nil, the fact onxsurvived the callg(), and the program threwNullReferenceExceptionon the second iteration. It now reportsGS0158, forfor,whileanddoloops. A loop that assigns any value to such a function value, also a named function, now removes the classification whether or not a fact is in force, as it already did with a fact in force. -
A user-defined conversion operator on a function-literal argument or a relational-pattern operand removes by-reference narrowing facts (Fixes #5663, Fixes #5665; ADR-0208 R12, R18, R19). The binder lowers a same-package
func operator implicitorfunc operator explicitto a call of itsop_Implicitorop_Explicitfunction symbol (BindUserDefinedSymbolConversion), whichAssignedRootsCollectorpreviously classified as a plain function call under amendment A3 (writesReferenceStorage: false). When a function literal was converted to a parameter type by such an operator (Use(func() int32 { return 1 }),Use(() -> 1)) or a relational pattern converted its operand to the tested type (n is > threshold,switch n { case > threshold { ... } }), and the operator cleared storage aliased by arefparameter, the narrowing survived in straight-line code, conditions,switchheaders, and loops and threwNullReferenceExceptionat run time.StatementBinder.IsConversionOperatornow marksop_Implicitandop_Explicitcalls as writing reference storage, andBoundClrConversionCallExpressionalso marks global roots and analyzes callable operands, while a function literal passed to a delegate or function parameter without a conversion operator and a relational pattern without a conversion operator keep the fact. -
Attribute constructor resolution prefers more specific parameter types over
objectand[]object(Fixes #4749).CustomAttributeEncodernow ranks applicable attribute constructors by per-argument conversion specificity (Exactbefore covariant[]objectbeforeobject) before applying the normal/defaulted/expanded form tie-breaker, across both same-compilation and imported attribute types. Previously@Marker(typeof(Owner))on an attribute declaring bothinit(type Type)andinit(value object)failed emission withGS9998("Ambiguous constructor for attribute") for same-compilation attributes or selected the first metadata constructor for imported attributes, and same-compilation enum parameters collided withint32parameters.DeclarationBinderalso accepts typednilconversions such ascast[Type?](nil)andcast[[]?Type](nil)as attribute arguments to disambiguate genuinely ambiguous overloads. -
An explicit address of differently typed storage is rejected at an imported by-reference parameter (Fixes #5558).
ClrOverloadResolution.ClassifyImplicitnow requires an address argument (&x,in x,out x) to match a by-reference parameter with the same pointee type, andConversion.Classifyrejects conversions betweenByRefTypeSymboland non-identical types. Previously,S.R(&h)andS.I(in h)forh int32atref long/in long, andS.F(&f)forf () -> int32atin Func<long>, compiled without a diagnostic and emitted unverifiable IL (StackUnexpected), whileCalls.In(&h, 1)forIn(in Func<long>, int)/In(object, long)reportedGS0160instead of rejecting theincandidate; they now reportGS0154at the argument. -
The
cs2gs-apps-nightlygsharp-csharp leg builds the same corpus package versions on every ref (Fixes #5659). Nerdbank.GitVersioning chose a public release fromGITHUB_REF, so a run onmainbuilt the corpusGsharp.NET.Sdkas0.4.1271and a branch run built0.4.1271-g<sha>. A branch run that restored the corpusoutcache saved bymainthen packed the second version beside the first during C# oracle capture, and 5 of 6 validate shards failed with "expected one corpus Gsharp.NET.Sdk package". The translate and validate jobs now setPublicRelease=false, and the cache key moves toselfmig-corpus-out-v2-*so no older entry is restored. -
gsgenprojects the synthesized copy constructor on class-fallbackdata classhierarchies and matches emitted primary-constructor signatures (Fixes #4748). When adata classcannot render as a C#recordin the generator stub because its inheritance chain includes a non-dataclassor an imported base type,GsStubRenderernow emits the synthesized copy constructor (protectedonopen,abstract, andsealedhierarchy classes;privateon closed classes) across thedata classancestry chain, chaining: base(original)to the direct base copy constructor and skipping synthesis when a copy-constructor signature is already declared. Positionaldata classdeclarations also omit the phantom parameterless stub constructor and useprotectedon declared-abstract primary constructors without a base initializer, matchinggscmetadata. -
A switch case's test removes the narrowings it can clear before the case body runs (Fixes #5629; ADR-0208 R19). A
switchcase or switch-expression arm whose constant pattern calls a userEquals, or whose property or list pattern runs a getter, now removes the facts that the test can clear before its guard and body, asif x is 1does. Previouslyswitch o { case 1 { return g.Value } }compiled and threwNullReferenceExceptionwhenEqualsclearedg; it now reportsGS0158. A case's guard now removes facts before its body and the later cases, as a condition does, and a case test that can clear the switched variable no longer narrows it. Adefaultthat is not the last case sees the tests and guards of the cases after it. A loop now also counts the effects of aswitchortrystatement whose only path back to the loop header is acontinueinside it (switch k { case 1 { g = nil; continue } }), which also threw before. -
cs2gsrepository migrations reuse loadedMSBuildWorkspaceprojects for transitive taint resolution, format translated units in parallel, and share run-level NuGet package caches across mirrored builds (part of issue #5646).CSharpProjectLoader.EvaluateCompileProjectReferencePathsAsyncevaluates transitive compileProjectReferenceedges in a single sharedMSBuildWorkspacewithout building compilations, andTranslateStage.ExecuteAsyncresolvessiblingCompilationsfromRepositoryLoadedProjectsusing those evaluated edges instead of reopeningMSBuildWorkspaceper project.ObliviousNullabilityAnalyzerscopesRegisterSourceAssembliesto each compilation's referenced assemblies so consumer projects do not invalidate shared libraries' cached taint results, and retains scalar-to-tuple flow edges for prebuilt sibling source assemblies.TranslateStage.ExecuteAsyncrenders and formats multi-unit projects in parallel while preserving deterministic emission order, andSdkCompileRunnershares<runDir>/.nuget-packagesacross all mirrored apps in a run instead of restoring into a separate empty.nuget-packagesdirectory for every app. -
Compiler.TestsandCs2Gs.TestscacheMetadataReferencesets, C# helper assemblies, and whole-project translations (part of issue #5646).NativeSliceLanguageTests.Fixture,Issue3956NamedTupleGenericArgumentIdentityTests,Issue4777ImportedRecordEqualityTests, andIssue3329CrossAssemblyStructLiteralEmitTestsnow reuse cachedMetadataReferencelists forTRUSTED_PLATFORM_ASSEMBLIES, andImportedMemberMatrixTestscompiles and caches its C# helper libraries in-process instead of invokingdotnet restoreanddotnet buildon every test case.Issue4719CastNullTupleLeafTestscompiles its 240-lineIssue4719Fixture.dllcontract once with deterministic bytes and reuses itsMetadataReferenceacross all 386 test cases, andSelfMigratedCompilerSourcecachesLoadProjectAsyncand translated files forIssue3347RemainingSpillInventoryTests,Issue3422RedundantNullForgivenessTranslationTests,Issue4779NullableReflectionArgumentsSelfMigrationTests,Issue4704ForwardedWarningIdTests, andIssue4681ChannelsNullPassThroughTests. -
CI rebalances
Compiler.Testsshards, packsGsharp.NET.Sdkonce for the E2E suite, and caches verified external C# test stamps incs2gs-apps-nightly(part of issue #5646).build/generate-ci-test-matrix.pysplitsEmit.Issue3,Emit.Issue47/Emit.Issue49, andEmit.Issue4out ofcompiler-emit-remainderand splits top-levelGSharp.Compiler.Tests.Issue3/Issue4andIssue5out ofcompiler-remainderso noCompiler.Testsshard exceeds ~10 minutes.build/run-e2e-tests.shnow packsGsharp.NET.Sdkinto.nugs/once from the repository root before running thee2etests/*-e2e.shscripts instead of repacking and purging the NuGet SDK cache 17 times sequentially, ande2etests/gsanalyzer-e2e.shbuilds its sample analyzer inReleasemode to reuse the builtGSharp.Core.dll.cs2gs-apps-nightlycaches the verified C# test stamp of the pinnedoahuandcode-explodercommits (saved only after the C# test suite passes) so subsequent runs still perform a fresh git checkout and C# build while skipping redundant C# test reruns when the pinned commit is unchanged. -
Loops remove the narrowings they can write before they are bound, and bind once (issues #5317 and #5315; ADR-0213 slice L1). A loop no longer binds its body, checks the back edge and binds again. It computes from its syntax which narrowings its header, body and post statement can write, removes them at the loop entry, and binds once. This closes #5315, where an enclosing
catch ... whenfilter that writes a narrowedrefvariable left the loop header readingnilthrough a non-null view (aNullReferenceExceptionat run time); the header read is now reported. It is stricter than before in these cases: a write on a path that leaves the loop (s.Length; if c { s = nil; break }), a reassignment from a variable or a call (node = Make()), a call or a member read in a loop that can reach a closure-assigned local, a mutable global or a member path, and afor ... inover a collection with user code. A reassignment from a variable that a type pattern in the loop binds keeps the narrowing where the binder scopes that variable (if node.Next is not Node next { break }and thennode = next). A struct literal such asx = Dog{}now keeps a type test likex = Dog()does. It is more permissive in one case: awhile,forordoloop without abreakgives the facts its condition proves when it ends (while s == nil { s = "ok" }; s.Length), so a laters!!reports GS0536. A narrowing of areforoutparameter still survives a method call and a field or auto-property read in a loop (ADR-0208 amendment A3), but not a call of a function value such ascallback(),callback.Invoke()or a function-typed field, nor a getter, indexer, operator or conversion that can run user code (Environment.CurrentDirectory,dict["a"]), as before; an argument or operand that the loop analysis cannot type counts as such code, son = n + Pick(m)with a genericPicknow drops the fact, as do an imported conversion of an array element ([]DateTimeOffset{dt}) or of an argument with named type arguments (Keep[DateTimeOffset](dt)),nilconverted to a struct by a conversion operator, a range bound converted by an operator, a call whose best overload takes an argument through a conversion operator (Consume("ab")with aReadOnlySpan[char]overload), and theSystem.Indexthatarr[^1]constructs. To keep a narrowing across a loop, test it again inside the loop or copy it into aletbefore the loop. The repository's own source meets the new rules at the next compiler pin move. -
Behavior fix: an
openoroverrideauto-property read or written inside its declaring type runs the override (issue #5630). The compiler lowered every access to an auto-property inside the type that declares it to its backing field. For anopenoroverrideauto-property, this skipped an override in a subclass without a diagnostic:Read()inopen class Base { open prop Auto int32 { get; set; } func Read() int32 -> Auto }returned the base storage for aDerivedthat overridesAuto, andAuto = vskipped the overriding setter. Such an access now calls the accessor (callvirt), as in C#, forthis, implicit and other receivers, compound assignment and constructor writes. An access still uses the backing field when the dispatch is exact: the property is notopenand notoverride, or its declaring type has no subclass (a struct, or a class that is neitheropennorsealed). A constructor store to a get-only auto-property still writes the backing field, as in C#.base.access is unchanged. A program that relied on the old behavior now prints the value that the override returns. -
cs2gs asserts a by-reference parameter read after an accessor that gsc treats as code, or after a write through a member or an element (Fixes #5617, ADR-0208 rows R12, R14, R16 and R17). gsc removes the narrowing fact of a
reforoutparameter at a getter or indexer that can run user code (also in a property or positional pattern, and in the guard's own pattern) and at every write through a member, an element or another by-reference variable, which includes awithcopy, a writablereflocal of a member or an element, and the address of a member. C# keeps the fact, soif (s == null) return 0; var n = lazy.Value; return s.Length + n;became a bares.Lengththat gsc rejected with GS0158. cs2gs now emitss!!.Lengthafter such a node. An accessor counts as code when gsc counts it: an imported getter or indexer that is not on the stable list (Lazy<T>.Value, aDictionary<K, V>indexer, anIList<T>Count), a source property that cs2gs emits with computed accessors (an expression body, an accessor body, or an auto property with an initializer that cs2gs lowers to a backing field), and anopenoroverrideauto property read through a receiver whose type can have a subclass (#5599). A field read, a getter on the stable list (string.Length,List<T>.Countand its indexer), a plain auto property andNullable<T>.Value(emitted as!!) keep the read bare. A redundant!!in the same statement as the accessor is removed by the polish pass. -
A read or write of an
openoroverrideauto property removes narrowing facts when it can run an override (issue #5599, ADR-0208 row R14). An auto property was treated as free of code, but through a receiver whose type can have a subclass the access can dispatch to an override whose accessor runs user code. That code could clear the storage behind a narrowedrefparameter, a mutable global or a closure-assigned local, and the narrowed read then threwNullReferenceExceptionat run time. Such an access now counts as a call, as a computed getter does, so the read reports GS0158. An auto property that is neitheropennoroverride, one on a value type or on a class that is neitheropennorsealed, and the initializers of a construction keep the facts. -
cs2gs passes a
varpattern capture of a non-null value on without!!in every pattern form (issue #5582, found in #5576). C# types avarcaptureT?, soq switch { var c => Take(c) }andcase var c: return Take(c);becameTake(c!!), which threw where C# passes the null on.p is var ckeptcunbridged. One decision now covers theisform, a switch arm, acaselabel, a property subpattern ({ Child: var c }) at any depth and a conjunction (var c and _): G# gives the capture the type of the value that the pattern matches, so the capture is non-null when that value is, or when a type test before it in the conjunction narrows it. A capture of aT?value or of a value that cs2gs widens keeps its bridge, now also in theis varform, which previously did not compile (GS0154). A positional subpattern keeps its previous translation (#4576). -
The repository compiler uses published SDK 0.5.460-g21e3f30fa3 (part of issue #5398). The bootstrap pin and the matching analyzer-testing package move from 0.5.212 to the prerelease
v0.5.460-rc1, built from main 21e3f30fa, with maintainer approval. On linux-x64 the build uses the ReadyToRun compiler fromGsharp.NET.Sdk.Compiler.linux-x64(ADR-0207). The new compiler reports no redundant!!(GS0536) in repository source, so no!!is removed. The 7 sites that its narrowing rules reject were restructured before the move (issue #5563). The new compiler drops unused locals and duplicate metadata rows inGsharp.Runtime.Values, so the #5244 ILVerify return certificate is renewed. The certified IL instructions and the two admittedReturnPtrToStackdiagnostics are unchanged. The published 0.5.212 and website installation examples remain the latest stable release. The pin PR's green CI provides N-1 stage-2 verification. -
The NuGet packages name a license, a project URL, a readme and an icon (issue #5621). The six
Gsharp.NET.Sdk.Compiler.<rid>packages now carry a short readme and the G# icon. The readme says thatGsharp.NET.Sdkrestores the package withPackageDownload(ADR-0207), that a project references the SDK and not this package, and thatGsharpUseReadyToRunCompiler=falseturns it off.Gsharp.Templatesnow has the MIT license expression and the project URL.build/release-publish.py verifynow requires a<license>,<projectUrl>,<readme>and<icon>in the.nuspecof each package in the release inventory, and the readme, icon and license files that the.nuspecnames must be in the package. Package contents and versions are otherwise unchanged. -
A constant pattern that calls a user
Equalsand a list pattern whoseCountor indexer can run user code remove narrowing facts (issue #5593, ADR-0208 row R19). A constant pattern on anobjectinput (x is 1) callsobject.Equals, which runs theEqualsoverride of the value's type, and a list pattern over an imported indexable type (ReadOnlyCollection[int32](l) is [1]) calls itsCountgetter and indexer, which can forward to user code. Both now count as calls, in a statement and in a condition: they remove member-path facts, facts on mutable globals and facts on closure-assigned locals (the list pattern's getters also remove facts behind by-reference parameters, as other getters do), and such a test no longer narrows its own operand when the call can change it. A program that guarded such a fact and then ran one of these tests before it used the fact compiled and could throwNullReferenceException; it now reportsGS0158orGS0159. Read the value into aletbefore the guard, or test it again after the pattern. A constant pattern on a primitive,string,decimalor a nullable primitive, anilpattern, a floating-point constant onobject, a list pattern over an array, aList<T>, aSpan<T>or aReadOnlySpan<T>, and a list pattern that reads no element ([],[..],[_]) keep their facts. cs2gs mirrors the constant-pattern rule: a closure-assigned local that is read after a C# constant pattern on anobjectinput, or that such a pattern guards itself (if (current is 1)), gets!!, so the translated code compiles. -
Repository source builds with the compiler on
mainas well as with the pinned 0.5.212 SDK (issue #5563). The newer narrowing and inference rules reject 7 sites of the repository's own source. Anoutparameter inTryGetCollectionInitializerArgumentTargetloses its non-null fact at the imported property reads in its guard (ADR-0208 row R16), so cs2gs now reads the guarded value from a local. The cs2gs report keeps only non-null triage artifacts, so its artifact list now declares a non-null element type. TheIssue4313emit test reads the declaring type of a nullable resolved method with?.. Behavior does not change. This lets the bootstrap pin move to a release with the new rules. -
SelfMigratedCompilerSourcecaches loaded projects and translated files for the default fixture root, andCompiler.Testsdriver/compound suites cache C# helper libraries and runtimeMetadataReferencesets (part of issue #5611).SelfMigratedCompilerSource.LoadAsyncnow reuses the boundLoadedCSharpProjectand translatedMigratedFileentries across tests when readingTestFixtureSource.Rootinstead of reloadingCs2Gs.Translator.csprojandCompiler.Tests.csprojthroughMSBuildWorkspaceon every call.Issue4056ConstructedGenericCompoundAssignmentTests,Issue5388ImportedBaseUpcastDriverTests, andIssue5536FunctionValueConversionDriverTestscache their compiled C# helper library bytes, runtimeMetadataReferencearrays, and invariant contract ILVerify checks across test cases. -
Reference resolvers share derived name indexes across default and identical image sets and preserve host CLR reflection caches on dispose, and C# test loaders cache runtime
MetadataReferencesets (part of issue #5611).ReferenceTypeNameIndexnow caches the namespace prefix set, arity-insensitive name groups, and emitted-to-raw name map alongside the type-name index, andReferenceResolverreuses that index across bothReferenceResolver.Default()and image-backedReferenceResolver.WithReferencesresolvers with matching assembly content fingerprints instead of rebuilding them over the host BCL on every compilation.ReferenceResolver.Dispose()continues to clear theTypeSymbolandMemberLookupcaches on every disposal while keeping theType-keyed CLR reflection caches (ClrTypeUtilities,ClrOperatorResolution) when the resolver owns neither aMetadataLoadContextnor aDriverReferenceLoadContext.CSharpProjectLoader.RuntimeReferences()andCSharpFixture.HostReferencescache theirMetadataReferencelists so Roslyn reuses itsAssemblySymbolmetadata cache across in-memory C# compilations, andbuild/generate-ci-test-matrix.pygroupsFormatting.TestsandRuntime.Channels.Testsintofast-suites. -
CI builds test assemblies once per run, narrows compiler PR routing, and reuses
cs2gs-apps-nightlyprerequisites across shards (part of issue #5611).test-partitionnow builds the selected test graph (and the cachedcs2gs/csharp-0.4tree whenCs2Gs.Testsis selected) once and uploadstest-build-outputs, which thetestsshards download instead of rebuilding the solution on every runner. Pull-request selection (build/ci-selection.py) no longer triggers editor extension builds (vscode-extension,vsix,visual-studio-extension), website visual/browser checks, or unrelated Python harness jobs on compiler-only changes, and runsgo2gson pull requests only whentools/go2gs/changes.cs2gs-apps-nightlycancels superseded branch dispatches (cancel-in-progresson non-mainrefs), accepts alegsworkflow_dispatchinput (gsharp-csharp,oahu,code-exploder, orall), caches the builtcs2gs/csharp-0.4prerequisites, and shares the builtmainand corpus outputs fromcsharp-migrateto thecsharp-validateshards instead of rebuilding them in every shard. -
A function literal with an inferred result checks a narrowed
returnvalue against a backwardgoto(issue #5603). Inlet f = () -> { var s string? = "a"; if s != nil { L: if n > 0 { return s }; n++; s = nil; goto L }; return "x" }, the result offwas inferred asstringfrom the narroweds. Thegotoremoves that narrowing, but the check did not apply to thereturnvalue, because the value converted to the result after the body, outside the narrowing. The program compiled, andf()returned nil as astring, which threwNullReferenceExceptionat a later dereference. The binder now records the use where thereturnvalue binds, and reportsGS0155at thereturnvalue when the inferred result needs the narrowing, as it does for a literal with a declared or delegate result. A result that anotherreturnmakes nullable, such asstring?, takes the value without the narrowing and is not changed. This applies to a literal in a local, a nested literal, an async literal, and a literal argument of a generic or source function whose result the binder infers from the body. The same decision now applies to a member that a type test narrows, such asholder.PetdeclaredAnimaland narrowed toDog. ADogorDog?result, inferred or declared, needs the narrowing and reportsGS0155at the value when a backwardgotoreplacesholder. Before, aDog?result compiled and threwInvalidCastException. AnAnimalresult reads the declared member, so it returns theCat, as C# does. A member that a nil guard narrows from an optional value, such asbox.Valuedeclaredint32?, is checked the same way: anint32result reportsGS0155when a backwardgotoreplacesboxwithBox(nil), where it compiled and threwInvalidOperationException, and anint32?result returns the stored nil. The natural result of a function literal at an imported overload (#5569) uses this decision too, for the narrowed reads of its ownreturnvalues. A narrowed value in a conditional,iforswitchbranch is covered by the next entry (#5613). -
A narrowed read in a branch of a conditional,
if,if letorswitchvalue, or in the right operand of??, is checked against a backwardgoto(issue #5613). Inif s != nil { L: if n > 0 { let t = n > 1 ? "t" : s; ... }; n++; s = nil; goto L }, the type oftwas inferred asstring, the common type of the branches. The branchsconverted to that type by identity, so the backwardgotocheck did not see the narrowed read. The program compiled, andtheld nil as astring. The same occurred forif n > 1 { "t" } else { s },switch n { case 5: "t" default: s },u ?? s, a nested branch, the trailing value of a branch block (also withdefer), andreturn n > 1 ? "t" : sin a function literal with an inferred result. The binder now captures the narrowing state of a narrowed branch value where the read binds, and decides the check when the common type is known, with the same rule aslet t = s(ConversionNeedsNarrowedSource). Agotothat removes the narrowing reportsGS0155at the narrowed read. An assignment in another branch (if n > 0 { s } else { s = nil; "x" }) or a backwardgotointo the branch does not hide the read. A branch that is a block yields its trailing read, also in parentheses, inchecked/unchecked, nested in a branch block, and as the right operand of??. A member that a type test or a nil guard narrows (holder.Pet,box.Value) is checked the same way, and the declared value is read when the common type takes it. A common type that takes the declared value, such asstring?inn > 1 ? U() : s, does not need the narrowing, and the program compiles as before. A branch that proves its own narrowing, such ass != nil ? s : "x"or the then-branch ofif let q = u && s != nil, does not depend on the outer narrowing either. Known limitation: the trailing value of a branch block withdeferorusingis checked against its own type, so a nullable common type does not prevent the report there (#5636). A narrowed read in a tuple element, an inferred type argument or a block value that is not a branch is covered by the next entry (#5635). -
A narrowed read that goes into a slot with no conversion is checked against a backward
goto(issue #5635). Inif s != nil { L: if n > 0 { let t = (s, 1); ... }; n++; s = nil; goto L }, the tuple element took the narrowed typestring, and no conversion to that type ran, so the backwardgotocheck did not see the read. The program compiled, andt.Item1held nil as astring. The same occurred for a deconstruction (let (a, b) = (s, 1)), a type argument that inference takes from the read (Id(s)forfunc Id[T](x T) T, and an imported generic method such asTask.FromResult(s)), an argument of a source function whose parameter has the read's type (F(s)forfunc F(x string), and a variadic element), and the trailing value of a block that is not a branch (let t = ({ n = n + 0; s }),({ ...; s }).Length, andreturn ({ ...; s })in a function literal with an inferred result). These values now use the decision oflet t = s(ConversionNeedsNarrowedSource) for the type that they take, with the narrowing state where the read binds, and agotothat removes the narrowing reportsGS0155at the read. A tuple literal that converts to a tuple type decides its elements for the target element types (let t (string?, int32) = (s, 1),yield (s, 1)intosequence[(string?, int32)]), and a typedlet, an assignment and an inferred result decide the trailing read of a block value for their own type, solet t string? = ({ ...; s }),t = ({ ...; s })and astring?inferred result compile as before. An explicit nullable type argument (Id[string?](s)), an imported slot that the signature declares nullable (T?, also aparams T?[]element) and a slot that the inferred type argument makes nullable (xs.Append(s)for a[]string?) do not need the narrowing. A call argument keeps the narrowing state where it binds, so a later argument that assigns the variable (F(s, ({ s = nil; 0 })), also for a method or constructor) does not hide the read; before, a method argument of this form compiled too. Known limitation: a block argument or operand is checked at the block's type, so a nullable consumer such asN(({ ...; s }))forfunc N(x string?)or({ ...; s }) == nilstill reportsGS0155after such agoto(#5653). -
The condition of an
ifstatement removes narrowing facts before its branches are bound (issue #5534, ADR-0208 row R18). A call, a getter with user code or an assignment in the condition runs before either branch, but the branches were bound with the facts from before it. A program that guarded a local that a closure assigns, then called a function or read a getter in anifcondition and used the local in the branch, compiled and could throwNullReferenceException; it now reportsGS0158. Read the value into aletbefore the guard, or test it again in the condition after the call (if Check(h) && x != nilorif Check(h) && x is C). Creating a closure no longer removes member-path facts, in a condition or in a statement: only a call of the closure does. The condition of anifnested in the then-branch of aniforif letdoes not remove facts for the sibling else-branch, and a property pattern after the call (Check(h) && x is {}) proves the fact again like a type test. A test whose pattern runs a getter or a call that can change the tested variable or member path (x is Dog { P: 1 }wherePsetsx = nil, orx is Read(h)) no longer narrows it, even without an earlier guard; such a program compiled and could throwNullReferenceException, and now reportsGS0158. Conditions of if-expressions,&&and||operands,whileandforheaders andif letbindings are not changed. -
A tag run pushes to nuget.org with trusted publishing, not with a stored API key (part of issue #5535, ADR-0218).
publish-nuget-compilerandpublish-nuget-sdkno longer read theNUGET_API_KEYrepository secret. Each job getsid-token: writeand runsNuGet/login@v1right before its push. The step exchanges a GitHub OIDC token for a nuget.org API key that is valid for one hour. "Re-run failed jobs" requests a new key, and--skip-duplicatekeeps the push safe to repeat. A manual push from the runbook still needs a nuget.org user API key. Known limitation: only a tag run can exercise the login, so the next release or prerelease tag is its first test. -
cs2gs gives a deconstruction target the treatment of a property read (issue #5561, follow-up to #5508). In a nullable-oblivious project, the null-taint analysis can widen a record's positional property to
T?, for exampleEntry.Itemafternew Entry(null, 0). A local that a deconstruction declares (var (item, _) = entry,(Node item, int id) = entry,foreach (var (item, id) in entries)) was dereferenced without!!(GS0159) and passed to a non-null parameter without!!(GS0154). A deconstruction into an existing local (Node n; (n, i) = entry;) stored theNode?element inton Node(GS0155). Each target now gets whatvar item = entry.Itemorn = entry.Itemgets: a declared local is asserted where C# reads it as non-null, a store into a target that stays non-null is bridged asn = nValue!!, and a target is widened toT?when the taint widens the element declaration itself, so the null that C# stores is stored. As forn = entry.Item!!, the bridge throws if the element is null. A local whose emitted storage is already nullable (G# infers it from the widened property) takes the element unchanged, a local whose emitted storage is not recorded (a pattern variable, #5605) keeps the unbridged store, and a user-defined conversion is bridged by its parameter, not by the target. A record from another project of the run is resolved through its source declaration. One resolution of a deconstruction target to itsDeconstructelement or positional property serves the read check, the store bridge and the taint. A deconstruction into an array element or indexer is covered by the next entry (#5595). -
cs2gs bridges a deconstruction into an array element or indexer as the plain element store (issue #5595, follow-up to #5561). In a nullable-oblivious project,
(arr[0], i) = entryand(list[0], i) = entrystored a widenedNode?element into[]NodeorList[Node]without a bridge (GS0155), where the plainarr[0] = entry.Itemis bridged (#2259). The deconstruction store bridge now asks the plain element store's query, so the store isarr[0] = arrValue!!, which throws if the element is null, asarr[0] = entry.Item!!does. An element that accepts null (an annotatedT?[]orList<T?>, an array local that the taint widens, oblivious container storage, a promoted indexer such as another project's[AllowNull]indexer, or an oblivious indexer or array element of a prebuilt library, also in a jagged array, a slice, or through avaralias or a loop variable that G# infers, which gsc imports as a platform type) takes the element unchanged in both forms. Behavior fix in the plain form: a plain store of a nullable value into such a slot of a prebuilt oblivious library (h[0] = entry.Item,h.Nodes[0] = entry.Item,h.Grid[0][0] = entry.Item, also through avaralias) is no longer emitted with!!. Before, it threw aNullReferenceExceptionwhere C# stores the null; now the null is stored, as in C#. The element of such a library'sT[]that the consumer substitutes, of an annotated array, and of an explicitly typed local stays non-null and keeps the bridge, and a value that a user-defined conversion converts keeps the bridge of the operator's input. A deconstruction into an element of an array that is not a declaration (a cast, for example) keeps the unbridged store, as before. -
cs2gs stores a maybe-null value into another project's
[AllowNull]slot without!!(issue #5577, follow-up to #5574). A project of the run emits an[AllowNull]property, field or parameter asT?(#3694). A consumer that binds it through that project's emitted reference assembly did not see the attribute, soh.Stored = mwithm Node?becameh.Stored = m!!, which threw where C# stores the null. cs2gs now reads the attribute on the source declaration in the run, also for a source file linked into several projects. The null-argument rule of #5574 uses the same query, so a parameter forwarded into such a slot is widened and not pinned. An indexer key and an extension method parameter are read the same way. A slot without[AllowNull]keeps its bridge, and so does a slot that the producer emits non-null: aparamscarrier, whose attribute admits a null array but not a null element (also in one project, where an expanded maybe-null argument previously had no bridge), and a slot typed by a type parameter that is not constrained to a class. -
cs2gs bridges a maybe-null store into an
[AllowNull]slot of the same project that is typed by an unconstrained type parameter (issue #5601, follow-up to #5577). cs2gs emits[AllowNull] public T Value;asvar Value T, because the[AllowNull]widening (#3694) applies only to a reference type. SoBox[Node].Valuedoes not acceptnil. In the same project,b.Value = mwithm Node?was emitted without a bridge (gsc GS0155), and a readb.Value.Namegot a redundant!!(GS0536): the promotion query read the substituted typeNodeofBox<Node>.Valueand treated the slot as widened. The query now reads the original declaration, as the translation of the declaration does and as the query for another project's slot (#5577) does. The store isb.Value = m!!, which throws if the value is null, as for any maybe-null value stored into a non-null slot. A slot of a type parameter constrained to a class is still emittedT?and takes the null without a bridge. -
cs2gs bridges a widened local stored into an explicitly typed local (issue #5602, follow-up to #5561). Fixes #5602. In a nullable-oblivious project, the null-taint analysis can widen
Entry.ItemtoNode?, so G# infersvar item = entry.Itemandvar (item, _) = entryasNode?.object o = itemwas emitted aslet o object = itemwithout a bridge (gsc GS0156), and so was the assignmento = item, because the store bridge asked a narrower question about a local value than the dereference and argument rules. The declaration also did not bridge a promoted value into its type clause. Each store is nowitem!!, aso = entry.Item!!is. C# throwsNullReferenceExceptionat the latero.ToString()when the item is null; G# throws it at the store. One query now decides whether a local holds a value that G# typesT?, for the dereference, value and store rules. A local whose declaration emitted non-null storage holds a non-null value, so the later read iso.ToString(), not the redundanto!!.ToString()(GS0536). A store into an existing local asks the same query about the local: a local that holds aT?value hasT?storage. The query also reads the arms of a composed initializer, sovar n = entry.Item ?? entry.ItemholdsNode?:n = itemtakes the null, andn.ToString()is nown!!.ToString()(it was GS0159). Behavior fix:Node n = entry.Item; n = entry.Item;(also withvar n) was emitted asn = entry.Item!!, which threw where C# stores the null; the store now takes the null. A user-defined conversion still bridges the input of its operator (b = item!!forimplicit operator Box(Node node), which was GS0155). A declaration without a type clause (Node n = entry.Item, which G# infers asNode?) and a typed local that the code null-tests (object? o) take the null without a bridge, as before. -
Reading or writing a static member of a type with a non-literal
sharedfield initializer removes narrowing facts (issue #5520, ADR-0208 rows R11 and R15, completes #5504). A type whosesharedfields have initializers but noinitblock isbeforefieldinit: its initializers run at the first access to a static field, static property or static event of the type, and can run any user code. When one of these initializers is not a literal, such an access now counts as a call: it removes member-path facts, facts behind by-reference parameters, facts on mutable globals and facts on closure-assigned locals. An initializer counts as a literal when it isnilinto a reference orT?field type, or a literal token, possibly in parentheses or under a unary operator that is predefined for it (5,-1,(2),"x"), of a built-in field type such asint32,stringorobject; a literal of another field type, ornilinto a value type, can call a user-defined conversion, a unary operator that is not predefined (-"x") calls a user-defined or extension operator, and a call, a name or a construction is not a literal. A program that guarded such a fact and then accessed such a static member before it used the fact now reportsGS0158where it previously compiled and could throwNullReferenceException; copy the guarded value into a local, or test again after the access. A constant, a construction of the type, an instance member, a type whosesharedinitializers are all literals and a plain local or parameter that no closure assigns keep their facts. cs2gs mirrors the rule: a C#outorrefparameter, or a closure-assigned local, that is read after a static field, property or event access of a type of the same project with a static constructor or a non-literal static initializer gets!!, so the translated code compiles. -
cs2gs widens a parameter that a call passes
nullonly when every read of it can take the null (issue #5574, regression from #5525). The #5508 rule widened a parameter that a call passesnull, and the declarations it forwards to, but a read that hands the value to a slot that stays non-null (a local function or lambda result, a virtual or interface member, a library or generic method, a stored field later passed on) was bridged with a!!that threw on the null the C# passes on: the self-migratedTypeSymbol.ContainsTypeParameter(nil)threw instead of returningfalse. Each read of a declaration the rule would widen is now classified: a dereference, a comparison, a null test, a read that a null test guards, or a hand-off to a slot that is nullable (a nullable expandedparamselement included) or widens too takes the null, and any other read (for example avarpattern capture, a deconstruction, a user-defined operator whose operand is non-null, or a generic slot such as the receiver of a generic extension method, which the translation asserts with!!) keeps the declaration, and everything that reaches it, at its non-null type, as before #5525. Reads are collected in a partial method's implementing part and through nested deconstructions, property patterns and another project's emitted record. The run decides this once, as a fixed point, so the order of files and declarations cannot change it. A declaration inGsharp.Runtime.Values,Gsharp.Runtime.ChannelsorGsharp.Extensionsis not widened either, because a G# call can bind to the copy the SDK ships (slice[string].FromArray(nil)was GS0155); the call keepsdefault([]string). -
cs2gs follows imported oblivious containers through the whole program (issue #5541, follow-up to #5537). One nested-position flow analysis now decides which storage keeps nullable element positions (
[]string?,List[string?]) and which reads need!!. It follows a value through assignments, initializers, arguments, returns,foreach(including loop bindings with a non-identity conversion that state an explicit range type), the arms of a conditional, switch or??expression, chained element and member reads (nested[0][0], jagged arrays,kv.Value,d.Keys), generic call results (Id(lines)[0],lines.First()), awaited results through the awaiter (ConfigureAwait(false)included), lambda parameters (l => l.Lengthis(l string?) -> l!!.Length, also for a constructor call that takes its positions from the storage that receives it), constructions that convert the storage (List[string?](lines), also target-typednew(lines)), explicit type arguments (Id[[]string?](lines)), expandedparamsarguments (a nil element passes through) and locals that infer a platform container. The implicitvalueparameter of a property or indexersetorinitaccessor shares the property's positions, while an indexer's key parameters map to their own parameter declarations. An argument for a type argument that the call binds toT?, and a value that a lambda returns for such a result, pass a nil element through. A nullable value gets!!only when it goes into a slot that is known to stay non-null: a declared parameter, local, field, property, return or iterator element that the run does not widen, a type parameter whose constraint rejectsT?, or a dereference. Any other slot, such as a type argument that a construction, call or lambda binds, takes the value as it is, so an unsupported shape is a compile error and never a!!that throws where C# stores nil. A construction or array literal states the element of the value it holds and of the storage it goes into, anasyncmethod's task result included (new[] { l }is[]string?{l},new[,] { { l } }is[1, 1]string?{l},new List<string>()returned from anasync Task<List<string>>method that returns such a container isList[string?]()), and anasynclambda returns its nullable element as it is. An array literal or collection expression states the whole position subtree of its element (new[] { lines }is[][]string?{lines},List<string[]> w = [lines]isList[[]string?], and a promoted collection expression coerces its elements against its promoted element contract). An indexer's key and value slots are bound by the receiver's storage as a method's parameters are, also in an object initializer ([key] = value) and through?[/?.(an unchangedDictionary<string, int>keepstable[lines[0]!!]), and a value returned from a property or indexer getter is stored in the property. A tuple element is asserted only when its target is declared:(string a, string b) = (lines[0], lines[1])and((string a, string b), int n) = ((lines[0], lines[1]), 3)keep!!, andvar (a, b) = ...takes a nil element as it is. A tuple literal (including one with eight or more elements), a conditional access (a?.M()) and an array slice (x[..]) carry the positions of what they hold: a tuple local states its elements (let t (a string?, b string?)) and its dereference asserts them (t.b!!.Length),var (x, n) = Pair()and nested deconstructions (var ((a, b), n) = ...) take each element's top-level and nested positions,a?.GetRange(0, 1)keeps the list's element, and a slice keeps the array's element and is itself non-null. A local that a G# nil test narrows passes a non-null value to a generic call. A type parameter whose constraint rejects aT?argument, such aswhere T : class, keeps its type argument, and the argument keeps its!!. Overrides, interface implementations (also one that a base class supplies), the members they implement, indexers andasyncmethods that return such a container now state one signature with the nullable element, when this run declares every member of the group with the same type. Enabled storage that is stored as a whole into such storage, such aslines = other,foreach (var row in rows) { lines = row; }or areturn otherfrom anasyncmethod, states the same element (including the collection of theforeachand its nested literals), so the output no longer depends on the uncheckedC[T]toC[T?]conversion (#4321). Aforeachvariable that a nil test narrows gets no!!, so the output has no GS0536 warning there, anda ?? bgets no!!whenbis a platform-typed read. Known limitation: a member that overrides or implements a member declared in metadata keeps the metadata signature, and still reports GS0155 when it returns an oblivious container. -
A tag run publishes each destination in its own job, and the GitHub release becomes public last (issue #5530, ADR-0218). The single
publishjob is replaced bypublish-verify,publish-github-release,publish-nuget-compiler,publish-nuget-sdk,publish-vscode-marketplace,publish-visual-studio-marketplaceandpublish-finalize, so "Re-run failed jobs" repeats only the destination that failed: NuGet pushes skip versions that exist, and a marketplace job succeeds when its version is already published. The sixGsharp.NET.Sdk.Compiler.<rid>packages go first, then the SDK and tools, then both extensions. The release is a draft until every destination has the version, and its body names a platform whose ReadyToRun smoke did not pass (the smoke no longer blocks a tag).verifyfails a run before the first push when the tag and the package version disagree. A tag with a SemVer suffix (v0.5.300-rc1) is a prerelease: it publishes to NuGet, GitHub (marked as a prerelease) and the VS Code Marketplace (as a pre-release), and never to the Visual Studio Marketplace. Known limitation: the new path has run only in tests until the first prerelease tag. -
Writing an imported property or reading or writing an imported indexer removes narrowing facts unless the accessor is on a short stable list (issue #5532, ADR-0208 row R17, follows #5231). An imported setter or indexer can run user code (an
ObservableCollection<T>indexer set raisesCollectionChanged; aDictionary<K,V>indexer callsGetHashCodeof the key), so it now counts as a call: it removes member-path facts, facts behind by-reference parameters, facts on mutable globals and facts on closure-assigned locals. A program that guarded such a local and then used one of these accessors before using the fact now reportsGS0158where it previously compiled and could throwNullReferenceException. These accessors keep the facts because they run no user code: theList<T>indexer andList<T>.Capacityset, theSpan<T>indexer, theReadOnlySpan<T>indexer get, thestringindexer get, theStringBuilderindexer andStringBuilder.Lengthset. An index read of aList[T]over a type parameter is the exception: it goes through the non-genericIListinterface, so it removes the facts. -
nilinto any non-nullable reference slot is nowGS0155(GS0154for an argument), including G#-declared classes, interfaces and type parameters (issue #4316).var b Box = Box(); b = nilandfunc A4() Box -> nilused to compile, while the same shapes withstringor an imported class were errors. ABox, an interface, a[T class]parameter and a parameter with a dependent reference bound acceptednil; the language now has one rule for every slot kind (assignment, initializer,return, argument, field, element, tuple element, channel send,yield, and generic instantiations such asList[Box].Add(nil)orGen[Box](nil)). Only a?slot (Box?,T?) and an obliviousT!slot takenil. This is a behaviour change: code that relied on the old leniency now fails to compile. Fix it with an explicit?on the slot (var next Node? = nil,func Find() Box? -> nil), or store a real value.b == nilandb != nilstay legal. A default argumentb Box = nilwas already refused (GS0265). Two joins follow from the rule. The join of anilarm and a non-nullable arm (c ? Box() : nil, aniforswitchexpression) is nowT?for reference types too, sovar f Box? = c ? Box() : nilcompiles in a field, a parenthesized initializer, a lambda body and a generic[T class]function without a target type;string?and imported-class joins that wereGS0155before are accepted for the same reason, andx ?? nilon a nullable reference isx. Tuple arms join element by element in the same way, solet t = c ? (Box(), 1) : (nil, 2)is(Box?, int32), and an all-nilcolumn in an inner tuple conditional or switch staysnilso an outer arm can resolve it; thestringform was an error before. A tuple whose element is a barenilnow converts arm by arm, so a nested conditional, aswitch, a??expression or a block that yields one emits instead of failing withGS9998. Anif,switch,??or block that runs code and then yieldsnilinto a nullable value-type or type-parameter slot (for example a tuple element of typeint32?) now runs that code; before, the whole expression was replaced bydefault(T?). A tuple elementnilpassed through a generic call (List[(Box, int32)].Add((nil, 1))) isGS0155for a class and forstring; it compiled for both before. Measured on this repository and the pinned Oahu corpus: the repository's own source had five sites, now fixed in source (aTypeSymbol?for anif/elsearm that yieldsnil, a(TypeSymbol?, int32)switch arm, a nullableDelegateTypeSymboldeclaration for compiler-synthesized delegates, an unreachablereturn nilreplaced by athrow, and three test-fixture stubs). Translated C# that passesnull!to a non-annotated class parameter (OahuId3TagintoFrame, andSynthesizedRefDelegateCacheintoDelegateTypeSymbolwhoseDeclarationis read through a switch expression into an explicitly nullableSyntaxNode?local) is handled by cs2gs, which widens that parameter (issues #5508 and #5574), an unreachablenullliteral (such asreturn null;after a[DoesNotReturn]helper, where Roslyn's flow state on the unsuppressed literal isNotNull) in a return, assignment, argument or tuple-element slot that stays non-nullable is emitted asdefault(T), a suppressedreturn null!;or=> null!;into a return slot that stays non-nullable (Issue2523Fixtures) is emitted asdefault(T), and a tuple-elementnullinto a non-nullable reference element of a substituted generic or SDK parameter (Assert.Equal((null, false), ChannelOps.Receive2(...))) is emitted asdefault(T)as scalar arguments already were (#3682), while reachable unsuppressednulland argumentnull!in hand-authored code staynil. -
cs2gs widens a parameter that a call passes
nullornull!(issue #5508). In a nullable-enabled project,base(header, null!)intoFrame(Header header, Frame parent)is the author saying that null goes in that slot. cs2gs now emitsparent Frame?for that parameter, and for each parameter, field or property that receives its value unchanged (Parent = parent,: base(h, p)), so the translated program stays valid when gsc rejectsnilat a non-nullable class slot (#4316). A virtual, abstract, overriding or interface-implementing member keeps its declared type, and a forwardedparent!is not treated as a forward. A local that a deconstruction declares from a widened element ((Node item, int id) = entryfor a widenedEntry.Item) is asserted with!!where C# reads it as non-null. The evidence is gathered across every project of the run. In an<auto-generated/>file, where the C# compiler reports no nullable diagnostics, anullliteral that still lands in a return, assignment or argument slot that stays non-nullable (for examplereturn null;in an override whose base signature is fixed) is now writtendefault(T), which is the same null and which gsc accepts. Hand-authored code keepsnilthere, so gsc still rejects it. -
A block-bodied function literal whose result does not convert to a delegate overload selects another overload (issue #5569). With
M(Func<long> f, int x)andM(object o, long x),Calls.M(() -> { return "s" }, 1)reportedGS0155(stringtoint64) at thereturnvalue, and C# selects theobjectoverload. When another candidate takes the literal's natural type at that position, the binder now binds the literal body once and converts itsreturnvalues afterwards. A literal that does not convert keeps its natural type, so only the other candidate applies. This includes a target-typed conditional,switch,ifor block return value, which binds again with its natural type when it does not convert, and an explicit parameter type or parameter count that the delegate does not accept. A destructured parameter whose written element types the delegate does not accept, and an interpolatedreturnvalue that is formattable only for anIFormattabledelegate result, use the same rule, and the other candidate can also take the literal as an element of a trailingparamsarray. Eachreturnvalue still converts to the delegate where it binds, as at a single candidate, so a narrowing that a backwardgotoremoves reportsGS0155there, unless the literal keeps a natural type whose result (such asstring?) takes the value without the narrowing. A literal that keeps its natural type keeps its written parameter types, so(x int64) -> "s"atM(Func<int, long> f, int x)andM(object o, long x)passes aFunc<long, string>, not aFunc<int, string>adapter. An open generic candidateM<T>(T value, long x)and a constructor of a generic type with a same-compilation type argument use the same rule. A literal body binds once and such a return value at most twice, so nested literals compile in linear time. A return value that contains a function literal keeps the target bind. This holds for by-value andindelegate parameters of imported methods, constructors, reduced extensions and generic receivers. A call with only delegate candidates, or a call where no candidate applies, still reports theGS0155at thereturnvalue. -
A function literal at an imported
indelegate parameter selects that overload (issue #5543). WithIn(in Func<long> f, int x)andIn(object o, long x),Calls.In(() -> 1, 1)reportedGS0160(ambiguous call), and C# selects the delegate overload. A function literal is a plain value, so it now binds to the pointee of aninorref readonlydelegate parameter, as it does for a by-value delegate parameter. This applies to imported static and instance methods, constructors and reduced extension calls, and also lets an untyped lambda such as(y) -> y + 1infer its parameter types from such a slot. A function value still needs a delegate that it can keep (#5536), an explicit address&fkeeps its exact storage, and a literal at arefdelegate parameter is unchanged. -
A source class converts again to an imported interface over a tuple whose elements differ only by
?(issue #5544, regression from #5388). A class that implementsIEqualityComparer[(Name string, Scope object)]converts toIEqualityComparer[(string?, object?)], for example as the comparer argument ofDictionary[(string?, object?), bool](...). The binder accepted this conversion, but emission reportedGS9998. The nominal reference proof now accepts two types that are one CLR type when reference annotations are removed, as the binder does. A tuple element that is an optional value type, such asint32?forint32, is a different CLR type and still reportsGS0155. -
cs2gs asserts the awaited value, and a
varlocal that holds a maybe-null call (issues #5526 and #5527, follow-ups to #5516).await callof aTask<T?>orValueTask<T?>written into a non-null declaration printedawait call!!, which asserts the task and left theT?result in place (GS0155). It now prints(await call)!!, and in a file with annotations but no warnings cs2gs reads the?on the task's type argument, as it does for a plain call. Avarlocal whose initializer is nullable by declaration isT?in G#; without flow analysis a read of it that feeds a non-null sink now gets!!, as it does under full#nullable enable. A nullable sink, avarlocal with a non-null initializer and a generic argument that G# infers are unchanged. -
Reading an imported property removes narrowing facts unless the getter is on a short stable list (issue #5231, ADR-0208 row R16). An imported getter can run user code (
Lazy<T>.Valueruns its factory, an interface property runs the implementation), so a read now counts as a call, as a source getter does: it removes member-path facts, facts behind by-reference parameters, facts on mutable globals and facts on closure-assigned locals. A program that guarded arefparameter or a closure-assigned local and then read such a getter before using the fact now reportsGS0158where it previously compiled and could throwNullReferenceException; read the property before the guard, or test again after it. These getters keep the facts because they run no user code:string.Length,StringBuilder.Length,Array.Length,Span<T>andReadOnlySpan<T>LengthandIsEmpty,CountofList<T>,Dictionary<K,V>andHashSet<T>,KeyValuePair<K,V>.KeyandValue, andNullable<T>.HasValue. A read through an interface or a static getter removes the facts, and so does an imported property in a property pattern (lazy is { Value: 1 }). Imported setters and indexers follow the same rule since issue #5532 (the entry above). -
cs2gs asserts a maybe-null call written into a non-null declaration when C# runs no flow analysis (issue #5516, follow-up to #5254). In a file with
#nullable enable annotationsand warnings off, which is the shape of a source-generated file, Roslyn gives a call no flow state and drops the?from its type, so a call to a method that returnsT?was written into a parameter, local, field, property, argument, return value, indexer key, object-initializer member or collection-initializer element that stays non-null without!!, and gsc reported GS0155. cs2gs now reads the declared return type of the method, as it already reads the declared type of a field, property, local or parameter. A[return: NotNullIfNotNull]result follows its argument. The write gets!!, the same as in a file with full#nullable enable. A declaration that cs2gs widens toT?, avarlocal that G# infers from the call, an unconstrained generic parameter that G# infers, and a parameter that accepts null keep theT?value. Known limitations: anawaitof aTask<T?>call keeps the existingawait call!!shape in both nullable modes, which asserts the task instead of the result (#5526), and avarlocal assigned a maybe-null call and then read as a non-null argument is not asserted in a file without flow analysis (#5527). -
A function value converts only when it keeps its delegate (issue #5536, ADR-0108). A function value or method group converts to another function or delegate type when each parameter and the result convert by a reference conversion, as in C#. The compiler now rejects a numeric result widening or a channel reader projection with
GS0155(GS0154for a call argument) where it previously wrote invalid IL, for example() -> int32to() -> int64. A function literal still converts its result value. A parameter contravariant conversion such as(Animal) -> voidto(Dog) -> voidnow compiles where it reportedGS9998. A covariant or contravariant conversion to another arrow type now gives the same delegate instance, soObject.ReferenceEqualsis true and a nil value stays nil. An explicit downcast such ascast[() -> Dog](f)is a checked reference conversion that throwsInvalidCastExceptionwhen the delegate is not of the target type. Overload resolution, also for imported overloads, skips a candidate when a function value argument would need a new body. -
cs2gs asserts a closure-assigned local that a call separates from its null check (issues #5513 and #5514, after #5464). gsc removes the narrowing of a local that a closure assigns at every node that runs source code (ADR-0208 row R15), but C# flow analysis keeps it. cs2gs now treats such a local as not narrowed once a call, object creation, loop, computed property, event subscription or user-defined operator lies between the null check and the read, so the read gets
!!and the translated code compiles. Locals that no closure assigns are unchanged. -
cs2gs forgives reads of the declarations it widens (issue #5254, completes #5217). One rule now covers a parameter, an
outorrefparameter and theout varlocals declared for it. cs2gs widens such a declaration toT?so that a null write binds. A read where the C# flow state is non-null now gets!!, and the declaration stays widened. In a file with nullable annotations but no warnings, Roslyn runs no flow analysis. There the declaration is the contract, so a read that feeds a non-null sink is forgiven. A sink that accepts null keeps theT?value. A source-generatedJsonSerializerContextno longer fails with GS0155 and GS0158. -
Reading or writing a static member of a type with a
shared { init { ... } }block removes narrowing facts (issue #5504, ADR-0208 rows R11 and R15). The first access to a static field, a static property or a static event of such a type runs its static initializer, which can assign a mutable global or run a closure that escaped. The access now counts as running user code, as a call does. The type that counts is the one that declares the member, so an inherited member triggers the base type. A program that read a closure-assigned local or a mutable global, narrowed before such an access, now reportsGS0158where it previously compiled and could throwNullReferenceException. A constant, an enum member and a type without aninitblock keep their facts. Issue #5520 extends the rule to thesharedfield initializers of a type without aninitblock. -
Constructing a class with a
shared { init { ... } }block removes narrowing facts (issue #5483, ADR-0208 rows R11 and R15). The static initializer runs at the first construction of the class, or of a derived class, and can run any user code. Construction now counts as running user code for it, as it does for field initializers and constructors. A program that read a closure-assigned local or a mutable global, narrowed before such a construction, now reportsGS0158where it previously compiled and could throwNullReferenceException. A value-type literal and a type with onlysharedfield initializers do not run user code at construction and keep their facts. -
gsgen generated parts follow the declared shape of a class that is abstract only by inheritance (issues #5252 and #5253, part of #5217). A class that inherits unimplemented abstract members is still
abstractin the stub, so generators observeIsAbstract(ADR-0195). Its generated.g.gsparts no longer stateabstract(which made the user's class uninstantiable, GS0386), and their members areopenonly when you declared the classopen(a plainoverrideis legal otherwise; GS0421). A class declaredabstractkeepsabstracton its parts. A System.Text.JsonJsonSerializerContextin a G# project no longer reports GS0386 or GS0421; GS0155 and GS0158 from #5254 remain. -
Source classes retain symbolic arguments when upcasting to imported bases (issue #5388). An imported generic base over a source struct now accepts its derived class. Transitive imported bases, including non-generic intermediate classes, retain their generic owner arguments. The compiler checks source type arguments and rejects incompatible base instantiations, including a different nullable value-type argument such as
List[int32?]forList[int32]. It checks every inherited instantiation of a generic interface, so a class that inheritsITag<int>andITag<string>converts to both. Source classes inherit only nominal upcasts, not conversions that create a different reference such as channel reader or writer projections. Native channel aliases and named CLR channel types use the same nominal checks. The shared proof also preserves source base classes, inherited source/CLR interfaces, symbolic arrays, sequence covariance and object upcasts in emission and narrowing joins. Asequence[T]orasync sequence[T]over a source element now converts implicitly toobject, and a slice converts to a covariantsequence[U]. Generic variance accepts only argument conversions that keep the same reference, so a nested channel getter projection, numeric function result or function-to-delegate conversion is rejected instead of emitting invalid IL (issue #5518). Variance still accepts equal-rank rectangular array covariance and a fixed array viewed as a slice. An arrow function type uses the variance of its naturalFunc/Action, sosequence[() -> Dog]converts tosequence[() -> Animal],sequence[(Animal) -> void]tosequence[(Dog) -> void], andsequence[() -> Item]tosequence[Func[object]]. A rectangular array of channels no longer converts to a rectangular array of channel readers. Each nested argument pair is proven once, so deeply nested covariant types no longer take exponential time to bind. Binding checks implemented CLR interface owners with that same proof, diagnosing mismatches instead of emitting invalid IL (issue #5511). -
A call removes the narrowing of a local that a closure assigns (issue #5237, ADR-0208 row R15). A declared function can run a closure that escaped, for example one stored in a field. After any call that can run user code, a plain local or parameter that a closure of the same function assigns is no longer narrowed. A program that read such a local after the call now reports
GS0158orGS0154instead of throwingNullReferenceException. A by-reference parameter and a local that no other closure assigns keep their narrowing. The loop form of the same shape is rejected too. Known limitation (accepted trade-off, #5502): a block or cleanup whose later assignment restores a fact after an earlier call, such asfinally { { Touch(); x = "abc" } }or{ Wrapper(h); action = callback }on a closure-assigned local, now reportsGS0158although the program is correct; the fix is the evaluation-order flow state of ADR-0208 slice 2. No diagnostic changes insrc/Core, Core.Tests, gsc or the pinned Oahu inputs. -
A callable alias follows the storage it names (issue #5482, ADR-0208 row R15). After a call that can run an escaped closure, a
refalias of a callable variable is no longer assumed to hold the external callable when a closure replaces the variable it names. A program that guarded a closure-assigned local, then invoked the alias and read the local, now reportsGS0158instead of throwingNullReferenceException. Known cost: arefalias of a callable local loses its classification at any call when some closure of the function assigns a name, so a valid program that relied on it with a closure-assigned local can reportGS0158. -
Source interfaces can write inherited CLR properties (issue #5389). Simple and compound assignments call imported setters, including in default bodies. Generic property access retains source type arguments and imported nullability, even after unrelated imported bases. Source methods still hide inherited properties; init-only, read-only, and inaccessible accessors still report errors. Write-only properties allow simple writes but reject reads and compound writes. Bare writes do not change enclosing shared fields.
-
Long named tuples retain CLR metadata padding (issue #5390). Exports now include unnamed positions for each synthesized
Restnode. C# consumers can read eight-element tuple returns. Imported names after long tuples retain their positions. -
Reference-closure advisories do not fail ordinary warnings-as-errors builds (issue #5493, ADR-0217). Global
/warnaserrorand SDKTreatWarningsAsErrorsretainGS9100as a warning. Explicit diagnostic promotion still rejects incomplete reference closure. Unavailable types and members still fail when used; other warnings retain global promotion. -
Global scopes are no longer chained;
BoundGlobalScope.GetCumulativeImportsis removed (issue #5312, ADR-0212 slice S8, step 1). No caller passed a non-nilprevious, and the REPL chains through emitted metadata.Binder.BindGlobalScopeand theBoundGlobalScopeconstructors keep thepreviousparameter and now throwArgumentExceptionfor a non-nil value.BoundGlobalScope.Importsis the whole import list of the compilation, so use it whereGetCumulativeImports()was called. The body-binding passes no longer walk a chain. No change togscoutput. -
cs2gs preserves included sibling projects (issue #5495). Excluding one project no longer hides an included sibling's generated project from repository inventory validation. Missing included projects and unexpected output still fail validation.
-
Source-interface receivers can subscribe to inherited CLR events (issue #5391). Qualified
+=and-=operations now call the inherited event accessors, including inside default instance bodies. Generic handlers retain source and type-parameter arguments. Unsupported bare inherited event names still report errors instead of changing enclosing delegates. -
SDK builds supply metadata dependencies (issue #5493). The compiler now receives resolved loose dependencies and NuGet runtime assemblies after selected compile references. Dependency-set changes invalidate incremental compilation even without newer input files. Reference-assembly precedence and
GS9100warning policy remain unchanged. -
Generic channel readers retain source element types (issue #5485). Inferred
out varlocals, method returns, and channel handle members (chan[T],in chan[T],out chan[T]) now preserve source-defined, nested-generic, tuple-named, and nullable-value elements throughChannelTypeSymbol.MakeClrType,MemberLookup.GetProjectionReceiverImportedType, andImportedMemberRefFactory.TryNormalizeToSymbolicContainerwith explicit runtime references. -
SemanticModel.LookupMemberslists inherited imported members, default interface methods and built-in members (#5441, ADR-0212). The query now answers the public instance members of an imported base class of a source class (objectwhen it has none), the members an imported interface inherits from its base interfaces, the default methods of the interfaces a class implements, and the built-in members of a slice, array, map, channel or sequence over a source element type. Member completion and hover offer them. The differential test against the binder no longer has a list of known gaps. No change togscoutput. -
SemanticModel.LookupMemberslists extension members (#5440, ADR-0212 question 12). After the members of the type, the query answers the extension functions declared in source and the extension methods of the imported namespaces whose receiver can take the type, by the rules a call uses. Member completion now offers them on a value receiver and never on a type name, and the hover overload count of a member counts extensions with extensions only. A call through an extension is still outsideGetMemberGroup. No change togscoutput. -
Channel member references retain symbolic elements (issue #5481).
ReaderandWritergetters now preserve source-defined and generic element types in their inherited CLR owner. Shared member-owner recovery also retains reordered generic base arguments. -
Generic interface bodies retain their type-parameter scope (issue #5477). Default methods can access source generic shared fields such as
Storage[T].Events. Method type parameters still shadow interface type parameters. -
GSharp.Coreno longer grantsInternalsVisibleToto the language server (issue #5311, ADR-0212 slice S7a). The server reaches the compiler through public queries only for everything exceptCompilation.GlobalScopeandCompilation.BoundProgram, which remain on the binding reference gate's allowance list. The server keeps its own path-identity rule and its own check for the parser's synthesized tokens. No change togscoutput or to the public API. -
SemanticModel.GetSpeculativeTypeInforeplacesBinder.TryInferExpressionType(issue #5308).GetSpeculativeTypeInfo(position, expression)binds an expression as if it stood atposition, with the locals of the scope query, the file's imports, and the compilation's nullability mode, and answers its type (TypeInfo.Noneon failure,voidor error). Flow narrowing in force atpositionis excluded from the contract (ADR-0212 Q15).Binder.TryInferExpressionTypeis removed from the public surface. A local now shadows a same-named field in the speculative bind, and the locals of top-level statements, constructors, accessors anddeinitbodies are in scope. No change togscoutput. -
Member queries in the semantic model (#5307, ADR-0212 slice S4).
SemanticModel.LookupMembers(position, type, name)returns the members of a type that a member access can name, andSemanticModel.GetMemberGroup(node)returns the candidates that overload resolution considered for a call. Imported members answer as symbols with types read through the nullability readers. Member completion, the hover member fallback, and Go to Definition on imported members now use these queries, andImportedClrMemberResolveris removed. Signature help lists one signature for each candidate, including imported overloads, and the hover overload count of a call is the size of its group. Completion no longer lists private or protected members from outside their type. -
GetEnclosingSymbolanswers the empty part of a nested partial type (issue #5455). A position inside a later part of a nestedpartialtype that has no member now answers the merged type, not the outer type. The merged declaration keeps the extent of every part for the lookup. -
Narrowing treats a closure's own locals as private (issue #5456). A local that a closure declares and only that closure assigns is no longer in the closure-assigned set. An unknown callable no longer removes its narrowing. A write from a nested closure, or to a variable the closure does not declare, still counts. No current diagnostic or emitted output changes in
src/Core, Core.Tests, gsc or the pinned Oahu inputs. -
Scope queries answer the rare declaration shapes (issue #5340).
LookupSymbolsandGetEnclosingSymbolnow answer field initializers (thesharedmembers of the type),deinitbodies (the destructor function andthis), every part of a nested partial type, the implicitctxof ascope, and an instance member of a base class that asharedmember of a derived class shares a name with (the instance member, as in the binder).GetSymbolInfonames the type of an interfacesharedfield or constant. The global names are listed in source order across kinds. -
Nightly test oracles use the validation runner (issue #5443). Each migration shard captures its selected C# test names locally. Different hosted targeting-pack inventories no longer cause false extra theory rows. Name and duplicate-count comparisons remain unchanged.
-
Go to implementation reports each implementer in its own file (issue #5329).
textDocument/implementationnow returns every implementing type under the URI of the file that declares it, not the URI of the requested document. -
Incremental reuse re-points enum and delegate declarations (issue #5324). A body-only edit that shifts text now updates the declaration syntax of enums, nested enums, and delegates, including constructed delegates and enums. Go-to-definition on an enum no longer reads the previous tree.
-
Imported record projections use their declaring constructors (issue #5435). Structural spreads, casts, and implicit projections no longer select source-emitted constructors for imported records. They retain the selected open constructor identity, constructed owner, optional defaults, and single evaluation.
-
Imported record expression trees defer projection effects (issue #5437). Generated capture blocks now retain initializer receiver aliases. Source construction, getters, constructors, and setters run once per invocation, not during tree construction.
-
Failed compiler emissions remove newly created outputs (issue #5451). Exceptions no longer leave newly created implementation, reference, Portable PDB, or documentation files. Existing output overwrite behavior and diagnostic-failure cleanup remain unchanged.
-
Imported data members keep derived name hiding (issue #5436). Member reads, writes, and property patterns now select the nearest eligible field or property before imported aggregate tables flatten inheritance. A derived property no longer reads an inherited same-name field. Base-typed access keeps the base member.
-
Generic map expression-tree parameters (#5430):
map[K,V]parameters now use the canonicalDictionary[K,V]type token instead of reportingGS9998. Map signatures and tokens retain generic owners, nested arguments, and nullable value types. Map literals inside expression-tree lambdas still reportGS0473.
The entries below record changes since v0.5.212. The earlier release section retains its original feature boundary.
-
More narrowing facts survive an
if, a bare block and a type test (ADR-0208, issues #5130 and #5206, part of #2189). The binder now joins the states at the end of the branches of anifand lifts what every path that falls through proves. These programs are accepted now and were rejected withGS0158orGS0159:if s != nil { ... } else { return }followed by a read ofs; sibling refinements such asif c { if x !is Dog { return } } else { if x !is Cat { return } }, which leavexat its declared non-null type; a guard inside a bare block{ if s == nil { return } }; a member path proven byif b.Pet is Dog { } else { return }; and a guard on a member path written as a predicate,if string.IsNullOrEmpty(b.Name) { return }. Anelse ifchain joins all its branches at once. When the incoming types do not convert to each other, the join keeps the declared non-null type, as forif settings is IInit init { ... }on aT?whoseTdoes not implementIInit; a forwardgotojoin uses the same rule. Two observable changes follow from a type-test fact that now survives theif: a read afterif x is Dog { } else { return }selects a member thatDoghides (x.Nameprintsdog, it printedanimal), and a call whose overloads become ambiguous for the narrowed type reportsGS0266(give the argument an explicit conversion). A write or a call in a branch still kills a fact as before, and a function with agotoor a label keeps its current rules. -
CI diagnostics: Add an explicitly head-gated, dump-free
core-remaindercrash-sequence diagnostic with bounded, sanitized metadata artifacts. The normalizer accepts all reviewed VSTest TRX counters, includinginProgress, and rejects empty successful runs. The prepared follow-up gate requires asynchronizeevent for PR #5432 and separate exact-head approval. Unarmed validation runs the complete ordinary shard under the existing Actions job budget without diagnostic collection, publishes no raw results, and removes private output. A healthy observation is not a correction for the unresolved crash. Part of #5393. -
Reference-closure warnings obey compiler diagnostic options (issue #5420). Early
GS9100warnings now use the driver's shared severity and suppression policy. Explicit diagnostic promotion stops compilation before emission; global promotion leavesGS9100advisory (issue #5493)./warnaserror+now selects the same global policy as/warnaserror. The ordinary warning, unmatched selections, explicit demotion and suppression retain their existing behavior. Optional assembly references used only by type forwarders are not eagerly required; actual type metadata dependencies remain checked, and unavailable forwarded types still fail when used. The netstandard SDK task declares the security-permission package needed to complete ConfigurationManager's metadata closure. Imported-base copy rejections retain the rejected declaration's source range (issue #5429). -
Imported generic data-class literals retain their type arguments (issue #5419). A literal such as
C[string?]{Value: nil}now resolves the imported primary constructor instead of requiring a parameterless constructor. Simple and namespace-qualified names use the same construction path and retain nullable and symbolic type arguments. Classes without primary inputs and foreign records without a matching primary signature retain the existing default constructor path. Foreign-record primary candidates match open member signatures before overloads close. Selected primary properties remain distinct from inherited same-name fields or properties: the nearest eligible property declaration wins, including reference assemblies without private backing fields. Omitted collection inputs use available declaration-shape metadata; nonnullable array, map, and sequence omissions without sufficient shape are diagnosed, including consumer-defined or symbolic element arguments. Known collection shapes supplied as whole primary type arguments remain available. Explicit collection inputs and nullable omissions remain legal. Structural spread type probes preserve the constructed target without validating omitted inputs prematurely. Spreads use the same primary constructor and constructed input slots as ordinary literals; collection omissions use the canonical collection-zero and declaration-shape checks instead of blindly passing optional null defaults. Other optional defaults are preserved, and member tails follow construction. Constructor inputs keep their declared nullability and run once in source order. Expression trees defer these inputs, construction, and constant or effectful tail assignments until the compiled lambda runs. Deferred CLR member accesses preserve exact member identity, including case-distinct names, symbolic collection receivers, constrained interfaces, nullable value accessors, and metadata-only generic owners in nested lambdas. Nullable results cannot flow into non-nullable slots. Ordinary constructor calls are unchanged. -
Imported data-class primary collections retain declaration shape (issue #5425, ADR-0218). New producers record existing collection-shape metadata for their own primary storage. Omitted slices, fixed arrays, maps, and synchronous sequences receive their distinct sound zeros through implementation or reference metadata. Primary field tokens resolve within the declaring type and module, including private backing fields, rather than colliding inherited fields. Legacy zero-token name lookup uses only declared fields or properties, never inherited storage. Missing or unusable required shape still reports located
GS0267without output. An unusable primary marker cannot fall back to another zero recipe, including for imported data structs. Failed nested recipes cannot become raw primary defaults in source or imported literals and spreads. Nullable-only nested closures keep their legal defaults. Explicit values, nullable omissions, ordinary constructor calls, and whole-primary-type-parameter shapes keep their behavior. Class inheritance and body-field initialization ownership are unchanged. -
Bare
/warnaserror-disables global warning promotion (issue #5426). A later minus option now clears an earlier/warnaserror. Selected-ID promotions, exemptions, and suppressions remain unchanged. -
Captured generic values retain constraint dependencies (issue #5427). Generated capture boxes and closures now declare parameters referenced transitively by their constraints. Dependent bounds retain their generated owner and declaration order, including expression-tree captures and nested generic owners.
-
Explicit reference assemblies resolve by metadata name (issue #5421). Transitive signatures now resolve supplied assemblies independently of their filenames, including
/refoutpaths such asLibrary.ref.dll. The resolver retains first-reference precedence and missing-dependency diagnostics. Cached images retain the winning reference's original path for documentation and source navigation. Case-sensitive filesystem paths retain distinct images. Host fallback and target core-library selection use metadata identity instead of filenames. Consumers no longer lose members because a supplied dependency has a different file basename. -
Imported generic fields preserve sound collection zeros (issue #5412). Source fields retain required empty collections inside imported value types, including symbolic generic arguments. Exported parents preserve these obligations for later consumers. Initialization does not replay nested scalar defaults or constructors. Unsupported external reconstruction of readonly fields reports located
GS0127diagnostics without an image. Explicit raw defaults remain unchanged. -
Breaking change: data struct constructors own fresh initialization (issues #5296 and #5364; ADR-0214). Local and imported fresh constructions now call ordinary constructors, including synthesized zero-argument, empty-primary, and accessible authored parameterless constructors. Constructor arguments run first. Declaration defaults and the constructor body run once before caller member assignments, including symbolic generic spreads and awaited member values. Foreign record-struct spreads retain their parameterless-constructor or implicit-zero path without inferring primary inputs from member names. Overwritten defaults still allocate, produce effects, and throw. Explicit static constructors follow ordinary CLR timing. Brace omissions use legal zeros, while ordinary calls retain optional defaults. Readonly defaults run inside their owner; caller readonly writes report located
GS0127without an image. No public per-field initializer helper protocol remains. Old G# libraries missing the required constructor reportGS0267. A nonnullable primary array omission also requires collection shape metadata; explicit values and nullable omissions remain legal. Recompile those libraries and their consumers; replacing a library cannot repair old consumer IL. Copies require nonnullable receivers while preserving nullable type arguments. Raw defaults, zero-initialized array elements, bare sound-zero initialization,with, and.copydo not replay fresh constructors or scalar defaults. -
Imported generic record returns accept matching nullable contracts (issue #5408). Imported annotation-backed records now convert to the same explicitly constructed generic signature. Returns, typed locals, and arguments preserve nullable type arguments, including nested positions. Different invariant argument contracts, including value-type optionality, remain rejected.
-
Imported value tuples retain identity with native tuple arguments (issue #5468). An imported
System.ValueTuple[C, int32]and(C, int32)now match inside generic interface conversions whenCis a source type. Safe reference covariance remains available for other arguments. Tuple elements retain their invariant nullable contracts, value optionality, and fixed-array identity. ReferenceSystem.Tupletypes remain distinct. -
Imported oblivious value containers accept nullable argument views (issue #5413). Safe
C[T!]toC[T?]conversions now include imported generic value containers. Returns, typed locals, arguments, and nullable-value lifts preserve nulls, nested contracts, and CLR storage. Widening preserves all other stated argument contracts. Non-null argument views and different value-type optionality remain rejected. Nullable-value lifts keep identity handling for native and imported tuple spellings. Breaking change: a nullable-element array such as[]string?no longer converts to an oblivious[]!string!destination. It reportsGS0155, as the sameList[string?]assignment already did, because ADR-0186 rejectsC[T?]toC[T!]. The pinned released compiler now builds the SDK task assembly, as it builds other repository projects. The packed-assembly checks for issues #4921 and #4924 are unchanged. The SDK.editorconfigseverity reader keeps nullable line elements and stops withInvalidDataExceptionon a null line. Nested covariant views, such as an obliviousIReadOnlyList<IReadOnlyList<string>>read asIEnumerable[IEnumerable[string?]?], relate each argument pair once, so compile time no longer grows exponentially with the nesting depth. -
cs2gs keeps nullable elements in storage for imported oblivious containers (issue #5537). A translated local, field, parameter, or method return that stores an oblivious
string[]orList<string>from frozen metadata now has the type[]string?orList[string?], not[]string. Aparams string[]parameter that receives one is spelled...string?. Aparamscarrier, such asList<string>[], keeps its carrier type with the same nullable positions. An expanded nil element passes to such a parameter without!!. A nil element written into such storage, or into a construction stored there, byAdd,Insert, an element or member write, an index argument, or a collection or object initializer stays nil, also through a conditional arm or??. Aforeachover a container that enumerates another type, such asTagged<T> : IEnumerable<int>, keeps its variable non-null. A source-declared generic interface that receives one, such asIEnumerable<string>, is spelledIEnumerable[string?]. Aliases of that storage, and constructions stored in it, use the same element type. Only positions that the producer leaves oblivious change. A non-null use of an element, including an indexer, field, property, or method result typed by the container's type parameter, gets!!, which throws where C# throws. Nullable targets and nil tests get no!!. The previousListtranslation reported GS0155, and the array translation reports it after #5413, because ADR-0186 has noC[T!]toC[T]conversion. Overrides, interface implementations, indexers, and async methods keep their declared types. -
Direct nullable numeric casts extract their value before conversion (issue #5400).
cast[uint64](value)forvalue uint32?now produces valid IL. The shared conversion path preserves signedness, checked overflow, and single evaluation. A missing value throwsInvalidOperationException, matching existing nullable-value casts. Expression-tree casts retain conversion nodes and the same missing-value behavior. Nullable targets still preserve null. Dropping value optionality requires an explicit cast, including numeric widening. -
Tuple equality retains integer constant conversions (issue #5399).
==and!=now retain constant elements when adapting a tuple comparison to nullable unsigned integers. For example,(value, 9) == (0, 9)accepts auint32?value. Nested tuple literals retain the same conversions. Operands still run once, left before right. Invalid constants and incompatible nonconstant elements remain rejected. -
Nullable integer destinations accept representable constants (issue #5414). Calls such as
F(0)for auint32?parameter and tuple returns such as(0, 9)for(uint32?, int32)now apply integer constant conversion before lifting to nullable. Nested tuple returns retain the same rule. User-defined and imported overloads compare numeric targets before conversion mechanism costs, preserving constant-narrowing target preferences, actual identity conversions, and nullable numeric preferences over boxing to objects or interfaces. Imported readonly-reference parameters follow the same target rule. Base-constructor chains and setter-only indexers use the shared overload ranking. Enum members still require explicit integer casts. Negative unsigned constants, out-of-range values, and nonconstant narrowing remain rejected. -
Binary integer operators adapt representable literal pairs (issue #5415). Expressions such as
4294967294 + 1now accept two integer literals with different inferred types. The shared operator binder uses the existing range-checked literal conversion. Arithmetic, bitwise operations, and comparisons preserve the adapted integer values. Negative unsigned conversions and out-of-range conversions remain rejected. Enum members retain their enum types and do not adapt as integer literals. -
Imported generic data copies keep nullable type arguments (issue #5405).
withand.copy(...)retain the receiver's type arguments during copying and member updates. A copy does not call constructors or repeat declaration initializers. Nullable values remain nullable after copying. Updates select the nearest declared member. A derived field can hide a writable or get-only base property without changing the base property's value. -
Source Link mappings stay current in incremental builds (issue #5404). The SDK tracks generated and explicit mapping files before compilation. Missing explicit files now cause an SDK error when compilation requests debug information. Consumer projects and repository builds use the same target. The SDK guide now describes repository metadata, symbol packages, and source-disclosure limits. Source embedding remains opt-in.
-
Repository mirrors keep source version history (issue #5402).
cs2gs migratenow keeps independent Git metadata for source repositories and linked working trees. Version tasks no longer use a repository above the destination. Archive mirrors get an empty Git boundary. Git sources must use the working-tree root. -
Qualified package components keep their complete names (issue #5396). A later component can match an unrelated source or imported type name. Qualified constructions and shared member access now use the complete package prefix. This corrects translated Oahu token references. The translator code stays unchanged.
-
Bank the three nightly applications (issue #5396). Record Oahu, Code Exploder, and GSharp after complete validation. A later failure on
mainreceives oneP0label through the existing issue classifier. Project selection and stage floors stay unchanged. -
Numeric coalescing keeps non-null fallback results unwrapped (issue #5395). Expressions such as
cast[uint64](selected?.OSThreadId ?? 0)now produce valid IL. Constant adaptation retries ordinary operator binding before nullable lifting. Null and present values retain their numeric values, signedness, and evaluation count. Nullable fallbacks and lifted arithmetic retain their nullable results. -
Source class literals retain primary initialization (issue #5361). Inferred and explicit generic literals now call the primary constructor, so declaration initializers run in their owning scope. Explicit member overrides retain source evaluation order and run once.
-
Check ref-like liveness after suspension inference across function bodies, top-level statements, field initializers, static initializer statements, and base-constructor arguments. Include nested async lambdas. Convert typed spill failures into source-located diagnostics. Keep synthesized-temporary diagnostics stable when inference renumbers spills. Reuse cached function-literal lowering across analyses. Complete deferred operand checks after inference, including unchanged bodies. Preserve exact diagnostic counts and safe parked-channel literal evaluation. Do not suggest unsupported operators for mixed adjacent literals. Recover unsupported triple-quoted forms as one rejected UTF-8 token. Resolve the required literal helper from the target reference set. Part of #5332 and #5328.
-
await usingawaits a source-defined asyncValueTaskdisposer (issue #5259). Cleanup now uses the observable return type ofasync func DisposeAsync() ValueTask, rather than its logicalvoidresult. This removesGS9998at top level and in async functions. Cleanup keeps its block-scoped LIFO order and waits for disposal before returning or propagating an exception. Non-async and importedValueTaskdisposers are unchanged. -
Duplicate labels report source errors instead of a compiler exception (issue #5288). A repeated
gotolabel now reports locatedGS0470diagnostics without reusing the first declaration's control-flow target. Parser recovery from a reservedrangeidentifier also preserves its source diagnostics instead of reportingGS9998for a repeated initializer name.rangeremains reserved. -
Method-wide
usingbindings in async functions no longer cause exponential analysis work (issue #5258). Repeated definite-assignment probes of nested cleanup regions caused the growth, not async disposal lowering. The per-analysis region cache from #5287 also corrects this case. Regression tests now bound region-analysis work for twenty distinct bindings and check lifetime, single evaluation, LIFO disposal, exception propagation and deterministic output. Cleanup scopes and async suspension behavior are unchanged. -
Inline constructor callbacks retain their array parameters (issue #5261). Lambda signature adaptation now rewrites array-assignment targets to the adapter's parameter, as it already rewrites parameter reads. An inline callback passed to an imported constructor no longer fails with
GS9998for a missing parameter slot. Captured state and operand evaluation order remain unchanged. -
Imported nested string constants work in attributes (issue #5272). Qualified CLR literal fields, such as
Android.Manifest.Permission.ManageDocuments, now retain their constant values in constructor arguments, named properties and attribute arrays. Empty and null string constants also work. Namespace aliases, type aliases and ordinary member lookup keep their precedence; static readonly fields, mutable fields and properties remain nonconstant. -
Overriding event accessors can forward to a base event (issue #5270).
base.Event += handlerandbase.Event -= handlernow call the selected base add/remove accessor nonvirtually, including imported generic bases, function literals and async/iterator bodies. Ordinary subscriptions retain virtual dispatch, and nil handlers retain their existing behavior. -
fixedaccepts inferred imported CLR arrays (issue #5266). A non-nullable, one-dimensional CLR array from a method, property or field now uses the pinning path of an annotated[]Tlocal. This concerns the static type; null and empty-array guards remain unchanged. For example,Encoding.UTF8.GetBytes("x")can be pinned without an annotation. Pinning retains the original array, evaluates its source once and does not copy elements. Pointer-element compatibility, unsafe-context requirements and rejection of rectangular and explicitly nullable arrays are unchanged. -
Qualified enum constant patterns retain their complete names (issue #5268). An enum member such as
Role.TextInputno longer becomes a type pattern because an unrelated class is namedTextInput. Boolean, nested, and switch patterns preserve enum equality. Actual qualified type patterns and declared aliases still resolve. Qualified inherited nested types retain their declaring construction in annotations, constructions and patterns. Qualified constructions, conversions, and generic static reads and writes select the same type as annotations, even inside a class with a nested homonym. Type calls retain nullable conversion rules and generic constructor/literal inference. Arguments retain their lexical scope. Null-conditional continuations retain their guards and nullable result types. Type names do not produce values or support null-conditional static access. Invalid qualified types and type arguments report located errors instead of binding by their final name or losing diagnostics. -
Nested value-field writes through native slices reach the stored element (issue #5325). Plain, compound and postfix writes now retain the selected element address through nested value fields. Previously an imported field could write a discarded copy, while a source field could fail emission with
GS9998. Mutating member receivers also retain their storage. Receiver and index selections run once before the right-hand side, including when that side replaces the parent value or rebinds the slice. Value reads still copy. Readonly and temporary targets remain rejected; existing borrowed-location suspension diagnostics are unchanged. The separate suspended-field-store defect #5012 remains open. This corrects synchronous behavior without enabling fixed-array value defaults, adding APIs or changing the SDK pin. -
Constructors inherit their containing type's unsafe context (issue #5263). Instance constructors and
sharedinitializer blocks now acceptfixedstatements in unsafe types. Nested types and merged partial declarations retain the same lexical context. Deferred base-constructor arguments and field initializers also retain unsafe pointer semantics. A top-level declaration does not inherit unsafe context from its metadata owner. Safe, unrelated types still reject unsafe operations. -
Nested types resolve enclosing shared fields by name (issue #5262). Unqualified reads and writes now use the nearest lexical declaring type, including private shared fields. Parameters, nearer declared members and visible inherited instance members, including implicit
System.Objectmethods, keep precedence. Inherited static members do not hide lexical state. Nested event subscriptions retain the declaring owner's add/remove accessors. Selected delegate fields and properties keep the same storage for compound writes. Each scope queries a candidate name once. The lookup does not supply outer instances or permit unrelated private access. -
Lexical shared-state lookup preserves inherited default interface methods (issue #5262). Nested classes now check the canonical inherited-call candidates before enclosing shared state. Transitive and constructed generic interface methods retain their targets. Shared bodies still receive no implicit instance.
-
Explicit interface methods do not hide lexical shared state (issue #5262). Source method barriers now use the ordinary method query. Instance, inherited and shared explicit implementations remain interface-only. Normal private methods keep precedence.
-
Nested interface bodies resolve enclosing shared state (issue #5262). Default bodies retain their interface owner during lexical lookup and private-access checks. Interface state, methods and inherited members keep precedence. Enclosing field, property, delegate and event operations keep their declaring storage.
-
Inherited CLR interface calls keep precedence over enclosing callbacks (issue #5262). Lexical hiding and implicit calls share the imported-interface overload query. Interface property queries keep inherited static properties separate from instance members and enclosing shared fields.
-
Implicit inherited generic calls preserve explicit type arguments (issue #5262). Bare calls in interface default bodies keep CLR and symbolic type arguments, matching qualified calls. Class and interface fallback share the same argument resolver.
-
Inherited interface properties and escaped CLR names keep lexical precedence (issue #5262). Bare property reads and accessor chains use the qualified inherited-property query. Imported calls share canonical collision-aware name matching. Unsupported imported-property writes diagnose instead of changing enclosing state.
-
Constructed interface data members keep lexical precedence (issue #5262). Generic source interface properties and events share canonical member enumeration and lookup. Imported interface events hide enclosing delegates; unsupported bare operations diagnose instead of mutating unrelated storage.
-
Inherited generic interface methods retain their constructed owner (issue #5392). Default bodies and calls through non-generic derived interfaces now resolve the source method's emitted handle on its declaring interface. Nested interfaces retain generic arguments and virtual dispatch.
-
Interface default bodies can mutate later shared fields (issue #5471). Field planning now reserves aggregate field tokens before emitting bodies. Later class fields retain their declaring storage, initialization order, and constructed generic owners.
-
Inherited interface reads skip write-only property candidates (issue #5262). Bare and qualified reads retain the first readable inherited instance property. Write-only properties still hide enclosing shared storage, so unsupported reads and writes cannot select unrelated fields.
-
Primitive type receivers keep their member lookup when unrelated nested types share the member name (issue #5267). Calls such as
string.Format("{0}", 1)no longer select an unrelated nestedFormatconstructor. Namespace-prefix classification checks namespace aliases before normal type lookup, so crossed aliases do not cause recursive type resolution. Canonical lookup recognizes predefined aliases and type parameters only at the leading segment. Later package components retain their source/import checks, even when a primitive alias or type parameter has the same name. An independent CLR receiver check preserves existing member lookup when imported source types are ambiguous. Actual nested constructors, imported CLR calls, and qualified source constructions retain their existing resolution. -
Generic callbacks infer from a lambda's symbolic signature (issue #5273). A generic function taking
Func[T]could reportGS0151for() -> Task.FromResult(Uri(...))in an SDK build. Inference now reads the delegate's signature without requiring the lambda's CLR delegate type. Nested generic returns and named delegates retain their type arguments. Callback inputs retain their upper-bound direction: a callback accepting a base class no longer widens a type inferred from a derived-class value or callback result, regardless of argument order. Input-only inference and nested variance remain supported. Mutable container elements contribute exact bounds. Method inference cannot replace fixed owner or receiver type arguments. Inference summarizes each lower or exact bound once instead of replaying prior bounds. Conflicting evidence retains the earlier argument contract, so diagnostics identify the incompatible later argument. A result containing the non-emittablenevertype, including nested function signatures and tuples, supplies no type argument; other signature slots can still supply one. Legalvoid-returning function types remain inferable. Constraint checks and overload ranking remain unchanged. -
Diagnose ref-like operand temporaries across async suspension (issue #5332). Calls and span receivers that need a ref-like temporary across explicit or implicit channel awaits now report located GS0219 diagnostics instead of silently losing the value after suspension. The existing liveness analysis runs after inferred-call rewriting and checks actual handler append, channel, exception-handler, and spill lifetimes, including async literals in field, static-block, and base-constructor initializers. Gated handlers can consume a span before a later awaited hole. Diagnostic queries return source-anchored preparation failures instead of throwing. Analysis reuses lowered literal bodies and the program's ordered function view. Source-local and ref-alias restrictions remain in force. Construct or consume spans outside the suspension lifetime; effectful calls are not deferred or hoisted.
-
Delegate.EnumerateInvocationListkeeps its delegate type through aforloop (issue #5269). Iterating an event with a same-compilation enum or struct in its delegate signature could emit invalid IL and throwBadImageFormatException. Pattern enumeration now projectsGetEnumerator()through the collection's symbolic type arguments. It also projects the declaredCurrentproperty or field for reference-type enumerators, without assuming the first generic argument is the element type. Imported method and field references no longer construct an unnecessary placeholder type that can violate generic constraints. Empty events return no callbacks; subscribed callbacks retain their order, arguments and short-circuit behavior on struct and class receivers. -
go2gs waits for owned Unix worker groups to terminate (issue #5344, part of #4333). A successful group signal did not prove that every descendant had exited. Cleanup now repeats
SIGKILLwith a two-second cleanup deadline. It requires the group to disappear or, on Linux, two matching complete observations of dead members only. Linux rejects a hidden process view, a live member beside a zombie, and live threads behind a zombie leader. Transient macOSEPERMerrors are retried, not treated as success. A termination failure returns without waiting indefinitely for the worker. Existing cancellation assertions and inherited-group handling are unchanged. -
P/Invoke accepts imported blittable value structs (issue #5264). Sequential and explicit structs now use the same recursive layout check in source and assembly references for by-value, return,
ref,out, andinsignatures, including@MarshalAs(UnmanagedType.Struct). Imported generic fields use their actual symbolic arguments rather than erased CLR stand-ins. Managed fields, Auto layout, nullable values, and unsupported generic aggregate slots remain rejected. Raw pointers retain their separate ABI rules; unmanagedbool,char, anddecimalfields do not become blittable. -
Content-only packages no longer attempt an empty default symbol package (issue #5265).
dotnet packnow defaultsIncludeSymbolsfrom the evaluatedIncludeBuildOutputproperty. A project withIncludeBuildOutput=falsecan package content withoutNU5017, including when no G# source exists orProgram.gsis empty. Ordinary libraries still producesnupkgfiles by default. ExplicitIncludeSymbolsvalues andSymbolPackageFormatselections remain unchanged. -
SemanticModelgainsGetEnclosingSymbolandLookupSymbols, and the language server resolves names through them (ADR-0212 slice S3, issue #5306, part of #5139 and #2189). Public API:SemanticModel.GetEnclosingSymbol(position)returns the innermost function (a method, a constructor's function, or an accessor's function), struct, interface or top-level variable that contains the position, ornull;SemanticModel.LookupSymbols(position, name?)returns the symbols a simple name resolves to there, one per name with the innermost declaration shadowing, ordered by scope depth and then declaration order: locals, parameters and bindings whose scope contains the position (including lambda parameters), local functions, the implicitthis, the members of the enclosing type, then the compilation's functions, variables and types (and the prior submissions' whenCompilation.Submissionis set). A type alias answers the type it names when queried by name.GetSymbolInfonow also answers an identifier in the type clause of a function, parameter or field declaration, the declaration identifier of a local function and of an element of a destructured lambda parameter, andGetDeclaredSymbolanswers declarations inside a function literal's body. The staticGetTypeClauseSymbolsthat slice S2 added is internal again (it was never in a release). Language server: name completion lists what is in scope at the caret (parameters, locals declared before it, the enclosing type's members, then the globals), so locals appear where only parameters of top-level functions and globals did; a name that binds to nothing falls back to the same scope rules, so lambda parameters, assignment targets and setter bodies now resolve; the implementation request walks the project's type declarations; the server no longer readsGlobalScopefor these. Compiled output is unchanged. -
The language server now evaluates
InternalsVisibleTofor the project's assembly name, asgscdoes (issue #5310, part of #5139 and #2189; ADR-0212 slice S6b). A behavior change:ProjectStatenever setCompilation.AssemblyName, so the server compared every referenced assembly'sInternalsVisibleTolist against an empty consumer name. Internals of a friend assembly (one that declaresInternalsVisibleTo("<your assembly>")) therefore showed false diagnostics, and the server could hide a diagnostic thatgscreports on code that reaches an assembly that is not a friend. The name is the project'sAssemblyName(the<AssemblyName>property, or the project file name), set on every compilation the server builds and inherited by every successor; renaming the project in the.gsprojrebuilds with the new name. The comparison is the compiler's: ordinal (a name that differs only in case is not a friend), with surrounding spaces ignored. A project without an assembly name (a loose file) keeps an empty name and gets no friendship. Compiled output and thegsccommand line are unchanged;GSharp.Coreis untouched. -
CompilationandSemanticModelanswer diagnostics, a compilation has a lifetime token, and the language server hides documentation warnings while the project has an error (issue #5309, part of #5139 and #2189; ADR-0212 slice S6). New public members:Compilation.GetDeclarationDiagnostics(cancellationToken)(every tree's parse diagnostics, then the global scope's),Compilation.GetBodyDiagnostics(cancellationToken)(the bound program's) andCompilation.GetDiagnostics(cancellationToken)(the declaration part, the body part, then the documentation diagnostics), each with@SuppressDiagnosticscopes applied and built once; andSemanticModel.GetDiagnostics(cancellationToken), theGetDiagnosticsentries that lie in the model's tree.GetDiagnosticsfollowsgsc: the documentation pass runs only when no declaration or body diagnostic is an error. Every lazy build of a compilation (global scope, bound program, diagnostics, the index of aSemanticModel) now runs underWorkBudget.CancellationTokenand under no other token. A cancelled build publishes nothing, a cancelled compilation throwsOperationCanceledExceptionfor every state it has not built, and recovery is a successor compilation with a newWorkBudget. A request token passed to a query cancels only that caller's wait. A compilation thatReplaceSyntaxTreere-pointed at a successor's tree (a body-only edit) is retired: it answers from state it already published and throwsOperationCanceledExceptionfor anything else. Language server behaviour change: a documentation warning such asGS0231is no longer shown while any file of the project has an error, asgscdoes, and it returns when the error is fixed. The server cancels the lifetime token of the compilation that a newer one replaces, and its diagnostics, code-action and warm-up paths use the new queries. A quick fix is no longer offered for a diagnostic that an@SuppressDiagnosticscope hides. Public API: addedCompilation.GetDeclarationDiagnostics,GetBodyDiagnostics,GetDiagnosticsandSemanticModel.GetDiagnostics; nothing removed. -
A call no longer drops the narrowing of a by-reference parameter (issue #5292, a regression of #5171, part of #2189). Since #5214, any call, including a read-only call and a call in a loop, made
if path == nil { return }; Use(path); Use(path)fail withGS0154orGS0155whenpathwas areforoutparameter, and twooutparameters of different types were treated as one storage, soTryGetValue(path, out found)in a loop dropped the fact. The translated compiler source used both shapes, so the nightly C#-to-G# gate reported 24 apps red. A plain call now keeps the fact, as in 0.5.212 and in C#; writes through a member, index or indirect target, direct writes to an overlapping by-reference parameter, and a variable passed twice to one call with aref/outstill drop it, and two by-reference parameters share a storage only when their types can overlap (ADR-0208 R12, amendment A3). A callee that writes the storage through a global or a container is a known limitation. -
Compilationhas successor factories, and the incremental-binding members leave the public API (issue #5304, part of #5139 and #2189; ADR-0212 slice S1). New public members:Compilation.ReplaceSyntaxTree(oldTree, newTree),AddSyntaxTrees(trees...),RemoveSyntaxTrees(trees...),WithReplacedSyntaxTree(oldTree, newTree),GetTypeByMetadataName(name, cancellationToken)and the optionIncrementalBodyReuse. A successor copies every option exceptWorkBudget.ReplaceSyntaxTreere-uses the global scope for an edit that changes only member bodies and re-points the previous compilation's symbols at the new tree, so the previous compilation is retired.WithReplacedSyntaxTreeis the one-shot variant for an unsaved buffer: it never re-points symbols and never shares the body cache. Removed from the public API:Compilation.BodyCache,Compilation.ReusedGlobalScope,Compilation.DirtyBodyTrees,BoundBodyCache,BoundBodyCacheKey,IncrementalGlobalScopeReuse, and the threeBinder.BindProgramoverloads that take a cache (theBindProgram(globalScope, references)overload stays). The lazyGlobalScopeandBoundProgrambuilds are now single-flight: concurrent first readers wait for one bind instead of binding twice. A build observes onlyWorkBudget.CancellationToken, and a cancelled build publishes nothing. In the language server, a snapshot compilation no longer shares the project's body cache, so a diagnostic pull for an unsaved buffer no longer evicts the live cache entries. A sibling-project go-to-definition on a delegate now matches the package as well as the name. Output and diagnostics ofgscare unchanged. -
InteractiveSessionHostandSubmissionRunResultmove fromGSharp.Coreto the REPL (issue #5303, part of #5139 and #2189; ADR-0212 slice S0). Only the REPL (gsi) used the session host, so it now lives insrc/Repl/Engine/asGSharp.Repl.Engine.InteractiveSessionHostandGSharp.Repl.Engine.SubmissionRunResult. This is a public API change forGSharp.Core: both types, which were inGSharp.Core.CodeAnalysis.Execution, are removed from the assembly, and the public API snapshot drops them. Nothing else in the repository referenced them. Behavior is unchanged and compiler output is untouched. -
Typed CLR-copy foundations for canonical fixed-array carriers (ADR-0210 F2a, issue #5323).
Gsharp.Values.FixedArrays.V1.ClrArrayCopiesprovides ordinary CLRFromArrayN<T>andToArrayN<T>methods for lengths 0–32. Copy-in checks null and exact physical length; copy-out allocates a fresh exactT[], including length zero. Typed field copies run no element constructor and never share element slots; contained references and slice descriptors keep their existing sharing. The frozen V1 carriers and owner epoch are unchanged. This is a runtime/compiler-service foundation, not native source[N]Tlowering, source cast/member recognition, views, a legacy mode or Go admission. Numeric empty allocations still infer[]T. The pre-existing nested native-slice field-store defect #5325 remains a separate full-F2 blocker. -
SemanticModelanswers more of what a bound node means, and has receiver queries (ADR-0212 slice S2, issue #5305, part of #5139 and #2189).GetSymbolInfonow returns the field or enum member behind a constant-folded read, the property behind an auto-property backing-field read (at the constructed receiver's signature), and the type behind a static qualifier whose read the binder folded; a parenthesized node answers for its operand; an identifier token answers the symbol it declares or names, and nothing when the name differs from the token text. Three members are added toSemanticModel:GetReceiverTypeInfo(expression)(the type of a receiver in a member-access chain after implicit conversions),GetReferencedExpression(token)(the read or call a token names; the language server uses it for imported members until slice S4) and the staticGetTypeClauseSymbols(typeClause, type)(the language server uses it until slice S3). Nothing is removed. The language server moves its receiver-chain interpretation into these queries, and a newLanguageServer.Testsgate lists the binding types the server still references so that later slices shrink the list. Compiled output and language-server behavior are unchanged. -
Auditable exception for an upstream ILVerify limitation (issue #5244, dotnet/runtime#129030). With explicit maintainer approval, the development validation gate still runs the complete pinned verifier and admits two exact existing native-slice
AsSpandiagnostics. A shared certificate binds nominal metadata, signatures, complete safe array-owner IL and reported offsets. The same policy admits one immutable UTF-8 research witness and one separately reviewed compiler-produced witness by full-image digests. Only the latter's three exact by-value returns are admitted; future generated images and the complete UTF-8 feature are not automatically certified. Each certificate requires its complete unique diagnostic set, even when a shortened report has a consistent summary. Changed signatures, bodies or payloads, by-reference returns, unknown diagnostics, malformed output and process/reference failures stay failures. Logs preserve the raw outcome and admitted count; this is not strict unsuppressed verification success. Runtime safety and applicable JIT/NativeAOT witnesses remain required. The upstream issue stays open, and the certificates must be removed after a separately approved corrected verifier passes those witnesses. This changes certification policy, not released syntax, SDK versions or runtime behavior. -
gsfmt --checknames the files that would change (issue #5299, part of #2189).--checkexited 1 without printing anything, so a failing CIformatjob gave no list of files. It now prints each file that would change on standard output, one path per line in the same sorted order and path form as-l, then a one-line summary with the fix command (gsfmt -w <path>) on standard error. The exit code is still 1 when a file would change; when everything is formatted it prints nothing and exits 0. -
Data equality and hashing retain field types (issue #5274). Synthesized typed equality now uses
EqualityComparer[T].Defaultfor each field instead of boxing operands forobject.Equals. Hashing uses field-typedHashCode.Combine, or field-typedHashCode.Addfor more than eight fields. This removes emitted field boxing and honors customIEquatable[T]implementations while retaining NaN, signed-zero and null equality semantics. The synthesized public members and the restriction on authored equality members are unchanged. -
Emitted assemblies write each
MemberRef,TypeSpecandMethodSpecrow once (issue #5172, part of #2189 and #4845). The emitter's token caches are keyed by symbol or reflection identity, so equal references that arrived as separate objects each added a row; about 75% of theMemberRef, 90% of theTypeSpecand 71% of theMethodSpecrows ofGSharp.Core.dllrepeated an earlier row. A row is now added once per distinct encoded form (parent, name and signature; signature blob; method and instantiation blob), and later references reuse the first row's token, in first-occurrence order.GSharp.Core.dllfalls from 5,838,848 to 5,436,416 bytes (6.9%) and its reference assembly by 1.8%. Behavior is unchanged: method bodies carry different tokens for the same references, and the repeatedMethodSpecrows that aMetadataLoadContextreference set produced (#4845) are gone. The output is deterministic but is not byte-identical to earlier compilers, so the committed IL baseline digests changed. Newemit.memberref.reused,emit.typespec.reusedandemit.methodspec.reusedcounters inGSHARP_MEASURE_PHASES. -
Synthesized syntax tokens are zero-width, and a body-less type no longer extends into the next declaration (issue #5277, part of #2189). The parser makes some tokens that are not written in source: the
{and}of a body-lessdata class P(X int32), thereturnof an expression body, and the()ofList[int32]{ ... }. They had the width of their text at the position of the next real token, so theSpanof a body-less type reached one character into the following declaration. These tokens now keep their text and have a zero-width span, and the braces of a body-less type sit at the end of its header. TheSpanof a body-less type ends at its header, and diagnostics,gsfmtand language-server ranges that used it no longer include the first character of the next declaration. Compiled output is unchanged. -
Package, import and indexer declarations list each token once (issue #5276, part of #2189).
PackageSyntax,ImportSyntaxand an indexerPropertyDeclarationSyntaxreturned one identifier (orthis) token twice fromGetChildren(), so a walker visited it twice andChildCountwas too large.PackageSyntax.Identifiers,ImportSyntax.IdentifiersandPropertyDeclarationSyntax.ThisKeywordstay available as properties but are no longer separate children; the dotted path is listed throughIdentifiersWithDots. -
Anonymous objects at top level and in bodies no longer share a type name (issue #5281, part of #5141 and #2189). A program with an
object { ... }literal in a top-level statement and another in a function body emitted two types both named<>AnonymousType0, and the same shape written in both places became two types. The body pass now continues the declaration pass's anonymous-type cache, so each shape is one type with a unique name. Output is unchanged for programs that did not hit the duplicate. -
Syntax node children are now in source order (issue #5185, part of #2189).
SyntaxNode.GetChildren()returned the children of some nodes in declaration order, so a postfixx!!listed!!beforex, a type clause such asstring?or(int32) -> int32listed its tokens out of order, a struct listed all fields, then properties and methods, then itssharedblock after its closing brace, and a declaration listed its annotations after its body.GetFirstToken(),GetLastToken(),GSharpSyntaxWalkervisit order andDescendantNodes()followed that order. Declarations, parameters, type clauses, unary expressions, struct literals and the compilation unit now sort their children by source position, with the order of the properties breaking ties.Spanis unchanged. A few children still overlap (an interpolated string token contains its holes, and the parser synthesizes some tokens at the position of a real one). The!token ofa !is Tlies inside theisexpression, so it follows that expression in the list, andGetLastToken()of that unary expression still returns the last token of theisexpression. Code that sorted children bySpan.Startas a workaround keeps working. -
An expression-bodied function can return a slice of a named tuple (issue #5191, part of #2189).
func M1() [](A int64, B object?) -> [](A int64, B object?){(A: 1, B: nil), (A: 2, B: "x")}reportedGS0113(Type 'A' doesn't exist.) andGS0005at the first element name of the return type, while the block-body spelling compiled. The parser read the parenthesized list as the parameter list of an arrow function type, which holds bare types and nevername Typepairs. A list with a top-level element writtenname Typeis now always a named tuple type (ADR-0172); theref,outandinparameter modifiers still make a function type. A slice of an unnamed tuple before->keeps its existing meaning, an array of function types. -
cs2gs keeps the null test of a nested recursive pattern (issue #4315, part of #2189).
p is { Address: { City: "Lima" } }andp is { Address: { } }translated withoutp.Address != nilwhenAddresswas declared non-nullable, on the premise that gsc rejects!= nilthere (GS0129). gsc accepts it on every reference type, and a declared-non-null member is null at run time when it is never assigned, comes from oblivious code or isnull!-initialized. The translated program then threwNullReferenceException, matched{ }where C# yields false, or failed to compile (GS0158) when the member was promoted toT?. The guard is now always emitted, and theparamsarray subject keeps its GS0523 exemption. Re-translate affected sources; the output gainsmember != nil &&tests. -
A by-ref-like type argument now binds for an imported
allows ref structtype parameter (issue #5216, part of #2189).dictionary.GetAlternateLookup[ReadOnlySpan[char]]()reportedGS0159, and the nested typeDictionary[string, int32].AlternateLookup[ReadOnlySpan[char]]reportedGS0219, because the compiler rejected everyref structtype argument. The compiler now reads the CLRAllowByRefLikeflag of the type parameter and accepts aref structargument only when the flag is set. This coversHashSet[T].GetAlternateLookup,TryGetAlternateLookup,Action[ReadOnlySpan[char]],Func[ReadOnlySpan[char], T],Unsafe.AreSameandIAlternateEqualityComparer[ReadOnlySpan[char], T]. A parameter without the flag still rejects the argument:List[ReadOnlySpan[char]]reportsGS0219(type position) orGS0152(constructor call), andArray.Empty[ReadOnlySpan[char]]()reportsGS0159. G# generic functions and types still reject aref structargument, because G# source has noallows ref structsyntax yet. -
An instance accessor on a reference receiver is now always a
callvirt(issue #4312, part of #2189). A user event+=/-=on a class or generic-class receiver was emitted as a non-virtualcallunless the event was declaredopenoroverride, so a receiver that was nil at run time (for example a value returned by a CLR call) ran the accessor with a nullthisinstead of throwingNullReferenceException. User property reads and writes chose their opcode from the receiver's type symbol rather than from whether it is a reference. All four sites now share one decision, the complement of the test that loads a value-type receiver as an address: value-type receivers keepcall, every other receiver iscallvirt, so the CLR null-checks the receiver and an override dispatches on the run-time type. Output of existing programs is byte-identical;base.accesses still bind non-virtually. -
Narrowing of a
reflocal or by-reference parameter is invalidated by writes to its storage (issue #5171, part of #2189). Areflocal and the variable it aliases name one storage, and a by-reference parameter, or areflocal of an element or member, may name storage that no variable names. A narrowing on the alias survivedx = nilon the aliased variable, a write through a sibling alias, an index or member write and a call, solet ref a C? = x; if a == nil { return }; x = nil; a.Valuecompiled and threwNullReferenceException. A write to any variable of the alias group now drops the facts on the whole group, and a member, index or indirect write or any call drops the facts on everyref/out/inparameter and on everyreflocal whose initializer is not a plain variable. A program that read the alias after such a write now reportsGS0158(orGS0159). Re-test the alias after the write, or copy it into alet. A write to one by-reference parameter or element alias also drops the facts on the others, becauseRun(ref x, ref x)makes them one storage, and a write to a variable whose address the function takes or a closure assigns drops the facts on every such alias. A computed property read with user code now also drops the facts on member paths and on these aliases. Five reads in the repository sources (BinderContext,CustomAttributeEncoder,OverloadResolver, two in the cs2gs translator) relied on the old behavior and now read a local copy. -
Reject ref-like operand temporaries that cross a suspension (issue #5332). Async ref-safety now applies the existing liveness analysis to compiler-generated operand temporaries as well as source locals. Analysis and emission share the same channel-to-await, handler and spill preparation, including implicit channel suspension and async lambdas. A span-valued argument or receiver evaluated before a suspension cannot silently become a default span when the function resumes; it diagnoses instead. This includes ordinary span constructors, span-returning calls and derived UTF-8 views. Pure UTF-8 literal roots can still be deferred safely, and spans constructed after the suspension remain valid. Existing source-local and ref-alias diagnostics are preserved and also apply at implicit suspensions; arbitrary calls are not deferred or hoisted into heap fields. Suspension diagnostics retain their source locations without adding visible debugger stops to generated spill statements.
-
Native UTF-8 span literals (issue #5242, ADR-0211, part of #5218). Adjacent
u8"..."produces canonical CLRreadonly span[byte]from deterministic private RVA data, with a hidden contiguous zero excluded from logical length. Text escapes validate the complete decoded UTF-16 scalar sequence;\xFFencodesC3 BF, unlike arbitrary-byteb"\xFF". Only literal/parenthesized/literal-only+representations fold. Raw forms, malformed scalars, lossy source, adjacent literals andconstuse diagnose; existing conversions and ref-safety restrictions remain unchanged. Formatter, hover, semantic coloring and shared editor grammar recognize the token. Static storage adds no runtime encoder, wrapper or managed-array fallback. Raw ILVerify still runs; generated span-return proof images require separately reviewed finite upstream-issue admission, not a general suppression. cs2gs syntax adoption requires the language release and a separate SDK-pin update; no Go-family admission is included. -
Native CLR span aliases (issue #5241, ADR-0211, part of #5218).
span[T]andreadonly span[T]now denote the existing CLRSystem.Span[T]andSystem.ReadOnlySpan[T], using the target core library rather than user-defined lookalikes. They retain CLR type identity, source-defined element types, readonly element access, and ref-safety rules: a span local may be dead before anawait, but may not remain live across it or be stored in an ordinary heap object. Visible user names retain precedence; useSystem.ReadOnlySpan[T]explicitly whenspanis shadowed. The aliases add no wrappers, allocation literals or implicit conversions. Invalid aliases reportGS0631. This is only the first UTF-8 compiler prerequisite:u8"...", native UTF-8 literal folding and cs2gs adoption are not implemented by this change; static-data emission remains subject to the strict verifier gate in #5242.Ordinary calls also retain static members on lexically enclosing types, and ordinary indexing retains inherited CLR fields/properties and default-interface properties named
span.Values from earlier REPL cells also retain ordinary indexing rather than being mistaken for native type aliases.
-
A
catchfilter's writes now invalidate narrowing in the handler code (issue #5168, part of #2189). Awhenfilter runs before its handler is chosen, and a filter that returns false or throws continues the handler search (ADR-0177). The compiler bound the clause body, later clauses and thefinallyblock with the narrowing from thetryentry, so a filter that storednilinto a narrowed variable (through arefargument or a callback) left a laters.Lengthcompiled as safe, and the program threwNullReferenceException. The binder now invalidates the facts that a filter writes before it binds the clause body and the later clauses. A program that read a narrowed variable after such a filter now reportsGS0158(orGS0159) on the read. Re-test the variable in the handler or copy it into aletbefore thetry. Filters that do not write the variable keep the narrowing. The filters of thetryitself and of every enclosingtryalso run before a handler orfinallyblock of an innertry, so those handlers drop every fact on a variable that a filter may write (an assignment target, aref,outor&operand; a filter that only reads a narrowed variable keeps it), the facts that any call can write (the filters are not bound yet, so each counts as an unknown call, even a getter without a call expression), and the external-callable alias facts that a filter or a closure can reassign. -
Accepted UTF-8 span literal design (issue #5218, ADR-0211). The accepted contract separates static UTF-8 byte views from immutable bytestring values and plans faithful cs2gs translation. The initial release includes
span[T]andreadonly span[T]aliases for existing CLR span types, plus native literal-only UTF-8+folding. Folding validates each operand and emits one hidden trailing zero outside the logical length; it does not add general span addition. Implementation and certification remain pending. This is not released syntax or an allocation guarantee for current G# output. -
Reference assemblies use the effective platform version in NuGet packages (issue #5271).
dotnet packnow uses the SDK's canonical framework identity forref/<tfm>/, as it does forlib/<tfm>/. An unversioned platform alias such asnet10.0-androidno longer causesNU1012. Already-versioned frameworks and each inner build of a multi-target project retain their own effective framework. Platform version selection, minimum supported OS versions, assembly contents and symbol packaging are unchanged. -
Fixed-array AOT witness protects repository configuration (issue #5337). The helper accepts dedicated directories under
out/test-artifacts, rejecting shared roots, protected source trees, redirected paths and multiply-linked files before builds or writes. Its default artifact directory is unchanged. -
Fixed-array ABI foundation, without changed array semantics (issue #5236, ADR-0210 F1).
Gsharp.Runtime.Valuesadds SDK-owned sequentialEmpty<T>,Leaf<T>andBranch<T,L,R>definitions inGsharp.Values.FixedArrays.V1, retaining its assembly-version epoch0.5.0.0. Explicitly marked imported contracts validate the canonical balanced 0-32 encoding, nominal owner and repeated element nullability across inherited public members, interfaces and constraints, reportingGS0630for incompatible claims. Receiver projection retains current symbolic arguments for root members with cached CLR erasure and matches ancestor paths by assembly-qualified constructed identity. Distinct same-named foreign elements and nested source-generic deconstruction keep their member types. Marked contracts reject canonical annotation-read failures instead of accepting fallback nullability. Unmarked foreign carrier signatures remain ordinary CLR types. Source[N]T, empty allocation inference, CLR-array interop and native-slice sharing are unchanged; value lowering, copying bridges, retained views and the breaking rollout remain later slices. No SDK release or pin change is included. -
A call now invalidates narrowing of a mutable top-level
var(issue #5170, part of #2189). Assignment narrowing applies to a mutable global, and any call can assign one, but a call to a function, method orbasemethod, a constructor (including the constructors and field initializers of base classes and generic definitions), a property accessor with user code, a composite literal that runs such code, or afor ... inover an iterator or other enumerable declared in the compilation did not drop the fact in straight-line code or in a loop.text = "safe"; Clear(); text.Lengthcompiled and threwNullReferenceExceptionwhenClearassignedtext. The narrowing analysis now treats every such call as able to assign any mutable global, as it already did for external callables andfinallyblocks. Indexed iteration over an array, slice or string runs no user code and keeps the fact. A program that read a narrowed global after a call now reportsGS0158(orGS0159) on the read. Re-test the global after the call, or copy it into aletbefore. Narrowed locals, parameters and read-only roots are not affected. -
ReadyToRun
gscpackages for six platforms (issue #5155, ADR-0207, part of #2189).Gsharp.NET.Sdknow restores a ReadyToRungscfor the host fromGsharp.NET.Sdk.Compiler.<rid>withPackageDownloadat its own exact version, forlinux-x64,linux-arm64,win-x64,win-arm64,osx-x64andosx-arm64. Hello-world compiles take about 31% less wall time and the Core compile about 9% less, with byte-identical output. A user downloads one package of about 7 MB; the six packages together are about 40 MB on the feed. Any other host (for examplelinux-musl-x64orwin-x86) and Visual Studio's .NET Framework MSBuild keep the portable ILgscinGsharp.NET.Sdk, which stays the fallback in every case.GsharpUseReadyToRunCompiler=falseturns the packages off for restore and build. The runtime files that reach user output (Gsharp.Runtime.Channels,Gsharp.Runtime.Values,Gsharp.Extensions,Gsharp.HotReload.Runtime) stay portable IL.gscaccepts/sdktoolsdir:and the variablesGSHARP_SDK_TOOLS_DIRandGSHARP_GSGEN_TOOLto findgsgenand those runtime files. The MSBuild tasks now start tools withDOTNET_HOST_PATH. A direct call of the packaged ReadyToRungscwithout/sdktoolsdir:orGSHARP_SDK_TOOLS_DIRno longer adds the bundledGsharp.Extensions,Gsharp.Runtime.ChannelsandGsharp.Runtime.Valuesreferences, because those files are not beside it; SDK builds pass/sdktoolsdir:themselves, and the portablegscinGsharp.NET.Sdkis unchanged. A CI smoke on all six platforms checks each package; a platform that was not verified in a release is named in its notes. -
Method-body emit reuses its scratch collections, and max-stack is scanned in place (issue #5137, part of #2189). The emitter keeps the slot dictionaries of a method-body emit session and the planner's collector lists in a small per-emitter pool instead of allocating about 17 dictionaries and 13 lists for every body, and the
.maxstackvalue is computed by reading the IL builder's chunks instead of copying the whole instruction stream first. Pooled collections are cleared when a body ends, a collection that grew large is dropped, and parallel method-body preparation keeps its own unpooled collections. The emitted assembly, reference assembly, PDB and diagnostics are byte-for-byte unchanged.GSHARP_MEASURE_PHASESreportsemit.session-scratch.created/reused,emit.planner-scratch.fresh/reusedandemit.maxstack.streamed. Metadata row deduplication stays with #4845. -
Syntax child access is generated and does not allocate (issue #5136, part of #2189). Each concrete syntax node class now has generated internal
ChildCountandGetChild(index)members (SyntaxNode.Children.g.gs, written bybuild/generate-syntax-children.pyand checked in CI).GetChildren(),Span,GetFirstToken/GetLastToken, the descendant walk, the syntax walker and the parent index read them instead of compiled reflection getters that boxed each child. The child order is unchanged. The reflection path stays as the fallback and the test oracle. Children are not always in source order (for example a postfixx!!), soSpanstill takes the minimum start and maximum end. -
Span[E](array)over a source enum compiles (issue #5189, part of #2189).Span[E](items),ReadOnlySpan[E](items, 0, n),ArraySegment[E](items)andList[E](items)whereEis an enum declared in the same compilation were rejected with GS9002 or GS0267, because the enum array was matched asint32[]against the constructor's erasedobject[]parameter. The enum array now matches the array constructor, as a struct or class array already did. -
For-in over
Span[T]andReadOnlySpan[T]of source types emits valid IL (issue #5151, part of #2189).for x in viewwhere the element type is declared in the same compilation, a generic parameter, or an enum typed the loop enumerator asSpan<object>.Enumerator, so the emitted assembly failed IL verification. The loop now calls the view's own struct enumerator typed with the view's element type. -
For-in over imported by-ref-like collections of source types emits valid IL (issue #5193, part of #2189).
for x in viewover an importedref structcollection other thanSpanandReadOnlySpan, with an element type declared in the same compilation or a generic parameter, typed the loop enumerator from the erased type (GView<object>.Enumerator), so the emitted assembly failed IL verification. The enumerator type is now mapped from the type arguments of the openGetEnumerator()return type, which also covers an enumerator that permutes the arguments. An enumerator whoseCurrentis a public field is supported. A shape that does not map keeps the closed route. -
Per-body facts are computed once, and function literals are lowered once for the flow analyses (issue #5131, part of #2189). The contains-yield answer is cached per bound body, and the definite-assignment and ref-struct liveness analyses share one lowering of each function literal instead of lowering it twice. Output and diagnostics are unchanged; the opt-in
GSHARP_MEASURE_PHASESreport addsbodyfacts.*counters. -
Bounded native protocol core (issue #5182, ADR-0205). Contextual nongeneric method-only
protocoldeclarations support checked owned class/struct conformance, exact accessible instance/by-value extension witnesses, target-typed insertion, paired capabilityis/asand original payload recovery. Concrete structs copy once into mutable saved storage; protocol assignment/views retain that entry, while independent insertion and concrete extraction copy. Canonical finite implementation/reference metadata carries symbolic targets/nullability and typed public contracts; unknown/conflicting evidence and invalid presence diagnose or fail explicit boundaries. Rich/generic/ref slots, enums, typed nil, managed projections, equality/object/generic escapes, general foreign export and Go admission remain blocked. The published pin is unchanged. Finite conformance also governs overload applicability; recursive generic storage analysis terminates without changing ordinary code. Nested native pattern inputs, native-bearing auto-properties/data-primary properties and imported native constructors require separately admitted boundaries. Native-storage aggregate equality/hash and payload-recovery escapes remain blocked; public container/property contracts and imported accessors are checked. Native dependencies survive annotated imported arrays and named delegate signatures; delegate/generic admission, safe casts, binding patterns, equality/hash method groups and lifted/imported operators enforce transitive storage restrictions. Public witness owners must be accessible. Fixed-array slot positions diagnose until their implementation/reference contract preserves the length. Whole-compilation finite insertion planning removes overload binding-order dependence, including imported overloads and top-level calls. Incidental unexportable capabilities remain unknown without discarding valid internal entries. Native-bearing throw transport is gated; imported operators require member-level contracts. Nominal interface static native fields carry the owning-type storage marker. Rejected overload probes do not contribute insertion coverage. Native compilations bypass global/body caches pending coherent synthesis replay. Imported optional parameters preserve presence; uninitialized interface fields receive storage/access checks. Distinct nominal storage identity, abstract member markers and static-field nullability preserve implementation/ref nominal dispatch. Body-local negative probes no longer mutate shared operation method tables during coverage planning. Bodyless nominal methods/accessors receive declaration validation and accessor feature markers preserve valid implementation/ref calls. -
Imported function-pointer fields keep their CLR signature (issue #5260). Assignments from matching source signatures now compile. Import and member-reference emission preserve calling conventions, pointer types, and native integers, including signatures on generic receivers and inside array-valued generic arguments. Overload checks, override matching, and named tuples preserve nested signatures. Managed function-pointer signatures also keep nullable reference annotations. Byref signature readers retain pointee annotations without making nested generic arguments nullable. Tuple-name metadata traverses pointer children and function-pointer returns before parameters, so later named tuple elements keep their positions across assembly boundaries.
-
Imported function-pointer signatures survive ref indexers, events, and async overrides (issue #5260). Signature readers retain modified CLR metadata and receiver substitutions. Override checks also distinguish pointer-wrapped signatures and calling conventions.
-
Imported CLR event overrides retain nested function-pointer signatures (issue #5260). Override matching reads modified accessor metadata for closed and symbolic receivers.
-
Imported CLR tuple overrides use structural signature matching (issue #5260). Tuple shapes retain nested function-pointer conventions, symbolic elements, and fixed-array lengths.
-
Reflection probes no longer use exceptions as the not-applicable answer (issue #5123, part of #2189). Probes that asked
System.Typequestions aTypeBuilderInstantiationor aMetadataLoadContextmethod cannot answer (GetMethod,GetMethods,GetInterfaces,IsEnum,IsByRefLike,IsAssignableFrom,GetBaseDefinition,TypeBuilder.GetMethod, andMakeGenericTypeacross reflection contexts) now test the condition first; thecatchstays as the last resort. A Core compile raised 4,791 first-chance exceptions before and 84 after (46 of them the unresolved transitive references and unloadable forwarded types of the reference set). Implementation, PDB, reference assembly, XML documentation and diagnostics are byte-identical. -
The remaining first-chance exceptions of a Core compile are gone (issue #5157, part of #2189). Inference bounds, method slots, member enumeration over a type still being defined, unresolved transitive references, the control flow graph of an unflattened function-literal body and
IsByRefLikeover an emit array type now test the condition before asking; thecatchstays as the last resort. A Core compile raises 0 first-chance exceptions, down from 71 on the previous commit. One observable difference: two inference bounds where one is a generic instantiation of a type still being defined are compared by the by-name classifier instead of dropping the candidate. Implementation, PDB, reference assembly, XML documentation and diagnostics of the Core compile are byte-identical. -
Smaller batch-path costs removed (issue #5121, part of #2189).
gscno longer walks every function body to decide whether it could be cached when there is no body cache (9,222 walks on the Core compile, 11,839 on Core.Tests; the language server still walks).BoundProgramOrder.Functionssorts a program's function map once per program instead of on every call (15 sorts to 5 on the Core compile). Sequence-point emission reads each location's lines and characters with two line lookups instead of six. PDB, reference assembly, XML documentation and diagnostics are unchanged, and the implementation DLL differs only in checksum, MVID and debug-directory bytes. The enum-kind arrays inSyntaxFactsand theGetDeclared*memoization listed in the issue were dropped: the first has no compiler caller and the second is called once per compile. -
The reference type-name index is read from metadata names (issue #5124, part of #2189). The resolver builds its full-name index from each reference's type-definition and exported-type tables instead of creating every type with
GetTypes()andGetForwardedTypes(), and creates aTypeonly when a name is looked up. The names, their order and the first-declarer rule are the ones reflection reported: a forwarded type is listed only when its target assembly supplies it, followed by its public nested types, and an image whose names would need reflection escaping is read through reflection as before. Thereferences.type-name-indexphase dropped from 135 ms to 17 ms on a hello-world compile and from 189 ms to 12.5 ms on the Core compile, with identical implementation, PDB, reference assembly and XML output and identical diagnostics. The language server's persisted index uses the same reader. Reading a persisted index ingscwas measured and not adopted: fingerprinting the images costs more than the new walk. -
Imported extension holders are indexed once per reference set (issue #5122, part of #2189). The reference assemblies are enumerated once per resolver instead of once per binder context, and each imported namespace is probed for static
[Extension]classes lazily, once, so only types in imported namespaces are inspected. Results keep the old reference-set order, and accessibility is re-applied for the current assembly on every lookup, so internal and friend-assembly rules are unchanged. On the Core compile thereferences.extension-holdersphase dropped from 812 openings (409.8 ms) to 1 (1.1 ms), with identical PDB, reference assembly and XML output. -
Imported member signatures are decoded once (issue #5125, part of #2189). The compiler keeps the decoded type of each imported property, field, method return and parameter for the life of the reflected member, one entry per nullability mode. Repeated lookups no longer rebuild the symbol and its nullability wrapper, and
metadata.contract-requestsonGSharp.Corefalls from 101,595 to 29,461. A newmetadata.signature-cache-hitscounter reports the reuse inGSHARP_MEASURE_PHASESoutput. Compiler output is unchanged. -
Equal imported generic constructions are shared, so emitted metadata has fewer duplicate rows (issue #5158, part of #2189).
ImportedTypeSymbol.GetConstructedreturns one instance for the same erased type, open definition and argument symbols, held in weak tables that never outlive a reference set or an argument. The emitter's symbol-keyed token caches now hit for equal constructions, soGSharp.Core.dllhas 137 fewerMemberRefrows (28,339 to 28,202) and 153 fewerTypeSpecrows (25,780 to 25,627); every removed row repeated a signature that stays in the table, and the order of the distinct signatures is unchanged. The lambda binder skips its erased adapter when the literal's parameter and return types are the same objects as the target's, and equal constructions now are, so 29 of the 44<lambda_erasedN>closure types of the Core compile are plain<lambdaN>closures with identical method bodies, and the synthetic lambda numbers after the first of them shift down by one each time. The program behaves the same, but the PDB, reference assembly and implementation DLL of a rebuild differ from those of the previous release, so anyone who diffs or hashes binaries should expect a one-time change. Output stays deterministic. A Core compile allocates about 60 MiB (0.5%) less.Binder.SubstituteTypeis not memoized: on the Core compile 267 of 17,232 calls reach its imported-generic branch, so a memo would save under 200 calls. -
Published 0.5 website snapshot (issues #5082, #5084). The default documentation and downloads target v0.5.212, with release-grounded guidance for native slices, platform nullability, SDK projects and editor tooling. Released scalar/code-point APIs are included; Next retains only post-tag changes; 0.4/0.3 snapshots and original archives remain unchanged. Original 0.4.591 editor captures are explicitly historical, while current examples execute independently with the published SDK. Downloads use canonical LF payloads, a fixed ZIP creator OS and relative POSIX entry ordering; cross-host regression checks cover Windows/POSIX defaults. Release-reference checks retain mandatory current references and hash-check authentic historical evidence. The sample hashing and standalone verifier harnesses include the runtime dependencies used by the driver.
-
Faster published compiler start and compile (issue #5120). The published
gsc,gsgenandgsfmtpayloads setTieredPGO=falsein their runtime configuration. The study measured 27.8% lower wall time on the Core compile with byte-identical output. Tiered compilation stays on. -
One effect summary per statement for narrowing (issue #5128). Narrowing invalidation and the callable alias update read one shared bound-tree summary of each statement instead of walking it twice, and the member-mutation check on statement syntax is cached per statement. Narrowing results, diagnostics and emitted output do not change. Opt-in measurements report
narrowing.effect-walksandnarrowing.effect-reuses. -
For-in over generic collections of source types no longer boxes the enumerator (issue #4907, part of #2189).
for x in collover aList,Dictionary,HashSetorImmutableArraywhose type arguments are same-compilation types, type parameters or named tuples now calls the collection's ownGetEnumerator()and drives the nested struct enumerator, as C# does, instead of going throughIEnumerable<T>, which allocated 40 to 48 bytes per loop. Emitted IL changes for these loops only;sequence[T], user collections and other imported collections keep the interface route. The compiler's own loops benefit once the SDK pin moves to a release carrying this change. -
Smart casts join normal branch exit states (Part of #5130; ADR-0208 R2 and R4). Writes and calls in an exiting branch no longer remove facts from the surviving path. Assignments in
switcharms, nested loops, andtrystatements contribute their normal exit facts. A fact survives only when every path reaching the join proves it. Newly proven facts can make a later!!redundant (GS0536). cs2gs omits these assertions in independent switch sections.outarguments use declared storage nullability, so a narrowed nullable slot accepts a nullable result without a false GS0612.refandinkeep their read-side checks. Nested assignment values restore non-null facts, including after a failed dictionary lookup. A later setter callback can still invalidate a captured or aliased local. Assignment replay uses entry callable aliases, and native-map accesses account for hashing callbacks. -
cs2gs: Preserve named-constant
istests and nullable numeric conversions. Enum and named constants test their values, not their types. Object and NaN patterns preserve C# value-equality semantics. Fallback patterns capture receiver and member values at their original evaluation points. Numeric comparisons and lifted conversions preserve values instead of using nullable runtime downcasts (#5675, #5676). -
Nullable list patterns in
cs2gsguard their inputs and preserve branch narrowing (Fixes #5684). Lowered list tests use the boundLengthorCountmember, reject nil before member and index reads, and avoid redundant assertions in matched branches. Strings and nullable switch inputs use guarded captures instead of unsupported native list patterns. Scrutinee getters and calls execute once. Suffix indices reuse the captured length. Element and slice bindings capture values before later getters or body writes. Parenthesized bindings retain the matched input's nullability. Discards do not read indexers. Nullable value matches use one mutable copy without changing the original nullable overload type. Null tests against that copy use its known non-null state. -
cs2gsrecords with a user-declaredDeconstructretain their custom deconstruction behavior (Fixes #5699). Translation keepsdata class/data structequality,with, andToString, renames the conflicting method, and routes deconstruction consumers through selected scalar or tuple adapters instead of reading data members. Adapters preserve nullable signatures and nested selected output types, receiver snapshots, implemented partial-method identity, and typed declaration/foreach conversions. Adapter names remain stable across source documents and repeated translation. Pattern outputs reset for each evaluation and emitted scope. Nested assignments complete extraction and conversion before writing targets. Nested user-record positional patterns, mixed positional/property decisions, and pointer outputs report explicit gaps. Selected extension overloads, renamed source-interface consumers, imported contracts, and metadata-backed migrated-producer consumers also report located translation gaps pending #5844. -
Compound switch guards retain their spill-local declarations (Fixes #5842). Guard-local temporaries receive IL slots when cached pattern outputs feed short-circuit tests, preventing
GS9998during emission. -
Typed
cs2gsforeach deconstruction conversions (Fixes #5700). Typed deconstructing loops now preserve numeric, reference, boxing, nullable, and user-defined conversions, including nested and asynchronous loops. Converted or captured variables bind inside each iteration before the loop body. Emitted conversions participate in loop effect analysis, and captured identity bindings retain translator-widened nullable storage. Inferred and identity-matched targets keep the directfor (a, b) in pairssyntax. -
cs2gspreserves single-precision integer conversions and collision-safe string construction; shared structMainentry points work again (Fixes #5824, Fixes #5826, Fixes #5873). Integer literals converted tofloatorfloat?emit single-precision literals, including decimal, hexadecimal, binary, and long spellings. Folded optional-parameter constants preserve theirfloatordoubleliteral type. CLR string and native-integer constructors use collision-safe import aliases, so sibling methods, properties, fields, locals, parameters, and types cannot shadow the construction target. Alias allocation also excludes visible value names. Entry-point discovery and case-sensitive-name diagnostics share the same package-function and shared class/struct candidate set. Struct entry-point bodies and async stubs remain on their declaring type, preserving private-member and state-machine access. -
Imported oblivious delegate-result contracts (Fixes #5857). cs2gs resolves a lambda's frozen metadata sink before adding result assertions in annotated and oblivious compilations, including user-defined conversion results. Concrete oblivious returns such as
Func<object>accept nullable results through platform types, so successfulMethodInfo.Invokecalls returning nil no longer acquire a throwing!!. Annotated returns, generic type-parameter slots, translated declarations, and explicit delegate casts retain their required checks. -
Indexed maintained narrowing queries (Part of #5130). The immutable flow state shares a path-to-position index across unchanged paths, so repeated reads no longer scan every active fact. Path enumeration retains its deterministic insertion order; a wide-frame work-count control covers the former quadratic lookup behavior.
-
Shared assignment exit postconditions and safe base-call symbol snapshots (Part of #5130; Fixes #5856). Synthesized
??=statements retain their assignment guarantees in the maintained exit state through the same classifier used by persistent frames. The semantic model snapshots nullable base-call method/property symbols before reading receiver types, preserving valid symbols without weakening ordered call invalidation. -
Null-conditional Boolean receiver proofs (Fixes #5849; part of #5130). Equality of
value?.BoolMemberwith a Boolean literal provesvaluenon-nil on the equality path. Early-exit guards, conditional expressions, and short-circuit conditions share this proof. A getter or call that can replace the receiver removes it. The inequality path still includes nil, and unguarded nullable collection elements still reportGS0155. -
ADR-0208 flow-state cleanup and switch-break path indexing (Fixes #5130, Fixes #5841). Narrowing reads use the maintained flow state, including external-callable facts. Legacy
ifjoins, early-exit restoration, pendingif/switchframes, and shadow comparison are retired. Node-keyed statement-effect records compose state-independent children while retaining ordered alias-sensitive classification and deferred cleanup transfers. Each switch indexes its reachable break paths in one traversal instead of walking from the switch root for every break. -
Inferred function values retain optional defaults, nested initializer literals parse in statement headers, and signed
int64minimum literals acceptLsuffixes. Calls through inferred function values substitute declared defaults, including named omissions (#5815). Written function types discard optional defaults; reassignment cannot change an inferred optional contract. Floating-point defaults distinguish positive and negative zero. Callable contracts follow parameter and return variance; writable aliases cannot erase an inferred contract. Array and map initializer bodies admit nested constructor literals without consuming the enclosing loop or condition body (#5864). Decimal-9223372036854775808L, including leading zeros, digit separators and lowercasel, compiles asint64.MinValue; its positive magnitude still reportsGS0004(#5872). -
Loop null constants preserve captured-local narrowing. Intrinsic
cast[T](value)uses the shared conversion-effect classifier instead of counting as an invocation. Null provenance follows null-preserving reference and nullable-value casts, defaults, and region-localconstaliases, but not mutable copies (#5879, #5881). Array-to-string materialization retains equality effects because a null character array becomes an empty string. Straight-line pattern analysis checks the same null-preservation rule. Constant folding checks the original conversion types and reportsGS0376instead of replacing such materialization with nil. Nullable value-type local constants retain their null defaults, including through boxed aliases. Regression tests also protect failed statement-switch guards throughfinally, subsequent guards, and non-lastdefaultarms (#5010). -
Statement-switch guards and non-last
defaultarms preserve external-callable narrowing (Fixes #5891). Header callable-alias updates intersect entry aliases withAliasesAfterafter restoring pre-pattern and pre-guard alias snapshots, so a failed guard that reassigns an external callable keeps captured-local narrowing across subsequent guards, non-lastdefaultarms, and post-switch calls while local-mutating closures still invalidate it.
Bug Fixes
-
Nullable tuple and block consumers after backward jumps (Fixes #5653). Tuple literals capture narrowed reads per element and resolve them for the consumer's target type, including nested tuples and
deferorusingblock values. Nullable destinations accept the declared value; non-null destinations still check a retracted narrowing. Existing tuple conversion classification and ordinary call results remain unchanged. Later conversions preserve committed element checks, and cleanup values keep the result saved before cleanup runs. Top-level statements in multiple files keep the same checks. -
Keep writable pattern destinations separate from narrowed reads in
cs2gs. Invalidate matched-value read proofs after writes, preserve nullable stores and projected storage contracts, and materialize reassigned or address-taken captures, including readonly aliases, exact readonly arguments, and receivers. Constructor writes complete before initializer reads. Guard reads, closures, switch bodies, and lifted recursive local functions share capture storage with matching nullable contracts. Readonly address-exposed captures use readonly reference parameters, not copies; suspending helpers and nested by-reference closures report explicit unsupported diagnostics (#6053). Lifted helpers use their own parameter contracts and local null guards, not outer pattern proofs. (Fixes #5991) -
Keep required
!!assertions incs2gswheregscdrops narrowing on exitedifconditions for by-reference (out/ref/in) parameters andreflocals when the condition contains a call or mutating expression, and on readonly fields after intervening calls or CLR member accesses inside the same&&/||operand, while keeping!!omitted wheregscgenuinely narrows. (Fixes #6124)
0.5.212 (October 22, 2026)
This snapshot is grounded in v0.5.212, commit 242d8777c778db4272103c9dcefd6d63609e10ee, published October 22, 2026 at 01:07:10 UTC. The compiler, language server, formatter and tools are written in G#. This release includes native shared-storage slices, platform nullability, immutable byte strings, explicit UTF-8 text boundaries, lazy scalar iteration and code-point collection conversions. The following entries preserve the tag's complete 0.5 change history.
-
Byte-string code-point collections (issue #5095, ADR-0204).
ByteString.FromCodePointssnapshots a readonly signed-int32slice as UTF-8 with mandatoryCodePointEncoding.StrictorReplaceInvalidCodePoint. Strict failures report appendedByteStringInputKind.CodePointsand the first invalid logical input element index; existingUtf8/Utf16identities are unchanged.DecodeCodePointsreuses scalar decoding and returns independent mutable native slices, including present empty rather than nil results. UTF-8 errors retain byte offsets; replacement consumes one malformed byte. No normalization, implicit conversion, SDK-pin change or Go translation is included. -
Generic member owners preserve swapped arguments (issue #5092). Field and property access through source generic receivers such as
Cursor[B, A]emits verifiable IL without collapsing the arguments. Nested argument types and composed generic base owners retain the receiver's exact construction. -
Source-declared pattern enumerator properties (issue #5088).
for value in sourceaccepts a public readable instanceCurrentproperty on a source-declared enumerator, as it already does for imported enumerators. Generic element types and mutable value-enumerator state are preserved. -
Allocation-free byte-string UTF-8 scalar iteration (issue #5087, ADR-0204).
value.DecodeUtf8Scalars(policy)returns concrete value-typeByteString.Utf8Enumerablewith an independent value enumerator. EachUtf8Itemreports its scalar value, relative byte offset and consumed byte length. Strict iteration is lazy and repeats failures at the same sequence start; replacement advances exactly one malformed byte. Logical substring bounds, BOM, embedded NUL and non-BMP scalars are preserved. Eager decoding shares the scalar decision without per-scalar strings. This scalar API ships in 0.5.212; Go translation remains deferred. -
Explicit byte-string UTF-8 text boundaries (issue #5080, ADR-0204).
ByteString.EncodeUtf8andDecodeUtf8require explicit strict or replacement policies. Strict failures reportByteStringEncodingException.InputKind(Utf8/Utf16) and the first malformed sequence's byte offset or unpaired surrogate's code-unit offset. Offsets are relative to the input value, including substrings. Replacement decoding advances exactly one invalid byte; replacement encoding handles each unpaired code unit. No implicit conversion, normalization or BOM insertion/stripping occurs. This text-boundary API ships in 0.5.212. -
Immutable arbitrary-byte strings (issue #5068, ADR-0204). Native
bytestringnamesGsharp.Values.ByteString;b"\xFF\0"preserves exact bytes without changing CLRstring. The core provides content equality/hash/order, byte indexing and ranges, pattern-based byte iteration, bytewise search/concatenation, copying mutable boundaries and explicit compactDetach(). Empty defaults are present values, distinct from nullablenil. Dollar signs in byte literals are data, not interpolation. Literal evaluation reuses private storage after initialization; formatting, hovers, completion and the code-model printer preserve byte semantics. Missing runtime support reports GS0627 and invalid literal/source encoding reports GS0628. This byte-string core ships in 0.5.212; the repository bootstrap pin remains 0.5.199. -
CLR overload applicability reuses local raw parameter arrays (issue #5071, ADR-0203). Normal-form preparation retains its raw declaration parameters, while closed generic candidates still read their substituted signatures. Expanded applicability normalizes the ABI-only count against its own parameter vector. Inference, constraints, callbacks and fallback order remain separate between forms. This is a small reflection-work reduction, not a demonstrated compiler throughput improvement.
-
Imported metadata readers reuse raw declaration facts (issue #5070, ADR-0203). Open-member token lookups and raw nullable/context attribute decoding share weak, actual-reflection-object caches. Receiver-specific nullability, module identity and direct versus signature-filtered load behavior remain unchanged. Failed attribute reads remain retryable, and host generic definitions do not retain private reference contexts. Fixed Core/Oahu.Core profiles reduced definition scans from 47,484/3,724 to 389/96 with identical emitted bytes and diagnostics. Direct compiler median times were 40.952 → 41.940 seconds for Core and 4.385 → 3.950 seconds for Oahu.Core, with overlapping ranges; no general throughput improvement is claimed.
-
The repository compiler uses published SDK 0.5.212 (issue #2189). The bootstrap pin and matching analyzer-testing package move from 0.5.199 to the ordinary managed release. Five matched fresh-output builds of the complete Linux solution reduced median wall time from 267.42 to 164.22 seconds on the same source and host. This is a measured workload result, not a universal speed guarantee. Experimental NativeAOT and ReadyToRun toolchains remain separate. The pin PR's green CI provides N-1 stage-2 verification.
-
The repository compiler uses published SDK 0.5.199 (issue #2189). The bootstrap pin and matching analyzer-testing package move from 0.5.179 to the new release. This pin update uses the ordinary managed SDK; experimental NativeAOT and ReadyToRun toolchains remain outside the published package and await human review. The separate pin PR's CI provides N-1 stage-2 verification.
-
SDK packaging reuses equivalent repository build graphs (issue #5103). Compiler, formatter and generator payloads publish from their normal MSBuild reference instances into separate staging directories. Incompatible publish settings keep isolated build outputs. Repository builds track tool contents before reusing compiled outputs. The package layout and the source-built compiler for the netstandard task remain unchanged.
-
The compiler now builds with the published G# SDK 0.5.179 (issue #2189). The bootstrap pin moves from 0.5.7 to the release containing the measured compiler lookup, generator setup and bounded-worker improvements. The analyzer-testing package follows the same pin. This separate pin update builds the repository with that released compiler; its CI provides stage-2 verification under the N-1 rule.
-
Declaration discovery skips impossible anonymous-object walks (issue #5055, ADR-0203). Parsing records whether each source tree can contain an anonymous object. Generator projection and compilation avoid the full-tree rich-anonymous declaration search for other trees, while keeping the existing synthesis order where needed. Core profiles eliminated 700 walks per declaration pass and reduced projection/declaration allocations by 667/410 MiB; the three-pair compiler and Oahu rebuild comparison did not demonstrate a build-speed gain. Declaration scopes remain request-owned, and generated partials still bind afresh; generator execution, diagnostics and SDK success stamps are unchanged.
-
Generated-document translation avoids metadata-only name scans (issue #5054, ADR-0203).
gsgenreuses the active Roslyn semantic model when reserving imports. Source-name collision checks visit source-bearing assemblies instead of traversing every metadata type. Globally visible source references, aliases, nullable types and generated partial declarations retain their existing spellings. The request stays sequential and uses no new cache. -
Body binding reuses canonical declaration readers (issue #5056, ADR-0203). Immutable alias and struct snapshots avoid rebuilding the declaration universe for repeated body lookups while invalidating ancestor declarations and alias overrides. Opt-in body workers also accept proven scalar string/character and source-enum switches. Receivers, calls, inferred signatures and shared synthesis retain their coordinated path and the existing request budget.
-
Definite-assignment analysis reuses region-local scratch sets (issue #5104). Fixed-point probes recycle unpublished entry and exit storage instead of allocating a new set for every block simulation and predecessor intersection. Nested regions borrow read-only input states. Published states, conditional edges, convergence and diagnostic order remain unchanged; no compiler throughput improvement is claimed.
-
File and stream emission share preparation (issue #5069, ADR-0203). Both entry points use the same diagnostic aggregation, documentation validation and ordered lowering pipeline for each invocation. Destination handling, staged publication and implementation/reference output remain separate. This is a maintenance refactor, not a build-speed improvement; the CLI already lowers once for implementation and reference output.
-
Bounded method-local lowering and instruction emission (issue #5042, ADR-0203). Opt-in compiler workers can lower noncapturing primitive lambdas and emit primitive/local method instructions into independent buffers. Cross-body discovery, metadata, generic remaps and PDB publication remain ordered; unknown or metadata-dependent bodies keep the sequential path. The existing shared worker and memory budget applies. Measurements now separate discovery, method instructions, implementation/reference output, PDB construction and PE serialization.
-
Opt-in bounded compiler workers (issue #5041, ADR-0203).
GSharpMaxWorkers(default 1) requests one MSBuild core grant shared across compiler phases and reusable requests; unsupported hosts stay sequential. File parsing and proven primitive/local bodies run independently, then publish results and diagnostics in their established order. Inferred signatures and shared synthesis remain coordinator-owned.GSharpWorkerMemoryBudgetMiBbounds workspace concurrency estimates, not the total process heap. Direct compiler users can select--workers:Nand--worker-memory-mib:N. Other bodies remain sequential; no general workload speedup is promised. -
Candidate lookup indexes and opt-in compiler measurements (issue #5040). Alias collision and unknown-arity nested lookup use name/arity and canonical-owner candidate buckets instead of scanning every alias. Imported extension metadata and record-shape classification reuse context-sensitive indexes, including negative results. Persisted reference indexes reject changed reference contents even when assembly identities match. Set
GSHARP_MEASURE_PHASESto a JSON path for nested phase timings, process counters, and input/cache metrics without changing diagnostics. -
Ordered visible imports share source-tree views (issue #5105, ADR-0203). Ordinary import lookup reuses binding-pass-owned indexes instead of filtering every file's imports at each reference. Empty lexical scopes share ancestor views, and import additions invalidate descendant snapshots. Historical scopes retain import segments; only requested scopes cache flattened views. File isolation, ancestor order, alias precedence, implicit fallback and ambiguity diagnostics remain unchanged. Five-pair fresh-process compiler replays reduced Core/Core.Tests median times from 35.44/71.48 seconds to 25.99/25.20 seconds with exact output parity. Peak RSS medians and separate single-sample process allocations were slightly higher. These two fixed workloads do not establish a full-solution build speedup.
-
Inferred-type hints match G# declaration syntax. Visual Studio and VS Code now show
FakeRunnerrather than: FakeRunnerafter an inferred local's name. Parameter-name hints such asexitCode:are unchanged. -
Indexed member values keep their hover and navigation targets (issue #5035). Hover and go-to-definition now follow the compiler's bound member through indexing, including source properties and fields, CLR members, and
List[T], array and string values.runner.Calls[0]andcall.Args[0]no longer lose their property hovers or source definitions. An indexed method result such asuri.ToString()[0]shows the method on its bound receiver instead of an unrelated same-named method. Index arguments still resolve to their own locals. -
Suspending
for … inloops dispose their enumerators (issue #5037). Loop cleanup now survivesyieldandawait: exhaustion, early consumer disposal,break,return, and exceptions release acquired disposable enumerators. Nested iterator cleanup runs inside-out even when an inner enumerator'sDisposethrows. -
Synchronous iterators reuse their first enumerator (issue #5102). An unused sequence returns its own state machine for the first enumeration on its creating thread. Later or cross-thread enumerations create independent frames from the original captured arguments and value receiver. Direct
IEnumeratorreturns remain ready forMoveNextwithout acquiring an enumerator. Iterator bodies remain deferred, and replay and disposal behavior are unchanged. Async iterators and local-field compaction are unchanged; this removes one frame allocation in the eligible path, not a demonstrated compiler-throughput improvement. -
Bounded compiler reuse is opt-in (issue #5038).
GSharpUseSharedCompilationreuses one serial compiler worker per MSBuild node and build. Requests isolate input paths, options, environment, and reference contexts. Workers retire by request count, idle time, or memory. Transport failures are explicit; compiler failures are never retried. Imported generic symbols no longer retain private metadata contexts through a host assembly's cache bucket. -
Generator discovery and setup avoid repeated work (issue #5039).
gsgendiscovers actual generators before loading G# sources or projecting declarations. Generator and foreign C# translation share metadata references, and back-translation reuses immutable Roslyn input and generated syntax trees. Opt-in bounded build workers reuse host code and content-validated metadata while loading fresh generators for every request. Empty manifests never bypass generation or diagnostics. Generator input descriptors and task-validated success stamps preserve no-op builds while invalidating changed options, metadata, and item membership; diagnostic errors remain visible on repeated builds, and removing the final source and analyzer deletes stale generated parts. Opt-in phase reports separate discovery, setup, projection, execution, translation, and output. -
Body-only edits preserve imported types in the language server (issue #5025). Incremental binding now moves each explicit import and alias to the edited file's current syntax tree along with its member declarations. Repeated edits no longer lose per-file namespace context, degrade inferred local hovers to
?, or introduce false missing-type/function diagnostics. This also fixes the same failure when VS Code opens unchanged text with a lowercase, encoded Windows drive URI. -
Local hovers work when a file opens before workspace discovery finishes (issue #5024). The language server now replaces the standalone document tree with its owning project's matching tree after discovery, preserving unsaved buffer text. Local declarations and references resolve without reopening the file or making another edit, including after a server restart with the file open. Watcher refreshes preserve regenerated project source when an older generated document remains open.
-
Stepping over a handled exception reaches the catch body instead of an earlier source line (issue #5014). Structural
trywrappers no longer replace the first statement's debug location, and catch/filter setup is marked as hidden compiler-generated code. This fixes the jump to the first top-level statement in Visual Studio and VS Code, while preserving source locations in ordinary functions and finally bodies. -
Test Explorer keeps loose-file tests and project tests visible (issue #5013). An open file without a project caused test discovery to throw a
NullReferenceExceptionand return no tests. Discovery now preserves nullable project metadata for loose files. It also matches open document URIs to file paths, so a buffer opened before project discovery replaces its disk snapshot instead of appearing as a duplicate loose test. -
A G# library's nullable annotations now reach its consumers from every kind of member (issue #4988). A member compiled without a method body lost the nullability of its return type in metadata, so a separately compiled consumer saw
Task[Token]for an interface method declaredfunc LoadAsync() Task[Token?];, typedawait store.LoadAsync()as non-null and reported a spurious GS0536 on its!!. The same loss affected abstractsharedinterface methods, a delegate'sInvoke, auto-property getters and setters, theadd/removeaccessors of field-like events, interface properties, events and indexers, and a data class'sDeconstruct. gsc now writes the same nullability metadata for a signature whichever way it was declared, and it matches what csc writes for the equivalent C#, including for netstandard2.0 libraries. A data class's==and!=now takeT?operands, like a C# record's. A consumer that depended on the lost annotations can now get nullability diagnostics it did not get before. -
Breaking: statement
if letnow has the same header as theif letexpression (issue #4961, ADR-0201).if let text = value && text.Length > 0 { … }reported GS0157 ("Cannot find type text"): the statement form folded the&&into the initializer, so the guard referencedtextoutside its scope. The statement and expression forms now share one header. A top-level&&after the last binding starts an optionalboolguard. Bindings are evaluated left to right and stop at the firstnil, so later initializers and the guard don't run; the statement form used to evaluate every initializer before testing any of them. A later initializer sees earlier bindings at their non-null type (if let a = s, let n = Len(a)reported GS0154). A statement with more than one binding and anelsewhose arms bothreturnno longer reports GS0100 ("Not all code paths return a value"). The bound names are visible in later initializers, the guard and the then-block only. In both forms the then-block now sees the guard as anifbranch sees its condition:&& o != nilnarrowso, and&& o is string tputstin scope (the expression form reported GS0159 and GS0532 for these). Every initializer ends at a top-level&&or||;??and?:initializers still work, and a?:initializer now also parses in the expression form. Compatibility: a statement initializer such asif let v = a && b ? x : yused to bind the whole conditional. It now reports GS0624; writeif let v = (a && b ? x : y)to keep the old meaning. Nullable assignment or conditional conversion can also hide the boolean: withcached bool?,if let v = cached = a && bnow reports GS0624 rather than silently changing the stored value and body execution. Parenthesize the entire initializer to preserve its meaning, or the prefix assignment/conditional to make the new guard explicit. Hover, go-to-definition and references now resolve anif letbinding in either form, including its uses in later initializers and the guard; before, they resolved nothing, or a same-named outer local. New diagnostics: GS0624 (an ambiguous initializer/guard boundary, including nullable conversions), GS0625 (guard letandwhile letdon't accept a guard yet, #4968; they reported GS0157 before) and GS0626 (a top-level||after the bindings). -
An
ifexpression accepts the sameif init; condinitializer as theifstatement (issue #4962, ADR-0064).let s = if var v = g(); v > 3 { "big ${v}" } else { "small ${v}" }reported a spurious GS0276 and a series of GS0005 errors, and so did a trailingif var v = g(); v > 3 { … } else { … }at the end of an arrow-lambda block body, even though the sameifcompiled as a statement. Both forms now read the header the same way. The initializer runs once, before the condition. What it declares is visible in the condition, in both branches and in everyelse iflink, and not after theif. gsfmt also keeps anif init; condheader on one line in both forms; it used to put a line break after the;. -
Hot reload calls
MetadataUpdateHandlercallbacks after each applied update (issue #4960). Underdotnet watch, G# applied method-body updates to the running process but never called the application's[assembly: MetadataUpdateHandler(typeof(T))]handlers. A UI framework that redraws fromUpdateApplicationtherefore kept showing old output until another event triggered a redraw. This affects every release with G# hot reload, including 0.4. Handlers now run as they do for C# underdotnet watch. EveryClearCacheruns before anyUpdateApplication, and handlers in referenced assemblies run before those of the assemblies that reference them. Each callback receives the changed types in update order, each type once: the type of each edited method and the types that contain it. A handler that throws, or one whose methods do not have the staticvoid (Type[]?)shape, is reported asGSHR1005, and the other handlers still run. -
The language server reports the member the compiler bound for a call on a narrowed or interface-typed receiver (issue #4989). After
guard let s = store, wherestoreis declaredIStore?and assigned a different implementation on each branch, hoverings.LoadAsync()could show one implementation's method (for examplefunc (KeychainTokenStore) LoadAsync()) when the interface came from a referenced assembly and that implementation'sLoadAsyncwas called elsewhere in the program. With the interface declared in source, hover and go-to-definition on the call showed nothing, and hoveringsshowed nothing either. Hover, go-to-definition, find references, signature help, semantic tokens and member completion now use the member and receiver type the compiler bound, sos.LoadAsync()isIStore.LoadAsync. The compiler itself was already correct, in 0.4.1270 too:sreads asIStore, and calling a member that only one implementation declares reports GS0159. Hovering the binding still shows its storage type,IStore?. -
Blocks, arrow bodies and
switchfollow one rule for their last item (issues #4963, #4965, #4966, ADR-0202). A value block can now end inthrow,return,breakorcontinue:let a = if c { 1 } else { return 0 }andlet v int32 = { log("x") throw e }compile, and such a branch takes the other branch's type. A switch expression can be the last item of a block, an if-branch or a lambda body, and aswitchwith:arms also works as a statement.case 1, 2:works in switch expressions, not only in switch statements.func f() T -> { … }takes the same block body a lambda does, soreturnstatements and a body ending inforwork. A void arrow body accepts anifwithoutelseand a switch with void arms (set -> if value > 0 { n = value }), and so does a lambda whose value is discarded.(c) -> { if c { return 1 } else { return 2 } }and a void lambda ending inif c { list.Remove(x) } else { list.Clear() }compile. A void switch, like a switch statement, needs nodefault.let a = throw ereports GS0124 instead of crashing the compiler. Compatibility: a lambda body whose last item is a nested{ … }or anif let … else …now returns that block's value, as a lambda ending in a plainif … else …already did; this can change an inferred lambda type (anAction/Funcoverload choice) when that value is not void. End the lambda withreturnto keep it void. -
??=is an expression, like every other assignment operator (issue #4967, ADR-0072 amendment).let r = (x ??= y),f(x ??= y),return x ??= y,x = y ??= zand the right-associative chaina ??= b ??= cused to fail to parse (GS0005);=, the compound operators and++/--already worked in those positions. The value is the left operand's final value: the value it already held, or the assigned value of the right side. When the right side is known non-nil its type is the target's underlying type, as in C#, soint32? ??= 42is anint32andstring? ??= "x"is astring; a right side that can be nil, including an unannotated (T!) value, keepsT?. The target's receiver and indices are still evaluated once and the right side only when the target is nil. Existing??=statements keep their lowering and narrowing, with the receiver-storage correction below. -
??=writes through struct receivers instead of losing the update in a copy (issue #5005). Both positions now update an array element (a[i].F ??= v), a nested field (h.Outer.Inner.F ??= v) or a property on that storage in place, including CLR fields across REPL submissions. The shared capture saves only reference owners and indices; a right side that awaits and reassigns those variables still writes to the original location, without a byref state-machine field. Receiver null and bounds checks still precede indexer-argument side effects. Read-only struct receivers and struct temporaries now report the same assignment diagnostics as=instead of writing a discarded copy. Smart-cast boxed struct receivers report GS0499 instead of emitting an invalid write. -
The conditional operator
?:narrows its branches like theifexpression (issue #4964).s != nil ? s.Length : 0,s == nil ? 0 : s.Length,(s != nil && t != nil) ? s.Length + t.Length : 0and(o is string) ? o.Length : 0reported GS0158 (Cannot find member Length), while the same code written asif s != nil { s.Length } else { 0 }compiled. A?:branch now sees the same nil-guard and type-test narrowing as the matchingif-expression branch, through!,&&,||, nullable value types (int32?) and platform types (T!). 0.4.1270 rejected these too, so this is not a regression. Because a narrowed branch has the narrowed type, a ternary that reads the guarded value can now have a narrower result type, as theifexpression already had: withn int32?,n != nil ? n : 0isint32rather thanint32?, which can change an inferredlet/vartype or the overload chosen for an argument. To keep the nullable type, state it (let r int32? = n != nil ? n : 0). A!!on a value the condition already proved non-nil, such ass != nil ? s!!.Length : 0, now reports the GS0536 redundant-assertion warning, as it does in anifbranch; remove the!!.Nullable<T>members keep working on the guarded value, in every narrowing form:n != nil ? n.Value : 0,n.HasValueandn.GetValueOrDefault()bind against theNullable<T>storage when the narrowed type has no member of that name, and now also compile after anif n != nilstatement or early return, where they used to report GS0158. A member the narrowed type has itself (a struct's ownValue) still binds to it.ValueandHasValuealso bind on a nullable same-compilation struct or enum (issue #4986). In an expression-tree lambda,(v int32?) -> v != nil ? v + 1 : 0used to compile and then throw when the tree was built; it now reports GS0473, as theifform does (issue #4974; write(v ?? -1) + 1). -
Calling a narrowed nullable function pointer no longer crashes (issue #4943). After a nil check (
if fn != nil { fn() }, an earlyreturn,if let fn = … { fn() },guard let), calling a(unmanaged[CC] () -> R)?local or parameter emittedcallion itsNullable<nint>storage instead of the address, so the call jumped to a garbage address and the process died with SIGSEGV. This happened since function pointers were introduced, so it is not a 0.4 regression. The call path now builds the narrowed callee through the same unwrap as every other narrowed read. A narrowed nullable function-pointer field also becomes callable, asFp(),this.Fp()orh.Fp();this.Fp()andh.Fp()reported GS0159 before. GS0536's advice to drop the redundant!!fromfn!!()is now safe to follow. The emitter now reports an internal error (GS9998) instead of emitting a narrowed value-type nullable read that skipped its unwrap. -
cast[T]converts an address to a raw function pointer, andas/isagainst a function-pointer type work again (issue #4938).cast[unmanaged[Cdecl] () -> int32](address)reported GS0125 / GS0130: the look-ahead that decides whethername[...]is a generic call did not recognise theunmanaged[CC] (T) -> Rclause, socast[...]parsed as an indexer. It now parses with or without[CC], with pointer parameters (unmanaged[Cdecl] (nint, *uint8) -> nint), and as a pointer target (cast[*uint8](address)); the calledcast[T](x)no longer reports GS0521, which still applies to every other generic argument list.[]unmanaged[Cdecl] () -> int32also parses as an array of function pointers (it readunmanagedas the element's type name). Separately,address as (unmanaged[CC] () -> R)?compiled but always returned nil,x is unmanaged[…]was always false andcase f is unmanaged[…]never matched, since v0.4.1270 and in every 0.5.x: issue #4685 made the type-test opcodes name the function pointer's FNPTR type, which no boxed value is an instance of. They nameSystem.IntPtragain, the behaviour of 0.4.1150, soasfrom anintyields the pointer (ADR-0095, amendment for #4938). Arrays of function pointers keep their exact FNPTR element type. -
The language server now ships MessagePack 2.5.307, which fixes GHSA-qhrr-8q5h-9q3h (issue #4941; "Nested arrays can blow past buffer length limits", moderate severity, patched in 2.5.303). The language server (and the REPL, which references it) reaches MessagePack through StreamJsonRpc, whose dependency floor is below the patched version, so the repository pins it in
build/gsharp.build.propsand in the isolatedsrc/vs-gsharp/test/VsGsharp.UnitTestsproject. Before the bump, NuGetAudit failed every restore of a project that pulled in 2.5.301 withNU1902(warnings are errors). The pin stays on the 2.5 line that StreamJsonRpc 2.22.x is built against. -
gsc embeds its own
NullableAttribute/NullableContextAttributefor netstandard2.0 and .NET Framework targets, and no longer references the build host'sSystem.Private.CoreLib(issues #4921 and #4922). Compiling for a target whose framework publishes neither attribute resolved them through the host-runtime fallback and emitted TypeRefs scoped toSystem.Private.CoreLib, an assembly that does not exist on .NET Framework, so the SDK task assembly built by gsc could not load under Visual Studio's MSBuild. Such outputs now carryinternalcopies of both attributes (plusMicrosoft.CodeAnalysis.EmbeddedAttribute) in the assembly, as csc emits, and nullability metadata is stamped against them, so it round-trips for consumers of netstandard2.0 libraries. A copy the project declares itself, or one a referenced framework publishes, is used instead.src/Sdk/Gsharp.NET.Sdkis now compiled by thegscbuilt from the same commit rather than the pinned bootstrap SDK, so a release ships a cleantools/task/Gsharp.NET.Sdk.dllwithout waiting for a second release;build/check-netstandard-host-refs.pyfails thebuildjob if the packed task assembly references anySystem.Private.*assembly. -
A netstandard2.0 / .NET Framework compilation binds only to members its target framework declares (issue #4924). Instance calls on a predefined type (
string,object,int32, ...) enumerated the build host'sSystem.Private.CoreLibtype, sos.Split(',')in the netstandard2.0 SDK task bound toSplit(char, StringSplitOptions), which .NET Framework does not have, and Visual Studio's MSBuild failed every G# build withMissingMethodException(released in 0.5.6). Member lookup on a receiver now goes through the target's declaration (ReferenceResolver.TryGetMemberLookupType, also used for staticstring.Xaccess), so the call bindsSplit(params char[]); a receiver whose type the downlevel target does not declare at all (a host type a dependency's signature pulled in, such asSystem.DateOnly) reports GS0546 instead of binding the host's members. For a downlevel target the resolver also no longer adds the host's BCL assemblies to what binding can name, so a host-only extension such asMemoryExtensions.ContainsorCollectionExtensions.TryAddis no longer bound (and referenced fromSystem.Private.CoreLib); such calls now report GS0159, as with csc. Code that relied on a host-only overload must use one netstandard2.0 has, and a netstandard2.0String.Splitresult is[]!string!(an oblivious array) like any other unannotated netstandard2.0 member.build/check-netstandard-member-refs.pynow fails thebuildjob if any TypeRef or MemberRef of the packed task assembly does not resolve on its netstandard2.0 reference surface, and a newdesktop-msbuild-sdk-smokejob buildsInternalAnalyzers.gsprojwith Visual Studio's MSBuild against the SDK package from the same build; publishing requires it. -
Design decision:
data class/data structwill synthesize the C# record ABI (ADR-0199, issue #3501). Planned breaking change:ToStringadopts the C# record format (Point { X = 3, Y = 4 }) in place ofPoint(X=3, Y=4), every data type implementsIEquatable<T>, declared data classes and structs getPrintMembers, and cs2gs stops emitting the@__Cs2GsRecordProvenance_4828marker. This entry records the accepted design; the behavior ships in follow-up PRs. -
cs2gs migrate --stop-after <stage>(issue #4853, parent #3501). Runs the stages up to and includingtranslate,compile,ilverifyortest-parity(the default).--stop-after compilestill performs the redundant-!!polish and writes the migrated tree, so a cut-over rehearsal no longer pays for test parity. A run that stops beforetest-parityrecords its passing apps as unverified (not green) and prints a partial-run line.--translate-onlyselects the same stages as--stop-after translatebut keeps its own reporting: it does not mark apps unverified, because the nightly pairs it withcs2gs validateshards. -
The
@__Cs2GsRecordProvenance_4828marker is removed (ADR-0199 seam a, issues #3501, #4828). cs2gs no longer tags translated records and gsc no longer recognizes the name, so it is an ordinary unknown annotation. A translated body-only record now keeps G#'s ownDeconstruct(fields, then auto properties), like a hand-writtendata class. The Core public-API snapshot allows exactly those ten recordDeconstructadditions throughgsharp-core-public-api-allowed-additions.txt; any other addition still fails. -
Breaking:
data class/data structprint and compare like a C#record(ADR-0199, issue #3501).ToStringnow renders the C# record format,Point { X = 3, Y = 4 }(Empty { }when there are no members), instead ofPoint(X=3, Y=4). Values use the current culture, as in C#, so afloat64prints1,5underde-DE; the old invariant-culture rule is gone. Only public fields and readable public properties print, in declaration order, and members inherited from a data base now appear. Every declared data type synthesizes the recordPrintMembers(StringBuilder)slot (private on a sealed type that starts it, otherwiseprotected virtual), and a hand-writtenPrintMembersof the compatible shape replaces it (GS0623 rejects any other shape). Every data type, including the backing type of adata objectorobjectliteral, now implementsIEquatable<Self>. Anonymous literals print as{ Name = David, Count = 2 }with no type name and get noPrintMembers, copy constructor or clone. cs2gs no longer generates aPrintMembersmethod for a translated record and its test-name parity no longer rewrites record spellings. -
Data-type documentation now describes the C# record ABI (ADR-0199 seam c, issue #3501). The language spec, the data-types tour page and the ADR-0029 diagnostics text describe the record
ToStringformat, current-culture formatting, implicitIEquatable<T>,PrintMembersand GS0623; ADR-0029, ADR-0146 item 6 and ADR-0157 carry supersession notes, and ADR-0199 is Accepted. Known gaps are tracked in #4874 (cs2gs duplicates a base parameter repeated by a derived positional record), #4876 (GS0387 over an abstractPrintMembers), #4877 (imported non-data intermediary hides the inherited slot) and #4879 (cs2gs-translated C# anonymous types print their generated type name). -
cs2gs migrate mirrors every file a project references and ignores stray
out/outputs (issues #4850 and #4852, parent #3501). A.csfile referenced as data or foreign input (aNone/Content/EmbeddedResourceitem, or aCompileitem of an already-G# project such assamples/ForeignCompile/ThisAssembly.csand the Adr0169 fixtures) is now copied verbatim instead of being translated or dropped; one decision point (RepositoryVerbatimSources) feeds the mirror copy, the orphan step and the completeness check, and an include it cannot resolve statically is reported as a warning. The top-levelout/build-output root is no longer inventoried, so tracked scratch tools there are not discovered as apps (out/scratch/ildumpis untracked; the self-migration corpus is 56 apps). -
cs2gs no longer asserts a nullable argument forwarded to a generic-method type parameter (issue #4843, parent #3501). A promoted
object?parameter forwarded toDecodeSignature(provider, genericContext)was bridged with a runtime!!and threw a NullReferenceException in the migrated Core.Tests public-API snapshot test; gsc infers the method type argument from the argument, so the forward is now emitted unasserted. -
cs2gs no longer emits
__yielded{N}temporaries foryield return(issue #4859, parent #3501). The #4705 fix hoisted most yielded values (array creations, string literals, calls) into synthetic locals. Only non-tuple values whose printed form starts with((whichyieldat statement position does not parse as a plain expression, #4705), sized array creations (printed[3]T, whichyield [would parse as indexing), and branching expressions and lambdas (which need the iterator element type as their target), are materialized now, and that local is nameditem(item_2, ... when taken) instead of__yielded{N}. The__yieldedfamily has a retired row in the self-migration counter table. -
cs2gs preserves nullable tuple values stored through generic indexers (issue #4833, parent #3501). Assigning a tuple containing an oblivious nullable return into a dictionary-style value slot now promotes the matching tuple element on the receiver declaration, avoiding a later GS0155 when an absent value is represented by
nil. -
cs2gs preserves nullable elements in bare array initializers (issue #4831, parent #3501). Initializers such as
object[] arguments = { null };now use the same nullable-element projection as explicit and implicit array creations, so migrated code emits[]object?{nil}instead of failing with GS0155. -
cs2gs preserves implicit value conversions on switch-expression arms (issue #4832, parent #3501). Arms now use their Roslyn-converted non-nullable value type, including user-defined conversions such as
TypeDefinitionHandletoEntityHandle, so migrated switches retain one result type instead of failing with GS0179. Existing numeric widening and reference-arm projection are unchanged. -
Self-migrated Core now has exact native public ABI parity (issue #4828, parent #3501). Record synthesis matches Roslyn constructor, deconstruction, parameter-name and override-finality metadata; ordinary overrides omit redundant
finalflags on sealed owners; and preserved owned extensions keep only their native static-holder MethodDef while translated receiver calls route through it. The strict #4654 renderer remains unchanged. -
Explicit abstract properties retain storage-free CLR contracts (issues #4765 and #4715, ADR-0197).
abstract propandabstract override proppreserve getter/setter/init requirements, accessor visibility and virtual slots; concrete descendants must implement every required accessor. Abstract indexer accessor parameters retain optional/default metadata in implementation and reference assemblies, so CLR callers can omit optional indices. cs2gs propagates C# abstractness explicitly across ordinary classes and positional, partial and generic records, while initialized get/init overrides retain their backing storage and init accessor. Existing concrete open auto-properties and getter-only contracts are unchanged. -
cs2gs preserves nullable inferred locals inside lambdas (issue #4826). Local nullability scans now stay in the declaring lambda block, so a
Record.Exceptionresult observed byAssert.Nullremains nullable instead of gaining a checked!!assertion. -
cs2gs distinguishes stated-nullable metadata from platform types in oblivious projects (issue #4816). Explicit locals that store imported or source-promoted maybe-null values now retain
T?, while ordinary oblivious reads keep gsc'sT!coercion. Anonymous contracts also converge nested array, tuple, generic and delegate nullability without widening proven non-null storage. -
Copies retain construction provenance (issues #4776 and #4796). Data-struct
withand.copy(...)copy existing storage without rerunning primary constructors or declaration initializers. Expression-tree source data-class copies use the exact virtual clone before ordered updates, retaining private/base state and invocation-time, once-only evaluation rather than constructing a fresh object.- The emitted-PE baseline now records the intentional storage-copy IL in
DataStructErgonomicsandWebsiteSwift; real gsc/native C# oracles pin fresh-construction counts, strict IL, output and original/copy state. The other 158 sample entries and hash policy are unchanged.
- The emitted-PE baseline now records the intentional storage-copy IL in
-
cs2gs converges linked-source nullability across repository projects (issue #4817). Shared declarations are remapped by identical source path and content before assembly identity, so null evidence from any linking project produces one order-independent signature. The linked-output consistency check remains strict.
-
Imported G# sealed hierarchies retain their declaring-assembly restriction (issue #4807, PR #4808). Class semantics metadata now records inheritance mode, so foreign plain/data subclasses cannot treat a sealed hierarchy's intentionally non-sealed CLR image as open, including closed and symbolic generics and reference assemblies. Native non-sealed records and same-compilation sealed hierarchies remain legal. Legacy marked G# producers must be rebuilt to establish external inheritance permission.
-
cs2gs self-hosting guards remapped type arguments before storing them (issue #4722). Failed sibling remapping returns before publishing a nullable result into a fixed non-null Roslyn type-argument array; constructed and nested imported contract annotations remain intact.
-
Data-class
withand.copy(...)use the existing clone contract (issue #4796). Generic classes with a primary/base constructor no longer invoke a nonexistent parameterless constructor. Copies retain their constructed runtime type, source-base and private/readonly state, without rerunning field or base initializers; updates execute once in written order. -
cs2gs keeps nil-observing reference casts and distinct constructed tuple contracts (issue #4722). Built-in reference casts preserve nullable operator results until a coalescing fallback, while user-defined conversions, unboxing and non-null operator inputs retain their checks. Fixed-contract identity and sibling remapping preserve nested type-argument annotations, so an enabled contract cannot freeze a different oblivious implementation. Reporting fixtures use collectible, byte-loaded native assemblies that remain deletable on assertion failures.
-
cs2gs reports converted generic-store checks independently of asserted inputs (issue #4722). An authored
value!still reports its own fail-fast input check; a nullable user-defined conversion result checked before a fixed generic store now has a separateCS2GS-GENERIC-STORE-BRIDGEreport. Unchanged asserted values do not gain duplicate reports, and generated assertions and conversion evaluation are unchanged. -
Imported oblivious tuple contracts no longer freeze source implementations as non-null (issue #4719). Imported declarations remain immutable, but concrete oblivious reference leaves are nil-compatible platform endpoints, not non-null locks. Inherited eligibility and shared-component lock seeding use the same contract decision, preserving legitimate nullable operator results while retaining explicit native non-null contracts, operator-input checks and open type-parameter rules.
-
cs2gs tuple-leaf promotion respects each declaration's writable contract (issues #4719 and #4751). Explicitly non-null source leaves and fixed imported interface, base, delegate and store positions retain their non-null result bridges. Genuinely oblivious source-owned contracts still promote null-bearing leaves together, including
Task/ValueTaskresults, partial declarations, containing-type generic parameters and local nullable-context islands. Parenthesized tuple returns, yields and conditional or switch arms share this destination policy, and whole tuples supplied as native generic arguments retain their caller-owned leaf contracts; an unrelated tuple argument does not unlock a fixed native reference slot. Original member annotations and inherited contracts remain authoritative after generic owner projection, including both partial-property declarations and fixed signature components spanning sibling projects. Fixed locks retain declaration identity rather than freezing unrelated members that share a containing-type argument; writable seeds are filtered before projected taint is combined. Indexer parameters follow the same inherited and partial declaration contracts by ordinal. Sibling remapping preserves assembly identity, overload signatures and constructed owner and method arguments; local-only queries reuse the computed fixed-contract closure. Getter queries use their owning property or indexer contract. Operator inputs and converted results remain separate boundaries; an intermediate result obeys its immediate conversion consumer's parameter contract before the final result is checked. Null-accepting inputs are not asserted merely because the result has a non-null destination, and nil-observing branch results reach their coalescing fallback without an early assertion, including through checked and unchecked wrappers. Nullable branch destinations retain their selected implicit operator instead of lowering it to a safe reference cast. Guarded scalar iterator operands likewise preserve a nullable operator result rather than asserting it as non-null. -
cs2gs transports retained build-generated compilation inputs across validation roots and configurations (issue #4801, ADR-0196). Validation manifests carry the actual producing source text, hash and project ownership for non-inventoried build inputs, including net10 and netstandard2.0 SDK declarations. Authored sources still require the clean authoritative corpus, and source-declared test counts and budgets are unchanged. Old manifests lacking generated evidence fail closed rather than inventing historical contents.
-
Declaration initializer provenance now survives lowering, so struct literal initializers run once without suppressing authored overrides. Managed-reference safety also checks initializer functions separately for each constructed owner.
-
Expression-tree brace literals retain initializer-only constructor semantics (issue #4755). Owning value-struct initializers select their exact hidden marker signature rather than an authored parameterless constructor; later explicit member writes remain ordered after declaration initialization. Authored constructor calls retain their original body and metadata.
-
Source data-class copies use their existing virtual clone slot (issue #4796).
withpreserves get-only and private readonly storage, declaration provenance and constructed-owner identity without selecting or rerunning an authored constructor. Explicit updates retain lexical, once-only evaluation after the receiver is copied. -
Ordinary generic struct literals retain declared field initializers and primary-parameter scope (issues #4755 and #4747). Construction runs definition-bound initializers once in their owning type, using the actual primary inputs before later explicit member writes or collection population, instead of silently leaving initialized fields at CLR zero or crashing on a primary-parameter reference. Missing primary inputs use the existing required-storage validation and report GS0604 if their substituted type would default a non-null managed handle, including nested aggregates and fixed arrays. Constructed value/reference arguments, private fixed-array and readonly storage retain their owning metadata. Braces initialize independently of an authored constructor body, preserving normal authored calls and legal raw array/default zero-initialization. Authored-constructor declaration closures retain their owning storage and nested captures; duplicate primary/explicit constructor signatures report the existing GS0284 diagnostic rather than emitting ambiguous constructor metadata. Imported primary structs retain their existing CLR literal path and reconstructed collection defaults instead of requesting a same-compilation constructor.
- Explicit authored constructors also validate declaration defaults in their constructed generic owner, reporting GS0604 before emitting a null non-null managed-reference slot; constructor-body field assignments and legal scalar, reference and nullable defaults keep their existing policy.
- Expression-tree lambdas retain supplied primary inputs as invocation-time tree locals, preserving lexical evaluation order and once-only capture before constructor-owned declaration initialization, including reordered inputs and later member writes.
-
Data-class copy constructors initialize imported record bases correctly (issue #4789). The shared copy emitter now calls the accessible copy constructor on the actual direct CLR base, retaining symbolic generic arguments and base state before copying derived members. Object-root and source-base copying are unchanged; an imported non-object base without an accessible copy contract fails emission instead of producing invalid IL.
-
Native non-sealed record bases use CLR inheritance eligibility (issue #4807). Ordinary and closed-generic imported records now follow the same imported-base constructor and copy paths as symbolic generic records, instead of being rejected by G# source-only
openpolicy. Real CLR sealed bases and closed G# source bases remain rejected; imported equality dispatch is a separate concern. -
Inherited generic CLR method returns preserve source owner arguments (issue #4785). Generic calls through a source-derived receiver now project the return from the actual declaring owner's symbolic arguments, including multilevel, reordered and nested bases, while keeping the method's own argument order and physical tuple types.
-
Qualified nested constructor calls retain their generic enclosing owner (issue #4803). Calls such as
Outer[int32].User()now use the existing receiver-aware nested-type resolution instead of looking for a shared method namedUser, including inside expression-tree lambdas. Authored overload selection, enclosing/own parameter projection and constructor-reference generic slots share the existing construction machinery; no syntax or field-initializer semantics change. -
Qualified source-enum conversions retain their enclosing owner (self-migration #3501).
Outer.Kind(value)now uses the enum resolved by the shared nested-type reader instead of looking for a shared method namedKind. Attribute constants, generic and inherited owners, and once-only operand evaluation retain the existing conversion contract; unrelated same-named enums do not replace the nested type. -
Generic inference accepts a comparer implementing multiple closed interfaces when other arguments determine the key type (issue #4780). Symbolic and CLR inference no longer treat a non-unique interface projection as a contradictory bound or choose its first interface. Typed identity selectors now bind the self-migrated symbol-ordering tests without changing the comparer or generated assertions; unfixed type arguments, incompatible interfaces and violated constraints remain rejected.
-
Inherited generic CLR calls preserve source-typed tuple arguments (issue #4738). Argument conversion now projects through the inherited member's actual generic owner, including reordered base arguments, rather than constructing an erased
ValueTuple<object, …>for a source-typed slot. Nested and long tuples retain their physical element types and evaluation order; genuine object slots still use their intended conversions. -
cs2gs artifact replay preserves original source identity across checkout relocation (issue #4752). Validation manifests now export corpus-relative C# source and project metadata; legacy manifests recover only an unambiguous full-path repository mapping. Missing or invalid authoritative sources fail explicitly instead of silently reducing the source-declared Fact count to zero. Linked-source and referenced-project ownership, original per-name oracles and the existing parity budget policy are unchanged; this does not establish a runtime hang cause or test-suite completion.
-
cs2gs preserves null-observing local stores before
??fallbacks (issue #4770). The shared nullable-usage scan now recognizes coalescing, including parenthesized observations, so an intentionally null params-slot classification reaches its"not-reported"fallback instead of throwing at an inserted assertion. Defensive coalescing does not widen fixed parameter or member contracts; explicit non-null bridges and generic-store diagnostics retain their existing policy. -
cs2gs preserves reference-array covariance inside null coalescing (issue #4768). Derived/base array operands now use the shared explicit conversion path, with a nullable left cast that preserves nil until the fallback decision. The compiler accepts those nullable checked array casts, including nullable reference elements; array identity, result type and short-circuit evaluation are preserved, while G# slices remain implicitly invariant and incompatible value arrays or ranks remain rejected.
-
cs2gs preserves nested local-function state across recursive calls (issue #4802). Recursive callable groups now allocate storage in each function's declaring block, so an inner invocation cannot replace its caller's helper closures. Mutual sibling recursion and escaped callbacks retain their existing behavior; migrated recursive-delegate walks preserve argument order and once-only visits.
-
Recursive named delegates no longer crash the compiler's type queries or generic construction (issue #4757). Self-recursive, mutually recursive and expanding generic
Invokesignatures, including tuple/imported-type wrappers, retain nominal CLR identity; constructed signatures are projected on demand and type-parameter walks inspect actual arguments independently of the recursive definition graph without forcing unfinished signature projection. Ordered collection preserves signature order across sibling and nested constructions in their containing argument context, visiting each argument slot once per delegate walk instead of exponentially repeating finite nested arguments. -
cs2gs keeps attributes naming a safely lifted source delegate on the original extension owner (issue #4676). A private nested delegate already maps to a bindable top-level name, so an external-receiver extension no longer unnecessarily splits into an owner helper and a public
<Program>companion. The shared exposure check still follows the delegate's signature, constraints and containing generic arguments for genuine private types, and does not relax imported delegate accessibility or CLR identity. -
cs2gs preserves explicit static extension calls across source-project references (issue #4790). Referenced owned extensions reuse their declaring project's holder-preservation decision, including its suspension and receiver eligibility, instead of being mistaken for current-project lifted declarations. Explicit holder calls retain their native static target even when the argument's derived type has a same-named instance method; canonical receiver calls and task envelopes remain unchanged.
-
cs2gs retains native static extension-holder contracts for owned receivers (issue #4790). Canonical receiver members forward to the original static method hosted through
ExtensionOwner, rather than moving its body and deleting its declaring method. Explicit static calls and native method groups retain their original owner, signatures, defaults and constraints; private holder helpers remain private. Receiver-parameter attributes, including nullability postconditions and custom metadata, survive on the original holder. Forwarders preserverefandref readonlyreturns and their live aliases. Ordinary CLR async and iterator companions return the original envelope directly, preserving task identity, continuation behavior and lazy iteration without a second state machine. G# suspending declarations and companions instead share their logical-result suspension contract, with one compiler-owned suspension marker; a located unsupported diagnostic rejects an owned suspension shape that would add a Context parameter absent from its native holder signature. This scoped repair does not establish full Core ABI parity or self-hosting readiness. -
cs2gs preserves nullable selector results observed by LINQ predicates (issue #4769).
Any,All,WhereandFirstOrDefaulttype-pattern and nil tests now receive the original nullable value instead of an inserted!!throwing before the predicate runs. This repairs the shared recursive-lift query in the self-migrated translator; fixed non-null delegate contracts retain their checks. -
An inherited non-virtual property accessor can satisfy a G# interface across assemblies (issue #4717). The derived class now emits a private forwarding slot that calls the exact imported accessor selected by binding, including setters, init accessors, indexers and constructed generic bases. Previously the two compilations succeeded but the derived type failed IL verification and runtime loading. Ordinary base accessors stay non-virtual; existing virtual and inherited interface mappings are preserved, and reference assemblies carry the same forwarding-slot metadata.
-
Ordinary class methods now emit non-virtual CLR metadata as specified by ADR-0017 (issue #4677).
openmethods, overrides, and interface implementations retain their virtual slots, including members inherited by a descendant introducing an interface, synthesized sync/async iterators, and symbolic generic event accessors. Unrelated inherited members remain non-virtual. -
cs2gs preserves C# value and generic parameter metadata names (issue #4680, ADR-0170). Reserved names use
$namein declarations, references, and named arguments instead of the lossyname_rename, regardless of member visibility. Named-argument binding compares semantic names, so$scope:binds the CLR parameterscope; escaped spelling preserves argument slots, optional defaults, and lexical evaluation order. Documentation tags use the original unescaped names. Locals and other names without metadata retain collision-safe sanitization.
Reader's overview
The G# compiler is now written in G#. Starting with 0.5, gsc, the
language server, the formatter and the other G# tools are written in G#.
Nothing changes in how you install or use G#: the package ids, the
Gsharp.NET.Sdk project SDK, the dotnet new templates, and the VS Code and
Visual Studio extensions are the same.
Before moving an application to 0.5, pin the intended SDK, select its documentation, run the project's tests, and review the affected diagnostics.
For changes after the published snapshot, pay particular attention to stricter generic-constraint and nullable-argument diagnostics. Code previously accepted with an invalid CLR contract may now be rejected at compile time; the detailed entries below identify the diagnostic and remedy.
Before moving an application to a different compiler version, pin the intended SDK, select its documentation, run the project's tests, and review the affected diagnostics. Do not treat the development branch's implementation notes as a stable compatibility promise.
Breaking changes
-
Assembly version 0.5.0.0. The minor-version bump changes the
AssemblyVersionofGSharp.Coreand the other compiler assemblies to0.5.0.0. A G# analyzer built against 0.4'sGSharp.Corestill loads, but reportsGS9303(an analyzer was built against a differentGSharp.Coreversion than the host). Remedy: rebuild the analyzer against 0.5. -
Fail-fast
!!. The compiler is G# translated from C#, so places where C# trusted a value to be non-null (!) are now!!: a runtime check that throwsNullReferenceExceptionat the site instead of carrying null onward (issue #4612). Valid input should behave the same as 0.4.1270. If a 0.5 compiler, language server or tool reports an internal error (GS9998) with a null-reference trace on input that 0.4.1270 accepted, please file it with the input. -
data class/data structprint and compare like a C#record(ADR-0199).ToStringrenders the C# record format and equality follows the record ABI, which the self-migrated compiler needs for exact public ABI parity. See the "Breaking:data class/data structprint and compare like a C#record" entry above for the exact format. -
Inherited data equality compares the most-derived fields through base-typed calls and interfaces (issues #4777 and #4675). Compiler-owned typed-base overrides preserve structural dispatch without changing the nonvirtual base-field comparison or permitting user-authored
Equals. Direct imported record bases share that decision: self equality compares their fields nonvirtually, while native base/interface calls dispatch through the matching override with the actual symbolic generic owner. The existing imported data/record semantics detector gates this path; an ordinary CLR base's virtual domain-specificEquals(Self)remains inherited, without a synthesized component call or forwarding override. Optional native parameter-name metadata uses the standard positional fallback when absent, without changing signatures or nullability. cs2gs retains native records'IEquatable<Self>interfaces; class operators share the correct dispatch. Typed parameter nullability and generic/nested owner mappings agree in implementation and reference assemblies. Source calls and method groups retain both typed equality and the nullable object override. Ordinary and class-constrained calls to equality inherited from a constructed source generic base resolve the actual declaring owner, like method groups, without an internal compiler error. The emitted-PE sample hashes accept only the reviewed equality-slot metadata and class-operator changes; the byte-identical gate remains intact. Unrelated record ABI differences remain outside this repair. -
A compound member assignment through a receiver declared
T?now reportsGS0158(issue #4354).xs.Capacity += 1on aList[int32]?ande.InnerException.Source += "x"bound with no diagnostic and failed at run time with an unattributedNullReferenceException, while the plain writexs.Capacity = 1and the read were already reported. The compound form now follows them.- Remedy: narrow the receiver (
if let l = xs { l.Capacity += 1 }or a nil guard) or assert it (xs!!.Capacity += 1). A receiver that was never nilable is unaffected. - Event subscription through a
T?receiver (x.E += h) shares this binder and is reported the same way.
- Remedy: narrow the receiver (
-
Named attribute constructor arguments now bind to constructor slots instead of corrupting the custom-attribute blob (issue #4503).
@GeneratedRegex("a", RegexOptions.None, matchTimeoutMilliseconds: 1000)now selects and reorders the constructor argument correctly, including omitted optional defaults. Attribute property/field assignments useName = value; the existingName: valuemember spelling remains accepted when no constructor parameter has that name. Invalid, duplicate, and positional-plus-named duplicates now report diagnostics instead of emitting unreadable metadata. cs2gs preserves C#'s:constructor and=member distinction. -
Prefix
^xis now a first-classSystem.Indexexpression, and one's-complement is spelled~x(ADR-0187, issue #4350). This matches C#:let last = ^1is a reusableSystem.Index,consume(^2)passes one, and a standalone range may start from the end (let r = ^4..^1), so the formerGS0410restriction is retired. Binaryx ^ yis still bitwise XOR, and bracket indexing (xs[^1],xs[1..^1]) is unchanged. Remedy: rewrite prefix one's-complement from^xto~x, including user-declared unary operators (func (a T) operator ~() T). Parentheses do not keep the old meaning, because(^x)is also an Index. cs2gs now translates C#System.Index/System.Rangelocals, fields, parameters and expressions directly instead of reportingCS2GS-GAP, and it translates C#~to~. -
Calling an imported .NET method on a receiver declared
T?now reportsGS0159(issue #4287). Examples:s.ToUpper()on astring?field, local or parameter;l.Add(1)on aList[int32]?;Path.GetDirectoryName(p).ToUpper(). These used to compile with no diagnostic and throw a bareNullReferenceExceptionwhen the receiver was nil. A property or field read on the same receiver (s.Length) has reported since #4356, and a call to a G#-declared method always has. Calls were the remaining gap.- Remedy: assert the receiver (
s!!.ToUpper(), same result type), call it null-safely (s?.ToUpper(), whose result isstring?), or narrow it (if s != nil { … }orif let t = s { … }). - Not affected: a value-type
T?such asint32?.GetValueOrDefault(), whose members are safe on nil; an extension function declared over the nilable type; and an obliviousT!receiver, which still compiles and gets ADR-0186's attributed runtime check. - The check runs after the method is chosen, so it never changes which method a call selects.
- A nil test now narrows a bare field or property name used as a receiver (issue #4310). Inside a type,
if memo != nil && memo.TryGetValue(k, out var v)on alet memo Dictionary[K, V]?field now compiles, as thethis.memospelling already did. Before, the bare name kept itsT?type as a receiver even after the test: a call reached the gap above, and a property read (memo.Capacity) failed to bind. - cs2gs concatenates a nullable operand the way C# does.
"p:" + ofor a C#object?now translates to"p:" + o?.ToString(). A nil operand concatenates as the empty string, as in C#. The previouso.ToString()threw on nil and now reportsGS0159.
- Remedy: assert the receiver (
-
An
ifjoin no longer lifts a non-nil local across a possible jump into either branch (issue #4290). Agotothat lands after a branch's assignment could previously bypass the proof while the compiler still treated the local as non-nil after theif, producing a runtimeNullReferenceException. Functions containing a user label orgotonow conservatively skip this join narrowing. Remedy: add!!at the dereference, or restructure the control flow so no jump enters the branch after its assignment. -
A
gotono longer inherits a non-nil narrowing from an assignment its edge can bypass or invalidate (issue #4519). The compiler now joins assignment-narrowing state for forward and backward edges at each target label, so an unsafe dereference reportsGS0158instead of compiling and throwingNullReferenceException. Assignments before every incoming jump and assignments re-established after the label remain narrowed; unrelated labels do not disable narrowing for the whole function. -
A ref-returning static CLR method is now observed through its pointee (issue #4350, ADR-0056 §1).
MemoryMarshal.GetArrayDataReference(xs)orUnsafe.As[TFrom, TTo](&x)used to bind as the pointer type*T, unlike ref-returning instance members and indexers, which already auto-dereference. Passing such a result by value even emitted an address, which failed at run time withInvalidProgramException. Remedy: take&Call(...)where the address itself is needed. -
Nullability-oblivious imported reference positions are now read as platform types
T!rather than asT?(ADR-0186 step 3).--nullability=platform-typesis the new default;--nullability=enabledrestores ADR-0136's reading. A reference position arriving from an assembly that says nothing about its nullability — no[Nullable], no[NullableContext], or an explicit oblivious byte — used to be imported asT?, and every use then had to discharge a proof obligation (!!,if let,?., or a smart cast) about a fact nobody had ever stated. It is now the platform typeT!, usable as bothTandT?with no operator, and the safety question is deferred to the point where the value is actually used as non-null, where the compiler inserts an attributed runtime nil check. Annotated metadata — the whole modern BCL — is unaffected:[NullableContext(1)]members stay non-nullT, a[Nullable(2)]member staysT?, andSystem.Object.ToString()still returnsstring?; a direct use of those positions binds exactly as before, but a member chain through aT?link now asks for the same proof a source-declaredT?does (see the member-chain bullet below).- Code that previously errored now compiles.
Environment.Version.ToString(),s.ToUpper().Trim(),values.Min()andxs.Reverse()on an oblivious receiver all bind with no diagnostic.GS0159("receiver may be nil") is unchanged in definition but narrower in reach: it fires only for a source-declaredT?, an annotated-nullable imported member, a tuple element or anasresult, and can no longer fire for an oblivious CLR receiver.GS0129,GS0296,GS0298,GS0300,GS0503,GS0523andGS0536each gainT!on the "admits nil" side of their test, andstring! + "x"concatenates exactly asstring? + "x"does — as dostring! + 'c'ands += 'c'on astring!local (issue #4324). - Existing null-handling constructs keep compiling, unchanged.
x!!on aT!is legal, is not reported as redundant, and emits the same check the compiler would have inserted anyway;if let,?.,??andx != nilall accept aT!, and a nil guard narrows it toTso no check is emitted after the guard. Assertions that are no longer required are harmless; removing them is a separate, optional, mechanical pass. This is a statement about those constructs only, not about the release as a whole — see the container-conversion bullet below for the one shape that stops compiling, and the overload-resolution bullet for the one that compiles to something different. - A nil that used to be a compile error is now an attributed runtime check. Where a platform value flows into a destination whose declared type is a non-null reference type — an explicitly typed
let/var, a field or property store, an array or slice element store, anout/reftarget, an argument (including an extension method's receiver), areturn, athrowoperand, alocksubject, afor … insource, a deconstruction source, a delegate invocation target, or an instance-member receiver — the compiler inserts a check that throwsNullReferenceExceptionwith a message naming the expression, the oblivious origin and the file:line. The exception type is deliberately unchanged, so existingcatchclauses behave as they do today; what improves is the message.--platform-nil-checks=offsuppresses insertion for measurement only and is strictly weaker than either the old model or the new one — it is not a supported mode. - One documented exception to the attributed message: inside an expression-tree lambda. A lambda converted to
Expression[...]is handed toSystem.Linq.Expressionsas data and is never lowered to IL by the compiler, so there is nowhere for the check'sdup; brtrue; …; throwto live. Two consequences. A platform value used as a receiver there (.Where(b -> b.Conversion.AccountId == id)over an oblivious API) compiles and still fails on nil — measured:System.Linq.Expressionsemits the dereferencing form for instance member access regardless of virtuality, including for a non-virtual getter on a sealed class that never readsthis— but it fails with the runtime's own unattributedNullReferenceExceptionrather than the named message above, and a user-writtenx!!in receiver position is erased on the same path. Any other platform coercion inside such a lambda — an argument, a store, a return, or the lambda's own result — is a compile error (GS0473) rather than an unchecked value. Tracked as #4352. Enumerable.Min()/Count()on a nil oblivious source now throwNullReferenceExceptioninstead ofArgumentNullException. An extension receiver is an argument, so the check fires at the call site where the program made the error rather than several frames inside the library. Acatch ArgumentNullExceptionaround such a call no longer matches.xs.Reverse()on an obliviousList[int32]now binds a different method. Member lookup on aT!receiver runs againstT, so an own-surface instance member wins over an extension exactly as it does for a non-nilable receiver:List<T>.Reverse(in place, void) rather thanEnumerable.Reverse(lazy, copying). This is the fix for a silent miscompile in which the receiver's static nullability selected between two methods with different runtime semantics — but it is a behaviour change on the path that was previously miscompiling, andstring?.Trim()similarly stops retyping toReadOnlySpan<char>viaMemoryExtensions.- One overload-resolution shape can select a different method. Given a G#-declared pair
func G(s string)/func G(s string?), the callG(obliviousCall())used to pickG(string?)and now picksG(string): aT!argument is applicable to both and the more specificTparameter wins. This needs a source-declared overload pair differing only in nullability, which CLR metadata cannot express, so no imported API is affected. - Passing an oblivious generic container to a non-null-element parameter is now rejected, and this one is a genuine tightening.
C[T!],C[T]andC[T?]are three distinct constructed types, and the only implicit conversion between them isC[T!] → C[T?]. Solet xs List[string] = obliviousList()no longer compiles, where under ADR-0136 it did — not because ADR-0136 permitted the conversion in principle, but because this compiler admitsC[T?] → C[T]in both directions today (a separate, pre-existing soundness gap tracked as #4321). ADR-0186 §3 asserts this is "not a new cost"; on this compiler it is. Remedy: declare the destinationList[string?], or copy element-wise through theT! → Tboundary so each element is checked. Reading an element through the container is unaffected and needs no conversion at all —obliviousList()[0]isstring!and is checked at its own coercion point, which is where essentially all of the ergonomic benefit is. Note the tightening is present whether or not #4321 is fixed; fixing #4321 would additionally tighten source-declaredT?containers.- The same rule now applies when the destination is an imported .NET method or constructor parameter (issue #4480). Imported overloads are ranked on erased CLR shapes, but the winning argument is rebound against its nullability-aware parameter type:
List[string!]!no longer reachesIEnumerable[string]silently and reportsGS0154, matching a G# callee. A destination such asIEnumerable[string?]remains valid; in particular,String.Join(string, IEnumerable<string?>)still accepts the oblivious list. - Imported generic parameters now use their substituted nullability when checking arguments (issue #4440). This applies to instance, static, and extension calls:
List[string].Add(nil)andList[string]{"a", nil}now reportGS0155; nullable and oblivious slots continue to accept nil.
- The same rule now applies when the destination is an imported .NET method or constructor parameter (issue #4480). Imported overloads are ranked on erased CLR shapes, but the winning argument is rebound against its nullability-aware parameter type:
- An unannotated generic's type argument keeps the nullability you gave it (issue #4361). An open type-parameter slot is not an oblivious position — its nullability arrives with the type argument — so
Array.Empty[string]()from a netstandard2.0 or#nullable disableassembly is a platform array of plainstring([]!string), not ofstring!, and converts to[]?stringor[]stringjust as the annotated BCL's does; the same holds forEnumerable.Empty[T](),Array.FindAll(xs, …)withTinferred fromxs, and FsCheck'sArb.From(gen). Only the concrete container position staysT!. One consequence is a tightening: aniltuple element passed through such a method'sparams T[]against a non-null sibling (AnyEqual((nil, false), ("x", false))) is now rejected, exactly as the same call to a G#-declaredfunc AnyEqual[T](values ...T)always has been; give the sibling a nilable type ((string?, bool)) to widenT. Diagnostics now print a nested platform argument (List[string!]!) and an imported platform array in ADR-0132's positional spelling ([]!string). - Oblivious positions now round-trip through metadata. A platform position emits the oblivious byte
0, which re-imports asT!— never1, which would launder an unknown into a guarantee. Under--nullability=enabledthe same byte reads as ADR-0136'sT?, so assemblies stay readable by either mode. This is the third value of the round-trip guarantee, which ADR-0136 could not express at all. - A member chain through a stated-nullable imported member now reports, reads and writes alike (issue #4356). Member lookup used to let a chain continue through ANY imported field or property read typed
T?:e.InnerException.Message(Exception.InnerExceptionis declaredException?by the BCL), the writee.InnerException.Source = "src", orb.Value.Counton aBox[List[int32]?]whose plain genericTmember takes its?from the type argument. It did so with no narrowing and no nil check, so a nil link threw an unattributedNullReferenceException. That carve-out existed for oblivious members, which are nowT!and checked by the attributed runtime check above; what it still admitted was nullability someone had actually stated. It is gone. Such a chain now reportsGS0158on the member after theT?link, exactly as a source-declaredT?receiver always has. Remedy: assert the link (e.InnerException!!.Message, same result type), read it null-conditionally (e.InnerException?.Message, whose result isstring?), or narrow it (if let inner = e.InnerException { … }). The member's own type does not change: an annotated member is stillT?, and a direct read of it, or a read that flows into aT?destination, is unaffected. Under--nullability=enabledan oblivious member is ADR-0136'sT?again, so an oblivious chain such asEnvironment.Version.Majornow reports too and needs!!in that mode; the default mode reads it asT!and is unaffected. Code produced bycs2gsalready carries the needed!!or?.(#4365).
- Code that previously errored now compiles.
-
return thisBY VALUE from aref structinstance method is now legal, with or without@UnscopedRef(ADR-0184 D1, correcting ADR-0058). ADR-0058 rejected it withGS0219and claimed that matched C#'s default behaviour; it does not. C# givesthisa ref-safe-context that is function-local by default and a safe-to-escape (value) scope that is the CALLER's — the value the receiver holds was produced by, and outlives, the call. The two had been conflated onto oneIsScopedbit.HasFunctionLocalEscapeScopenow excludes the receiver parameter from itsIsScopedtest, and the ref-scope half moved to a dedicatedIsUnscopedRefReceiverflag read byHasFunctionLocalRefScope. A genuinelyscopedsource is unaffected: returning ascopedparameter, or a local seeded from one, is stillGS0219, inside a struct member exactly as at top level. Two existingRefSafeEscapeTestscases changed their expected outcome; one of them (RefStructMethod_WithUnscopedRef_ReturnsThis_IsLegal) had also been silently emittingGS0198for its whole life, because it wrote@UnscopedRefwith noimportand only assertedDoesNotContain(GS0219). -
A struct member that returns a reference to its own instance state without
@UnscopedRefnow reports the newGS0589(ADR-0184, the CS8170 analogue), instead ofGS0253's inaccurate "must be an lvalue". A reference rooted at a LOCAL still reportsGS0254, and a genuinely read-only (let) field still reportsGS0253whether the member is annotated or not —@UnscopedReflifts the escape-scope restriction only. -
@UnscopedRefon a declaration where it means nothing is rejected withGS0590(ADR-0184), rather than silently ignored: a class member, ashared(static) member or property, a receiver-clause function (ADR-0182 makes every receiver clause an extension, whose receiver is an ordinary by-value parameter), or a free function. Interface members and matching override/interface implementations are now supported (issue #4292): an interface implementation may add@UnscopedRefonly when the matched slot carries it, including ordinary by-value methods and property accessors, while overrides apply C#'s narrower ref-safety relevance gate. An implementation may keep its receiver scoped by omitting the annotation from an annotated slot. The check follows the implementation selected by override/interface dispatch: an explicit implementation must match the exact slot and constructed interface owner, while implicit satisfaction ignores every explicit-interface member. This closes the previous placement-diagnostic gap without lettingIBase[A]satisfyIBase[B]or an unrelated explicit implementation mask a default body. Default interface bodies keep a missing implementation optional, but an implementation that replaces one is checked by the same rule, including inherited default properties. Auto-property setters/init accessors contribute their implicitvalueparameter before accessor symbols exist, and importedScopedRefAttributemetadata is recognized by runtime assembly identity so a cross-assembly lookalike cannot change this safety decision. -
Parameter ref escapes now use C#'s implicit scopes (issue #4293, ADR-0184 amendment). Returning an ordinary
outparameter by reference now reportsGS0254, and anoutargument no longer constrains a ref-returning call.refandinparameters use the return-only ref scope, while arefparameter of ref-struct type has a separate function-local value scope and reportsGS0219if returned by value.@UnscopedRefwidens the applicable defaults, including the ref-struct value scope; it is rejected withGS0590on by-value and explicitlyscopedparameters. Constructed generic declarations preserve this contract through substitution. Imported modules opt into the implicit defaults withRefSafetyRulesAttribute(11); markerless modules retain legacy caller-scoped by-reference parameters, and explicitScopedRef/UnscopedRefmetadata remains authoritative. G# does not yet emitRefSafetyRulesAttribute, so the release does not claim equivalent C# consumer behavior or Roslyn's full ref-struct value-mixing analysis. -
Returning a reference obtained through a READ-ONLY RECEIVER is now rejected with the new
GS0591, closing a dangling-reference hole in the@UnscopedRefwork above (ADR-0184 amendment, the CS8156 analogue; found in adversarial review of the definition-side change and proven at run time before the fix).func fromIn(in a Acc) ref readonly int32 { return ref a.Slot() }— whereSlotis a legal@UnscopedRefmember returning a reference intoAcc's own instance state — compiled with ZERO diagnostics and returned a dangling reference. Stored value 7; read back after one intervening call, across two builds of the same source:-1048597222,-1083017767,-1040415262. Three different values, so this was genuinely reused stack memory, not a stale-but-stable copy. Realcscrejects the C# analogue withCS8156. Root cause: the emitter and the binder disagreed about what the emitter emits. The emitter defensively COPIES a value-type receiver into a function-local temp whenever the receiver is a read-only reference — aninparameter, aref readonlyalias, or aref readonlycall/property result — and the called member is not itself areadonlymember, which (G# has noreadonly func) is every native G# member. Three sites encode that rule:MethodBodyEmitter.EmitInstanceReceiver,MethodBodyEmitter.EmitConstrainedTypeParameterReceiver(which has noisReadOnlyCallopt-out at all, since aconstrained.-prefixed receiver is addressed through a temp regardless), andReflectionMetadataEmitter.NeedsRvalueReceiverSpill.StatementBinder.HasFunctionLocalRefScopemodelled NONE of them — it gave such a receiver caller scope, correct for the storage the author wrote and wrong for the temp the emitter substituted underneath. The definition-side change did not create the copy; it created the first way to observe it, by makingreturn ref this.<field>expressible. The rule now lives in exactly one place,RefCapabilities.RequiresReadOnlyReceiverDefensiveCopy, consulted by all three emitter sites (a behaviour-preserving extraction — each site's current condition is reproduced exactly, the constrained-receiver site via the default argument) and by the binder's newIsDefensivelyCopiedReceiverForwarding.GS0591is reported rather than the genericGS0254for the same reasonGS0589got its own identity: the defensive copy has no spelling in the source, soGS0254's "function-local storage" would point the author at storage they never wrote, whereasGS0591names the copy and the remedy (take the receiver byrefrather thanin, or return the value). The[UnscopedRef]CLR-indexer variant is closed by the same hook: issue #4265 rejected forwarding such an indexer through a BY-VALUE parameter, but thein-parameter spelling of the same forward was still accepted and dangled identically — an independently pre-existing bug, not a regression from this ADR. TheSpan[T]shape is deliberately NOT affected:func first(in s Span[int32]) ref readonly int32 { return ref s[0] }stays legal, because aSpan[T]/ReadOnlySpan[T]indexer returns a reference into the ENCAPSULATED BUFFER the value merely wraps — copying the receiver copies its pointer and length and leaves the pointee untouched — so #4265's premise still holds for every indexer that is not explicitly[UnscopedRef]. One consequence is correct but non-obvious, and is pinned by a test on purpose:func k(in a Acc, ref y int32) ref readonly int32 { return ref a.Pick(ref y) }is rejected even though the reference ultimately comes fromy, the caller's own storage. This is NOT theCS8156case — realcscACCEPTS the C# analogue (verified directly, in the same file where it rejects theSlot()shape above), because C# gives a non-[UnscopedRef]struct method'sthisascoped refref-safe-context and excludes the receiver from the result's scope entirely. G# rejects it because G#'s escape walk includes a call's receiver unconditionally,@UnscopedRefor not — pre-existing behaviour, not introduced here: the by-VALUE receiver spelling of the same shape already reportedGS0254before this change. The defensive copy makes aninreceiver function-local too, so theinspelling now joins it consistently. G# is therefore strictly MORE conservative than C# on this point, never less; narrowing it to match C#'s precision is its own separate change, recorded in the ADR under "What it does NOT address". The safe path is unchanged and verified at run time: aref(rather thanin) receiver is passed by address with no copy, and mutating through the reference the member hands back is still observed on the caller's own storage. -
A closure that captures a
ref/out/inPARAMETER of its enclosing function is now rejected withGS9010instead of silently compiling a lossy by-value snapshot (issue #4259, found auditing #4221 for DoD coverage).LambdaBinder's capture-legality checks already rejected aref structcapture (GS0219), a managed-pointer capture (GS9004), and afixed-pointer capture (GS9008), but had no check for a captured variable that is itself a by-ref PARAMETER —func Foo(ref x int32) { let Bad = func(a int32) int32 { x = x + 1; return a } }compiled clean and silently dropped the mutation (the closure's field held a snapshot ofx's value, not a live reference to the caller's argument), since neither prior check inspectsParameterSymbol.RefKindand a plain parameter's ownTypecarries no by-ref marker. The check is scoped toParameterSymbolinstances withRefKind.Ref/Out/Inspecifically, so it does not affect aref/var refLOCAL alias capture — a distinct, plain-LocalVariableSymbolcapture kind with its own (separately handled, and per #4222 sometimes legal) rules — nor a struct instance method's implicitthis(constructed withRefKind.None, verified with a struct-method closure repro). -
A closure that captures a
ref/var refLOCAL alias of its enclosing function is now rejected withGS9011instead of silently compiling a lossy by-value snapshot (issue #4271, the sibling gap #4259/GS9010deliberately left open — a ref-alias local is a plainLocalVariableSymbol, not aParameterSymbol).func Foo() { var arr = []int32{1}; var ref alias = arr[0]; var f = func() { alias = alias + 1 }; f(); Console.WriteLine(arr[0]) }compiled clean and printed1instead of2— the alias's slot holds a managed pointer, andCaptureBoxingRewriter.IsBoxablerefuses to hoist it into the shared box that gives an ordinary captured local its write-through semantics (boxing would corrupt the aliasing), so the capture silently fell back to a snapshot. Rather than build a live-reference capture path, this is rejected outright, mirroring C#'s CS8175 for the same shape (a closure may outlive the storage the alias points at — an array element, a field, another stack frame's local — and the CLR has no mechanism to keep a managed pointer valid past that). Distinct from issue #4222's per-suspension-point liveness check (GS0258): an alias declared and fully consumed within one async/iterator suspension segment, never captured by a nested closure, is unaffected — that is a different code path (RefStructAsyncLivenessAnalyzer, notLambdaBinder's capture-legality checks). The whole.gscorpus was swept: 0 files usevar ref/let refat all, so 0 files affected. -
A G#-declared generic INTERFACE must now forward its constraints too, and a CLOSED violating type argument at any G#-declared generic type clause is now refused (issues #4089 and #4090).
class Holder[T] : IGsBox[T], whereinterface IGsBox[TI SchemeOptions]is declared in the same compilation, compiled with no diagnostic and its IL VERIFIED — an interface-implementation row is not something ILVerify checks — while the CLR refused the instantiation at load time withTypeLoadException: GenericArguments[0], 'T', ... violates the constraint of type parameter 'TI'. It now reportsGS0580, exactly as the class spelling has since #4067, andclass Holder[T SchemeOptions] : IGsBox[T]keeps binding. Separately,class Bad : GsHandler[Unrelated]andvar f GsHandler[Unrelated]overopen class GsHandler[TOptions SchemeOptions]compiled and emitted IL that does not verify ([UnsatisfiedMethodParentInst] ... Method parent instantiation has unsatisfied class type parameter constraints); the constructor spellingGsHandler[Unrelated]()has always reportedGS0152, and the TYPE-clause spelling now reports the same thing, at a base clause, a field type, a variable type, a return type, a nested argument, a qualified name and a method body alike. No new diagnostic id was taken — this is C#'s CS0311, which G# already spellsGS0152, and CS0314, which it already spellsGS0580. -
Both of the above were one defect, and the fix moved WHEN the question is asked rather than adding call sites. A declaration's type-parameter constraints are resolved when its own body (a class) or its members (an interface) are bound — the aggregate-shell lifecycle of #2519, which exists so a bound may name any same-compilation type and so CRTP keeps working. A type clause in another declaration can bind first, and then the declared parameter carries no constraints at all and every checker accepts. Interfaces bind their members after every class body, which is why a G#-declared generic interface was never checked; classes are ordered base-first, which is why #4067's base-clause repro happened to work. A field type has no such ordering, so
class Unf[T] { public var f GsLate[T] }was silently accepted wheneverGsLatewas declared BELOW it and reportedGS0580when it was declared above — measured both ways, and a third witness neither issue named. Every G#-declared generic type-clause construction is now queued during the declaration phase and answered once every same-compilation constraint is resolved; constructions bound later (method bodies) are answered in place as before. The whole.gscorpus was swept with the fixed build: 197 files, 170 emitting an assembly, 0 occurrences ofGS0152and 0 ofGS0580. -
A generic declaration must now forward the constraints a G#-DECLARED generic base requires too (issue #4067). #4037 closed this for an IMPORTED base; the same shape over a base declared in the same compilation is a different code path and was still accepted.
class Unf[T] : GsHandler[T], whereopen class GsHandler[TOptions SchemeOptions]is declared in the same file, compiled with no diagnostic and emitted IL that ILVerify rejects with[UnsatisfiedMethodParentInst] … Method parent instantiation has unsatisfied class type parameter constraints. It now reports the sameGS0580, with the same remedy — forward the constraint,class Fwd[T SchemeOptions] : GsHandler[T], which verified before and still does. The rule is identical; only the substrate differs. A G#-declared generic base is closed by symbol substitution in the type-clause binder and never byType.MakeGenericType, so #4037's checker never saw it, and the implication test is written against the symbolic constraint surface instead. Two positions are still not asked about and each is a fixture row rather than a sentence: a composite open argument (GsList[[]T]) and a bound that mentions another of the definition's own parameters. A third, the G#-declared generic INTERFACE, was left open here because its own parameters have not resolved their constraints yet when a class body binds (the CRTP shell lifecycle of #2519); it was filed as #4089 together with the closed-argument gap at the same site as #4090, and both have since been closed — see the entries above. The whole.gscorpus was swept: 0 files affected. -
A bare imported dependent constraint (
where TDerived : TBase) is now checked over erased same-compilation classes (issue #4063). #4041 taught the imported constraint check to answer a dependent bound on the symbolic vector, but with INVARIANT IDENTITY — right at a generic argument position, wrong at the top of a bound, where the relation is assignability. Rather than answer with the wrong relation it declined there, andvar c Chain[ChA, ChB]over two unrelated same-compilation classes compiled and threwTypeLoadExceptionnamingTDerivedthe first time the program touched the type. That position now asks the symbols for assignability, through the very predicate the G#-declared spelling of the same bound has used since #4043, so the two spellings cannot drift apart. It reportsGS0152naming the bound the author wrote —TDeriveddoes not satisfy theTBaseconstraint — rather than theSystem.Objectthe erasure substitutes into it.Chain[ChBase, ChDerived],Chain[IFoo, ChImpl],Chain[object, string]andChain[object, int32]all keep binding; an indeterminate answer still falls through to the pre-existing comparison rather than to a rejection. The whole.gscorpus was swept: 0 files affected. -
A generic declaration must now FORWARD the constraints its imported generic base requires (issue #4037).
class Unforwarded[T] : Handler[T], where the importedHandler<TOptions>declareswhere TOptions : SchemeOptions, compiled with no diagnostic and emitted anextendsrow that names an instantiation which is not valid for everyT; ILVerify rejected it with[UnsatisfiedMethodParentInst] … Method parent instantiation has unsatisfied class type parameter constraints, and the type only became unloadable if something ever closed it. It now reports the newGS0580, which names the type parameter, the bound it does not carry, and the remedy — forward the constraint,class Forwarded[T SchemeOptions] : Handler[T], which verified before and still does. This is a different question fromGS0152(#4032), which asks whether a CLOSED type argument satisfies a bound; here there is no argument, so the rule is whether the declaration's own constraint set implies the base's. C# spells this CS0314 — measured againstcsc, not CS0311 as the issue reported, because CS0311 is the concrete-argument case G# already spellsGS0152. The same measurement set the scope:cscreports it at a base clause, a field type, a local declaration, an interface list entry and a return type alike, so the rule sits at the shared generic-type construction sites and every spelling inherits it. A type argument that merely MENTIONS a type parameter (Handler[List[T]]) and a bound that mentions another of the definition's own parameters (where U : IList[T]) are both still skipped — the rule only adds rejections it can prove. The whole.gscorpus was swept: 0 files affected. -
G# formatting is now canonical and option-free (ADR-0179).
gsfmtand the language server always use 4-space indentation, K&R braces, a fixed 120-column width, and LF output; LSP tab-size and insert-spaces options are ignored. Range and on-type formatting are now available, and the VS Code extension enables format-on-save for.gsfiles by default. -
chan Tis respelledchan[T](ADR-0174 D2). The element type moves inside brackets likesequence[T]andmap[K, V];in chan[T]/out chan[T]are the receive-only / send-only handles (ChannelReader<T>/ChannelWriter<T>),chan[T]?is a nullable channel andchan[T?]a channel of nullable — the(chan T)?grouping carve-out is gone. The legacy spelling is rejected withGS0567, which names the exact replacement. -
make(chan T[, n])is retired in favour ofchan[T]()(rendezvous — capacity 0, Go's unbuffered channel),chan[T](n), andChan.Unbounded[T]()(the wave-1 behavior ofmake(chan T), now named).GS0566names the replacement per site; note the semantic change for the no-capacity form. -
close(ch)is retired in favour of the memberch.Close()(GS0566). Closing twice throws (Go's panic);Dispose()is the idempotent close, sousing letworks.len(ch)/cap(ch)becomech.Length()/ch.Capacityon a channel you constructed. -
Receiving from a closed channel no longer raises and swallows
ChannelClosedException— the zero value is delivered directly (about 400× faster on that path). -
import Gsharp.Extensions.Gois gone (ADR-0174 D13): the concurrency syntax is the language, the namespace and its marker type are deleted, and the gate diagnosticsGS0316/GS0317are retired. The concurrency library lives in the implicitly importedGsharp.Concurrencynamespace (/noimplicitimportsdisables it). -
len,cap,append, anddeleteare retired (ADR-0174 D13). A call reportsGS0566naming the member replacement for that site:xs.Length,m.Count,m.Remove(k),ch.Length()/ch.Capacity;appendhas no member spelling — a slice is a fixed CLR array, so keep a growableList[T]and.Add;capon a slice is removed outright (its capacity was its length). A user-defined function of the same name is an ordinary call. -
A nullable argument at a non-nullable G#-declared parameter is now an error even when the parameter's type is still open (issue #3988). Passing a
chan[T]?to achan[T]parameter, a([]T)?to a[]Tone, or aT?to a reference-constrained[T class]one used to compile with no diagnostic at all, while every closed spelling of the same call reportedGS0154. It was not only a missing message: anilreached the non-nullable slot and failed at run time. All of these now reportGS0154, which names the parameter and both types; the remedies are!!at the call site, declaring the parameter nullable, or narrowing the value first — either an ordinary!= nilcheck or an assignment from a non-nullable value, both of which now lift these shapes (assignment narrowing did not, for a slice, array or channel whose element was still open). An UNCONSTRAINEDT?is deliberately unaffected — it erases toNullable<T>and keeps the value-type rules. -
A nullable
map,sequenceorasync sequenceat a non-nullable parameter is now an error, in every spelling (issue #3997). Two holes closed together, because closing either alone would have left the two spellings disagreeing the other way round. First,map[K, V]?,(sequence[T])?and(async sequence[T])?at a non-nullable parameter of their own type compiled with no diagnostic at all whenever the element was still an open type parameter — the shapes were missing from the list of "reference types whose CLR backing is unavailable while binding" that #3985 and #3988 filled in for channels, slices and arrays, so the null-safety gate declined to gate them; anilreached the non-nullable slot and threwNullReferenceExceptionat run time. Second, and contrary to the issue's own diagnosis, the CLOSED sequence spellings were not being rejected either:(sequence[int32])?at asequence[int32]parameter, and a plain importedIEnumerable[int32]?at anIEnumerable[int32]parameter, were both classified as an IDENTITY conversion by thesequence[T]≡IEnumerable[T]alias rule (issue #3093), which compared the two sides ignoring reference nullability. The enumerable shapes were the only reference types in the language exempt from Kotlin-model null safety. All of these now reportGS0154(orGS0155at an initializer), naming the parameter and both types; the remedies are the usual ones —!!, a nullable-typed parameter, or narrowing with!= nilor an assignment from a non-nullable value. Note the migration this implies for unannotated imported libraries: anIEnumerable<T>returned by a C# assembly with no nullable annotations arrives asIEnumerable[T]?(see Unannotated imported reference types are nullable by default, 0.3), so it now needs!!or a narrowing check at a non-nullablesequence[T]orIEnumerable[T]parameter — exactly as that same library'sstringreturn already does at astringparameter. The alias itself is untouched in the directions that drop nothing:sequence[T]andIEnumerable[T]still convert to one another as identity, and both still reach anIEnumerable[T]?slot, so LINQ flowing into asequence[T]parameter is unaffected. Measured blast radius across all 192.gsfiles in the repository and the SDK's own G# sources: zero. -
A bare
nilliteral at a non-null-tolerant parameter is now an error even when the parameter's type is still open (issue #4010). Non-null-tolerant means a slot whose CLOSED spelling already rejectsnil— every shape except a G#-declared class or interface, a reference-constrained[T class], and any?-annotated type, all of which keep accepting it. This is the other half of #3988, which taught the same clause to look at a nullable annotation: anilLITERAL has no annotation to inspect, so thenilargument intakesChan[T](nil),takesSlice[T](nil),takesMap[K, V](nil)ortakesSeq[T](nil)was still passed through unchecked whenever the substituted parameter type mentioned a type parameter — while every closed spelling of the same call reportedGS0154. It was unsound, not merely silent: forwardingtakesMap[K, V](nil)out of a generic and instantiating it at[string, int32]compiled, IL-verified, and threwNullReferenceExceptionwhen the callee readm.Count. All of these now reportGS0154. Three shapes the issue did not name change with them, each of which its closed sibling already rejected: an UNCONSTRAINEDTparameter, a fixed array[N]T, and a function type(T) -> T.nilstill reaches every null-tolerant open shape — a reference-constrained[T class], aT?, achan[T]?, a G#-declared open class or interface — and the remedies are the usual ones: annotate the parameter, or pass a real value. Measured blast radius across all 180.gsfiles undersamples/,src/Sdk/,bench/,e2etests/andtest-assets/: zero. -
Two constructions of one generic type no longer structurally project to each other (issue #4014).
let zs List[string] = xsfor anxs List[int32]used to compile, IL-verify, run, and print0— the ADR-0148 projection planner answered yes becauseList<int>andList<string>share a parameterless constructor and a settableCapacity, so the "conversion" built a NEW, EMPTYList<string>, copied a capacity, and dropped every element. The argument position of the same pair behaved identically. A projection between two constructions of one generic definition is now refused (GS0490at an assignment,GS0154at an argument), because the state the type argument names is exactly what a member-by-member copy cannot carry. The rule is scoped to CLR-backed pairs whose CLOSED types differ, so identity is untouched, a same-compilation G# generic is untouched — a userclass Box[T]still projectsBox[int32]toBox[int64]and carries the value, because a G# class's public fields ARE its state — and an ordinary projection into a generic CLR target from a DIFFERENT source type still works. The refusal is narrow in a second way: it applies only where the two constructions' public member SURFACES are type-identical, so the difference lives in state the author cannot name. Where the surface does carry it — an importedBox[T]whose settableValueisT— nothing changes, and ADR-0148 §B explicit object spread can still supply it (Box[string]{ ...boxOfInt, Value: "replacement" }still compiles); a spread that does NOT supply it still reports the sameGS0490naming the member. One pair that was already rejected changes diagnostic id: this pair at an IMPORTED CLR parameter moves fromGS0155toGS0159, because the candidate is now never applicable rather than applicable-then-unconvertible. Measured blast radius across all 180.gsfiles undersamples/,src/Sdk/,bench/,e2etests/andtest-assets/: zero. -
A generic instantiated over a fixed-length array is a distinct type per length (issue #3962).
List[[3]int32]andList[[4]int32]used to be the SAME type and converted to one another silently:[N]Tis backed by the plain CLRT[], so both spellings resolved to oneList<System.Int32[]>symbol before any conversion ran. The declared length is now kept beside the erased CLR shape, exactly as a same-compilation element or a named tuple already was, so the two reportGS0155/GS0154naming both lengths. This holds through a variant interface (IEnumerable[[3]int32]does not convert toIEnumerable[[4]int32]despiteIEnumerable's covariance, andIComparerlikewise contravariantly) and for a static generic receiver (EqualityComparer[[3]int32].Defaultis not anEqualityComparer[[4]int32]). A length that MATCHES is still one type, a covariant widening over the same length still widens, and an array recovered from METADATA still converts either way — a G#List[[3]int32]reaches a C#List<int[]>parameter, since reflection records no length to disagree with. The SLICE half of the same erasure is closed by #4024, below. -
A fixed-length array's declared length is part of its type (issue #3998). This is the bare rule underneath #3962, and it was wrong in both directions:
[3]int32converted implicitly to[4]int32,[]int32converted implicitly to[3]int32, andvar lit [3]int32 = [2]int32{1, 2}was accepted withlit.Lengthreporting 2.[N]Tis backed by the plain CLRT[]— the same type as[]Tand as every other length — so these pairs fell through to the general CLR reference-assignability rule; the #2516 invariance guard that stops array covariance fired only for a slice or imported-array SOURCE. The rule is now stated as a widening:[N]Tconverts implicitly to[]T(dropping a known length for an unknown one is a representation no-op, so a fixed array still reaches every[]Tslot), and nothing converts implicitly INTO a[N]Texcept a[N]Tof the same length. Rejected pairs reportGS0156(orGS0154at a call argument) and keep their explicitcast[…], exactly as slice covariance does; the cast reinterprets rather than converts, so a[3]int32cast to[4]int32still reports.Length3. An array recovered from METADATA is exempt in both directions — a G#[3]int32still reaches a C#int[]parameter and a C#int[]return still fills a[3]int32slot. The same change also closes two gaps it found.[2]Footo[]Foofor a same-compilationFooused to be REJECTED (GS0154/GS0156), because the widening path existed only for a CLR-backed element; it now widens like every other fixed array. And a covariant element used to reportGS0155— no conversion at all, socast[[]Base](d)did not compile either — and now reportsGS0156with a working cast, matching what[]Derived->[]Basehas had since #2516; element invariance for implicit conversions is unchanged. Zero of the 175.gsfiles undersamples/,src/Sdk/,bench/,e2etests/andtest-assets/relied on any rejected conversion. The member-slot gap this left is closed by #4012, below. -
An explicitly-implemented interface member is no longer a candidate for an ordinary call (issue #4013).
List[int32]().Add("x")COMPILED and threwArgumentExceptionat run time:List<T>implements the non-genericSystem.Collections.IList, whoseAdd(object)accepts anything, and the member-lookup walk that exists to surface DEFAULT interface methods admitted abstract interface members too — so when the argument did not fit the genericAdd(T), resolution fell through to the explicit implementation and silently widened the call site toobject. In C# such a member is not part of the implementing type's surface and is reachable only through an interface-typed reference; it now behaves the same way in G#. A class receiver keeps only genuine DEFAULT interface methods from that walk (they are non-abstract, and the class need not implement them at all); an INTERFACE receiver is unaffected, since a base interface's members really are members of the derived one, and an IMPLICITLY implemented member is on the class surface and still binds. Reaching the explicit member still works through an interface-typed receiver —cast[IList](ys).Add("x"). An inapplicable argument now reportsGS0159, which is what an imported overload with no interface sibling (Stack[int32]().Push("x")) already reported; where the explicit member was the ONLY candidate of that name the call used to compile and now reports the newGS0577, which names the member, the interface that declares it and how to reach it, rather than reading like a misspelling —map[string, int32]{}.Contains(k)is that shape, sinceDictionary<K, V>implementsContainsonly explicitly. Measured blast radius over every.gsfile undersamples/ande2etests/: 27 such members were being offered, every one of them alongside another candidate of the same name on the type's own surface, and the corpus still compiles unchanged. Two call shapes are deliberately NOT narrowed, because the compiler still depends on the member there, and both keep the hole: an ADR-0117 collection literal (and the #3096 spread form), which fills aDictionary[K, V]through the explicitICollection<KeyValuePair<K, V>>.Add; and a call whose argument carries a same-compilation type, whereIList.Add(object)is an erasure escape hatch wherever two erasures of one type disagree (List[System.Action[Mode]].Add((item Mode) -> …)for a same-compilation enum presents the receiver asList<Action<object>>and the lambda asAction<int>). Both turn on something the call site has rather than on the member, so the reported hole — a genuinestringat a genuineint32— is closed;List[int32]{"x"}and the same-compilation-argument form went on compiling and throwing, and are closed by #4028 below. -
A generic's member slot over a fixed-length array follows the retained
[N]T, not the erased CLR shape (issue #4012). Two gaps, one family. First,List[[3]int32]().Add([4]int32{…})was accepted, withxs[0].Lengthreporting 4:List[[3]int32]keeps[3]int32in its type arguments (#3962), but the helper that rewrites an imported member's parameter through them admitted a type argument only when it needed symbolic projection — and a[3]int32has a perfectly realint32[]CLR type, which is exactly the problem, since that type is shared with[]int32and with every other length.Add's parameter therefore stayed theint32[]reflection reports off the erasedList<int32[]>. It is now the[3]int32the receiver carries, so a differing length reportsGS0156(and[]Fooat a[3]Fooslot does too), withcast[…]still available exactly as at the bare level.Stack[[3]int32]'sPushisolates the rule —List[T]also exposesIList.Add(object), which accepts anything (#4013). Second,List[[3]Foo]().Add([3]Foo{…})for a same-compilationFooreportedGS0159 "Cannot find function Add"and was simply unreachable: an argument with no CLR type of its own is ridden through to its erasure so overload resolution can rank candidates, and[]Tand[N,M]Thad that ride-through while[N]Tdid not — so resolution never ran at all. It now presents asobject[], exactly as[]Fooalready did; what a genuineobject[]parameter accepts is unchanged. The third sub-case of the issue —List[[]int32]converting toList[[3]int32], a slice type argument erased before any comparison can see it — is a different mechanism and is closed by #4024, below. -
A generic instantiated over a slice is a distinct type from one instantiated over a fixed-length array (issue #4024).
List[[]int32]converted toList[[3]int32], silently — the last open sub-case of #4012, and the residue #3962, #3998 and #4012 each declined in turn. The cause was one step earlier than any conversion rule: #3962 taught the binder to RETAIN a[N]Ttype argument symbolically, soList[[3]int32]carries[3]int32, but a slice argument was still erased toT[]. That leftList[[]int32]carrying an EMPTY symbolic argument vector — which is exactly what aList<int[]>recovered from METADATA carries, and a metadata array's shape genuinely is unknowable — so the metadata carve-out correctly kept the lenient CLR comparison and there was nothing left to compare. Both G# array spellings are now retained, at the same four gates (declared type, construction, fully-qualified construction, static generic receiver), so the two reportGS0155/GS0154naming both spellings, in both directions, at any nesting depth, in a value position of a multi-argument generic (Dictionary[string, []int32]), and through a variant interface. Note this deliberately does NOT mirror the bare rule, where[3]int32still widens implicitly to[]int32: a generic's type argument is matched by identity, not convertibility, soListbeing invariant inTmakes the two instantiations as unrelated asList[Derived]andList[Base]. The sharpest case is a COVARIANT interface — aList[[3]int32]at anIEnumerable[[]int32]parameter is now refused, even thoughIEnumerableis covariant and read-only and the bare element conversion is implicit — which is the same line #3962 drew when it refusedIEnumerable[[3]int32]toIEnumerable[[4]int32], through the same shared predicate. What does not change: a member slot over a slice keeps the bare widening (List[[]int32]().Add([3]int32{…})still binds), because[]Tand the CLRT[]describe the same shape and need no symbolic rescue; member parameters, indexers and iteration over aList[[]T]are byte-for-byte as before, since a retained slice is still not a substitutable type argument. One member position DOES move, and it is the only breaking change here beyond type identity: a generic's METHOD RETURN follows the retained slice, because that path projects on a nonempty symbolic vector without consulting substitutability. SoStack[[]int32]().Pop()now surfaces[]int32rather than the erasedint32[], and assigning it to a[3]int32goes from accepted to rejected — which is what #3998's bare rule already required of every other position, the old acceptance being the metadata carve-out firing on a type that only looked reflected because the slice had been erased. The explicitcast[[3]int32](…)still works. The indexer is unchanged and is pinned as such; the #1354 nullable-flags path is untouched in substance, because an ANNOTATED slice ([]string?) was already retained before this change and never took that branch, so the arguments newly diverted off it are exactly those with no annotation to lose — the emittedNullableAttributebyte arrays forList[[]string],List[[]string?]andList[string?]are identical before and after; and an array recovered from METADATA is still exempt in both directions and against both spellings — a G#List[[]int32]and a G#List[[3]int32]both still reach a C#List<int[]>parameter, and a C#List<int[]>return still fills either slot. Zero of the 180.gsfiles undersamples/,src/Sdk/,bench/,e2etests/andtest-assets/change a single diagnostic. -
A
map[K, V]reaches the interfaces itsDictionary[K, V]backing implements, not only the class (issue #4011).var d IDictionary[K, V] = mreportedGS0155whenever the key or value was still open, while the closed spelling of the very same conversion (map[string, int32]at anIDictionary[string, int32]) was accepted — the one row where the two spellings disagreed, and it disagreed in the direction that rejects working code. #3987 taught the lattice that amap[K, V]IS aDictionary[K, V]by shape once an element is open, and stopped at the concrete class; the interfaces had no rule of their own, and the reflective assignability rules that would otherwise answer need a CLR type the open map does not have. Amap[K, V]now converts implicitly toIDictionary[K, V],IReadOnlyDictionary[K, V], andICollection/IReadOnlyCollection/IEnumerableofKeyValuePair[K, V](and tosequence[KeyValuePair[K, V]], the alias spelling of the last) whenever the elements match, in that direction only — anIDictionary[K, V]is not necessarily aDictionary[K, V]. The conversion emits no IL: the value already is that interface. One side effect, at a G#-declared parameter: a(map[K, V])?at a non-nullableIDictionary[K, V]now reportsGS0154instead of being silently accepted, because the null-safety gate (#3999) declines to blame nullability when the non-nullable form would not reach the parameter either — and until now it would not. The closed spelling of that row already reportedGS0154, so the two now agree. At an imported parameter nothing changes and nothing disagreed: both spellings are accepted, before and after, which isBindClrParameterConversions' general leniency about a CLR parameter's declared nullability rather than this gap. -
A closed generic type clause whose type argument violates the definition's constraint is now an error (issue #4032).
class Bad : Handler[string], where the importedHandler<TOptions>declareswhere TOptions : SchemeOptions, compiled with NO diagnostic and threwTypeLoadException: GenericArguments[0], 'System.String', on 'Handler`1[TOptions]' violates the constraint of type parameter 'TOptions'the first time the program touched the type.Type.MakeGenericTypevalidates constraints for a live runtime definition and does not for one loaded by aMetadataLoadContext, which is where every/referenceassembly lives; the imported generic METHOD path has compensated for exactly that since #750, and the generic TYPE path never did. Every user-facing construction of a closed imported generic now reportsGS0152naming the type argument, the type parameter and the constraint that failed — the four type-clause spellings (a base clause, a field or local type, a function parameter or return type, a nested type argument) and the three expression spellings that never pass through a clause at all: a direct constructor callHandler[string](), a static member through a closed receiverHandler[string].Describe(), and an object literalHandler[string]{…}. Only CLOSED instantiations are asked: a type argument that still mentions a type parameter is erased to anobjectplaceholder, and asking a constraint of a placeholder is how #4016's projection broke a SIBLING parameter's constraint, so an open instantiation is left alone. A same-compilation class is NOT skipped — the check reads the symbol's own base chain rather than itsobjectsurrogate — soclass MyOptions : SchemeOptionsstill satisfieswhere TOptions : SchemeOptions. The GS0149 half of #4032 as reported (a SATISFYINGclass MyHandler : Handler[MyOptions]rejected as "not generic") did not reproduce on565b9a04across eleven shapes and four reference kinds; those shapes are pinned as green fixture rows. Not covered, each pre-existing, measured on the parent and filed separately: a G# generic class that derives from a constrained imported base without forwarding the bound (class H[T] : Handler[T]) still compiles and emits IL that ILVerify rejects withUnsatisfiedMethodParentInst(issue #4037, the forwarded spellingclass H[T SchemeOptions] : Handler[T]verifies); a DEPENDENT constraint over two distinct same-compilation classes (Coupled[A, List[Bee]]againstwhere U : IList<T>) was still accepted because both erase to the sameobjectplaceholder (issue #4041, closed in this same release by answering a dependent bound on the symbolic vector; the same mismatch spelled with imported types was already caught here); and an object literal of an imported generic over a same-compilation type argument does not bind at all, reportingGS0157(issue #4042, the constructor spelling of the same instantiation works). One violation reports ONE diagnostic at every spelling. The binder PROBES the same receiver several times before committing to a reading of it — a qualified accessor is walked three times through three different entry points, an unqualified one twice — so the first form of this check reported the identicalGS0152three times forSystem.Nullable[string].Valueand twice forHandler[string].Describe()— a count that was a function of how many internal paths the binder happened to take; the report is now made once per expression, in the shared checker, so a future caller cannot reintroduce the fan-out. The qualified spelling also used to FOLLOW the accurate error with a false one:GS0149 "Type 'Nullable' is not generic"is a last-resort fallback the qualified walker reached whenever a closed construction failed for any reason, andSystem.Nullableis of course generic — it is the argument that is wrong. That fallback is now suppressed when the failure has already explained itself, soSystem.Nullable[string].ValuereportsGS0152alone. A genuinely non-generic type named with type arguments still reportsGS0149. Two spellings still emit a CONSEQUENTIAL follow-on rather than a duplicate — an unqualified receiver (Nullable[string].Value) falls through to ordinary index-expression binding and adds twoGS0125s, andHandler[string]()adds aGS0130— tracked as issue #4051.-after(d)andtick(d)round a delay or period UP to a whole millisecond (ADR-0174 D8/D9 erratum 46, issue #4008).System.Threading.Timertruncates aTimeSpanto whole milliseconds, which armed a timer at an interval SHORTER than the one asked for — and, below 1 ms, at a period of zero, which per theTimer.Changecontract disables periodic signalling. Atick(d)with any0 < d < 1mstherefore produced exactly one tick and then went silent for ever, with no error and no diagnostic: measured over a busy-polled 500 ms window, periods of 0.1, 0.5 and 0.9 ms each produced 1 tick against 1 ms's 426, and none of the three reached 20 ticks in 10 s. Both timers now arm a strictly positive interval rounded up to the next whole millisecond, so the interval armed is never shorter than the one requested. Two visible changes for existing programs: a sub-millisecondticknow keeps ticking, at 1 ms; and a fractional period above the cliff slows to the next millisecond instead of running fast — a period of 1.5 ms ticked at 1 ms (426 in 500 ms) and now ticks at 2 ms (249), and 2.5 ms ticked at 2 ms (249) and now at 3 ms (166). (There is no duration literal in G#; both timers take aTimeSpan, so these aretick(TimeSpan.FromMilliseconds(1.5))and so on.)aftermoves with it, so a sub-millisecond delay is no longer truncated to an immediate fire (mean latency over 200 samples: 0.9 ms was 0.007 ms and now lands with the 1 ms row at ~1.19 ms).after(0)is still immediate, andtickstill rejects a period of zero or less withArgumentOutOfRangeException— the same shape Go's ticker panics on. Rejecting a sub-millisecond period was the alternative and was declined: it would maketickpartial on inputs Go'stime.Tickeraccepts, and would say so as a runtime exception inside a program that had been running. -
An explicit type argument naming a BASE of the real element is refused rather than compiled to unverifiable IL (issue #4026).
Probes.CountAny[ImportedBase](List[Derived]())COMPILED, ran, printedany:0— and ILVerify rejected the assembly (StackUnexpected: aList<Derived>found where aList<ImportedBase>is expected). The type argument is genuine, so the MethodSpec really is closed overImportedBaseand the parameter really is the INVARIANTList<ImportedBase>; only the argument's erasedList<object>surrogate made it look applicable, and the #3989/#4006 check that exists to refuse exactly that was waived because the slot's open declaration readsList<T>and so counted as "possibly erased". It is not erased when the call site PINNED it: a slot whose open declaration mentions only method type parameters the call supplied with types that have a CLR identity of their own is no longer exempt, and the call reportsGS0159— the same diagnosticList[Derived]at a genuineList[ImportedBase]parameter already reported. Themapspelling of the same mistake is refused with it, and so is a call that pins one type parameter genuinely beside one it does not (TakeMap[ImportedBase, Derived](map[Derived, Derived]{})), whose genuine invariant KEY mismatch used to be waived along with the whole parameter. Nothing else narrows: a type argument that is itself an erasure SURROGATE (a same-compilation class arriving as its imported base, which is what #4016 made the placeholder produce) is not genuine and keeps the exemption, so every #4016 spelling goes on binding, and a genuinely COVARIANT slot still takes a base type argument —Probes.CountSeq[ImportedBase](List[Derived]())at anIEnumerable<T>parameter, andProbes.CountArray[ImportedBase]([]Derived{…})at aT[]one, since CLR reference arrays are covariant. -
A collection literal, and a call carrying a same-compilation argument, no longer reach a widening explicitly-implemented interface member (issue #4028). #4013 closed this for an author-written call but had to cut two exemptions at candidate COLLECTION — which is memoized on
(Type, name)and cannot see arguments — soList[int32]{"x"}andDictionary[string, int32]{"a": "x"}went on compiling and throwingArgumentExceptionfrom insideIList.Add(object)/IDictionary.Add(object, object), as didList[int32]().Add(someUserTypedValue). The discrimination is now made at applicability, on the collected candidate list, where the receiver's and the arguments' real types are both in hand: an abstract member of a NON-GENERIC interface is kept only when there is a genuine erasure to repair — either the RECEIVER carries a same-compilation type, so its own members' parameter types are surrogates that cannot judge anything (List[System.Action[Mode]].Add((item Mode) -> …)), or the receiver's own same-named member WOULD have taken the call on the arguments' real types (a[]Celsiusspread into aList[float64], whose user-defined conversion the erasure hid). Everything else reportsGS0159, which is what the author-writtenList[int32]().Add("x")already reported. A GENERIC interface's member is never affected: on a constructed class receiver it is closed over the receiver's own type arguments and cannot widen, soDictionary[K, V](){ ...pairs }goes on filling throughICollection<KeyValuePair<K, V>>.Add. -
A user-defined implicit conversion is applied at a call on a generic collection, not only in the spread form (issue #4036).
List[float64]().Add(someCelsius)compiled to verifiable IL and threwArgumentExceptionfrom inside the BCL, while the spreadList[float64](){ ...someCelsiusSlice }printed the value — the same pair of types, two answers. A same-compilation struct has no CLR type while binding, soCelsiuspresents to overload resolution asobject; against aList<double>that is an IDENTITY match forSystem.Collections.IList.Add(object)and no match at all forAdd(double), so the widening member won and theCelsiuswas boxed and handed over as-is. The spread form escapes because it types its item placeholder as the collection's ELEMENT type and converts BEFORE bindingAdd, so applicability never sees the erased argument. The two forms now AGREE rather than share a path: where the receiver's own non-widening surface would have taken the call and some position needs a user-defined implicit conversion to do so, that position is converted before applicability runs. #4028's decision is untouched — the widening member is still KEPT whenever a conversion exists; it simply stops WINNING, because a realdoublebeats a boxed one. Six neighbouring forms close with it, two of them previously silent rather than loud: the collection literalList[float64]{ celsius },Dictionary[string, float64]().Add("a", celsius)andlist.Insert(0, celsius)threw;list.Contains(celsius)answeredFalseandlist.IndexOf(celsius)answered-1; andlist.Remove(celsius)reportedGS0124becauseIList.RemoveisvoidwhileICollection<T>.Removereturnsbool. Named arguments bind correctly at both halves of the decision: the candidacy filter #4028 added, and this repair, each compared SOURCE-order arguments against DECLARATION-order parameters, solookup.Add(value: someCelsius, key: "a")asked whether aCelsiusfitskey: stringand reportedGS0159for a valid call — pre-existing on the candidacy side, measured. Both now reorder through the resolver's own named-argument mapping, the same one #4026 reached for. Still refused, unchanged: an argument with no conversion to the element type (List[int32]().Add(someCelsius),List[int32]().Add("x"), or a reorderedDictionary[string, int32]().Add(value: someCelsius, key: "a")) reportsGS0159. -
A same-compilation user-defined implicit conversion now participates in ordinary imported CLR method overload resolution (issue #4054).
Math.Abs(someCelsius)reportedGS0159even though the sameCelsius -> float64operator already worked at a G# parameter and, since #4036, at a generic collection member. The argument has no CLR type while its assembly is being emitted, so the reflection resolver saw only itsobjecterasure and rejectedAbs(double)before the conversion binder could apply the operator. Imported static, instance, inherited and extension method calls now retain the symbolic argument only for one narrow callback: classify whether the candidate parameter is reachable through the existing implicit user-conversion resolver, including its ambiguity rules. The winning argument is still converted by the established CLR-parameter conversion pass. Erased arguments gain no general applicability, explicit-only operators remain inapplicable, and imported arguments stay entirely on the existing CLR classifier, so their conversion precedence is unchanged. The rule covers ordinary, overloaded, generic andparamsmethods and both value- and reference-returning conversion operators; unrelated conversion targets remain ambiguous and a target with no conversion still reportsGS0159. -
A constraint violation on an unqualified generic receiver no longer cascades into false diagnostics (issue #4051). #4032 made gsc validate declared generic constraints at every construction site, and at the qualified spellings the resulting
GS0152stands alone. At the unqualified ones it did not: the resolver returned "not a type" after it had already REPORTED, so the binder re-readName[Arg]as an ordinary index expression and lookedNameandArgup as values — telling the authorGS0125: Variable 'Nullable' doesn't exist.andGS0125: Variable 'string' doesn't exist.about a predefined type keyword. The resolver now says whether a failure already explained itself, and each caller stops instead of inventing a second reason. Twelve spellings reportGS0152exactly once and nothing else: the eight in the issue plus a static-field read, write and compound assignment (GS0125 x2each) and the generic-name receiver shapeHandler[string?](GS0124+GS0159). The constructor spellingHandler[string]()is one resolver over — it addedGS0130 Function 'Handler' doesn't existabout a type that plainly exists — and now claims the call as a refused CLR construction. Nothing individually correct is suppressed:GS0152is still reported at every spelling, and every satisfying instantiation goes on compiling, IL-verifying and running. Not covered, each pre-existing, measured on the parent and filed separately: a fully-qualified generic CONSTRUCTOR callSystem.Nullable[int32]()reportsGS0157 Cannot find type System, about a namespace (issue #4055); and a static compound assignment through a generic receiver over a same-compilation type argument (Handler[MyOptions].Field += "z") emitsHandler<object>and throwsTypeLoadExceptioneven though the constraint is satisfied (issue #4056, the generic-CONSTRUCTION placeholder erasure of #4016/#4041 one receiver shape over — since fixed, and listed under Fixed below). -
A receiver clause always declares an extension now — the
extensioncontextual keyword,GS0103, andGS0314are all retired (ADR-0182, issue #4240). ADR-0024 and ADR-0079 gavefunc (r T) M() { ... }an ownership-dependent meaning: an instance method (with a softGS0314nudge toward the in-body form) when the current package ownsT, an extension otherwise, and an outrightGS0103rejection for a same-package non-aggregate receiver (an enum, an interface, a non-struct alias). ADR-0165 (v0.4) patched the enum/owned gap with a contextualfunc extension (r T) M()marker, which worked but reintroduced exactly the kind of ambient contextual keyword the language has been retiring elsewhere (:=, the=named-argument separator, thedelegatetype-alias spelling) — and collided with ordinary use: the website's own Trail sample usesextensionas a plain parameter name, which the Prism and VS Code grammars had to special-case to avoid mis-highlighting.func (r T) M() { ... }is now unconditionally an extension, for anyT— owned or not, class, struct, or enum — exactly like today's non-owned case: parameter zero is the receiver, no interface conformance, no private-member access, no entry in the receiver type's own method table. Owned instance methods are declared inside the type body ONLY; there is no receiver-clause spelling for one anymore.GS0103andGS0314are retired outright — the ownership-dependent binding rule they policed no longer exists — and the reserved IDs are pinned inDiagnosticIdUniquenessTestsso they cannot be reused, the same way ADR-0174 retiredGS0316/GS0317. Thefunc extension (...)marker is itself a retired spelling: the parser recognizes the shape and reports the newGS0587rather than silently accepting it, then recovers by parsing the declaration exactly as ifextensionhad not been written — one clean diagnostic, no cascade.extensionis an ordinary identifier again everywhere else:func extension(x int32) int32 { ... }(a plain function namedextension) andfunc (s string) extension() string { ... }(an extension method namedextension) are both unaffected, and the website/VS Code grammars drop their carve-out. The one genuinely silent behavior change: source still on the pre-ADR-0182GS0314-warned spelling (an owned-type receiver-clause method never migrated to in-body) now binds as an extension instead of an instance method. Interface-conformance loss,overrideloss, and private-member access all fail loudly at compile time under the new binding — but a receiver-clause method on an owned struct that mutates a field now silently mutates a throwaway by-value copy instead of the caller's struct, with no diagnostic (the same hazard any struct extension method on a non-owned type already has; owned struct receivers now inherit it too). This repository has no surviving instance of the hazard — the Oats sweep already migrated every in-treeGS0314trigger to the in-body form when that warning shipped in v0.4 — but source outside this tree that never migrated should be checked before upgrading. Operators are the one deliberate carve-out and are unaffected:func (a T) operator +(b T) T { ... }has no in-body spelling (ADR-0079), so an operator on an owned struct/class keeps attaching directly to that type exactly as before; only the "explicit extension operator on an owned type" combination ADR-0165 allowed has no replacement spelling, and nothing in-tree used it.cs2gs's enum/owned special case (RequiresExplicitExtensionReceiver, added for ADR-0165) is deleted outright — every C# extension method now translates to the same plain receiver-clausefunc, regardless of receiver ownership or kind. -
Several imported members now keep a
?they declare, so code that used a nil value as non-null may now report a diagnostic (ADR-0193 Phase 2, issue #4363). The affected positions include a duck-typed enumerator'sCurrent, an awaiter'sGetResult(), and imported CLR operators. The list and the remedy (narrow, assert with!!, or make the destinationT?) are in the Fixed entry "Several imported members now keep the nullability they declare" below. -
A derived class can no longer reach a
protectedinstance member through a receiver typed as the base class (issue #4453). Insideclass Derived : Source,s.f,s.M(),s.Pands.E += hwiths Source(or withsof a sibling subclass) compiled, and the output failed IL verification (FieldAccess/MethodAccess) because the CLR, like C#'s CS1540, allows that access only through the derived type. It now reports GS0379 for fields, methods, method groups, properties and events, in reads, writes, compound assignments, lambdas, null-conditional accesses and initializers.this,base, bare names, receivers of the derived type or its subclasses, and staticprotectedmembers are unaffected. Remedy: type the receiver as the derived class, or expose the member through a non-protected accessor on the base. -
cs2gs now rejects C#
#ifand#elif(issue #4632). G# has no conditional compilation. cs2gs used to translate only the arm active under the build's preprocessor symbols, so the other arms disappeared without notice. A Release-only test assertion was lost this way in the self-migrated tree. Every#ifand#elif, including those nested in inactive arms, now reports theCS2GS-CONDITIONAL-COMPILATIONtranslation error at its source location, and the app fails the Translate stage.- Remedy: rewrite the condition as a runtime check of whatever the arm actually depends on, such as a configuration setting or an environment variable, or delete the arm that is not needed. A
#if DEBUGthat guards behavior only valid for optimized code can testDebuggableAttribute.IsJITOptimizerDisabledon the assembly. This repository's allocation tests do that, but it reflects the optimizer setting, not theDEBUGsymbol. cs2gs migrate --allow-conditional-compilationdowngrades each site to a non-fatal warning in stderr andtranslate.logand translates the active arm. It exists for a pinned external corpus that cannot be edited, and covers only the Translate stage's project sources. A#ifin an analyzer test snippet, an orphan source, or a library's.Testsproject translated for parity is still an error.
- Remedy: rewrite the condition as a runtime check of whatever the arm actually depends on, such as a configuration setting or an environment variable, or delete the arm that is not needed. A
Added
-
abstract classandshared classmodifiers (ADR-0195, issue #4674).abstract class Walker { … }is inheritable and cannot be instantiated even when it declares no abstract member (Walker()andWalker{}areGS0386).shared class Helpers { … }is the spelling of a C#static class: it is emitted CLRabstract sealed, cannot be instantiated, and its body is the shared member list, so every field,const, property, event andfuncdeclared in it is shared,init { }is its static initializer, and ashared { }block inside it is rejected (GS0617, which also coversinit(…), primary constructors,deinitandopen/overridemembers;GS0618onopen/sealed/abstract/data;GS0619on a base type; every part of a partial shared class carriesshared,GS0479). Both are contextual and valid only on aclasshead. cs2gs now emitsabstract classfor a C#abstract class(previously dropped, leaving an instantiableopen class) andshared classwith flat members for a C#static class(previously an instantiable class with ashared { }block), so a migrated library keeps the CLR shape of those public types; non-static classes keep their trailingshared { }block. -
cs2gs capture-test-oracleand per-test-name test parity (issue #4633). A migrated test project used to pass parity on its exit code and a count of[Fact]methods, so[Theory]rows and renamed or dropped cases went unnoticed.- The new verb lists each C# test project's cases.
cs2gs validate --csharp-test-oracle <dir>andcs2gs migrate --csharp-test-oracle <dir>compare the migrated run's TRX with that list, name for name.- Justified differences go in
tools/cs2gs/selfmig-test-name-baseline.json. cs2gs validatenow requires the oracle, or an explicit--count-only-test-parity.- The mirrored test budget ceiling is now 120 minutes (was 90).
-
cs2gs migrate --sdk-version <v>and--sdk-pin global-json(issue #4631). A repository migration can now pin an exactGsharp.NET.Sdkversion, such as a published release, instead of the newest locally built package, and can write that pin undermsbuild-sdksin the migrated repository's root and nestedglobal.jsonfiles instead of into every generated project file. All nested scopes use the same version while retaining their other settings.cs2gs validatefollows the pin recorded in the migrated tree, rejects missing or conflicting nested pins, and accepts--sdk-versionto check it. SDK attributes, explicit SDK elements, and SDK imports participate in pin rebinding and validation without dropping unrelated SDKs in translated or excluded projects. Global-json migration canonicalizes existing root pins. Copied native.gsprojfiles use the same pin; template payloads, including project/item templates and theirglobal.jsonfiles, remain untouched. Per-project validation rejects bare G# SDK declarations instead of silently resolving a different SDK, and rejects root or nested global pins that would mix pin modes. Bootstrap projects are rebound even with existing root SDKs, without dropping unrelated SDK declarations. Isolated stage-4 parity projects retain the resolved version, including when the exact package must be restored from NuGet instead of a local build. -
cs2gs reports every fail-fast
!!it puts on a value stored into generic storage (issue #4612, option 1).- What: nullable-oblivious C# can pass a possible null to
list.Add(x),items.Append(x), a delegateInvoke(x),dict[k] = v, a lambda returning intoFunc<..., TResult>, an array element (new[] { a, b },arr[i] = v), a collection initializer or expression element, or an iteratoryield, and the null is stored. cs2gs keeps its fail-fast policy and asserts the value, so the migrated code throws where the C# ran. - Where: each such site produces a
CS2GS-GENERIC-STORE-BRIDGEline in the app'stranslate.log. The line gives the location, the kind of slot (inferred or explicit method type argument, constructed generic member, delegate argument or result, type-parameter variable assignment or tuple element, array element, collection element, iterator element), the target, the destination slot's nullability, whether the result depends on that slot (using the containing type for constructor results), and the value. Embedded analyzer-test snippets retain this diagnostic identity and each distinct inner source span, including identical messages across namespace units. Nested tuple paths retain declared type-parameter classification and the actual leaf destination type, including nullable tuple envelopes at every nesting level, expandedparamselements, block-bodied/async lambda delegate return contracts, and substituted method type arguments. Synthesized tuple-key leaf suffixes survive value truncation. Whole-array or whole-collection writes toparamsparameter variables and direct carriers passed toparamsindexers are not expanded element stores. stderr gets one count per app. - Effect: generated code is unchanged. Explicit C#
value!assertions are also reported through null-preservingas,??,?., checked/unchecked wrappers, and value-producing=/??=assignments feeding generic arguments, elements, declarations, or method/delegate results, even when the destination accepts null, including nullable span and builder collection expressions. Ordinary assignment bridges also resolve the outer generic store even when their immediate target is concrete. Distinct store metadata and synthesized tuple-key member paths remain separate at a shared source span; exact speculative repeats of the same store and leaf still report once. A bridge whose target cannot be resolved is reported asunknown-target, so the list over-approximates rather than missing a site.
- What: nullable-oblivious C# can pass a possible null to
-
go2gs analyzenow provides the M0 typed Go inventory (ADR-0191, issue #4333). The separately versioned Go helper pinsgolang.org/x/tools/go/packagesand records schema-v1 package/test variants, module and build provenance, source bytes/spans, stable typed identities, exact constants, scopes, selections, calls, method sets, generic instances, embeds, generators, dependencies, diagnostics, and blockers. Analysis is offline and fail-closed: automatic toolchain downloads, ambient workspaces,GOPACKAGESDRIVER, generators, target binaries, and network module resolution are disabled. Exit zero means the requested inventory completed, whilemigrationReadyremains independent and false in M0. Migration blockers preserve typed nil/interface, byte-string, map, panic/defer/recover, fixed-array, and concurrency sites without choosing their later G# representation. Profile flags are allowlisted against tool execution/path overrides, and the selected Go executable supplies its own verified GOROOT. Preload-only failure inventories now obey the same final record bound as loaded inventories; package-input drift covers every Go-recognized extension independently of CGo selection; and validation recomputes source-manifest identity and UTF-8 claims while indexing scope ownership linearly. Version and GOROOT discovery use captured build metadata and the verified path/handoff rather than executinggo versionorgo env. The captured executable must identify as nativecmd/go; on Linux it must also be static ELF (including an internally linked static PIE) with no interpreter, dynamic imports, RPATH, or RUNPATH. Scripts and wrappers are rejected, and child PATH contains only its private stage. The Linux analysis worker applies a 2 GiBRLIMIT_DATAceiling before package loading so x/tools' internal command buffers remain process-bounded. Darwin preload now requires a native executable Mach-O with the matching CPU and executable file type. Non-Linux preload checks can publish deterministic toolchain/source mismatch blockers without loading packages; a matching profile still fails closed before publication. M0 now usesgo/packagesonly for metadata withCGO_ENABLED=0, then parses captured source and type-checks it in-process without compiled-file/export requests. It never executes the GOROOT compiler, assembler, linker, cgo, vet, a C/C++ compiler, pkg-config, or helper. It independently records profile-selected CGo/native source inputs and emits deterministic blockers; legacy profile compiler fields must be empty. The selectedcmd/go, captured GOROOT, and helper runtime/build information must self-report the same canonical final-release Go version label before preload. These labels are provenance metadata rather than authentication; executable and captured content hashes are authoritative identities, while validation checks structural and relational consistency. Unsupported labels and nonemptygoExperiment/goDebugsettings or helper build-timeGOEXPERIMENT/DefaultGODEBUGoverrides fail bootstrap rather than silently using different in-process parser/type-checker semantics. Entry package patterns are limited to canonical module-relative paths (with an optional final/...recursion), preventinggo/packagesquery forms or absolute paths from selecting source outside the captured mirror. Source capture and verification reject symlinks in every path component, bound directory reads and all traversed entry types before sorting, and share a deterministic traversal budget with local replacements. Profile bootstrap now requires a stable regular file no larger than 256 KiB before decoding or applying the configured timeout. Blocker messages now redact private filesystem roots and are UTF-8-normalized and bounded before stable-ID derivation, so incomplete inventories remain checkout-independent and each ID names the exact published message. Redaction respects path-component boundaries, selects nested roots before their parents, and recognizes Windows drive/UNC case and separator aliases without over-redacting lookalike prefixes or remote URIs; absolute,localhost, drive-authority, and configured UNCfile:URI paths are redacted, while unknown or encoded authority forms, unmatched drive paths, dot-segment aliases, and malformed or path-bearing query/fragment text fail closed. Strict path components also reject malformed whitespace, punctuation, and embedded drive tails, includinglocalhosttext outside the actual file authority. Operational local-replacement rewriting makes only the mirroredgo.modowner-writable; persistent descriptor-relative temporary-file open failures now abort cleanup instead of being retried. Structural type identities include positional ownership for unexported anonymous fields and interface methods, and compiled-file records publishgo/types' effective per-file language version. Profile andgoFlagstags share one canonical selection set, architecture feature levels expand to cmd/go-equivalent cumulative tool tags, and complete artifacts require a typed*ast.Fileroot for every compiled file. Output locking, invalidation, and publication stay relative to one held directory handle across ancestor renames. The output directory must remain exclusively controlled by go2gs; the lock excludes cooperating writers and observed identity drift fails, while active same-UID mutation is explicitly outside the portable threat boundary. Hashes detect provenance drift but do not authenticate such a peer. Span validation reparses captured bytes to verify exact raw and line-directive-adjusted paths, lines, and columns. Diagnostics are path-stable, initialization order is explicit, and schema validation rejects missing fields, count mismatches, stale payload-derived deterministic record IDs, including package IDs derived from semantic-profile plus authoritative GOROOT/toolchain and actual module/replacement identities, and type IDs scoped to that semantic profile. This separates GOOS/GOARCH/tag and local-replacement-content inventories without losing within-profile canonical type deduplication. Validation also rejects unknown file roles, native/embed role-flag disagreement, mismatches betweencompiledrole and owning-packagecompiledFileIds, noncompiled-file syntax trees, detached nodes, parent cycles, and complete artifacts without a loaded main-module package/source ownership graph. Self-embedded sources retain their compiled roles and embed links. Each node-bearing file must be one*ast.File-rooted tree. Blocker IDs are indexed during construction so bounded deduplication remains linear. These checks reuse producer contracts and establish internal consistency, not artifact authenticity. The pinned cliamp profile reports an actionable mismatch rather than substituting the installed Go toolchain. -
ADR-0191 now defines conservative Go interface/address lowering and staged performance gates (issue #4513). Concrete values snapshot at conversion, pointers retain their selected location, existing and converted interfaces preserve original Go dynamic identity, and value receivers copy per call. Wrapper reuse requires explicit proof that evaluation timing, typed-nil/comparability behavior, mutable adapter state, and observable CLR interop identity cannot change; address reuse similarly preserves dynamic bindings, slice owner/index selection, append reallocation, side effects and throwing behavior. The prerequisite spike merged in #4514 now requires non-empty Go/JIT/NativeAOT semantic parity, paired checksums, raw samples/allocation totals and exact provenance. Its runner has ADR-0154 failure mutants, while
--no-aotis explicitly exploratory. The allocation fixes for issues #4511 and #4512, implemented by PRs #4515 and #4516, are enforced by the integrated prerequisite gate; semantic completion and later package/application performance readiness remain separate. This is policy and native-mechanism evidence, not ago2gstranslator implementation. -
@GeneratedRegexworks in native G# projects (ADR-0192 follow-on 2, ADR-0145 amendment). Declare the method as a partial method in asharedblock,shared { @GeneratedRegex("\\d+") private partial func Digits() Regex; }, and the SDK runs the real Regex source generator throughgsgen. The generated implementation becomes a G# implementing part that pairs with your declaring part, so calls run through the generatedRegexsubclass. The same applies to other generators that implement partial methods, such as@LoggerMessage. -
A
partial data classorpartial data structcan hold partial methods, and@GeneratedRegexworks in one (ADR-0192 amendment). This is the G# spelling of a C#partial recordwith a[GeneratedRegex]method, e.g.public sealed partial data class GitHubUrl(Owner string, Name string) { shared { @GeneratedRegex("^https://...$") private partial func Pattern() Regex; } }.gsgennow shows generators a data type as a C#recordwhen its inheritance chain allows it: it has no base class other than record-rendered data types, and no plain class derives from it. Otherwise the type is still a C#class. Either way, the generated part getsdataso it merges with yours. A positional parameter list a generator adds to a data type that already has one is reported asGS9209. Before, the build failed withGS0479.GS0607andGS0608now say that a data class or data struct qualifies.- The implementing part is spelled with your declaring part's header, so
System.Text.RegularExpressions.Regexorcount intpair as well asRegexorcount int32. A parameter-name mismatch between your declaring part and the generated implementation is reported asGS9208instead of being paired. - The generator's helper types keep their own package,
System.Text.RegularExpressions.Generated, so a type of yours namedUtilitiesno longer collides with them. - A pattern that backtracks inside a loop, such as
(foo|ba+r)+\w*?baz, builds too: issue #4422 lets the generated helpers pass&base.runstack, and cs2gs carries the generator's!across as a scoped@SuppressDiagnostic("GS0612").
- The implementing part is spelled with your declaring part's header, so
-
cs2gs migratetranslates[GeneratedRegex]to a G# declaring part, and the__generatedRegex_rewrite is gone (issue #4301, ADR-0192 follow-on 3, ADR-0143). A C#[GeneratedRegex(...)] private static partial Regex Digits();becomes@GeneratedRegex(...) private partial func Digits() Regex;in the type'ssharedblock (an instance method stays an instance member), and the migrated project's build runs the real Regex generator throughgsgen, exactly as a native G# project does. The old translation constructed a cachedRegexin a private__generatedRegex_Digitsfield instead.- The pattern, options, match timeout and culture name are re-spelled from their constant values, positionally, so a
constpattern or a namedmatchTimeoutMilliseconds:argument migrates as a literal. - Culture-sensitive IgnoreCase (
RegexOptions.IgnoreCasewith a culture name, or an inline(?i)withoutCultureInvariant) now migrates; the old translation reported it as unsupported. - The generated C# implementation is dropped, even when it is a committed file.
- A C#
partial recordorpartial record structkeeps the declaring part in the translated G#partial data classorpartial data struct. - A top-level-statements program's partial
Programclass that declares a[GeneratedRegex]method stays a class instead of being hoisted to top-level funcs, and its private members becomeinternalso the G# top-level statements can reach them. - A
[GeneratedRegex]method of a nested type is reported as unsupported because gsgen implements only top-level types; move it to a top-level partial type. The partial-property form is still unsupported because G# has no partial properties.
- The pattern, options, match timeout and culture name are re-spelled from their constant values, positionally, so a
-
A
fixedstatement can pin a fixed-size buffer field directly (issue #4378, ADR-0125 amendment).fixed p *int8 = h.Bone.Name { … }— or a barefixed p *int8 = Name { … }inside the declaring struct — bindspto the buffer's first element and keeps the buffer's containing storage pinned for the whole block, the G# spelling of C#'sfixed (sbyte* p = Name) { … }and the sameint8& pinnedIL csc emits. This unblocks the Raylib-csBoneInfo/ModelAnimationinterop pattern:cs2gsnow translates suchfixedstatements instead of reporting them as an Unsupported translation gap. As in C#, only a buffer in movable storage (a class field, an array/slice element, arefparameter, or a struct method's receiver) can be pinned; a buffer reached through a local, a by-value parameter or a pointer dereference is already fixed and reports the newGS0507(C#'s CS0213) — use it directly as a*Tinstead. -
A fixed-size buffer field can be used by its bare name inside the declaring struct (issue #4377).
Name[i],Name[i] = vandreturn Namenow decay the buffer to its*Tfirst-element pointer exactly asthis.Namedoes, instead of failing withGS0116("is not indexable"). -
G# source can declare a scope nullability-oblivious:
--nullability=oblivious,@Obliviousand@NullabilityEnabled(ADR-0186 §9, step 5). They exist socs2gscan translate a nullability-oblivious C# project without inventing a nullability nobody stated; hand-written G# has no reason to use them.- What changes. Inside an oblivious scope the top level of an unadorned reference type written as the type of a slot means the platform type
T!rather thanT: the declared type of a field, property, event, parameter, return, local,forvariable, inlineoutdeclaration or lambda parameter. Every nested position stays exactly as written: type arguments, array and slice elements, map keys and values, tuple elements, function-type parameters and returns, and the like. Sovar xs List[string]there has typeList[string]!: the slot's top level is platform, and the element is stillstring. Likewise[]stringis[]!string. A nil stored into an unadorned element is therefore an error, as outside the scope; writeList[string?]for a container that carries nils.T?still meansT?, and value types and open type parameters are unchanged. (The owner reversed the first cut, which also made nested positionsT!, because §3 rule 3 then rejected every container handed between an oblivious scope and an enabled declaration: about 2,700 of them in the self-migration corpus. Imported oblivious metadata is unaffected; its nested positions are stillT!.) - What does not. Base-type / interface lists, generic constraints, explicit-interface qualifiers and
@DllImport/@LibraryImportsignatures are exempt; the top level of acatch, pattern orif letbinding stays non-null. - Where it applies.
--nullability=obliviousmakes a whole compilation oblivious;@Obliviouson a type, function, property, field, event, parameter, local or block does it for one declaration, and@NullabilityEnabledopts one back out. The nearest annotation wins. Both are compiler-intrinsic (no attribute type, no metadata of their own); a malformed one is GS9307. - Metadata. An oblivious declaration emits explicit oblivious nullability metadata (byte
0) for its top level, and its nested positions' own state (soList[string]is{0, 1}). It re-imports asList[string]!from another assembly. Acscconsumer reads the top level as it reads a#nullable disablemember, and the element as non-null.
- What changes. Inside an oblivious scope the top level of an unadorned reference type written as the type of a slot means the platform type
-
A get-only auto-property can be assigned in its declaring constructor (issue #4350). As in C#,
prop Length int32 { get; }may be written — plainly, throughthis., with a compound operator, or with++— inside aninit(...)of the declaring type on the instance being constructed; the store goes straight to the backing field and no setter is emitted. Everywhere else, including a derived constructor and a lambda inside the constructor, it stays read-only (GS0127). cs2gs therefore translates a C# instance get-only auto-property to{ get; }instead of{ get; init; }, so migrated assemblies no longer gain a publicinitsetter the C# assembly never had (found comparing the migratedGsharp.Runtime.ValuesABI, whereSlice<T>.Length/Capacityhad acquired setters). Virtual, override, and static get-only auto-properties keep the previous spelling. -
A struct member can return a reference into its own instance state, with
@UnscopedRef(ADR-0184, issue #376, found restoring the fixture PR #4288 had to work around). G# has advertised@UnscopedRefsince ADR-0058, but what shipped only ever clearedIsScopedon aref structreceiver — which governs the by-VALUEGS0219check, not the ref-safe-context thatreturn ref this.<field>actually depends on.HasFunctionLocalRefScope's parameter case readp.IsScoped || p.RefKind == RefKind.None, and a receiver'sRefKindis alwaysNone, so the second disjunct was unconditionally true and the annotation was inert for its entire stated purpose; there was no property/indexer spelling at all, because accessors are built withdeclaration: nulland the old recogniser read raw declaration syntax.@UnscopedRefis now recognised by CLR TYPE IDENTITY (System.Diagnostics.CodeAnalysis.UnscopedRefAttribute, ADR-0084 §L5) off the bound attribute list, works on afunc, aprop, and an indexer of any struct orref struct, and is emitted as a realCustomAttributerow — on the MethodDef for thefuncspelling and the PropertyDef for theprop/indexer spelling — so a C# consumer of the assembly sees the same contract gsc enforced. The emitted body isldarg.0; ldflda; ret— the same sequencecscproduces for[UnscopedRef] public ref int Slot() => ref this.total;;ldarga.0there would yield a pointer to the receiver's own pointer slot, which would compile and verify and return garbage, so the emit test asserts the opcodes rather than just that it compiled. Because it is a real attribute type, it now requiresimport System.Diagnostics.CodeAnalysis; without it the binder reportsGS0198and the member is not un-scoped. cs2gs also hoists a C# ACCESSOR-level[UnscopedRef]up to the G# member-level annotation (C# treats both placements identically; G#'s code model has no accessor-attribute slot, so it used to vanish silently) —test/Core.Tests/Fixtures/UnscopedRefIndexerFixture.csis restored as a real.csfile and migrates again.- #4664 follow-up: The fixture restoration above records the ADR-0184
milestone. Its CLR import contract is now embedded C# source data in
test/Core.Tests/TestData/NativeMetadataContracts.cs.txt, compiled by the existing RoslynCSharpFixturehelper and passed to importer tests as an explicit physical native assembly so the oracle stays native when the test harness migrates. ADR-0184's UnscopedRef and escape semantics are unchanged.
- #4664 follow-up: The fixture restoration above records the ADR-0184
milestone. Its CLR import contract is now embedded C# source data in
-
A struct member's
thisis writable storage, in every instance member (ADR-0184 D2).ParameterSymbolderivesIsReadOnlyfrom itsRefKind, and a receiver'sRefKindisNone, soRefCapabilities.IsReadOnlyStorageclassified everythisas READ-ONLY — which is backwards, since the CLR passes a struct's receiver asref S.return ref this.Totaltherefore failed the lvalue/readonly gate and reportedGS0253("the operand of 'return ref' must be an lvalue") instead of ever reaching the escape check. The assignment binder already carried the correct exemption for member WRITES (ReceiverVariableIsThis, issue #947); the same fact is now on the symbol, where the static ref-capability classifiers can see it. Not conditional on@UnscopedRef— a value-type receiver is writable whether or not the member is annotated. A REFERENCE-type receiver is deliberately not exempted. -
awaitis legal in a plainfunc, and colours it (ADR-0174 D4'sawait g()row, issue #3954). Awaiting makes the awaiting function suspending, so colourless Go-style code can await an ordinaryTask/ValueTaskwithout becomingasync func. Where inference may not change a signature — an entry point, anopen/override/interface member, an accessor, a constructor, an operator, an iterator, a function literal, anunsafeorfixedbody —GS0574asks forasync func(an observableTask[R]) orsuspend func(implicitly awaited,R).GS0132keeps only the case where no enclosing function exists. -
An awaitable means in G# what it means in C#. The compiler awaits for you only where the syntax is a channel operation —
ch <- v,<-ch,select, channelfor..in— never because a library method returns a task.ReceiveBatch/SendBatchare ordinaryValueTask[int32]calls: writeawait ch.SendBatch(items), and.AsTask()on one names the task exactly as in C#. -
Gsharp.Runtime.Channels: a C#-authored channel runtime bundled with the SDK (tools/channels/) and auto-referenced by every project.Chan<T>is a rendezvous-capableChannel<T>subclass with Go-exact close semantics, a two-value receive, batch transfer, and the transactionalselectwaiter protocol;gsccopies it beside an emitted program that references it. -
Directional channel types and the D2 operation matrix: foreign BCL channels, readers, and writers flow into
chan[T]/in chan[T]/out chan[T]with no adapter — and back out, so achan[T]is accepted wherever a C# API asks for aChannel<T>, aChannelWriter<T>, or aChannelReader<T>(issue #3976). The lattice reads the types rather than the spelling, so a plain BCLChannel<T>now converts implicitly to a writer or reader target — thechan[T]->out chan[T]row written in CLR names, and the same conversion C# has always had throughChannel<TWrite, TRead>'s implicit operators. This holds when the element type is still open: insidefunc f[T](ch chan[T]), the channel reaches an imported constructor or method takingChannel<T>/ChannelReader<T>/ChannelWriter<T>(issue #3876), where it previously reported that no overload was applicable. -
A
: base(...)initializer argument whose type carries an open type parameter now resolves against the base's constructors (issue #3984).class MyList[T] : List[T] { init(items []T) : base(items) {} }reported thatListhad no one-argument constructor; the argument was never ranked at all.[]T,map[K, V],chan[T]and a tuple with a symbolic element all bind in that position now, and a base call that really is inapplicable reportsGS0267(naming applicability) rather thanGS0214claiming an arity the base does declare. Two shapes that used to compile become errors, because they were emitting unverifiable IL: an argument whose element does not match the base's type argument, such as[]stringor(int32, object)passed to aBase[T]'sIEnumerable<T>/(int32, T)parameter. -
A C#-authored generic extension on
ChannelReader<T>orChannelWriter<T>is now found on thechan[T]spelling callers actually write (issue #3877), so a C# library can publish an extension onChannelReader<T>/ChannelWriter<T>and have it bind on a whole channel. Method type inference contributes the channel's element through the direction lattice; the lattice itself is unchanged, so anout chan[T]still finds no reader surface, anin chan[T]no writer surface, and the element still has to match. The batch surface (D10) drops the fourChannel[T]overloads that existed only to work around this. -
A C#-authored generic method or CONSTRUCTOR over a
ChannelReader<T>orChannelWriter<T>also binds when the channel's element type is declared in the same program —chan[Pair]for a G#struct Pair, as well as an openchan[T]inside a generic function (issue #3982). Applicability compares the channel against the candidate at the same level of erasure, and the winning candidate is closed over the real element, so the emitted call carriesPairrather thanobject. The lattice is unchanged: anout chan[T]still finds no reader surface, anin chan[T]no writer surface, and the element still has to match. A genuineChannelReader<object>parameter stays out of reach, so a library that declares one beside its generic overload does not change which one a channel call picks. -
A nullable channel reaches a non-nullable imported
Channel<T>parameter whatever its element type (issue #3985).chan[T]?there used to reportGS0155where the closedchan[int32]?— and astring?at a non-nullablestringparameter — was accepted; both spellings now behave the same way, so!!is no longer needed at such a call, and the same now holds at a generic method's or generic class'sChannelReader<T>/ChannelWriter<T>parameter. This is a CLR-boundary rule only: passing achan[int32]?to a G#-declaredchan[int32]parameter still reportsGS0154, and direction and element are still enforced. -
A nullable channel also reaches a non-generic imported
ChannelWriter<T>/ChannelReader<T>parameter (issue #3992), so the last slot where achan[int32]?behaved differently from achan[int32]is gone:Plain.W(c)used to reportGS0159for the nullable form and bind for the non-nullable one. Applicability had already been ignoring the annotation wherever the CLR shapes were related (achan[int32]?reaches aChannel[int32]parameter exactly as astring?reaches astringone); only the fallback that ranks a candidate on G#'s structural shapes still re-asked the question on the annotated type, which is why the ADR-0174 direction view — the one relation the CLR does not carry — was the only one affected. Nothing becomes applicable whose non-nullable form was not already applicable, and the same limits hold: direction and element still decide, and a G#-declared parameter still reportsGS0154. -
A nullable channel reaches a non-nullable imported
Channel<T>parameter whatever its element type (issue #3985).chan[T]?there used to reportGS0155where the closedchan[int32]?— and astring?at a non-nullablestringparameter — was accepted; both spellings now behave the same way, so!!is no longer needed at such a call, and the same now holds at a generic method's or generic class'sChannelReader<T>/ChannelWriter<T>parameter. A nullable channel still does not reach a non-genericChannelReader<T>/ChannelWriter<T>parameter (issue #3992). This is a CLR-boundary rule only: passing achan[int32]?to a G#-declaredchan[int32]parameter still reportsGS0154, and direction and element are still enforced. -
A
map[K, V]reaches aDictionary<K, V>parameter, and a tuple aSystem.ValueTuple<…>one, when an element is still open (issue #3987).map[K, V]ISDictionary<K, V>(ADR-0104) and a G# tuple IS aValueTuple<…>(ADR-0158), and with closed elements the compiler said so — but the rule compared the two sides' CLR types, and an open element leaves neither side with one to read, sofunc makeMap[K, V](entries map[K, V]) MapHolder[K, V] { return MapHolder[K, V](entries) }reportedGS0155against the parameter it already matched. Both spellings are now recognised by shape, in either direction and at any call position. One shape that used to compile becomes an error, because it was emitting unverifiable IL: a tuple whose element does not match the target's type argument, such as(int32, object)passed to a(int32, T)parameter. -
An argument whose type carries a same-compilation or open element no longer binds to a genuine
objectslot (issue #3989). A same-compilation type argument erases toobjectwhile binding — that erasure is what lets[]Pair{…}.Count()reach LINQ — but at the erased level it was indistinguishable from a realobject, soList[Pair]bound to a parameter that genuinely isList<object>and emitted IL ILVerify rejects; the covariant sibling (IEnumerable<object>) went further and threwEntryPointNotFoundExceptionat run time, because CLR variance does not reach a value-type element. Applicability now asks whether this slot'sobjectCOULD have come from erasure — the same question #3982's channel gate asks, with the opposite answer acted on — and refuses the bind when it could not. What the erasure exists to serve is untouched: an inferred generic slot (Count[TSource](IEnumerable[TSource]),M[T](List[T])), a parameter that genuinely isobject, a reference element riding real covariance, and every non-generic target (System.Array,IEnumerable,ICollection,IList,IDictionary) all bind exactly as before. A library that declares anobjectoverload beside a generic one now picks the generic one instead of the overload that cannot hold the argument. -
An erased CLASS surrogate no longer binds to the imported base it erased into (issue #4006). A same-compilation class has no CLR identity while binding, so it is presented as its IMPORTED BASE — and at that level
List[Derived]was indistinguishable from a genuineList<ImportedBase>. Both spellings of the confusion emitted IL ILVerify rejects, becauseList<T>andDictionary<K, V>are INVARIANT, and each reached the parameter by a different route:map[string, Derived]matched a genuineDictionary<string, ImportedBase>by IDENTITY, which #3989's gate declined to question because it only looked for a nestedobject;List[Derived]was not applicable by CLR shape at all, and was instead admitted by the ADR-0148 structural-projection fallback, which asked the projection planner directly and got a nonsense "yes" (twoLists share a parameterless constructor and aCapacity) for a pair the conversion layer refuses outright — so nothing was emitted and the raw list was pushed. One gate now covers both: the erased-argument check derives its surrogate set from the argument itself rather than looking only forobject, and applicability asks it on the structural-projection arm too. Everything legitimate is untouched: covariance still binds (IEnumerable<ImportedBase>, and[]Derivedat anImportedBase[]parameter, since CLR arrays really are covariant), a genuineList[ImportedBase]orDictionary[string, ImportedBase]still binds, an inferred generic slot (M[T](List[T]), and an imported delegate's erasedInvoke) is never second-guessed, and a real ADR-0148 projection at an imported method parameter still binds and emits. The same-compilation ENUM surrogate had no such hole —List[MyEnum]at aList<int>parameter was already refused, and still is. -
A symbolic tuple at an imported generic method's parameter now emits verifiable IL (issue #4000). Inside
func firstOf[T](pair (int32, T)), the callProbes.FirstOf[T](pair)compiled, ran, and printed the right answer while emitting IL ILVerify rejects: the argument was converted against the ERASED parameter shapeValueTuple<int32, object>— boxing the element and rebuilding the tuple — and handed to a call closed over the realT, which wantsValueTuple<int32, T>. The erased-slot recovery that already handles a bareT, aT?, a same-compilation type, a lambda and a channel now handles a tuple too, so the argument is identity and nothing is rebuilt. This holds for the open element in either position and nested one level down. Nothing else changes: a parameter that GENUINELY is(int, object)still boxes and rebuilds, and themap[K, V]sibling of the same call, which was already correct, is unaffected. -
A
map, slice or fixed-length array of a same-compilation class reaches an inferred generic slot when the type arguments are written explicitly (issue #4016).Probes.CountAnyMap[string, Derived](entries)reportedGS0159while theListspelling of the same call bound, and while the very same map call bound when the type arguments were INFERRED. Two projections of one class disagreed: every structural spelling presents a same-compilation class as its IMPORTED BASE (class Derived : ImportedBasearrives asImportedBase), but an explicit type argument closed the candidate over a flatSystem.Objectplaceholder — so aDictionary<string, ImportedBase>argument was ranked against aDictionary<string, object>parameter, which is invariant, and no candidate applied. The placeholder now uses the same erasure the arguments use, so the two sides agree; this is the correction #3087 already made for symbolic TUPLE type arguments. The issue's own boundary was narrower than reported and is corrected on it: inference always bound, a same-compilation class with NO imported base always bound (its erasure was alreadyobject), and the failure was nevermap-specific —[]Derivedand[N]Derivedat aT[]slot failed identically. Nothing is loosened: #4006's rejections stand, so an erased class surrogate still does not satisfy a GENUINE (non-erased)List<ImportedBase>orDictionary<string, ImportedBase>slot in either spelling. -
GS0548(advisory:chan[T]()is a rendezvous channel),GS0549/GS0550(send/receive through the wrong directional handle),GS0554(a channel-receive binding form with the wrong number of targets),GS0555(while let v = chwhere a receive was meant). -
go { … }(ADR-0174 D14): the block form ofgospawns the block as a goroutine, capturing the enclosing locals (per iteration for afor … invariable) —go func() { … }()without the ceremony. -
scopeis completed (ADR-0174 D5/D6): everygoinside a scope reports to the scope's frame (noTaskper goroutine); the block binds an implicitctx(Gsharp.Concurrency.Context) that the first goroutine failure cancels promptly; exit follows the documented precedence table (ScopeExceptionwith the cause first, a failing body rethrown unwrapped) and, inside a suspending function, is awaited rather than blocked. A nested scope'sctxis linked to the enclosing one (ctx.Parent), andreturnfrom inside a scope still counts as returning on every path. A freegooutside any scope is fail-fast on an unhandled exception (GoroutineRuntime.UnhandledGoroutineExceptionto observe). -
A small concurrency library (ADR-0174 D9):
after(d)andtick(d)are selectable timers —case <-after(d)is the timeout arm, and a select receive arm now accepts anything selectable, not only a channel — andmerge(a, b, …)fans several channels into one receive-only channel that closes when the last input does. They live in the implicitly importedGsharp.Concurrencynamespace and are called by bare name; a program that declares its ownafterkeeps its own. -
Batch channel operations and
chunks(ADR-0174 D10). A channel handle gainsTryReceiveBatch/TrySendBatch(aSpan[T], never waits) andReceiveBatch/SendBatch(aMemory[T], can park, and returns aValueTask[int32]youawaitlike any other — issue #3954 — a destination that survives a park cannot be ref-like).chunks(ch, n)reads a channel in batches:for batch in chunks(input, 1024)is ordinary channel iteration wherebatchis aReadOnlyMemory[T]that the receiver owns, so one lock acquisition and one park are amortized across the batch. A batch cut short by a close or a cancellation returns the count it moved rather than throwing, so a retry cannot duplicate elements.GS0562warns when the channel is a rendezvous, where batching is correct but pointless. -
async let(ADR-0174 D15):async let name = exprstartsexpras a child of the enclosingscopeand bindsnameto its eventual result, read asawait name. Both children of twoasync letbindings run concurrently; the binding is a value of typeR, never a handle, so a spawn cannot outlive the block that owns it. A binding you never read has its child cancelled and joined at block exit, and a failure nobody read still reaches the block'sScopeExceptionrather than being dropped; a failing child does not cancel its siblings. New diagnostics:GS0551(no enclosingscope),GS0559(never awaited),GS0569(read withoutawait). -
Three more
selectarm shapes (ADR-0174 D8). Every arm may carry awhenguard, evaluated once when the select is entered; a false guard keeps its arm out of the select entirely, which is how G# spells Go's "set the channel tonilto disable this case".case await taskandcase let v = await tasklet aTaskorTask[T]race the channels on the same waiter.case cancelledreplaces Go'scase <-ctx.Done(): the ambient context's cancellation becomes an arm instead of an unwind. New diagnostics:GS0556(a guard that is not abool),GS0557(acancelledarm with no context to observe, so it would be unreachable), andGS0564(one channel both sent to and received from by the same select). Cancellation also now reaches aselectwritten in a callee with noscopeof its own, through the caller's context. -
selectis rebuilt on one registered waiter (ADR-0174 D8): arms are attempted in uniform-random order like Go's, so two ready arms are both chosen instead of the first one written always winning; a select with no ready arm registers on every arm at once and parks the state machine rather than blocking a thread onTask.WhenAny; and winning is the transfer, so a value can no longer be stolen between choosing an arm and running it. Aselectinside a cancelledscopeunwinds. -
Cancellation unwinds parked channel operations (ADR-0174 D7): a receive, send, or channel loop inside a
scopeparks on that block'sctx, so the first goroutine failure collapses siblings that are waiting on a channel instead of leaving them parked. An operation that already committed keeps its value — cancellation wins only before the transfer. Hosts can retune the budgets and observe the diagnostics throughGsharp.Concurrency.GsharpRuntime(DeferGraceBudget,ScopeStallTimeout,DeferGraceExpired,ScopeStalled). Cancellation crosses calls: a suspending function receives the caller's context as a trailing optional parameter, so an operation inside a callee unwinds with the caller's scope. Declaringctx Contextin a signature uses that parameter instead, and a C# consumer calls the signature as written or passes aContextexplicitly. -
defercleanup is shielded (ADR-0174 D7): a deferred body runs under a cancellation-immune context, so cleanup that drains a channel or signals completion still runs while the block around it unwinds. A grace budget bounds it (GSHARP_DEFER_GRACE_MS, five seconds by default) so cleanup cannot hold cancellation up forever;GsharpRuntime.DeferGraceExpiredreports an abandoned one. Cleanup outside any scope costs nothing. -
Suspension is inferred (ADR-0174 D4): a plain
functhat performs a channel operation, or calls a function that suspends, is compiled as a suspending function — aValueTask[R]state machine labelled[Suspending]— with no keyword, as a fixed point over the call graph. Go-shaped pipelines keep their shape and stop holding threads. Inference stops atasync func,open/override/abstract methods, interface members and their implementations, constructors, accessors, operators, P/Invoke, iterators,Dispose, and function literals; a call to a suspending function from one of those blocks through the runtime's root bridge and warns withGS0558. Every emitted G# method that suspends now returnsValueTask/ValueTask[R]instead ofR— a binary change for C# callers of such functions. -
suspend func(ADR-0174 D4, the declared form): a suspending function compiles to aValueTask[R]-returning state machine on the pooling builder, carries[Suspending], and is awaited implicitly by every G# call site — callers writelet v = take(ch)and seeR; an explicitawait take(ch)is accepted as the same thing. From a function that is neither suspending norasyncthe call blocks the thread andGS0558warns; the entry point is the silent root. Inference of suspension for plainfuncfollows in a later step of Phase 3. -
Debugging through suspension (ADR-0174 P3-8): every async or suspending kickoff carries
[AsyncStateMachine]and[DebuggerStepThrough], soEnvironment.StackTraceand debuggers name the logical function instead of<f>d__1.MoveNext, and the Portable PDB carries the async-method-stepping blob (yield/resume offsets per await) that lets a debugger step over a parked channel receive onto the next source line. Fixed: bodies rewritten by the compiler — everyasync funcbody, and now every suspending one — carried no line information at all, so breakpoints inside them never bound; each source line of such a body now maps into the state machine. -
Channel operations inside an
async funcsuspend instead of blocking (ADR-0174 D4, first step): a receive, two-value receive, send,for v in ch, orwhile let v = <-chin anasync func(or async lambda /async sequence) parks the state machine, not a thread — hundreds of parked receives no longer pin thread-pool threads. A channel operation inside alockbody keeps the blocking lowering (the monitor is thread-affine). -
Observable completion (ADR-0174 D3): the two-value receive
let (v, ok) = <-ch(orv, ok = <-ch) distinguishes a delivered zero value from a closed channel;while let v = <-ch { … }andfor v in ch { … }loop until the channel is closed. Achan[T?]element that isnilis delivered, not mistaken for close. -
Mutual-recursion groups now also work for NON-generic local functions, not only generic ones (issue #4219 umbrella remainder).
let first[T] = func(x T) ... { ... second(x) ... }/let second[U] = func(x U) ... { ... first(x) ... }— two or more consecutive generic local functions calling each other, forward or in a cycle — has compiled since the original #4219 milestone (b84bf800) and its #4221/#4223 follow-ups; the plain (non-generic) spellinglet first = func(x int32) int32 { return second(x) }/let second = func(x int32) int32 { return first(x) }still reportedGS0130("undefined variable") on the forward reference, becauseStatementBinder's consecutive-declaration-group mechanism required a[T, ...]list to opt in. The SAME prepare-then-bind signature-registration machinery (LambdaBinder.PrepareGenericLocalFunctionDeclaration, generalized to tolerate a null type-parameter list) now also groups a run of TWO OR MORE consecutive non-genericlet name = func (...) ... { ... }declarations, registering every member's signature before any member's body binds. A LONE non-generic local function (no sibling to form a run with) is untouched and keeps its existing delegate-valued-variable representation — this is a deliberate compatibility boundary, not an accident: blindly hoisting every ordinarylet/varclosure would change name resolution and mutable-recursion semantics for the overwhelming majority of existing code, so only the unambiguous "two-or-more named local functions in a row" shape opts in. Capturing outer state composes:ClosureEmitter's capturing-direct-call-local closure-dispatch path (GenericLocalClosures, built for #4221's generic case) is widened fromFunction.IsGenerictoFunction.LocalDeclaration != null, so a capturing non-generic group member dispatches through its closure'sInvokemethod exactly like a generic one, and shared/mutated captured state (via the pre-existingCaptureBoxingRewriter) is visible across sibling calls. One narrow, deliberately-deferred limitation: converting a CAPTURING group member's bare name to an explicit delegate value (let cb (int32) -> int32 = first) now reportsGS0126("not a variable") instead of working, because a capturing direct-call local has no single stable closure instance to bind a bare-name conversion to (each direct call it makes materializes its own) — this matches the pre-existing behavior of a capturing GENERIC local function, but is a narrowing relative to the old non-generic delegate-variable baseline for that one shape; a NON-capturing group member's bare-name conversion is unaffected and still works (ExpressionBinder.IsMethodGroupCandidateUsablenow also accepts a non-generic, non-capturing direct-call local). A run mixing generic and non-generic members remains out of scope (unchangedGS0130on the cross-kind forward reference), matching the existing generic/non-generic mixed-group exclusion. -
A
ref-returning function LITERAL is now supported as a direct-call local function (issue #4219 umbrella remainder, workstream B — distinct from #4224's scope, a NAMED ref-returning call/property usable as storage).let at = func(values []int32, index int32) ref int32 { return ref values[index] }declares a local function whose own return kind isref, reusing the named-function ref-return machinery in full (FunctionSymbol.ReturnRefKind, the existingreturn refstatement binder, #4224's alias/storage machinery for a call result, and the existing escape/lifetime checker —var ref alias = at(xs, 0); alias = 42mutates the original storage,let v = at(xs, 0)reads a value, andfunc() ref int32 { var x = 1; return ref x }still reportsGS0254for escaping function-local storage). Aref-returning literal always routes through the direct-call local-function path — standing alone or grouped with another ref-returning sibling — because a CLR delegate'sInvokecannot be made to return by ref without a dedicated synthesized delegate shape; only a non-genericlet name = func (...) ref T { ... }declaration is accepted. Deliberately deferred, and reported as the newGS0588rather than silently accepted or crashing: converting a ref-returning function (literal-backed local OR named) to a delegate/function-type VALUE —DelegateTypeSymbol/FunctionTypeSymbolcarry no return-ref-kind, so the existing method-group/delegate-conversion machinery would otherwise silently narrow a by-ref function to a by-value one instead of rejecting the conversion — and a GENERIC ref-returning local function (let f[T] = func (...) ref T { ... }), whose MethodSpec/signature-encoding interaction with a by-ref return has not been verified. -
A type parameter may be constrained by another type parameter (issue #4043). C#'s
where TDerived : TBasehas a G# spelling —[TBase, TDerived TBase]— that the parser already accepted and the binder then rejected withGS0153: Type 'TBase' cannot be used as a type-parameter constraint because it is neither an interface nor a class. The constraint resolver walked an interface branch, a user-class branch and an imported-class branch and simply fell off the end for a type parameter. All three placements are now bound and emitted: a generic function's own list (func Dependent[TBase, TDerived TBase]()), a generic type's own list (class Pair[TBase, TDerived TBase]), and a generic method's parameter bounded by its ENCLOSING type's parameter (class Box[T] { func Accept[U T](u U) }). The bound projects onto aGenericParamConstraintmetadata row namingVAR(n)orMVAR(n)— the encodingcscemits for the same C# source, measured by reflecting over both outputs — so the assembly IL-verifies. A type argument that does not equal, derive from or implement the argument supplied for the bounding parameter reportsGS0152naming the bounding parameter; where the relation has no closed answer because either side still mentions an unsubstituted type parameter, the instantiation is accepted, since the CLR only loads it once it is closed. A dependent bound deliberately does NOT propagate the bounding parameter's reference-type nature:[TBase class, TDerived TBase]does not makenillegal atTDerived, because the CLR constraint row carries no such implication and the looser reading is the #4027 unverifiable-ldnulldefect one release later. A circular chain ([T T],[A B, B A]) reports the newGS0581, mirroring C#'s CS0454. This was the single compile error the self-migration gate reported fortest/Core.Tests. -
The G# analyzer API gains an operation-block registration and the operation surface the ADR-0193 funnel rules use, and
cs2gsmaps the Roslyn equivalents (issue #4436, ADR-0169).AnalysisContext.RegisterBoundBodyActionruns a rule once per function body with aBoundBodyAnalysisContext(the analogue ofRegisterOperationBlockAction). Bound nodes gainChildNodes,Descendants()andDescendantsAndSelf(). Two analyzer-facing bases,BoundMethodReferenceOperationExpressionandBoundPropertyReferenceOperationExpression, span the user and CLR forms of a method group or property access. Symbols gainGetAttributes(), andFunctionSymbolgainsAssociatedSymbolandMethodKind.cs2gsnow translates the matching Roslyn members: local references, simple assignments, variable declarators,foreachlocals, inlineout var,istests, type/declaration/recursive patterns andtypeof. Previously an analyzer that used them stopped atCS2GS-GAP. Each row is checked by a parity test: Roslyn runs the analyzer over a C# corpus, and the translated analyzer, compiled by gsc, must report the same diagnostics over the translated corpus. Registering several kinds that map to one G# kind (the three Roslyn pattern kinds) now runs the rule once per node instead of once per kind. -
Bound-node analyzer actions now see the same operation tree as operation-block actions (issue #4457).
RegisterBoundNodeActionand translated RoslynRegisterOperationActionrules enter lambda and local-function bodies, visit a local assignment's target before its value, and still treat a plainx is Tas one type-test operation. Nested nodes retain the enclosing member as their containing function, matching Roslyn.
Fixed
-
Aligned VS Code and Visual Studio TextMate highlighting with website Prism for escaped and Unicode names, contextual intrinsics and reference/slice vocabulary, numeric and character literals, and nested string interpolation. Shared regression cases exercise both tokenizers.
-
Property writes through tuple elements update the stored struct (issue #5023).
tuple.Item1.Value = "v"previously changed a copy and silently lost the update. Tuple-element receivers now keep their storage through nested tuples, field and array chains, explicit address/dereference pairs, compound assignments, control-flow right-hand sides, and suspension. Receiver components run once, before the right-hand side; read-only storage remains protected. Native and CLR ref-returning owners are captured once for writes and diagnosed if their managed address would have to survive suspension; non-suspending opaque borrows retain their once-captured address. Capturable array/reference owners stop borrowed-address propagation. Conditional and nested-field borrows preserve the selected storage across suspension without retaining a managed pointer. -
The SDK's assembly-info task and four compiler helpers no longer assert values the C# null-tested (issue #4932). The cut-over turned C# code that passed a value on and then checked it for null into a
!!assertion before the check, so these places threw a NullReferenceException where 0.4 did not:WriteGsharpAssemblyInfoTask, whenOutputFileis a filesystem root andPath.GetDirectoryNamereturns null. The task now skips creating a directory, as the C# did, and fails at the write.ClrTypeUtilities.SafeGetEventIncludingInterfaces,SafeGetPropertyIncludingInterfacesandSafeGetMethodsIncludingInterfaces, given a nil type. They now return nil, nil and an empty array.TypeSymbol.AreRuntimeEquivalentIgnoringReferenceNullability, given a nil operand. Two nils now compare equal, and nil against a type compares unequal.
-
cs2gs translates Oahu again, and its report renders a failed run (issue #4918). The cut-over turned three null-tolerant C# locals in cs2gs's own sources into
!!assertions. Two of them were in the checks that decide whether a constructor statement, or a static constructor's right-hand side, reads the type's own members. They threw a NullReferenceException on the first simple name that binds to no symbol, such as thenameofinnameof(executor). That crashed the translate stage for Oahu'ssrc/Oahu.Cli.App, every project depending on it then failed to compile, and thecs2gs-apps-nightlyoahu leg went red. The third was in the HTML report, where a compile error that carries a line but no file crashedreport.htmlgeneration with the same exception. All three locals are now nullable and checked: an unbound name counts as "not a member", and a location with no file renders without one. -
@ThreadStatic(and every other@annotation) on asharedfield is now emitted (issue #4903). gsc bound the annotation but never wrote theCustomAttributerow for a field declared in asharedblock orshared class, so a@ThreadStaticfield silently became one process-wide slot. The migratedGsharp.Runtime.Channelspooled its per-threadSelectWaiterin such a field, so concurrent selects raced and threwArgumentOutOfRangeExceptionfromCollectGates. The runtime now keeps that per-thread state inThreadLocal<T>until the pinned bootstrap SDK carries the emitter fix, avoids a boxed enumerator and a per-call comparison delegate on the ready-select path (back to zero steady-state allocation), and the runtime test projects now compile against the in-treeGsharp.Runtime.Channels/Gsharp.Runtime.Valuesinstead of the SDK package's copy. -
Per-thread compiler and runtime state is back in
@ThreadStaticfields (issue #4909). With the bootstrap pin on a release that carries the #4911 emitter fix,DeclarationBinder'sconformanceMatchingDepthand theGsharp.Runtime.ChannelsSelectWaiterpool,SelectRandomgenerator andInlineBudgetcounters drop theirThreadLocal<T>workarounds and return to@ThreadStaticsharedfields, which avoids aThreadLocallookup on every select. New tests check that each field is emitted with[ThreadStatic]and really is per-thread, and fail if the SDK package's copy ofGsharp.Runtime.Channelsreplaces the in-tree build under test. -
cs2gs preserves the public/protected ABI of translated C# records (issue #4675). Translated records retain
IEquatable<Self>, non-sealed record classes get their protected virtualPrintMembers, copy-constructor visibility follows record sealing, and getter-only/init-only properties keep their C# metadata and initializer values. Bare positional data-struct declarations retain empty collection zero values without invoking ordinary initializers; explicit construction still runs those initializers exactly once. Omitted positional arguments are prepared before local-slot planning, preserving non-primitive and open-generic defaults in both data structs and data classes. Named constructor expression trees do not acquire anonymous member metadata or ambiguous inherited property lookup; anonymous literals retain their ordered property members. Required managed-reference slots cannot escape through record zero initialization, including constructed generic property storage. Hidden, inherited, and source-interface-constrained expression-tree property bindings retain their actual declaring owner, including constructed generic interface constraints and substituted read signatures. Nested in-type collection-zero helper values are checked only for actual definition-owned field writes, retaining validated ordinary generic constructors without crediting newly required storage. Staged expression-tree lambda arguments retain required quotes.- Ordinary generic constructor initializers are checked at their constructed member types without replacing explicit array elements; positive and unknown allocations cannot leave required handles nil, while constant zero-length allocations remain valid. Explicit positional record properties retain initializer evaluation, default storage values, and private init-accessor metadata rather than being replaced by a synthesized public property.
- Explicit positional auto-properties retain private backing-field visibility and readonly metadata. Semantic parameter names remain distinct from escaped emitted-name reservations; null initializers and properties with escaped positional names keep their independent default storage.
- Positional accessor metadata comparisons use explicit Roslyn enum equality, preserving cs2gs own-source translation without changing record storage or accessor behavior.
- Preserved partial records share semantic primary-constructor ownership; explicit get-only positional properties retain independent default storage. Ordinary generic scalar initializers are checked and credited at their constructed type without crediting absent, default, or incomplete nested values. Unwritten auto-property backing storage receives no constructor credit.
- Nested explicit literals check effective backing storage and actual constructor-owned initializer writes at their constructed types. Initializer functions are validated separately for each constructed owner, so an earlier value-type instantiation cannot hide a later required-handle default.
- Constructor initializer expressions are checked even when a literal later overwrites their results, retaining final supplied-storage coverage without skipping executed calls or array-element checks. Recursive initializer analysis is bounded by constructed owner and initializer identity, so conditional recursive class construction no longer overflows the compiler stack.
- Constructor initializer validation reuses completed checks only for the same constructed owner, construction site, result-storage policy, and state-machine context. Shared-child graphs no longer cause exponential analysis; indefinitely growing generic recursion reports source-anchored GS0604 after 64 active initializer levels instead of overflowing the compiler stack. A focused analysis regression now measures exactly one initializer-body visit per owner/expression in a shared-child graph, independently of the native compiler timeout controls.
- Initializer function bodies retain construction-site diagnostics even when repeated constructions share the same function and owner. Context-aware initializer checks provide deduplication and recursion protection; ordinary function validation remains deduplicated. Closed-generic public-field collection-zero children remain bound and planned when the in-type constructor does not write their storage, including when a private collection sibling selects that constructor. Synthesized nested ordinary-constructor values are checked at their constructed types: an existing initialized handle cannot mask a newly required generic field or property. Private fixed-array zero helpers also check required element initialization. Unsupported closed-generic private-field zero construction fails with GS0472 instead of leaving a null collection or emitting an illegal external field store; real definition-owned private-field stores remain supported.
-
cs2gs hosts an extension on an external receiver on its owner even when the owner has a private nested type (issue #4676). A C# static class with a private nested aggregate used to keep its extension methods as in-owner helpers and publish a public forwarding companion on the package's
<Program>, so the migrated GSharp.Core exported an extra public<Program>type with sevenTypehelpers and the owner's own methods lost their extension marker. Those extensions are now lifted once with their real body and hosted on the owner through@ExtensionOwner, which reaches the owner's private members. Extensions on an owned receiver (a source type in the same namespace, or an enum), and extensions whose signature or attributes name one of the owner's private nested types, keep the previous scheme (a method whose signature names a private type cannot be public API; one that only has such an attribute keeps the in-owner helper and its forwarding companion, which leaves off only the attributes that name the private type). A bound method group of an async extension (Func<Task<int>> f = "x".M;) now reaches a gsc gap that the old scheme hid (#4699). -
cs2gs preserves named BCL delegate identity (issue #4679).
Predicate<T>and other non-Func/Actiondelegates retain their names in type positions, includingtypeof, casts, type patterns, inferred types, and nested generic arguments, instead of silently becoming an incompatible structural delegate. Imported nested delegates also retain constructed owners (Outer[string].Callback[int32]); source-declared nested delegates keep their lifted top-level names. The independent compiler lookup failure for escaped nested CLR type names is tracked in #4754. -
Lifted value-to-reference conversions now preserve nil and skip the operator (issue #4741). A nullable
Token?converted through an operator takingTokenand returningBoxpreviously called the operator on the default token and could return a non-null box for nil. ExplicitBox(value)/Box?(value)and contextual implicit conversions into nil-accepting targets now evaluate the operand once, bypass the operator on nil, and call it once on present input. The effective reference result is nullable, so non-nullable destinations remain rejected. Source-declared G# and imported CLR operators that explicitly accept a nullable operand take precedence over the lift, actually run on nil, and retain their own result contracts. Imported nullable-value operands now match their actualNullable<Token>parameter instead of its erased underlying type; remaining imported nullable-value signature gaps are tracked in issue #4737. -
Constructor tuple and multi-assignment preserve
thisfor getter-only auto-property stores (issue #4734). Assigningthis.First, this.Second = (3, 7)now emits verifiable readonly backing-field stores in classes and works in structs without looking for nonexistent setters. The backing fields remaininitonly; other receivers and index arguments still capture their locations before the right-hand side, and readonly assignments outside the declaring constructor remain rejected. -
gsgen projects semantic class abstractness consistently with emitted metadata (issue #4674). Generators now see
IsAbstractfor classes with unimplemented declared or inherited abstract members, not only an explicitabstractmodifier. Generated partial parts retain their own explicit modifiers rather than making temporary stub abstractness permanent, preserving instance Regex generation and source constructor visibility. Shared classes continue to project as C# static classes. Constructor projection also preserves actual access and signatures: inferred-abstract implicit constructors stay public, declared-abstract implicit constructors stay protected, primary constructors retain their real overloads, and forwarding primaries gain no phantom parameterless constructor. Shared classes do not expose the emitter's private placeholder constructor to C# generators. cs2gs reports a retained shared-class mapping only when that declaration survives translation; an extension-only holder whose methods move into their owning type no longer gets a misleading retention diagnostic. Generator-authored abstract modifiers also survive the generated partial data-part rewrite, whether the C# stub projects the data class as a record or as a class. -
cs2gs preserves parenthesized iterator values (issue #4705). Expressions such as
yield return (x + y) * zand string literals that can become spliced concatenations now use a typed, collision-safe local immediately beforeyield, avoiding G#'s tuple-yield ambiguity without changing deferred evaluation. The local uses the same nullable-promotion rules as the iterator element. The decision uses expression nodes rather than printer text, and source identifiers are collected once per syntax tree. -
A G# class implicitly converts to interfaces inherited through an imported .NET base (issue #4731). The same nominal relation now governs binding and emission, including intervening G# bases, substituted generic arguments and interface variance through sequence aliases in either direction. Emission retains the actual element type at imported generic calls instead of casting to their erased reflection envelope. Nested invariant generic arguments remain distinct through sequence aliases and annotation carriers rather than collapsing to the same erased CLR shape. Closed imported value wrappers retain genuine interface covariance when boxed, while symbolic wrapper arguments cannot bypass the shared relation through erased CLR probes. CLR argument conversions target the actual substituted method signature, including boxing symbolic value wrappers, rather than their erased parameter probes. This preserves existing CLR reference-annotation applicability and the natural
Action/Funcidentity inside constructed arguments, while rejecting genuinely incompatible reified slots before emission. Constrained instance and static calls retain inferred method arguments through the receiver-aware parameter reader, and imported map-interface arguments retain their invariant key/value relation and existing nil policy. A CLR-inferred method closure does not invent non-null reference annotations for an unrecovered symbolic method slot, including partially recovered vectors and invalid slot positions; recovered nullable, non-nullable, explicit and receiver-projected contracts remain authoritative. Symbolic sequence and async-sequence boxing, unboxing and checked casts share interface recognition and reified signature-based opcode tokens. Implicit and checked conversions preserve reference identity and inherited interface dispatch without structural adapters or redundant interface declarations. Sealed classes stay sealed, and unrelated sealed-class conversions remain rejected. -
cs2gs promotes null-bearing tuple elements in iterator signatures (issue #4718). A conditional yield such as
choose ? (text, 1) : ("x", 2), withtextinitialized to null, now declaressequence[(Text string?, Code int32)]instead of promising a non-nullText. Iterator methods, property/indexer getters and synthesized yield locals use the same tuple-position evidence; leaves proven non-null by a guard remain non-null unless an intervening or loop-carried write, unstructured jump, writable capture (including an enclosing-body write between resumptions), or escaping writable reference invalidates that proof. Read-onlyinarguments and aliases preserve the proof. Source interface and override contracts whose return declarations contain matching tuple slots, including generic methods, async iterators, properties/indexers and other implementations of the same slot, stay synchronized through the same nested tuple paths. Positional record parameters and their synthesized properties share that evidence too. Constructed generic interface/base arguments and their other uses, including sibling-project references, share the same tuple-position evidence; reordered and nested arguments preserve their actual positions and source tuple labels (issue #4727). Covariant shapes do not borrow potentially reordered paths. Unaffected elements and runtime evaluation stay unchanged. -
A non-
openclass may declare aprotected override, and cs2gs keeps the inheritance shape of public C# classes (issue #4674).protectedon a member of a non-openclass is stillGS0380, except on anoverridemethod, property or event, whose accessibility the base member dictates; asealed class Lowerer : BoundTreeRewritercan now keep overriding the base's protected hooks while staying CLR-sealed. cs2gs used to seal every class with no in-project subclass, which silently sealed public types that other assemblies (analyzers, for GSharp.Core) derive from. It now emitsopenfor every C# class that is notsealedand is reachable from another assembly, and keeps a C#sealedclass (including a sealed record, whose synthesizedprotectedmembers never neededopen) non-open. Migrated output therefore gainsopenon public non-sealed classes in every project. -
A library no longer exports an empty public
<Program>type per package, and a lifted nested delegate keeps the reach of its container (issue #4676). Every package of a G# assembly gets a synthesized<Program>host type that carries its top-level functions, and it was alwayspublic, so a library of types only exported one empty public host per namespace (22 in the GSharp.Core built from its G# translation, none in the C# build), visible to reflection-based tooling. The host is nowpubliconly when it carries a public top-level function or the compilation has an entry point (an executable keeps every host public); otherwise it is emitted non-public. Function literals and local functions hosted there do not count. cs2gs lifted apublicdelegate nested in aninternalclass to a top-levelpublicdelegate; it now emitsinternalunless the delegate and every type enclosing it are public. Aprotectedorprotected internalcontainer also bounds the lifted delegate tointernal, preserving legal inside-owner and derived uses without exporting a globally public type. -
A ref-returning local function that captures outer state no longer emits a program that crashes with
AccessViolationException(issue #4580). gsc emits a capturinglet At = func (i int32) ref int32 { return ref data[i] }as theInvokemethod of a closure class. That method was declared to return by value while its body returned a managed pointer, and the caller stored the result as one, so writing through the alias crashed the process.Invokenow carries the literal'sref/ref readonlyreturn, for captured locals, parameters,thisfields, nested literals and literals inside struct members.- A ref-returning literal inside a struct member that returns a reference into
thisnow reportsGS0254. The closure holds a copy ofthis, so the reference would alias the copy, not the caller's struct. Before, an@UnscopedRefmember letreturn ref this.ncompile, along with forwarding forms such asreturn ref this.Slot(), and writes through the reference were silently lost. Remedy: return a reference into heap storage (an array element or a class field), or make the literal a member function.
- A ref-returning literal inside a struct member that returns a reference into
-
cs2gs no longer adds redundant empty-array allocations (issue #4684). An empty collection expression targeting a rank-one array (
T[] a = []) translates toSystem.Array.Empty[T](), as csc lowers it. Pointer and function-pointer elements retain non-generic literals; function-pointer arrays preserve their exact element signature in allocation metadata. A bare non-nullable class instance array field gets the cached initializer only when every constructor is proved to overwrite it before any read or escape, on a sealed, object-based type without a finalizer. Other fields retain their original fresh zero value and identity. This removes both throwaway arrays from the migratedManagedLocationKey, restoring 40 bytes per key instead of 88 without changing constructor assignments or explicit array allocations. -
Synthesized names and orderings in
/deterministicemit no longer depend on object identity (issue #4663). Several lowering passes numbered synthesized types while walking the program in an order derived from object identity: capture boxes (<>__Box_<name>_<n>), iterator and async state machines of same-named methods, managed-location helpers and interpolation temporaries. Adding an unrelated file, reordering files within a package, or building with a differently-built compiler renumbered them, so the emitted assembly changed. Synthesized names now follow the established MethodDef source key, with structural package, nested type and overload identities breaking ties. The<Module>initializer calls[ModuleInitializer]functions in that same deterministic order instead of an unspecified one. This does not make the assembly independent of input order in general: packages are kept in first-seen syntax-tree order and emit assigns each package'sMethodDefrows in that order, so reversing files that belong to different packages can still change the assembly. -
cs2gs keeps each C# file's header comment (issue #4653).
- Before: a license or copyright block at the top of a C# file disappeared, because it sits before the first
usingornamespacerather than on a declaration. - Now: it opens the translated G# file with its text unchanged except that trailing whitespace is trimmed from each line and line endings are normalized to
\n, followed by a blank line and thepackagedeclaration. A file split into several packages repeats it in each. - The rule: the header is the run of
//and/* */comments at the start of the file, ending at the first blank line, preprocessor directive, documentation comment or token. Comments directly above a first declaration still stay on that declaration.#region,#pragma,#nullableand other preprocessor lines are still dropped.
- Before: a license or copyright block at the top of a C# file disappeared, because it sits before the first
-
A type can now implement the static abstract and static virtual members of an imported .NET interface (issue #4614). The runtime never matches a static interface member by name, and gsc bound static interface members only for G#-declared interfaces. So
struct SD : IS { shared { func Z() int32 { ... } } }over an importedinterface IS { static abstract int Z(); }failed to load with aTypeLoadException, asharedmember overriding a static virtual's default was ignored, andclass DZ : BaseS, IS2, where the importedBaseSalready implementsIS, silently ranBaseS.Z. gsc now binds each such member, including static properties, static events and members inherited through a base interface, to the type's static member of the same name and signature, as the C# compiler does, except that the member may have any accessibility (C# requires an implicit implementation to be public; G# already applies this rule to its own interfaces). An explicit-interface member such asfunc (IB) Z()no longer counts as an implementation of another interface'sZ, for G# interfaces as well. A type that declares onlyfunc (IB) Z()while also listingIAwith a staticZnow reportsGS0331; before, the explicit member was silently bound toIA.Ztoo. -
A type that lists an imported .NET interface now also declares that interface's base interfaces, so interface dispatch reaches its members (issue #4601). The runtime re-maps only the interfaces a type itself lists. gsc listed the declared interface alone, so in
class Derived : Base, IDerivedI, where the importedBasealready implementsIDerivedI's baseIBaseI, aValuedeclared onDerivedwas silently ignored when called throughIBaseI: the program ranBase.Value. The same happened forCollection[int32], IList[int32]with anICollection[int32]member, and for diamond and generic base interfaces. gsc now emits the full interface closure, as the C# compiler does. Every G#-compiled type that implements a .NET interface with base interfaces gets additionalInterfaceImplmetadata rows. -
The self-migrated cs2gs translator no longer throws while building an anonymous function's control-flow graph (issue #4611).
CreateControlFlowGraphappended each block's possibly-null branch value to its operations and filtered the null afterwards. The migration bridges a maybe-null value entering generic storage with a fail-fast!!, so the migrated translator threw on the first block without a branch value, failing 16Cs2Gs.Testsin the self-migration. The translator now yields the branch value only when it is present. -
Computed property accessors are emitted as
SpecialNamemethods (issue #4589). gsc set the CLRSpecialNameflag only on auto-property, abstract, interface and indexer accessors, so theget_/set_methods of computed properties, explicit-interface properties andsharedproperties looked like ordinary methods to reflection, and gsc's own reference-assembly output (which already set the flag) disagreed with the implementation assembly. Every property accessor now carriesSpecialName, as C# emits it, so tools that recognize accessors throughMethodInfo.IsSpecialNametreat them as accessors. G# code that references a G#-compiled implementation assembly no longer sees thoseget_/set_methods as callable methods, which matches C# libraries and gsc's reference assemblies, and@UnscopedRefon such a computed property is now honored. -
A class may re-list an interface its imported base class already implements (issue #4593).
class BuildTask : Task, ICancelableTask(MSBuild'sTaskimplementsITask, whichICancelableTaskextends),class Bag : Collection[int32], IList[int32]andclass S : MemoryStream, IDisposableused to reportGS0187for every interface member the base supplies, such asITask.BuildEngineorIDisposable.Dispose. As in C#, the base's implementation now satisfies those slots at run time; members the class declares itself are still matched and checked. Re-listing an interface the base does not implement still requires every abstract member. -
A tuple over an imported class now has a usable CLR type, so arrays of it convert to
IEnumerable[...]and infer generic arguments (issue #4591). The compiler closed the hostValueTupleover a type loaded from the reference assemblies, which produced a type nothing could reflect on.let e IEnumerable[(int32, Type)] = xswas an internal compiler error (GS9998), andAssert.Single(calls)over[](OpCode, Method MethodBase?)silently picked xunit's non-genericobjectoverload, so the followingcall.Item1reportedGS0158. The tuple is now built in its elements' own load context, including theNullable<T>of a nullable value-type element such as(int32, DateTime?). This was a compiler bug, not a cs2gs one; it blocked the self-migratedtest/Compiler.Tests. -
cs2gs preserves typed null casts through parentheses (issue #4721).
(string)(null)now emits the samedefault(string)as(string)null, instead of an unbindablestring((nil))conversion. Nested parentheses, other reference targets, and nullable value targets use the same typed-null path; non-null operands retain their existing conversions. -
cs2gs no longer synthesizes an import for a type it maps only to analyze an array receiver (issue #4556). The managed-reference array analysis maps a receiver's array type to inspect its element shape, and that mapping recorded the element's namespace as an import even though nothing from it is printed. In self-migrated Core.Tests, a
ParameterInfo[]receiver importedSystem.Reflection, so the file's bare compilerBinderbecame ambiguous withSystem.Reflection.Binder(GS0547). Analysis-only mappings now leave the import set alone; a printed reference still adds its import. -
cs2gs asserts a
foreachbinding over a source iterator whose element it promoted to nullable (issues #4578 and #4577). In a nullable-oblivious project, an iterator that yields a null-tainted value renderssequence[T?], so G# infersfor x in Iterator(...)asT?. cs2gs still treated the loop binding as non-null and emittedx.Member,F(x)and lambda captures such as.OfType[T]().Where((s T) -> s.SpanStart > x.SpanStart)with no!!(GS0158, GS0154; gsc reported the failed lambda as "Cannot find function Where"). The binding now asks the same promotion question the iterator's own declaration asks, so each non-null use gets the!!that matches C#'s throw-at-dereference behavior. -
Generic inference now finds interfaces inherited through an imported type's direct interfaces (issue #4559). A G#-emitted assembly lists only a type's direct interfaces, so
First(ProjectedCollection[int32]())over a class declaring onlyIReadOnlyCollection[string]failed with "Cannot infer type argument 'T'" instead of inferringT = stringthroughIEnumerable[string]. Inference now walks interface inheritance transitively, including through base classes. Conflicting interface projections are still rejected. -
@UnscopedRefis recognized when a project builds against reference assemblies (issue #4584). gsc compared the attribute's assembly identity only with the host runtime's (System.Private.CoreLib), so an SDK build, which binds theSystem.Runtimereference assembly, ignored a genuine@UnscopedRefand reportedGS0589on a struct member that returned a reference to its own state. The BCL identities (System.Private.CoreLib,System.Runtime,mscorlib,netstandard) are now accepted by name and public key token; a same-named assembly with a different key is still rejected. The same recognition covers@ScopedRefandRefSafetyRules, so in SDK builds imported APIs, including third-party libraries built for .NET 7 or later, now follow the C# 11 ref-safety rules (and explicitscoped) instead of being treated as legacy, which can change which ref-safety diagnostics appear on calls to imported members. -
cs2gs preserves C# dereference and concatenation behavior for nullable conditional, switch, and coalescing values (issue #4555). A receiver such as
(argument.Value is Type type ? type.FullName : argument.Value).ToString()now emits one G#!!assertion instead of a migrated call that gsc rejects withGS0159, and the same value used as a string-concatenation operand converts with the null-safe?.ToString()so nil concatenates as the empty string. Already asserted and statically non-null receivers remain unchanged. -
cs2gs no longer emits
__local_{owner}_{name}lifted-local helpers (issue #4302). Consecutive homogeneous recursive groups that use generics,params,ref/out/in, or static non-generic, non-ref readonlyref returns now remain nativelet Name = func ...declarations under their source names. Optional-parameter helpers reached only from a nullable recursion group fold into that group, with omitted defaults materialized at calls. The compiler's deliberately unsupported mixed generic/non-generic group still uses a member helper to preserve valid C# behavior, but the helper keeps the source name and adds only a short collision suffix. The self-migrationliftedLocalCeilingis ratcheted from 3 to 0. -
cs2gs no longer emits
__deconNidentifiers for nested tuple deconstruction (issue #4300). G# tuple bindings are flat, so nested declaration and assignment shapes still use recursive carrier locals, but those carriers now derive readable names from their source leaves, avoid collisions within each translated body, and do not drift when unrelated methods are inserted earlier in a file. Simple immutable declaration leaves bind their actual names directly, while structural or mutable leaves retain only the carriers their semantics require. Nested declarations now route through that recursive lowering instead of silently discarding inner bindings. The real migration pipeline gates nested declarations and assignments, mixed existing/new/discard leaves, all-discard arms, value-position assignments, storage-target evaluation order, compilation, IL verification, and runtime parity. -
Language-server
TryGetwrappers now preserve their non-null success contract (issue #4560). The migrated server now narrows document content after a successful lookup instead of retainingDocumentContent?and rejectingcontent.SyntaxTreewithGS0158; failed lookups still leave the output nullable. -
cs2gs uses G# discard parameters for parameterless C# anonymous methods (issue #4297). A C#
delegate { ... }converted to a delegate with parameters now emits repeatable, non-referenceable_slots instead of__anonNnames. The targetInvokesignature still determines arity, types, and ref kinds, while captured outer locals — including names such asobj,__anon0, and reserved spellings — cannot be shadowed by parameters the C# body could never name. -
Value-type nullable signatures no longer match their non-nullable underlying type (issue #4446). Overrides and interface implementations now reject
int32?where the slot declaresint32, and hierarchy-projection inference keepsIBox[int32]andIBox[int32?]ambiguous instead of collapsing them. The distinction also holds inside arrays, tuples, constructed types, user structs, enums, andstruct-constrained type parameters. Reference nullability remains signature-compatible where conformance rules require it, and exact nullable pairs remain equal. -
cs2gs preserves Roslyn's maybe-null type for locals inferred from
default(T)(issue #4445). Direct locals, aliases, conditional and coalescing flows, tuple declarations, whole-tuple defaults, declaration expressions, nested deconstruction, and loop clauses now emitT?when Roslyn marks the inferred local maybe-null, so passing that storage toref T?no longer producesGS0612. Value-type substitutions, explicit local types, non-null initializers, discards, anddefault(T)!keep their previous forms. -
Generic method inference through a base type or interface preserves nested platform and nullable positions (issue #4479, ADR-0186 §3).
Ob.Strings().Select(s -> s)over an oblivious C#List<string>now infersTSource = string!, and a G# generic takingsequence[T]infers the same element instead of erasing it tostring;[Nullable(2)]elements likewise remainstring?. Exact-definition inference, non-null and value-type elements, variance, and ambiguous hierarchy projections are unchanged. -
Concrete arrays and value tuples reached through an imported receiver keep nested declared nullability (issues #4402 and #4449, ADR-0193).
Counter[T].Add(T, KeyValuePair[string, object?][])no longer erases the nullableobject?tag value, and an oblivious concretestring[]is consistently a platform array of platform elements ([]!string!) whether read from a field, property, method return, parameter, or indexer. Unannotated netstandard2.0 positions such asFile.ReadAllLinesandTaskFactory[T].ContinueWhenAll(Task[])retain both positions. Positions containing type parameters still preserve receiver substitution, including value-type arguments. -
Nested attribute arrays retain their static element type. A
[]Typenested in an[]objectargument and containingtypeofof a same-compilation type now reaches metadata and source generators asType[], rather than being exposed as the compiler's internalobject[]placeholder (issue #4369). -
cs2gs preserves definition-side defaults when a C# partial method falls back to one implementation (issue #4398). When different file imports, parameter names, generated parts, or another incompatibility prevent a G#
partial funcpair, the surviving implementation now inherits the defaults C# callers observe from the definition. Defaults are spelled in the implementation file's scope, while its parameter names, attributes, signature, and body remain unchanged. -
cs2gs keeps C# top-level statements able to reach members of a retained
Programclass (issue #4472). WhenProgrammust remain a class because it contains a nested aggregate, exports a member, is preserved for a referencing project, or declares aGeneratedRegexmethod, private members reachable from C# top-level statements are emittedinternal, and nested type references are qualified throughProgram. Private-only programs still use the unchanged canonical hoisted output. -
Captured locals and parameters whose types are private nested types no longer fail assembly loading (issue #4526). Capture boxes are now emitted inside the declaring type's CLR access domain, including generic and deeply nested generic owners, while preserving the complete enclosing generic-parameter vector. Managed-location helpers nested in generic owners likewise retain their enclosing and helper-specific generic arity. This fixes migrated code that compiled successfully but threw
TypeLoadException: Access is deniedwhen a lambda captured a private nested record struct. -
Composite literals and source indexers now enforce accessor accessibility before emit (issue #4474).
Source{ P: 1 }now checksP's setter rather than the property's broader visibility, and source indexer reads and writes now check the getter or setter they invoke. Unrelated code receives the establishedGS0472/GS0379diagnostics for private/protected accessors; declaring and derived contexts remain allowed, subject to the existing protected-receiver rule. -
@LibraryImportpreserves native-transition attributes (issue #4410). Method-level@SuppressGCTransitionand@DefaultDllImportSearchPaths(...)now move from the managed outer stub to the hidden inner P/Invoke where the runtime observes them.cs2gstranslates the corresponding C# attributes instead of reporting them as unsupported. -
Writes through nested fields of a constructed generic struct now persist inside closures (issue #4384). A lambda assigning through
w.C.NwherewisWrap[string], or through the same generic struct chain beneath a captured class field, failed withGS9998because emitter addressability checks looked for the construction-substituted field symbol in a cache keyed by the open definition. Field storage is now classified from its receiver chain, while the existing generic-aware token resolver maps the field back to its definition, so the compiler emitsldfldarather than spilling and mutating a copy. -
A property override whose type differs from the base property's is checked, and a covariant override is read through its own accessor (issue #4481). The emission of a C# 9 covariant property override (a MethodImpl row and
PreserveBaseOverridesAttribute) is #4508's fix; this change covers what surrounds it. An override whose type is unrelated to, or wider than, the base type used to compile silently and now reportsGS0185. So does a narrowing that has no CLR covariant form: a narrowing with a setter, over a base property that has a setter or no getter, or by-ref. A difference in reference nullability alone, at any nesting depth (List[Sym]overList[Sym?]), is still the same slot. The narrowing test now runs after every type, interface base clause and interface closure is bound. Before, a narrowing to a type declared later in the compilation, such asPropertySymbolin the migratedGSharp.Core, or to a source interface, was wrongly rejected. A read of a covariant override on a receiver whose chain mixes generic and non-generic classes (GenericLeaf[int32] : Access : Node[Sym]) used to call the base's accessor, which returns the wider type, and failed IL verification. It now calls the accessor of the class that declares the bound property. -
cs2gs no longer silently drops property or indexer accessor attributes (issue #4294, ADR-0184). An unsupported attribute on a
get,set, orinitaccessor now emits the non-fatalCS2GS-ACCESSOR-ATTRIBUTE-DROPPEDwarning to stderr and the run'stranslate.log, naming the source location, instead of disappearing without notice.[UnscopedRef]on a getter keeps its existing, semantics-preserving hoist to the G# member; no broader attribute mappings are inferred. -
Taking a
suspendmethod as a delegate now emits a context-capturing thunk (issue #4412, ADR-0174 D7). Direct instance,base.M, imported, structural-function, and named-delegate conversions no longer bind the delegate directly to a MethodDef whose hidden trailingContextparameter is absent fromInvoke; the generated delegate now passes IL verification and carries the ambient context from its conversion site. A declared or inferred suspending method with aref,out, orinparameter now reportsGS0422instead of emitting a state machine that copies an address into a value field. -
A
suspendmethod can now override a G# base method imported from another assembly (issue #4413, ADR-0174). Override matching now compares the source-visible parameter and awaited return types instead of counting the hidden trailingContextparameter and physicalValueTaskreturn as part of the G# signature. The emitted override keeps that physical ABI and an explicit MethodImpl, so virtual dispatch andbase.M()work across the assembly boundary. -
String indexing, string length, and rectangular-array length now match
csc'scallvirtopcode choice (issue #4313). The three specialized emitter paths used non-virtualcallforString.get_Chars,String.get_Length, andArray.get_Length, unlike other reference-receiver member accesses. Valid non-nil operations return the same values, and the emitted IL now has C#'s explicit null-checking instruction semantics without promising a particular stack-frame presentation after JIT inlining or tiering. -
cs2gs method-group wrappers now keep source-derived parameter names through collisions and reserved words (issue #4298). Instead of replacing such names with unrelated
__argNidentifiers, the translator uses the established underscore suffix (value_,value__,params_); a synthetic fallback remains only when no usable source name exists. -
IL verification no longer fails valid code that has a
catch … whenfilter inside afinallyblock (issue #4489). The repo-pinneddotnet-ilverify10.0.8 reports[StackUnderflow]at the first instruction of an exception filter whose start lies inside afinallyorfaulthandler (upstream dotnet/runtime#134711). Roslyn's IL for the same C# fails the same way, and the code runs correctly. This kept the nightly self-migration red ontest/Core.Tests. The cs2gs ilverify stage and the Compiler.TestsIlVerifiernow drop that one error. They drop it only when the verified assembly's metadata shows that the reported offset is a filter start and that the innermost handler enclosing it isfinallyorfault.StackUnderflowis not ignored as a category, so every other reported stack underflow still fails verification. Known limitation: ilverify stops checking a method at its first error, so in a method where this error is dropped, the IL after the filter start is not verified until the upstream fix lands. -
Capturing rich objects now reuse one managed capture location per dynamic lexical binding (issue #4512, ADR-0189). Constructing another rich object over an existing mutable capture now allocates only the fresh object, while separate loop iterations and factory calls still create separate cells and locations. Snapshots, explicit managed aliases, nested/generic captures, pre-base initialization, and rich-object identity are unchanged.
-
Array and native-slice
managedlocations no longer allocate their identity key until equality or hashing observes it (issue #4511, ADR-0188). Immediate-use, retained, and directly-created readonly element handles now allocate one 40-byte handle instead of the previous 80-byte handle-plus-key graph on the recorded 64-bit profile. The handle still retains its selected owner immediately; first identity observation safely publishes one immutable key per handle, and warmed identity/dereference operations allocate zero. -
cs2gs widens by-ref storage along with a promoted
outorrefparameter (issue #4482). When cs2gs widens an obliviousout/refparameter toT?, gsc now requires the storage passed to it to match (GS0612). An array element passed byout(new string[n]thenout a[i]) now makes the array[n]string?, and a local passed byrefwidens the same wayoutlocals already did. -
cs2gs emits managed-reference array types with nullable elements (issue #4525). C# arrays of
ManagedRef<T>andReadOnlyManagedRef<T>now usemanaged[T]?elements in allocations, declarations, fields, parameters and returns, including rectangular arrays. Explicit, implicit, rectangular and collection-expression initializers preserve nil elements without inserting!!; element reads,foreachbindings and generic results receive!!only when consumed by a non-null operation without a G# null guard. This matches CLR default initialization and prevents both gsc'sGS0604rejection and translator-introduced null-reference exceptions. Fixed generic storage that cannot adopt the projected nullable element now reports an Unsupported diagnostic instead of inserting!!. -
cs2gs no longer asserts a conditional or switch arm where C# takes a null as a value (issue #4452). An arm feeding an interpolation hole, a string concatenation, the operand of
as, or a switch scrutinee used to get!!, and it threw where C# formats, casts or matches the null. A C#!into a local that cs2gs widens toT?is now erased too, instead of becoming a!!. -
A nullability-oblivious value passed to an imported method's non-null parameter is now checked at the call (issue #4451, ADR-0186 §4). A
string!argument to a C# method, constructor or constrained interface call whose parameter is non-nullstringwas passed through with no check, because both sides are the same CLR type. Such an argument is now checked, and a nil throwsNullReferenceExceptionat the call, naming the expression. This is a runtime change: code that passed a nil into an enabled C# parameter now fails there. A parameter the callee leaves oblivious or declares nullable (string?) still accepts a nil unchecked.- Explicit type arguments at an oblivious generic (ADR-0193 amendment). The reported shape, an oblivious
List<T> WrapList<T>(T value)called asOb.WrapList[string](x), now bindsTto the platform typestring!: the call returnsList[string!]and takes a nil unchecked, as the C# does (Ob.IsNil[string](nil)returnstrue). A nil element read through the list is checked where it is used. Before,Twasstring, so a nil entered a non-nullList[string]and failed later with an unattributedNullReferenceException.
- Explicit type arguments at an oblivious generic (ADR-0193 amendment). The reported shape, an oblivious
-
A container with nullability-oblivious elements no longer converts to a supertype that promises non-null elements (issue #4420, ADR-0186 §3 rule 3).
List[string!]toList[string]was already rejected, but the same container passed as anIEnumerable[string]or anIReadOnlyList[string], or an obliviousstring[]passed as one, was accepted. The receiver then read a nil element as a non-nullstring, with no check anywhere. These conversions now reportGS0154orGS0155at G# conversion sites; imported CLR call parameters remain a known exception tracked by #4480. A view whose element is nilable (IEnumerable[string?]) and a non-generic one (IEnumerable,object) still convert. To pass the elements as non-null, copy them through a checked conversion, for example into aList[string]element by element. -
An object initializer on an imported type now finds a friend assembly's
internalproperty or field (issue #4468).Options{Hidden: 1}reportedGS0158 Cannot find memberfor aninternalmember of an assembly that named this compilation in anInternalsVisibleTo, althoughoptions.Hidden = 1bound. Onlyassemblyaccessibility is admitted, as on the assignment path;private,protectedandprivate protectedmembers stay hidden, and a non-friend assembly still sees none of them. This kept the migratedtools/cs2gs/Cs2Gs.Testsfrom compiling in the nightly self-migration. -
An async function's physical
TaskorValueTaskreturn now keeps every nullability position in metadata (issue #4465, first exposed while fixing #4287). gsc originally wrote no nullability for an async kickoff return and relied on the enclosing default, which could make another assembly readTask[Rep]asTask[Rep]?or lose a nestedRep?. The first fix made every referenceTaskenvelope non-null, which still laundered an@Oblivious asyncdeclaration's platform top level. Signature and metadata emission now share one physical return symbol: an enabledTask[string?]re-imports asTask[string?], an oblivious one asTask[string?]!, and suspending or explicitlyValueTaskfunctions retain the corresponding value-task layout. Non-generic tasks, value-type results, tuple names, and return attributes are unchanged. -
Three more positions now check an oblivious
T!value with the attributed nil message, and named deconstruction accepts one (ADR-0186 §4, issues #4323, #4324, #4325). An audit of every place a platform value can appear as a receiver or value found three gaps:- Invoking a delegate-typed field or property.
x.F(),Type.F(), or a field of an@ObliviousG# class used to throw an unattributedNullReferenceExceptionfrom inside the invocation when the delegate was nil. Invoking a local (f()) or a parenthesised callee ((f)()) already named the source. - An
await forsource. A nil obliviousIAsyncEnumerablenow fails with the same message as afor … insource. - Named deconstruction.
let { X = x } = obliviousCall()reportedGS0164where the same code on a plainTcompiled. It now compiles and checks its source, as positional deconstruction already did.
The other positions checked are index reads, writes and compound writes; member reads, writes, compound and
??=writes;await;lock;throw; returns; and positional deconstruction. They already behaved correctly, and a regression test now covers each of them. Positions that accept nil insert no check: interpolation, string concatenation,using, aswitchscrutinee, andas. - Invoking a delegate-typed field or property.
-
A by-reference argument may now differ from its parameter only in reference nullability, as in C#, with the new
GS0612warning (issue #4422).&base.runstackat aref []int32parameter, where the reference pack declaresRegexRunner.runstackasint[]?, was rejected withGS0154. That blocked the[GeneratedRegex]runner for any regex that backtracks inside a loop.[]?int32and[]int32, orList[string?]andList[string], are one runtime type, so the storage is now accepted.GS0612warns in the direction a nil can flow through the shared storage: any difference forref, nullable storage at a non-nullin, a nullableoutparameter over non-null storage, and any nested difference. A platform (T!) position never warns. The same-compilation shapes (&swiths string?) used to compile with no diagnostic at all; they now get the warning too. Breaking: a value-typeint32?isNullable<int32>, not an annotation, and passing its storage toref int32(or[]int32?toref []int32) is nowGS0154. It used to compile, and the callee's store overwrote theNullable'shasValuefield. The same holds for imported callees:Interlocked.Increment(&x)orInt32.TryParse(s, &x)withx int32?compiled to unverifiable IL and is nowGS0154. Overload resolution follows the rule too: withP(ref int32)andP(ref int32?),int32?storage selectsref int32?, andstring?storage prefers an exactref string?overref string.@SuppressDiagnostic(ADR-0175) now also suppresses compiler warnings such asGS0612(never errors) in gsc and the language server, and cs2gs emits@SuppressDiagnostic("GS0612"), scoped to the one statement, where it drops a C#!fromref x!, so the[GeneratedRegex]runner builds with no warning.GS0612reads declared types rather than C#'s flow state, so it can fire where csc is silent. -
Events of a generic class now work (issue #4391). For
open class GB[T] { event Got EventHandler[T]? }, the generatedadd_Got/remove_Gotcast the combined delegate toEventHandler<object>. They failed IL verification, and the first subscription threwInvalidCastException. They now cast toEventHandler<T>, like C#'s field-like event accessors. Subscribing through a constructed receiver (g.Got += hon aGB[string]), or by bare name from a class derivingGB[string], now takes anEventHandler[string]handler rather than rejecting it as not anEventHandler[T]. -
Delegate conversions now preserve the exact target identity (issues #4381 and #4433). A method group or stored function value passed to a user assembly's own
System.Func<T>constructed the BCLFuncwith the matching structural signature, and a function literal passed directly toEventHandler[T]on a constructed G# receiver used the naturalAction<object, object>shape. Both produced ILVerifyStackUnexpected; delegate combination could also throw at run time. Conversions now retain the target assembly and substitute the constructed receiver before materializing the delegate. -
base.Mconverted directly to a delegate now calls the base implementation (issue #4393). In a generic class,let f (T) -> string = base.Namein a member body bound the derived override. In a class deriving a constructed generic base (class DC : Base[string]), the conversion failed IL verification (DelegateCtor) and threw at run time. The delegate now targets the base method, instantiated as the derived class names it, as Roslyn'sldftndoes. -
Subscribing to an event you cannot access is now an error (issue #4394).
s.Changed += hon aprivateorprotectedevent compiled from an unrelated class. It now reports GS0472 or GS0379, asbase.E += halready did, on every subscription path:obj.Eand bareE,+=and-=, through a class-constrained type parameter, and for source and imported events. An imported event that exists but is out of reach now reports GS0472 or GS0379 instead of GS0158 ("cannot find member"). A class deriving an imported type can now subscribe to itsprotectedevents through its own instance (this.E += h), as in C#. -
Generic type inference no longer infers a platform type
T!from an argument (issue #4443, ADR-0186 §3 as amended). Passing a value from nullability-oblivious code to a generic method, as inWrap(x)orEnumerable.Repeat(x, 2)wherexisstring!, inferredList[string!], which does not convert to a declaredList[string](GS0155).- The rule. A
T!argument now contributesT, and aT!argument alongside aTone also givesT. - The check. The argument is checked at the call, so a nil throws
NullReferenceExceptionthere, naming the expression. - What keeps
T!. Only the argument's top level is affected: the element of an obliviousList<string>still infersstring!. Arefargument, and an argument to a parameter an oblivious library method declares, keep their exact type. - Inference over such a list (
First(xs)againstFirst[T](xs List[T]) T) now works; it used to inferstringand then reject the argument. An annotated list from enabled metadata reads the same way:Firstover aList<string?>now infersstring?, as C# does, where it used to infer a non-nullstringwith no diagnostic.
- The rule. A
-
A platform-typed value of a G#-declared type now resolves imported calls like the plain type does (issue #4444, ADR-0186 §1 and §5a). In an
@Obliviousscope a parameter typed with a G# class isNode!.List[Node].Add(n), aList[Node]{n}initializer,Enumerable.Repeat(n, 2), and a method group of such a function passed toSelectall reported GS0159 "Cannot find function", although the same calls overstring!bound. They now bind the same method as forNode, and a nil argument is checked where it is coerced to the non-null parameter (§4). -
A user-defined method group with a nullable base-class parameter now converts contravariantly to a delegate with a derived-class parameter (issue #4289). For example,
func Check(a Animal?) boolnow satisfiesFunc[Dog, bool], matching the existing non-nullable conversion and the imported-method-group path. The reverse null-unsafe direction remains rejected: a method takingAnimaldoes not satisfy a delegate that may passDog?. -
cs2gs asserts a member chain through a sibling project's member that it widened to
T?(issue #4356 follow-up). cs2gs renders some fields and propertiesT?for reasons only the declaring project's source shows:[AllowNull](#3694), or the project's own== nulltests on the member (#1072). Another project in the same migration sees that member through the declaring project's reference assembly. It therefore readcompilation.DebugInformation.Formatorx.Definition.Namebare, and gsc rejected the chain withGS0158once its stated-nullable carve-out was removed. cs2gs now asks the declaring project's own compilation, so the consumer emits the!!that the widened declaration requires. This had turnedsrc/Compiler, its five dependants andtest/Core.Testsred in the nightly self-migration. -
A nullable argument to an imported generic
T?parameter now infersTas its underlying type (issue #4425). Calling a referenced assembly'sstatic T Required<T>(T? value) where T : classwith aType?argument inferredT := Type?, so the call returnedType?and assigning it to aTypefailed withGS0155. The same method declared in G# source already inferredT := Type, as C# does. Inference now reads the slot's[Nullable(2)]through ADR-0193'sNullabilityImportRule, as the inverse of the rule that widens that slot. A value-type argument is unaffected: an unconstrainedT?given anint32?still infersT := int32?. -
cs2gs no longer asserts a conditional or switch arm whose whole expression flows into a nullable target (issue #4450). The arm's own type used to decide the assertion. So
string emittedName = i >= 0 ? null : argument.Name;became… else { argument.Name!! }inside astring?local, and it threw on the null C# stores there. An arm now takes the whole expression's target: a local, assignment, field, property, parameter or return. An arm flowing into a non-null target keeps its!!. This was the nightly self-migration'sCs2Gs.Teststest-parity failure in the migratedCSharpToGSharpTranslator.LibraryImport. -
cs2gs maps a
Deconstructout-parameter to its member case-insensitively (issue #4382). A positional subpattern whoseDeconstructout-parameter differed in case from the member it reads (out Inner? pfor propertyP) was reported as unsupported and translated to a bare type test, soo is Outer({ X: 0 })becameo is Outer. cs2gs now follows the C# conventionout T xtoX: it maps the out-parameter to the one property or field whose name matches case-insensitively and whose type is the parameter's, including inherited members and fields. The lowering keeps its nil guard and reads a nullable slot once, inispatterns and switch arms. An ambiguous match, a member of another type, no matching member, a member that a derived type hides from an inheritedDeconstruct, a member or getter that isn't accessible, or an extensionDeconstructis still reported loudly, and the diagnostic now says why. Aname:label on a positional subpattern is no longer emitted as a member access, and a binding under a nested typed positional pattern over a nullable slot (Outer(Inner(var a, _))) now compiles. -
cs2gs no longer asserts
!!on reads of nullability-oblivious CLR metadata (ADR-0186 step 6, PR 0). A member of an assembly that says nothing about nullability, and that the migration does not itself translate, is the platform typeT!in G# since ADR-0186 step 3. gsc inserts the nil check itself wherever such a value is used as non-null, so the translated!!only duplicated it, and the polish pass could not remove it. Those reads are now emitted bare. A nil still throwsNullReferenceExceptionat the same point. Three cases keep the!!: a member of another project in the same migration, whose G# type cs2gs decides; a value whose type would otherwise be inferred asT!(for example, a local's initializer, or an argument that fixes a generic method's type argument); and a read of a container type such asstring[]orList<string>, where the!!is still needed for the value to convert to an enabled container (for example,lines = File.ReadAllLines(path)against netstandard2.0, #4449). SettingCS2GS_NULL_FORGIVENESS_TELEMETRYto a file path now makes cs2gs write its per-rule!!counts there when it exits. -
base.M()on asuspendbase method now calls the base implementation (issue #4392). Asuspendoverride that calledbase.M()on asuspendbase method dispatched the call virtually, re-entered its own override and crashed the process with a stack overflow; the output passed ILVerify. Overload resolution returns a call to a suspending method already completed (the implicit await, or the blocking bridge in a plain member), and the base-call binder only recognised the bare call, so it never marked it as a base call. The inner call is now marked and completed again. The base call also receives the hiddenContextargument, and it is forwarded non-virtually from a function literal, agooperand or anasync letinitializer through the same<>n__Nforwardersasyncbodies use.go base.M()andasync let x = base.M()are now accepted instead ofGS0137. A non-virtual base method that inference makes suspending now makes itsbase.M()caller suspending too. A suspending method of a base class from another assembly, called throughbase.M()or unqualified, is now awaited instead of staying typedValueTask[R]. A call to such an imported suspending instance method, whether throughbaseor on an ordinary receiver, now also receives the caller's context, so cancelling the caller's scope reaches it. Previously it ran underContext.None. -
Imported nullability reads more consistently across the paths that read it (ADR-0193 Phase 1, issue #4363). One internal rule now decides what an imported position's nullability becomes, and every metadata reader calls it. A new differential test compares the readers across every public generic member of the reference BCL, netstandard2.0, FsCheck and a
csc-built fixture. That test found these defects, which are now fixed:- A field, property or event of an imported generic type now reads its type argument's nullability. For example,
Tuple[string].Item1from a netstandard2.0 library used to read asstring!. It now reads asstring, as the same member's methods already did (issue #4361, on the paths its fix did not reach). A generic event's handler type used to lose its declared nullability entirely. - A static property of a generic type keeps the receiver's
?.EqualityComparer[string?].Defaultis nowEqualityComparer[string?], notEqualityComparer[string]. [Nullable(2)] Tmarks only the argument's own position as nullable.FirstOrDefault()over anIEnumerable[List[string]]now returnsList[string]?. Some reading paths used to returnList[string?]?. A value-type argument no longer receives a?on its inner positions.- An unconstrained type parameter is no longer widened at a
T?-returning member. Insidefunc F[T](xs List[T]),xs.Find(p)now has typeT, notT?. This matchesvalues.Min().T?on an unconstrainedTwould meanNullable<T>for a value-type substitution. This follows ADR-0193's ruling on the case, which #4385 revisits. - A
ref Treturn through a generic receiver is nowref Trather than a platform-wrapped reference. - The platform type
T!is no longer constructed over a type that has no reference nullability. This coversT?!and value types. As a result, an obliviousSystem.Tupleresult now reads as a tuple rather than(T1, T2)!. - Three known reader disagreements remain, each tracked separately:
- A field, property or event of an imported generic type now reads its type argument's nullability. For example,
-
An argument written without
inat aninparameter is passed by readonly reference, as in C# (issue #4400, ADR-0060 §15).this.In(9),base.In(9), the same call in a lambda, and every call to an imported C# method, constructor, base constructor or extension with aninparameter used to push the value where the callee expected an address, which failed IL verification (StackUnexpected) and threwInvalidProgramExceptionat run time. The free-function, delegate and constructor forms rejected the call withGS0242, and the importedinindexer withGS0155. Now the argument is converted to the parameter type, then passed as the address of the variable, field or array element itself, or of a readonly temp for a literal, call result or converted value.GS0242is retired, and cs2gs no longer turns an rvalue such asScale(x + 1)into the non-lvalue&(x + 1). A plain value at aref/outparameter of a method call now reportsGS0235instead of emitting unverifiable IL. -
Several imported members now keep the nullability they declare (ADR-0193 Phase 2, issue #4363). Some compiler paths converted a member's CLR type directly and never read its
[Nullable]metadata, so a declaredstring?arrived asstringand a nil value reached a non-null variable unchecked. Every such path now reads through the same funnel the ordinary member readers use. Affected positions:- the
Currentof a duck-typed enumerator, infor x in …andawait for; - the result of an awaiter's
GetResult(); - the
Invokesignature of a generic delegate used through a type parameter (Maker[T]); - a static member reached through a generic receiver;
- a static call on a generic class;
- the operands and result of an imported CLR operator;
- structural projection into an imported CLR type.
Remedy for code that now reports a diagnostic here: the value really can be nil, so narrow it, assert it with
!!, or give the destination a?type. An oblivious position (from an assembly that states no nullability) now reads as the platform typeT!on these paths, as it already did elsewhere. A new internal analyzer,GSA0007, keeps compiler code from converting a member's type without reading its nullability. - the
-
An event's handler-type nullability now survives a round trip through metadata (found implementing ADR-0186 step 5). gsc wrote no
[Nullable]on Event rows, which is where bothcscand gsc's own importer read an event's handler nullability, so every gsc-emitted event re-imported as wholly non-null:event Changed Action[string?]came back asAction[string]. Event rows now carry[Nullable]whenever any position is not plain non-null, exactly as fields and properties do. -
Ref returns through a struct receiver now follow C#'s scoped-
thisrule (ADR-0187 / issue #4350, resolving an item ADR-0184 recorded as future work). A member of a concrete struct that is not@UnscopedRefcannot return a reference into its own receiver (GS0589 already enforces that), so its receiver no longer limits where the returned reference may go.prop this[i int32] ref readonly T -> inner[i]over a struct field now compiles, as doesfunc k(in a Acc, ref y int32) ref readonly int32 { return ref a.Pick(ref y) }, which csc also accepts. A writablerefhanded back by such a member stays writable through alet/inreceiver, sovar ref alias = h.Valueandh.Value = 55are accepted and write the storage the reference names.@UnscopedRefmembers, type-parameter and interface receivers, and a ref struct receiver's value scope keep their existing checks (GS0254 / GS0591 / GS0499). -
Generic operators declared on a nullable receiver bind against their owner (issue #4350).
func (left Box[T]?) operator ==(right Box[T]?) boolnow opensBox'sTexactly likefunc (left Box[T]) operator ==, instead of reportingGS0113forT. -
Construction syntax is no longer shadowed by a same-named extension function (issue #4350).
Slice[T](owner, 0, n, n)constructsSlice[T]even when an extensionfunc (s Slice[T]) Slice[T](lo int32, hi int32, max int32)exists, matching C#, which never considers extension methods fornew. A free function of the same name still shadows the type, as before. -
An in-body conversion operator is declared on its enclosing type (issue #4350).
func operator implicit(value Slice[T]) ReadOnlySlice[T]insidestruct ReadOnlySlice[T]used to be attached to the source typeSlice, and when that type's ownsharedblock bound later the operator disappeared from the assembly. It is now emitted on the enclosing type, as in C#. -
Imported generic implicit conversions stay symbolic inside generic code (issue #4350).
Span[T] -> ReadOnlySpan[T]andMemory[T] -> ReadOnlyMemory[T]used to call the erased<object>operator and fail IL verification. An inlineout varpassed to an inferred generic CLR method (MemoryMarshal.TryGetArray(memory, out var segment)) now also keeps the symbolicArraySegment[T]. -
User types may overload indexers (issue #4350). A struct, class or interface may declare several
this[...]indexers that differ by parameter types or count, including multi-parameter ones. Access picks the best overload, as in C#. -
cs2gs keeps struct
overridemembers and every indexer argument (issue #4350). A struct'soverride func Equals(obj object?)used to loseoverride, which silently hid the override so boxed equality fell back toValueType.Equals.slice[index, fromEnd]used to drop every argument after the first, and a long constant operand (2L * capacity) was narrowed toint32. -
gsfmtno longer splits a C-stylefor init; cond; post { … }loop header across three lines, one per clause.SyntaxFacts.IsBreakRequiredBetweentreats every;as a statement terminator that forces a following line break — true for an ordinary statement, but not for the two separators insideForClauseStatementSyntax, which are list separators like,rather than terminators.GSharpFormatter's layout builder now recognizes a;whose direct parent isForClauseStatementSyntaxand treats it the way it already treats a comma: no forced break, aDoc.Linewrap point that collapses to one space when the header fits and indents by 4 when it does not, and (viaIsContinuationBoundary) the layout re-derives the break rather than preserving an author-written one, so the fix collapses hand-formatted three-line headers already in the repository, not only newly-formatted ones. A related spacing defect surfaced in the same code path: an empty initializer clause (for ; cond; post {) left the separator glued directly to theforkeyword (for;) because the pre-existing "no space before;" rule assumed a;always closes a preceding token; it now special-cases a for-clause separator with nothing to its left.samples/Loop.gs,samples/VariadicDelegate.gs,samples/VariadicMethods.gs,samples/WhileAndLabeledLoops.gs, andsrc/Sdk/Gsharp.Extensions/Sequences/Sequences.gscarried the three-line form and are reformatted in the same change sogsfmt --check .stays clean. A second, unrelated gap found investigating the same class of defect: ADR-0179's own phase-7b measurement table lists&&/||/??/or/andchains together as a family that goes fully to zero reducible long lines, but only&&,||, and the pattern-disjunctionor/andhad a wrap point implemented — a??chain had none and could overflow the canonical 120-column width with no way to break.??now gets the identical treatment as&&/||. -
A native ref-returning function taking a by-value byref-like (ref struct, e.g.
Span[T]) parameter and returning a ref through it (return ref s[0]) is no longer unconditionally rejected (issue #4265, found reviewing #4263/#4224).func First(s Span[int32]) ref int32 { return ref s[0] }reportedGS0254("cannot return a managed pointer to function-local storage") regardless of wheres's backing storage actually came from — unlike C#, which allows exactly this (MemoryMarshal.GetReference[T](Span[T])-shaped BCL APIs rely on it). Root cause:StatementBinder.HasFunctionLocalRefScopehad no case at all forBoundClrIndexExpression— the node a CLR/imported indexer read such asSpan[T]'ss[0]binds to (wrapped in aBoundDereferenceExpressionbyConversionClassifier.AutoDereferenceRefReturn) — so it fell straight through to the fully-conservative default and reported unconditionally, never even inspectings. C# draws a sharp line here that the fix mirrors precisely rather than blanket-relaxing: a by-value ref-struct parameter's OWN storage (its fields) is a function-local copy exactly like any other by-value struct and still cannot be returned by ref (ref struct Acc { var Total int32 } func Bad(a Acc) ref int32 { return ref a.Total }still reportsGS0254, unchanged) — only the REFERENT such a value ENCAPSULATES (Span[T]'s backing pointer, reached only through its indexer/methods, never through a field) has caller scope, because the caller already guaranteed that referent's lifetime by constructing/passing theSpanin the first place. The newBoundClrIndexExpressioncase delegates to a newHasFunctionLocalReferentScopehelper — mirroring the file's existing pointer-parameter-dereference precedent exactly — only when the indexed target's typeTypeSymbol.IsByRefLike; a reference-type or ordinary-struct target keeps the previous storage-scope walk unchanged.RefCapabilities.SelectByRefArgumentsis split into two separate argument lists (byRefArguments, checked as before, and a newbyValueByRefLikeArguments, checked via the new referent-scope helper) so a forwarding chain through a by-value byref-like parameter (return ref First(s)from another ref-returning function takings Span[int32]) is escape-checked with the same precision as #4224's existingref/in/outforwarding, without aref/in/outargument that happens to be byref-like-typed ever being checked by the more permissive referent-scope rule (that would reopen the same hole from a different angle — confirmed against a repro during review:func Fwd(ref a Acc) ref int32 { return ref a.Total }called asFwd(ref a)from a by-valuea Accstill correctly reportsGS0254). Ascopedby-valueSpan[T]parameter forwarded this way still reportsGS0254; a non-scopedone compiles and correctly aliases the original storage.ReadOnlySpan[T]works the same way for aref readonlyreturn; a plain (mutable)refreturn from aReadOnlySpan[T]indexer is unaffected by this change and still reportsGS0253(its indexer only ever yieldsref readonly). Soundness hardening (found in review before this fix merged): the newBoundClrIndexExpressioncase originally trusted ANY byref-like CLR indexer target as encapsulating a caller-supplied referent, the waySpan[T]/ReadOnlySpan[T]genuinely do — but nothing in the CLR type system guarantees that. An externally-compiled ref struct can legally declare its indexer[UnscopedRef](System.Diagnostics.CodeAnalysis), a real C# 11+ pattern (nounsafe, no IL authoring) meaning the indexer returns arefinto the RECEIVER'S OWN storage rather than an encapsulated referent — exactly theAcc.Totalshape this fix's own guard exists to reject, just authored in a referenced assembly instead of natively. Without checking for that attribute, a G# function forwardingbuf[0]from a by-value parameter of such a type (e.g.func M(buf RingBuffer) ref int32 { return ref buf[0] }) compiled clean and the returned reference pointed at dead stack memory (confirmed reproducible: an intervening call's locals silently overwrote the "aliased" value on read-back). Real C# rejects the analogous code with CS8166 ([UnscopedRef]inverts the receiver's contribution to the call's ref-safe-context from safe-to-escape back to function-local for a by-value receiver).RefCapabilities.IsUnscopedRefIndexerGetternow inspects the resolved indexer for[UnscopedRef]viaCustomAttributeData(so it works correctly through gsc'sMetadataLoadContext-based reference loading, not just live reflection), checking BOTH the property and itsgetaccessor — C# allows the attribute on either, and an expression-bodied indexer ([UnscopedRef] public ref int this[int i] => ref field;) emits it on the property rather thanget_Item— and theBoundClrIndexExpressioncase falls back to the strictHasFunctionLocalRefScopetreatment whenever either carries it, matching C#'s behavior exactly (including still accepting the same member forwarded through a genuinerefparameter, where the referent legitimately is the caller's own storage). -
cs2gsno longer inserts a spurious!!non-null assertion on an intentionally-nullable delegate argument passed cross-project into a nullable-oblivious sibling project, which used to throwNullReferenceExceptionat runtime on a legitimatenil(issue #4262, found migratingDavidObando/Oahu). A nullable-ENABLED consumer project (e.g.Oahu.Cli.App) calling a delegate parameter declared in a nullable-OBLIVIOUS sibling project it references (e.g.Oahu.Core) — where the sibling's own whole-program taint fixpoint (ObliviousNullabilityAnalyzer, issue #2113/#2412) proves that parameter acceptsnilvia a transitiveif (convertAction != null)guard several calls downstream — gotconvertAction!!at the call site instead of a bareconvertAction, becauseObliviousNullabilityAnalyzer.IsTainted's three-argument (cross-project) overload bailed out immediately whenever the ASKING compilation (the consumer's own) was nullable-enabled, before its sibling-walk loop — which already correctly remaps into, and gates on the obliviousness of, each sibling independently — ever got a chance to run; #2412's cross-project machinery therefore only ever fired when the CONSUMER itself was oblivious, never when an enabled consumer called into an oblivious sibling. The entry gate now bails only when neither the asking compilation nor any sibling is oblivious. A second, narrower defect surfaced while fixing the first:IsTaintedCore's own whole-program fixpoint (Compute) reads raw syntax with no nullable-context guard of its own (an oblivious-only heuristic, since oblivious code carries no trustworthy annotation to read instead), so once the entry gate stopped preventing it from ever running against a nullable-ENABLED compilation, aT?local legitimately initialized tonullin the ENABLED consumer's own source could self-taint a cross-project call target through an ordinary argument-to-parameter edge — an unsound false positive that happened to look correct for a genuinely-tainted target but would have silently suppressed the!!bridge for an oblivious sibling parameter with no null-check evidence anywhere.IsTaintedCorenow only ever consults a compilation's own cached fixpoint when that compilation is itself oblivious, and always still walks the sibling set. The identical entry-gate shape was also present, and is also fixed, onObliviousNullabilityAnalyzer.IsParamsElementTainted(issue #3888's cross-projectparams T[]element taint) — reachable the same way, fromTargetWillRemainNonNullableReference's variadic-carrier branch, for a nullable-enabled consumer's expanded-params-tail argument into an oblivious sibling; its own candidate loop already gated each candidate (including itself) on obliviousness before touching its cache, so only the entry bail needed widening there, not the innerIsTaintedCore-style guard.!!is a real runtime throw in G# (unlike C#'s erased!), so this was a silent, systemic correctness regression rather than a cosmetic one — every plain (non---export)oahu-cli downloadcall crashed post-migration. Found during review: the same widened-gate reachability exposed three further call sites that consulted cross-project taint evidence without requiring the queried declaration's own annotation to be genuinely oblivious (NullableAnnotation.None) first — unlikeShouldPromoteToNullableReference's ordinary path, which already required that.IsParamsElementTainted's candidate loop matches by a compilation-independent documentation-comment ID rather than remapping by symbol identity the wayIsTainted's sibling walk does, so an UNRELATED oblivious sibling anywhere in the run — one with no connection to the actual call site — calling the same targetparamsmethod with a literalnullin its own source could suppress the!!bridge for a genuinely non-nullable enabled target, or (viaPromoteParamsElementIfUsedAsNullable's declaration-side promotion) repaint that target's OWN emittedparamselement nullable. A third, structurally identical gap existed inPromoteAwaitedReturnIfTainted(anasync Task[T]declaration's return-type promotion), where an oblivious override or interface implementation of an enabled base/interface member could repaint the enabled member's own declared return type nullable. All three are now guarded:IsParamsElementTaintedrequires the queried parameter's own element annotation to beNonebefore consulting any candidate's cache, andPromoteAwaitedReturnIfTaintedrequires the awaited type's own annotation to beNonebefore consultingIsTainted. -
A local function nested inside a generic method or type can now reference the ENCLOSING type parameter, whether or not the local function declares type parameters of its own (issue #4223, completing the diagnostic-only stopgaps of #1940 and #2016).
func Outer[U](seed U) U { let Keep[T] = func(ignored T, value U) U { return value }; return Keep(1, seed) }and its non-generic siblinglet Keep = func(value U) U { return value }(arrow syntax included) both reportedGS0468even with zero outer-value captures, because the emitted hoisted method carried only its own declared type-parameter list and the enclosingUhad no corresponding CLR slot.UserTokenResolver.TryPromoteNonCapturingGenericLambda(the issue #2118 machinery that already promoted a zero-capture NON-generic local/lambda referencing an enclosing type parameter into a genuine generic method) is extended to also apply when the local ALREADY declares its own[T, ...]list: every referenced enclosing type parameter is cloned as an ADDITIONAL method type parameter appended after the local's own, withBuildMethodSpecForGenericCallsupplying the extra type arguments directly (they are exactly the in-scope originals, never inferable from the call's arguments, since the local's own signature still names the original enclosing parameter rather than the clone) alongside the ordinary inferred/explicit ones for the local's own slots. The generic-own-type-parameter path's type-parameter-list binding is also fixed to resolve a constraint against the ENCLOSING scope (let Keep[T IComparable[U]] = ...,Uowned by the enclosing method) — previouslyGS0113 "Type 'U' doesn't exist"before the reference even reached the enclosing-type-parameter check, because the constraint clause bound in a scope seeded empty rather than merged with the enclosing type parameters. Two further gaps surfaced only once the diagnostic itself stopped masking them. First,LambdaEnclosingTypeParameterCollector— the shared scanner this promotion and the pre-existing capturing-closure reification (issues #1477/#3933) both use — never checked an implicit-receiver call's STATIC OWNER TYPE, a method group's owner type, a field/property access's declaring type, or a function-pointer's owner type; a local function calling asharedmember of the enclosing GENERIC type by its unqualified name (return Public()resolving toHolder[Outer].Public()) therefore had itsOuterreference missed entirely, silently falling back to an invalidVARslot on the promoted (non-generic-owner) host —System.BadImageFormatExceptionat load. Second, and more insidious: promoting a CALLEE to carry an extra enclosing type parameter can require its CALLER — another zero-capture local function in the same pass, textually unrelated to the enclosing parameter — to ALSO carry it, purely so the call site has something to pass; a caller that only reaches the parameter indirectly (calling a promoted sibling whose extra parameter never appears in ITS OWN argument or return types) was left unpromoted, and its call site's missing argument fell back to whatever type parameter happened to share the same ordinal in the wrong context — a WRONG VALUE at runtime with no error at all, worse than a crash.TryPromoteNonCapturingGenericLambdanow runs to a fixed point over every zero-capture local function/lambda in a compilation unit (each pass re-derives a function's complete referenced set, consulting a newGetPromotedExtraslookup for every call it makes, until a full pass promotes nothing further), so a callee promoted late in one pass still reaches an earlier-processed caller on the next. The ASYNC route needed a third, independent fix:ReflectionMetadataEmitter.RegisterStateMachineEnclosingGenericsbuilt the async state machine's outer-type-parameter remap keyed by the promoted local's OWN (cloned) type parameters, never consulting the promotion's enclosing-TP-to-clone-ordinal remap the wayRegisterGeneratedGenericRemapsalready does for the analogous ITERATOR state machine (issue #810 + #2118 combined) — so a body reference to the original enclosing parameter fell through to a danglingMVarslot insideMoveNext(a non-generic member of the now-generic state machine),System.BadImageFormatExceptionat load. It now aliases each original enclosing type parameter onto the same class slot its clone occupies, mirroring that existing iterator fix exactly. Two combinations remain unsupported and correctly still reportGS0468. First: a CAPTURING generic local function (issue #4221/#4252's synthesized-closure-class emission path, a different mechanism from the zero-capture top-level MethodDef path this fix extends) referencing an enclosing type parameter in its own signature or an own-type-parameter constraint — confirmed by direct repro to otherwise compile clean and crash (TypeLoadException/invalid IL) the moment the enclosing method executed; composing enclosing-type-parameter reification with capture support is left for a follow-up, as the issue itself anticipates. Second, found during this PR's own adversarial review: a NON-generic, zero-capture, ASYNC local function (arrow syntax included) whose OWN PARAMETER type — not its return type or body, both of which are fully supported and covered above — references an enclosing type parameter. That shape routes through a pre-existing async "erased delegate" adapter (predates issue #2118, used whenever a function-literal's declared type mentions an open type parameter) rather than throughRegisterStateMachineEnclosingGenerics's reification, and the adapter's parameter-unboxing conversion has a confirmed defect for a value-typed instantiation:func Outer[U](seed U) U { let Local = async func (x U) U { return x }; return Local(seed).Result }, if allowed to compile, runsOuter("hi")successfully but throwsNullReferenceExceptionforOuter(42). The identical crash reproduces on an already-legal CAPTURING async local of the same shape, and on a zero-capture async local of the same shape nested inside a non-generic type (both confirmed onmainpredating this issue entirely — neither was ever GS0468-gated, so that pre-existing exposure is unchanged here), so the adapter defect itself is pre-existing and unrelated to #4223. What IS in this issue's scope: relaxing GS0468 unconditionally for the newly-enabled zero-capture case would have newly routed a previously-rejected program (this parameter-referencing shape was unconditionally GS0468 before #4223) through that same broken adapter, trading a compile-time diagnostic for a runtime crash — which the issue's own guidance rules out ("Relax GS0468 only for routes with proven valid emission").LambdaBinder.CheckAsyncNonGenericLocalFunctionEnclosingTypeParameterInParameterretains the diagnostic for exactly this narrow combination, matching this shape's pre-#4223 footprint exactly (including the existing non-generic-owner-type exclusion, so it does not newly reject the already-legal, already-crashing struct/class-nested case either). Fixing the erased-delegate adapter itself remains a separate, pre-existing defect, disclosed here rather than fixed. -
Merging #4223 onto #4221's transitive-capture reconciliation (issue #4261) surfaced one more gap in the "capturing generic local referencing an enclosing type parameter" exclusion above, closed as part of that merge. The exclusion is decided once, at a group member's own bind time, from its
CapturedVariablesas known then — butLambdaBinder.ReconcileGenericLocalFunctionGroupCaptures(#4221's fixed point) can still widen that set afterward, for a FORWARD reference to, or a call CYCLE with, a sibling that captures outer state, since that widening is only discoverable once every member in the region has bound. A member that looked capture-free (and therefore eligible for #4223's zero-capture reification) when its own gate ran could be found to capture transitively only after the fixed point converged, and the gate never re-ran:func Run[Outer]() int32 { var outer = 1; let first[T] = func(a T, y Outer) int32 { return second(a) }; let second[U] = func(a U) int32 { return outer } return first(1, default(Outer)) }—firstis declared beforesecond(a forward reference), sosecond's capture ofouterisn't folded intofirstuntil after both members bind — compiled with no diagnostic and crashed the CLR with an invalid-program error the momentfirstexecuted. Each generic local-function literal now caches the enclosing type parameter it referenced (if any) at its own bind time; once the region's fixed point converges, every member whose capture set grew from empty is re-evaluated against that cached reference and rejected withGS0468if it now captures anything, instead of silently reaching the emitter. The two mechanisms otherwise coexist correctly: a member that only captures (no enclosing-type-parameter reference) and a sibling that only needs enclosing-type-parameter reification (no capture) are unaffected by each other, including within the same consecutive-declaration region. -
A lambda assigned to a named delegate whose trailing variadic parameter carries a generalized carrier type (ADR-0173 / #3627, e.g.
...List[T]) no longer has its own parameter mis-bound as a slice OF that carrier (issue #4235).delegate D(a int32, xs ...List[int32]) int32followed bylet d D = (a int32, xs ...List[int32]) -> areportedGS0155: Cannot convert type 'List[int32]' to '[]List[int32]'on the assignment — with no invocation involved, since the mismatch was already there in the declared types. The delegate side correctly resolved its...List[int32]parameter to the carrierList[int32]itself viaVariadicCarriers.ResolveDeclaredParameterType, butLambdaBinder's two lambda-parameter binding sites (function-literalfunc(...)and arrow(...) ->) still had the pre-ADR-0173 unconditional...T->[]Twrap left over from #812, so the lambda's ownxsbound as[]List[int32]— a slice of the carrier, not the carrier — and the two sides disagreed. Both sites now route through the sameVariadicCarriers.ResolveDeclaredParameterTypehelper the delegate and every named-function/constructor declaration already use, so an explicitly-typed lambda variadic parameter resolves to the identical carrier (array,List[T],Span[T]/ReadOnlySpan[T], or one of the fiveIEnumerable-family interfaces) regardless of which side of the assignment declares it first. Target-typed inference (an omitted lambda parameter type filled in from the delegate) was already correct and is untouched. The real "array of carrier" shape (...[]List[T]) and a non-carrier generic element (...Dictionary[K, V], which keeps the ADR-0101 element interpretation) are unaffected. -
A default-parameter-value expression that forward-references a sibling type's static member no longer gives a misleading diagnostic that depends purely on declaration order (issue #4183, found while measuring #4166).
func M(x int32 = B.Value) int32— whereclass C(declaringM) is declared BEFOREclass B(declaringshared { var Value int32 = 42 }) — reportedGS0158: Cannot find member Value.even thoughB.Valueplainly exists; reversing the declaration order instead reported the semantically-correctGS0265: Optional parameter 'x' is invalid: ... must be a compile-time constant. Root cause:ConversionClassifier.BindAndAttachParameterDefaultValueran eagerly, inline, duringBinder.BindGlobalScope's single per-struct declaration-body pass — the same class of forward-reference gap field/const initializers had (#1070/#1194) before those were deferred. Default-parameter-value binding (covering primary-constructor, instance-method, static-method and explicit-init(...)-constructor parameters alike) is now deferred the same way, via a newpendingParameterDefaultValueBindingsqueue drained byDeclarationBinder.BindPendingParameterDefaultValues()once every struct's static-member surface exists compilation-wide. The drain runs BEFOREBindPendingBaseInitializers, per the ordering constraint the investigation identified: a: base(...)initializer readsParameterSymbol.HasExplicitDefaultValuewhile resolving against a base constructor's optional trailing parameters, so binding defaults any later would make that resolution see a not-yet-populated default. Both declaration orders now report the identicalGS0265— no cross-type field/const read is foldable into a compile-time constant today (a separate, orthogonal gap this issue does not fix), matching the equivalentcscbehavior for a non-constant static-field default. This also incidentally strengthens #4166's structural finding (already downgraded to "theoretical, no confirmed bug"): default-value binding now runs strictly afterDetectClassInheritanceCycles, rather than before it. -
A nullable-reference annotation on a tuple element nested inside an imported
async Task[...]return type is no longer dropped (issue #4159, found while investigating #4133/#4156).Store.GetNullableAsync() Task[IReadOnlyList[(Key string, Value string?)]], imported from a referenced (already-compiled) assembly, compiledlet x string = rows[0].Valuewith no diagnostic — the same-compilation (symbolic) equivalent already correctly reportedGS0155. Root cause, inNullabilityAnnotatedTypeSymbol.TransferTupleNames: a tuple nested one level inside another generic argument (IReadOnlyList[...]insideTask[...]) is represented LAZILY, andTransferTupleNamesonly matched a tuple sitting directly under oneNullablewrapper or a top-levelImportedTypeSymbol, so it silently returned the unnamed shape unchanged instead of materializing and naming the lazy nested generic; that same fix also covers a PLAIN (non-tuple) nullable-reference-typed awaited element —ExpressionBinder.TryGetTaskElementType's CLR-fallback path (traced directly: taken specifically when the awaitable's own type-argument tree contains no tuple needing eager reconstruction, e.g.Task[string?], as opposed to the tuple-containing case above, which instead takes the same method's symbolicGetTypeArgumentSymbolfast path) recovered the result via a naiveTypeSymbol.FromClrTypeinstead of the nullability-awareNullabilityAnnotatedTypeSymbolaccessor — so this fix is general to any reference-typed awaited element, not tuple-specific, and simply went unnoticed until a named tuple made the loss visible. This is the root cause referenced in #4133's own PR notes below (theGS0159symptom in a real-world corpus, mitigated there by treating two mutually-convertible bounds as mergeable rather than an unresolvable ambiguity); this fix addresses the underlying metadata-import defect directly. Two Copilot review findings on this PR surfaced two further, narrower edges in this same machinery:TransferTupleNames's nullable-wrapper case required BOTH the naive, name-bearing tree AND the flags-derived tree to already beNullable-wrapped to recurse, missing a tuple nested inside a nullable REFERENCE generic argument specifically (e.g.IReadOnlyList[(...)]?, the list itself nullable) since the naive tree never reliably wraps reference nullability the way the flags-derived one does — now keys off the flags-derived side alone; andGetTypeArgumentSymbolForClrType(the CLR-fallback path above) matched the outer awaitable's generic argument by closed-CLR-type equality alone, ambiguous for a custom (non-Task) awaitable with two type parameters that happen to erase to the identical CLR type — now refuses to guess and falls back to the unannotated result rather than ever return an annotation that might belong to a different type parameter. -
A bare method group whose declared parameter type is a BASE class/interface can now convert to a concrete delegate type over a DERIVED element type (issue #4165).
Name(x Base?) stringpassed asitems.Select(Name)overIEnumerable[Derived]— or directly,Func[Derived, string] f = Name— reportedGS0155: Cannot convert type '(Base?) -> string' to 'System.Func[Derived, string]';cscaccepts this as an ordinary contravariant method-group conversion.Conversion.IsFunctionToDelegateConvertibleclassified each parameter/return slot by comparing raw CLRTypes (ClrTypeUtilities.IsAssignableByName), which can only ever fire when the method group's own parameter type carries aClrType— never true for a same-compilationclass/interfacemid-binding, whoseTypeBuilderdoes not exist yet. (A CLR-imported base/derived pair, e.g. Roslyn'sISymbol/INamespaceOrTypeSymbol, was measured to never reach this classifier at all for either a.Select(...)argument or a direct delegate-variable assignment — some other resolution path handles that shape, so this defect was specific to same-compilation parameter types and never visible for an imported one.) Each slot now falls back toConversion.IsImplicitReferenceVariantSlot— the same reference-only, hierarchy-aware classificationConversion.Classify's own upcast rules already use — when the CLR-type check cannot even ask the question, covering both parameter (contravariant) and return (covariant) positions and both same-compilation and CLR-imported element types alike. A delegate closed over a same-compilation type argument (Func[Derived, string]) also erases that argument toobjectin the CLR-reflected signature mid-binding, so the real argument is recovered from the delegate's ownTypeSymbol.ConstructedTypeArguments(symbolic, not erased) by position before classification. Removing the parameter loop's unconditional rejection also surfaced a dormant sibling defect the pre-existingIssue1518NullableDelegateInferenceEmitTestssuite caught as a regression during this fix's own validation:NullableTypeSymbol.ClrTypeerases a nullable VALUE type (bool?) to its bare underlying type (bool), so the return-type identity check could no longer tell a lambda that actually returnsbool?apart from one returningboolonce the parameter gate that used to reject every same-compilation-parameter candidate outright stopped masking it —Select'sTResultoutput-type inference locked onto the non-nullable candidate first and the emitter builtFunc[S, bool]where callers still expectedFunc[S, bool?](an ilverifyStackUnexpected). The return-type check now usesNullableLifting.GetEffectiveClrType(identity for every other shape, including reference types) instead of the raw, erasingClrType, matching whatFunctionTypeSymbol.BuildClrTypealready does to avoid this exact erasure for the emitted delegate itself. The identical erasure gap exists on the PARAMETER side too (a method group declaring aT?parameter satisfying a delegate declared over the bareT, whichcscrejects withCS0123) but was not reachable by any currently-passing test and is tracked separately as issue #4184 rather than fixed here without a red witness. -
A bare method group whose declared parameter type is a nullable value type (
T?) no longer silently satisfies a delegate slot declared over the bare non-nullableT, and vice versa (issue #4184, the parameter-side sibling of #4165's return-type fix above).func HasValue(x int32?) bool -> x != nilassigned toFunc[int32, bool]compiled with no diagnostic and ran, silently dropping the nullable requirementHasValuedeclared;cscrejects the equivalent C# withCS0123.Conversion.IsFunctionToDelegateConvertible's parameter fast path compared the method's declared parameter type against the delegate's using the raw, erasingfnParamType?.ClrType—NullableTypeSymbol.ClrTypeis the bare underlying value type, soint32?was indistinguishable fromint32. The fast path now routes throughNullableLifting.GetEffectiveClrType(the same helper #4165's return-type fix uses), which re-wraps a value-type underlying inNullable[T]. That alone was insufficient for the REVERSE direction (a method declaring bareTwrongly satisfying a delegate'sT?slot — alsoCS0123undercsc, and measured as a live gap while building this fix's own T/T? matrix):Type.IsAssignableFromhas its own CLR-level special case whereNullable<T>.IsAssignableFrom(T)istrue(supporting the implicitT -> T?lift used in ordinary expression contexts), whichClrTypeUtilities.IsAssignableByNamewould otherwise honor here even though C#'s method-group parameter matching does not extend it to value types. A new narrow guard,IsClrNullableWideningMismatch, closes that reflection-level gap at this one call site without narrowingIsAssignableByNameitself, which many unrelated assignability probes elsewhere in the binder and emitter still rely on. The full T/T? parameter matrix (T -> T,T? -> T,T -> T?,T? -> T?) now matchescscexactly. The identical reflection quirk also affects the RETURN side'sT -> T?direction for a bare method group, but fixing it safely requires distinguishing a method group from a lambda at this shared call site (a lambda'sbool-returning body IS accepted bycscwhen target-typed againstFunc[int32, bool?]) — tracked separately as issue #4186 rather than fixed here without resolving that discriminator. -
A doubly-nested contravariant delegate parameter (
Action[Action[T]]) with an unresolvable bare method-group argument no longer crashesgsc(issue #4171, found verifying a Copilot review finding on #4156).NestedVariance.Pick(strings, NestedVariance.Handler)— wherePick[T](items IEnumerable[T], handler Action[Action[T]])correctly infersT = stringfrom the receiver, andHandler's ownAction[object]parameter does NOT satisfy the resultingAction[Action[string]]slot (cscrejects the equivalent call withCS1503) — crashed with an internalGS9998: NotSupportedException: Cannot encode signature for type '?' yet.during PE emission, rather than reporting a clean diagnostic. An unresolved bare method group is deliberately typedTypeSymbol.Erroras a "defer me" sentinel until overload resolution picks a candidate (ClrOverloadResolution.IsUnresolvedMethodGroupArgument), andExpressionBinder.Calls.Invocation's "an argument that already failed to bind cannot participate in overload resolution" guard treated ANYTypeSymbol.Error-typed argument as already-diagnosed and silently returned an undiagnosedBoundErrorExpressionwhen no candidate accepted the call — but a deferred method group is never a prior failure. The top-level declaration's inferred type became the bareTypeSymbol.Errorsentinel with zero diagnostics reported, reaching the emitter, which has no encoding for it. That guard now excludes an unresolved method-group argument, so the call falls through to the existingGS0159("cannot find function") diagnostic instead — a real, if generic, rejection with no crash. The doubly-nested shape with a handler that DOES satisfy the inferred delegate (Action[string]) continues to compile and run, matchingcsc. -
An annotation naming a type caught in an unresolved base-class cycle no longer hangs
gscand grows memory without bound (issue #4162).StructSymbol.GetHierarchy()walked the symbol-levelBaseClasschain with no cycle guard; the post-bind cycle detector (#973) normally rejects a genuineclass B : C/class C : Bcycle before anything else walks that chain, butGetHierarchy()is also reachable earlier, during declaration binding, viaDerivesFromSystemAttribute()→IsAttributeType(), whenever an annotation names a type that is itself part of an unresolved cycle. Without a guard the walk never terminated, so@Bon an unrelated class over a cyclicB/Cpair grew RSS from 3.6 GB to 18 GB in ten seconds rather than reporting a diagnostic.GetHierarchy()now folds avisitedcheck into its own walk — a repeat both detects the cycle and stops it — so the source now cleanly reportsGS0381for the cycle andGS0200for the resulting non-attribute type, with no change to any acyclic hierarchy's result. -
An explicit
init(...)constructor parameter typed as a same-compilation class no longer hangsgscwhen its enclosing class is part of a base-class cycle (issue #4164). A different, independently reachable unguardedBaseClasswalk than #4162's:BoundScope.TryLookupNestedTypeAliasIncludingInherited()loopedfor (var c = container.BaseClass; c != null; c = c.BaseClass)with no cycle guard, reached while binding an explicit constructor parameter's type clause —Binder.LookupType()→TryLookupLexicalNestedTypeAlias()→ here — before the post-bind cycle detector (#973) has run. A livedotnet-stacksample of the hanging process confirmed the same frame repeating indefinitely. A primitive-typed explicit parameter, or the same class-typed parameter on a PRIMARY constructor, never reached this path and were unaffected. The loop now folds in the samevisited-set guard #4162 used, soopen class B : C { init(value Widget) { } }/open class C : B { let W int32 }now cleanly reportsGS0381instead of hanging. -
cs2gs's ADR-0169 analyzer-translation mode can now translate a C# analyzer's own null-conditional-access detection, SOUNDLY, across the full idiom set — the type test, the registration guard, receiver/tail reads, chain walks, name extraction, bare casts, and descendant/ancestor walks (issue #4173). An earlier version of this fix (landed first in this same PR) covered only the type test and the registration guard, and had to remove a THIRD idiom a reviewer found unsound (a syntactic "is this single-hop" test that cannot actually be proven from analyzer source text alone — both a genuine single hop and an inner chain node satisfy the same syntactic shape). A follow-up design pass found the real structural correspondence: Roslyn'sConditionalAccessExpressionSyntax/WhenNotNullchain and G#'s own postfix-chain parse are NOT mirror images of each other (an earlier draft of this same fix assumed they were, and that assumption was wrong) —./?.continuations right-nest in G# too (throughAccessorExpressionSyntax.RightPart, exactly like Roslyn's ownWhenNotNullnesting, confirmed independently byAssignmentTargetSyntaxFacts.TryLiftTrailingMemberAccess's existing recursion), while[/?[/(continuations still nest the ordinary iterative way (throughIndexExpressionSyntax.Target/CallExpressionSyntax.Callee). A new src/Core utility,GSharp.Core.CodeAnalysis.Syntax.NullConditionalChain, walks this hybrid shape directly over real G# syntax trees at analysis time (IsNullConditionalHop,ChainTop,NextNullConditionalHop,TailIsMemberBinding/TailIsElementBinding,ReceiverIsMemberBinding/ReceiverIsElementBinding/ReceiverIsPlainMemberAccess, and Roslyn-exactHopSpan/ReceiverSpan/WhenNotNullSpanlocation math), and cs2gs now rewrites:expr is ConditionalAccessExpressionSyntax [x]toNullConditionalChain.AsNullConditionalHop(expr) is ExpressionSyntax [x](coveringa?.bANDa?[i]uniformly, closing a genuinea?[i]under-fire the first landing left in place);RegisterSyntaxNodeAction(handler, SyntaxKind.ConditionalAccessExpression)to a guarded wrapper registered for BOTHSyntaxKind.AccessorExpressionandSyntaxKind.IndexExpression;<x>.WhenNotNull is <Type> [designator]and<x>.Expression is <Type> [designator]to the matchingNullConditionalChainpredicate, with the designator narrowed to the real G# type the predicate proves;MemberBindingExpressionSyntax.Name/.OperatorTokenandElementBindingExpressionSyntax.ArgumentListtoRightPart/DotToken/Indices; a bare cast or variable-typedConditionalAccessExpressionSyntaxread to G#'s non-discriminatingExpressionSyntaxsupertype (safe because every DISCRIMINATING use is intercepted by the idioms above — trusting the registration guard for soundness, deliberately NOT trying to statically prove a handler is exclusively guard-registered, the same reasoning that made the removed idiom unsound); and.OfType<ConditionalAccessExpressionSyntax>()/FirstAncestorOrSelf<ConditionalAccessExpressionSyntax>()to an explicitNullConditionalChain.IsNullConditionalHopfilter. Every rewrite handles BOTH C# shapes a type test can take — a designatedis Type x/pattern-combinator form (IsPatternExpressionSyntax) and a BAREexpr is Typewith no designator, which parses as the olderBinaryExpressionSyntax/SyntaxKind.IsExpressionnode and never reaches pattern translation at all; missing the bare form would have made the new non-discriminatingExpressionSyntaxmap row silently vacuous for the commonest real-world spelling of a type probe. A sibling pre-existing bug is fixed alongside:MemberAccessExpressionSyntax→AccessorExpressionSyntaxandSyntaxKind.SimpleMemberAccessExpression→SyntaxKind.AccessorExpressionwere BOTH unconditional, but Roslyn's ordinaryMemberAccessExpressionSyntaxEXCLUDES a?.hop's tail (Roslyn gives that its own receiverlessMemberBindingExpressionSyntaxkind) — sonode is MemberAccessExpressionSyntaxand an unguardedSimpleMemberAccessExpressionregistration both silently over-fired on every?.hop's tail too; both now carry the sameIsNullConditional-discriminating fix, inverted..WhenNotNullread as a bare value (not the scrutinee of anistest) still has no G# counterpart and stays a loudCS2GS-GAP, as does<x>.Expression is ConditionalAccessExpressionSyntax(Roslyn only reaches a genuine CAE there through a parenthesized chain break, which cannot be told apart from an ordinary hop without risking a vacuously-true test — the same class of reasoning that sank the removed idiom). G#'s own null-conditional INDIRECT invocation (f?(x), a G#-only construct with no C# counterpart) is out of scope and does not dispatch through any of this. Round 3 (adversarial review of round 2, above) found the type-test fix still only recognized the TOP-LEVEL shape of a pattern (a bare/designatedDeclarationPatternSyntax/TypePatternSyntax/ConstantPatternSyntax, via one dedicated entry point) — anot,and,or, a switch-case label, or a nested property subpattern fell through to the ordinary native-pattern/boolean-lowering translation, which had no CAE/shared-node awareness at all, and silently over-matched: reviewer's reproduction, a designatedis not ConditionalAccessExpressionSyntax caeregistered onSyntaxKind.IdentifierNameand run over PLAIN (non-null-conditional)box.Name, reported 2 diagnostics where real Roslyn reports 0. Round 3 fixes this at the LEAF instead of enumerating more pattern shapes (the same enumeration mistake twice already): every pattern-position type-mapping call site (TranslatePattern,TranslateRecursivePattern,BuildNativePattern,TranslatePatternTest,TranslateNotPatternTest,TranslateRecursivePatternTest, the loop-condition guard emitter, and the statement-levelif let/guard-hoist family) now routes through two shared builders instead of calling the general type mapper directly. ForMemberAccessExpressionSyntax/ElementAccessExpressionSyntax(the latter a previously-unreported sibling of the identical bug — the map row carried no guard of any kind), the fix is a pure G# PATTERN leaf swap (AccessorExpressionSyntax/IndexExpressionSyntaxplus anIsNullConditional: falsesuffix), which composes for free undernot/and/or/parens/switch/nested subpatterns through the existing, already-tested pattern walkers — no new shape enumeration anywhere. ForConditionalAccessExpressionSyntax, whose faithful G# form is theNullConditionalChain.AsNullConditionalHop(x) != nilPREDICATE (not a pattern), a shape-agnosticDescendantNodesAndSelfscan — deliberately not a switch over pattern kinds, so a future shape can't defeat it the way the first two rounds' enumerations did — detects any CAE-mentioningis-pattern and routes the WHOLE pattern off the native-G#-pattern paths onto the existing boolean-lowering path, where the same leaf hook emits the predicate andnot/and/orcompose for free; a CAE designator binds by substitution at the only three positions C#/G# both allow one (top level, under top-levelnot, or underand— GS0390/CS8780). A position that is G#-pattern-ONLY (a switch-case label, a switch-expression arm, or a nested property subpattern that could not be boolean-lowered) has no sound CAE rewrite and now surfaces a loudCS2GS-GAPinstead of silently falling back to the non-discriminatingExpressionSyntaxsupertype. The statement-levelif let/guard-hoist machinery builds its own hoisted local ahead of the pattern-test translation ever running, so it needed its own fix, not just a caller of the shared leaf: for CAE the hoist's initializer becomesAsNullConditionalHop(receiver)directly (already nullable, so it drops into the existinglet t T? = …; if t != nilshape unchanged), and for a plain-access type the existingas-cast is kept but the guard gains an extraIsNullConditionalconjunct; where adapting the hoist wasn't safe to do inline it declines and falls back to the general lowering instead. Two real, in-repo sites insrc/Analyzers/InternalAnalyzers/RewriterClonePreservationAnalyzer.cs(a nested property-subpattern designator and a switch-case label, both testingMemberAccessExpressionSyntax) go from silently over-matching to the faithful discriminated rewrite — an intentional, expected change in the self-hosted migration's own translated output, not a regression.NullConditionalChain.HopSpan/ReceiverSpanalso now throwArgumentExceptionon a non-hop node instead of silently returning a plausible-but-meaningless span (precondition hardening; the sole existing emitter only ever calls them on an already-proven hop, so this is not a behavior change there). Still explicitly out of scope, unchanged from round 2 and pending a repo-owner decision: anas ConditionalAccessExpressionSyntax/as MemberAccessExpressionSyntax/as ElementAccessExpressionSyntaxcast still gets only the warn-and-passCS2GS-ANALYZER-SHAPEtreatment, not the discriminating rewrite. Adversarial re-review of round 3 found one more unguarded site of the exact same bug class:TranslateRecursivePatternTest's OWN designator binding (is T { }/is T { ... }over a shared-node type) calledBuildPatternNarrowingReplacementdirectly instead of routing through the round-3 leaf, which is unreachable from anif-statement condition (the guard-hoist machinery intercepts that shape first) but very much reachable from any other boolean-expression position — a ternary condition over a smart-castable local/parameter receiver failed to bind at all (GS0158/GS0130) before this fix, since the designator was bound to the bare, un-narrowed receiver instead ofNullConditionalChain.AsNullConditionalHop(receiver). Fixed with the sameIsConditionalAccessAnalyzerType/IsPlainAccessAnalyzerTypebranchTranslatePatternTest'sDeclarationPatternSyntaxcase already used. -
A contravariant delegate/interface argument now raises the inferred type argument, matching
csc(issue #4133). Insidefunc f[T DisposableBase](value T),VarianceOverloads.DelegateType(value, ObjectAction())— whereObjectAction()returnsAction<object>— printedDisposableBase;cscprintsObject, because the contravariantAction<T>/IComparer<T>argument's own type is an UPPER bound onTthat must be able to raise it past the lower bound the plainvalueargument contributes.MemberLookup.FixSymbolicMethodTypeArgumentscollected both bounds correctly but picked the fixed type from the lower-bound list whenever it was non-empty and consulted the upper-bound list only afterwards, to VALIDATE that pick, never to WIN it — so an upper bound could confirm a narrower answer but never replace it.FindSymbolicInferenceCandidatenow builds its candidate set from both lists together and keeps the unique survivor every other survivor converts into, the same rule that already let one upper bound narrow another (order-independence, unaffected by this fix). The*Winneroverload does not move — only the inferred type argument does — which is why this was a narrower, separate defect from #4086's. A related permissiveness surfaced by this same change was closed alongside it: bound satisfaction was checkingConversion.Classify, which also admits ADR-0148 structural projection (constructing a new, unrelated user object through its public surface) — a VALUE conversion, not a type relationship, that must never let one generic bound satisfy another. It now checksConversion.ClassifyNonStructural, so a homonym imported type still reports its ambiguity (GS0159/GS0547) rather than silently inferring the wrong one of the two. Consulting both bound categories together also makes a NEW pair reachable that a single category alone never produced: a lower and an upper bound that are mutually convertible underConversion.ClassifyNonStructural(identity modulo a reference-nullability annotation or a tuple element name — e.g.(Key string, Value string)against(Key string, Value string?)) but notTypeSignaturesEquivalent. C#'s own fixing never treats that as ambiguous — nullability is folded in after fixing picks a type, not used to eliminate a candidate — so this case now merges through the sameMergeRecoveredTypeArgumentthe equivalent-bounds branch already used, instead of falling to the true-ambiguity branch and reporting a spuriousGS0159. -
A bare method group argument's own parameter type no longer raises a generic method's inferred type argument (issue #4133 follow-up, found by the hot-core translation guard). #4133's fix (above) taught symbolic inference to consult an upper bound alongside a lower one, but a bare method-group argument's recovered natural type is not a genuine upper bound in the first place: C#'s own method-type inference (§12.6.3.7) makes only an OUTPUT inference from a method group's return type, never an INPUT inference from its parameters.
RefineSymbolicArgsForMethodGroupsrecovers a method group's naturalFunc/Action-shaped type from its real declared signature so its same-compilation return type is not lost to erasure, and that natural type then flowed into the same delegate-shape unification #4133 touched — so the group's own PARAMETER type, not just its return type, was treated as a real upper bound.Where[TSource]overIReadOnlyList[Item]with a bare predicatepred(x Item?) bool(the nullable annotation cs2gs's oblivious-nullability heuristic adds to nullable-oblivious C#) correctly lower-boundedTSourcetoItemfrom the receiver, but the predicate's ownItem?parameter then raised it toItem?— a false ambiguity two calls downstream, reported asGS0159(tools/cs2gs/Cs2Gs.Pipeline/DeclaredProjectItem.gs). Worse, a real subtype (not just a nullable annotation) could raiseTSourcepast what the receiver actually enumerates:INamespaceSymbol.GetMembers()(a shadowing declaration returningIEnumerable<INamespaceOrTypeSymbol>) correctly lower-boundedTSourceto the narrowerINamespaceOrTypeSymbol, but a bare method group whose own parameter was the widerISymbol?raised it back toISymbol— gsc emitted aSelect<ISymbol,…>MethodSpec at a call site whose delegate creation was still pinned toFunc<INamespaceOrTypeSymbol,string>by the extension method's own receiver, an inconsistency gsc's binder did not catch but ILVerify did (StackUnexpected,Cs2Gs.Translator.EmittedNameAllocator.GetScopeNames). A newSymbolicInferenceBoundKind.MethodGroupUppercategory keeps a method group's parameter-type contribution out of the ordinary bound lists — its legitimate return-type (output) contribution is unaffected — andSymbolicInferenceBounds.Adddiscards it outright, with NO fallback:cscreportsCS0411forWrap[T](predicate Func[T, bool])called asWrap(Check)with no other argument to fixTfrom, so a same-slot "fallback" promoting the discarded bound back in whenever no other bound exists (an earlier draft of this fix) would have made gsc silently accept that call — strictly MORE permissive thancsc, the opposite direction of #4133's own defect (caught in review). Reversing an already-demotedMethodGroupUpperbound through a SECOND contravariant level (nested inside another delegate type argument) now stays demoted rather than cycling back to a real bound, so the demotion holds at any nesting depth, not only the first.HasImplicitSymbolicConversionalso now treats a pure reference-nullable-annotation difference as mutually satisfying at its own elimination gate, not only inside the later merge branch that resolves it — closing the reverse direction of the #4133 nullable-merge case above (a nullable LOWER bound against a non-nullable UPPER bound), which the gate rejected outright before the merge branch ever ran. Threaded through every CLR call-resolution path that recovers a method group's natural type for its FINAL generic instantiation (extension, instance, static, inherited and constraint-dispatched calls) rather than only the one the two reported failures exercised; one narrower internal helper — recovering a target delegate's PARAMETER shape for a second, still-unresolved method-group/lambda argument in the same call — is left on the pre-fix behavior, since it only feeds a secondary lambda-shape heuristic and no known call site depends on it. Both failures bisect to #4133's own first commit, not pre-existing. -
A
func(...)->R-shaped structural cache key no longer aliases two differently-named, same-shaped tuples (issue #4160, found alongside #4133).FunctionTypeSymbol.AppendStructuralKey's tuple case built its key fragment from element types only, never folding inTupleTypeSymbol.ElementNamesthe wayTupleTypeSymbol.Get's own cache key does (ADR-0172) — so(Id Guid, Text string)and(Id Guid, Content string)produced an identical key wherever this shared builder is used (FunctionTypeSymbol's own cache,FunctionPointerTypeSymbol, synthesized state-machine/anonymous-type/ref-delegate caches). Two textually-separate calls in one compilation, each with an explicitly-typed tuple lambda parameter of one of these shapes, could have the SECOND one silently resolve to the FIRST one's (wrong) tuple type. Confirmed pre-existing and unrelated to #4133's own change via a control build of the pre-#4133 compiler reproducing the identical aliasing. The key now folds in element names exactly asTupleTypeSymbol.Getdoes. -
paramspacking, interpolated-string-handler forwarding and named arguments now bind, in SOURCE evaluation order (issue #4134). Ten call shapescsccompiles and runs were previously a mix of rejection and incorrect ordering. Eight reportedGS0159 Cannot find function— aparamsarray of interpolated-string handlers, a namedFormattableStringin an expanded call, and every spelling of anInterpolatedStringHandlerArgument-forwarded handler except the extension-method one, which reportedGS0246and was never executed. The remaining two — a reordered named argument into aparamsslot, and itsreflvalue variant — already bound, from the erased-type-parameter fix's named-argument mapping, but evaluated in PARAMETER order rather than source order:second|first|andref|first|wherecscprintsfirst|second|andfirst|ref|. They now all bind, and with C#'s ordering rule rather than the parameter order they are reordered into:EvaluationOrder(items: first(), value: second())evaluatesfirst|second|, a forwarded handler evaluatesfirst|prefix|handler|, and a synthesized extension receiver — unreachable before, since that call never bound — is evaluated exactly ONCE (receiver|first|prefix|handler|). Aref/outlvalue in a reordered expanded call is captured through a managed-pointer local so the write-back still lands. The forward-reference rule C# spells CS8950 — a handler-forwarded argument occurring at or after the handler expression — is now reported asGS0221naming the parameter that is not a preceding argument, where the parent said only "cannot find function". Measured against a compiled and run C# twin on every row, including side-effect order. Stacked on #4086's PR: the erased-type-parameter fix is what makes the named mapping reach these calls at all, and the two rows it pinned as known-wrong (binding in parameter order) are flipped green here. -
An inferred imported generic overload now keeps a type-parameter identity conversion ahead of a genuine
objectoverload (issue #4086). Insidefunc callIt[T DisposableBase](value T),Overloads.Take(value)overTake<T>(T) where T : IDisposableandTake(object)erased the caller'sTtoSystem.Object. Both candidates therefore appeared to take the argument by identity, and the later parameter-specificity tie-break preferred the non-genericobjectslot;cscinstead picks the inferredTake<T>(T). The resolver now carries source argument symbols beside their CLR erasures and checks the candidate's OPEN parameter: a method type-parameter slot keeps identity only when its recovered symbolic argument is the same source parameter and no genuineobjectbound also fixed that method parameter; otherwise the real reference/boxing conversion is ranked. The prerequisite thatT : DisposableBaseimpliesIDisposableis supplied by #4070/#4088's rule, which this change relies on rather than duplicates. This is not a generic-over-non-generic preference: an actual or mixed-inferenceobjectargument still selects the non-generic overload. Symbolic method arguments also survive constrained imported instance/static dispatch through async rewriting/spilling into conversion and MethodSpec emission — measured, that path also stops emitting IL ILVerify rejected with[StackUnexpected] … [found value 'T'][expected ref 'object']. A neighbouring divergence surfaced by this same review — a contravariantAction[object]/IComparer[object]argument not raising the inferred type argument the waycscdoes — was pinned rather than ridden along at the time and is fixed separately, above (issue #4133). Focused regressions compile against C# sibling libraries, IL-verify, run, and cover the exact inferred/explicit repro, mixedTplusobjectinference, constrained instance/static calls, and genuine-objectcontrols. -
A
typeofattribute argument now keeps the type arguments supplied by an enclosing generic (issue #4095).@Marker(typeof(Outer[Status].Inner))compiled, IL-verified and ran, but the custom-attribute blob wroteP.Outer`1+Innerwith no instantiation, so reflection handed back the OPENOuter<T>.Innerrather than the type the source names — a wrong answer that resolves, which is why nothing threw. A nested type records the encloser's vector onEnclosingTypeArgumentsand leavesTypeArgumentsholding only what its own level declares, so the constructed-generic arm added in #4073 never fired for it. The serializer now writes the flattened enclosing-then-own vector, matching the GenericParam rowsTypeDefEmittercopies down each nesting level (ADR-0087 §3 R1). A nested ENUM takes the same repair:EnumSymbol.ConstructNestedrecords the identical vector, andtypeof(Outer[Status].Kind)wrote the openP.Outer`1+Kind. Two further shapes were wrong for a second reason and are fixed with it: the blob computed a nested name's backtick suffix from the FLATTENED parameter count while the TypeDef declares only the parameters of that level (issue #2916), sotypeof(Outer[Status].GenericInner[string])namedP.Outer`1+GenericInner`2— a type the emitted metadata does not declare, which made the attribute undecodable rather than merely wrong; the suffix is now taken from the same expressionTypeDefEmitteruses, so the two cannot drift again. An operand whose identity still depends on an IN-SCOPE type parameter —typeof(Outer[T].Inner)insideclass C[T]— now reportsGS0202instead of silently serializing the erased close as a different closed type; an unbound generic DEFINITION such astypeof(Box[_])ortypeof(Outer[_].Inner)stays legal and reifies as the open type. Every other operand shape keeps the path it had. The nested class, the nested enum, a nested type with its own argument, a three-level nesting, and enclosing arguments that are themselves a source generic, an imported generic, an interface, a delegate, a nilable value type or a nilable reference are compiled, IL-verified, read back through raw metadata and aMetadataLoadContext, and materialized at run time. -
A same-compilation enum now satisfies a
structconstraint (issue #4139).GsStruct[Color]()andclass Source : ISource[Color], whereenum ColorandISource[T struct]are declared in the same compilation, reported a falseGS0152; so did theunmanagedspelling, whose check thestructone gates. An enum is a non-nullable value type (ECMA-335 II.14.3) andcscaccepts the equivalent.IsNonNullableValueTypeForConstrainthandled type parameters and structs explicitly and otherwise fell through to a reflectiveClrTypeprobe, which a same-compilation enum does not have while binding; the imported spelling of the same shape always worked, because that one does. Same root as #4124 (a same-compilation symbol has noClrTypewhile binding, so a reflective probe answers "no" without reading the symbol), but in a sibling predicate that #4124's consolidation does not reach — measured on both sides, not assumed. It is a true prerequisite of the type-clause enforcement above rather than a separate user-visible failure: the interface-implementation spellingclass Source : ISource[Color]only becomes reachable by this predicate once that enforcement makes a type clause ask it at all. -
A method group used as an ordinary value now reports
GS0582before emit (issue #4065). Member chaining such asitems.Add.ToString(), targetless inference, ordinary object-typed arguments/returns, and targetless conditional arms previously retained an unresolved method group until IL emission, where they surfaced as the internal-compiler-errorGS9998. The binder now records whether contextual conversion supplied a delegate target and rejects only groups that escape without one. The public diagnostic names the group and distinguishes user/imported instance, static, and extension groups; successful calls, natural method-group interpolation, and delegate-targeted assignments, arguments, returns, and conditional arms are unchanged. -
Imported generic member projection now keeps both symbolic receiver arguments and their nullable flags (issues #4059 and #4066). A CLR generic constructed over a same-compilation G# type no longer reads members typed by that parameter as the binding-time
objectsurrogate, and a receiver imported as (for example)Dictionary<string, string?>no longer drops the value argument's?. Property reads/writes, fields, method returns/parameters/out, indexers, nested generic member types,.Values, enumerators andforiteration now substitute from the receiver's symbolic vector, while declaration-site nullable metadata is merged back over concrete positions. Annotated and non-annotated receivers therefore remain distinct through binding and emitted metadata. -
A class constraint reached through a dependent type-parameter bound no longer reports a false
GS0152(issue #4091). Infunc f[U SchemeOptions, T U](), constructingGsHandler[T]whereGsHandler[TOptions SchemeOptions]requiresSchemeOptionswas rejected even thoughT : U : SchemeOptions. The shared class-constraint predicate followed onlyClassConstraint, while dependent bounds deliberately live in the separateTypeParameterBoundslot. It now walks both links with reference-identity cycle detection, so every generic construction path accepts transitive class bounds without imposing an arbitrary depth limit. -
A dependent constraint now propagates the bounding parameter's
classconstraint, sonilis legal at[TBase class, TDerived TBase](issue #4062).return nilat aTDerivedslot reportedGS0155: Cannot convert type 'nil' to 'TDerived'.wherecscaccepts it: C# propagates a bounding parameter's special constraints to the bounded one, andTDerived : TBase : classprovesTDerivedis a reference type in every instantiation.[T class]on its own was already accepted (#2354's rule); the reference-ness simply did not travel down aTypeParameterBoundchain. #4043 kept that slot separate fromClassConstrainton purpose — roughly forty consumers readClassConstraint != nullboth as "this is a reference type" AND as "this is the type it derives from", and merging them is #4027's defect shape — so the repair answers only the reference-ness half, in one depth-bounded chain walk read by exactly one consumer. The emitted IL is unchanged and needed no new path:nilat any bare type-parameter target has been lowered todefault(T)(ldloca; initobj; ldloc) since #4027, and the dependent-bound body is asserted opcode-for-opcode identical to the bare[T class]one. Every sink is covered — areturn, a local initialiser, an assignment, and an argument — as are a three-link chain, a root carrying a class-BASE bound rather than the bare flag, and a method parameter bounded by its enclosing type's parameter. This is a completeness fix, never a soundness one: a chain whose root is unconstrained,struct-constrained, or interface-constrained still reportsGS0155, because those admit a value type andnilat a value-type slot is exactly what #4027 fixed. -
An imported generic method constrained to an interface now binds when the type argument is a type parameter whose CLASS bound implements it (issue #4070).
Probes.NeedsDisposable[T]()insidefunc callIt[T DisposableBase]()— overNeedsDisposable<T> where T : System.IDisposableandDisposableBase : System.IDisposable— reportedGS0159: Cannot find function NeedsDisposable.whilecscaccepts the C# equivalent.T's own bound proves the interface in every instantiation, so the candidate was legal; it was FILTERED out of overload resolution rather than diagnosed, which is why the author saw "cannot find function" instead of a constraint message. The question "does this type parameter satisfy an interface constraint" is asked in exactly two places: the generic-TYPE construction path walked the parameter's class-constraint chain (since #4037), and the generic-METHOD path did not (since #750/ADR-0088), soclass Forwarded[T DisposableBase] : DisposableConstrained[T]bound while the method call did not. That walk is now EXTRACTED and called from both, so one rule answers one question; the shared leaf that reads only the declared interface bounds is left byte-identical, because its other callers need that narrower meaning. Every arm is covered: an imported class bound, an interface inherited from the bound's own base, a same-compilation class bound reaching the interface through its imported base, and a same-compilation class implementing the imported interface directly. The rule skips a bound that MENTIONS a type parameter, which is the same skip the generic-type path applies: an unguarded first version boundProbes.NeedsEquatable[T]()underwhere T : IEquatable<T>from a same-compilationclass GsEq : IEquatable[GsEq], and that program compiled and then threwSystem.Security.VerificationException— bothIEquatable<T>and the erasedIEquatable<GsEq>project toIEquatable<object>, so the walk proved an implication that does not hold, andcscreports CS0311 on the C# equivalent. The skip is narrow: a constructed bound over concrete arguments (where T : IEnumerable<string>from[T StringBag]) still forwards, and a self-referential bound carried by the parameter itself ([T IEquatable[T]]) never reached the new rule at all. The change is monotone — it can only turn a rejection into an acceptance — so nothing the CLR refuses is newly accepted, and an unconstrained parameter, a class bound implementing a different interface, and a class bound implementing none are all still refused. No overload winner moves, which was measured on both sides rather than reasoned about: the explicit spelling of a call with a constrained and an unconstrained sibling reportedGS0159before (an explicit type argument removes the non-generic sibling from the candidate set entirely) and now picks the constrained one, ascscdoes, while the inferred spelling picks the boxing overload both before and after. Three neighbouring gaps stay open and are filed rather than ridden along: a BASE-CLASS constraint at a generic method (#4083), which lives on the non-interface fallthrough every imported generic method call takes; a DEPENDENT bound (#4084), which neither path reads; and that inferred spelling's divergence fromcsc(#4086), which this change leaves exactly where it found it. -
A generic attribute's
System.Typeargument now names the type the source wrote, not its erased surrogate (issue #4073).@JsonConverter(typeof(JsonStringEnumConverter[ConstructStatus]))over a same-compilation enum serialised the constructed generic withSystem.Int32in the argument slot, and reflection materialisation threwGenericArguments[0], System.Int32, on JsonStringEnumConverter<TEnum> violates TEnum : struct, Enum— the assembly passed ILVerify both before and after, because the defect is in the custom-attribute blob rather than in any instruction. A same-compilation type has no CLR type while binding, so a constructed generic over one closes over a surrogate and keeps the real argument only on its symbolic vector; the attribute binder preferred the CLR type whenever it was non-null, and for a constructed generic it always is. The enum is not special: measured across the argument kinds, a same-compilation CLASS wroteSystem.Object, a nested generic wrote the surrogate at depth, a two-parameter generic wrote one of each, a slice argument wroteSystem.Int32[]and a nilable enum wroteSystem.Object. Sweeping the sibling shapes found two more kinds the issue did not name. A same-compilation GENERIC —typeof(MyBox[Status])— serialised as the bareP.MyBoxwith neither arity suffix nor argument list, because a constructed user generic carries its arguments onTypeArgumentsand leavesTypeParametersempty; that name does not resolve, so the attribute could not be decoded at all, with an imported argument (MyBox[int32]) just as much as an erased one. And an attribute whoseType[]argument contained a same-compilationtypeofwas dropped from the assembly ENTIRELY with no diagnostic, because #3684 widened the constant container toobject[]to hold the placeholder and the constructor matcher then refusedobject[]for aType[]parameter. All three are fixed together, and every position is covered: positional, named, and array element alike. A fully imported argument such astypeof(Box[int32])has a faithful CLR type and keeps the byte-identical path it always took, as does a scalartypeofof a same-compilation type. A nullable REFERENCE annotation (typeof(Box[string?])) is deliberately left on the CLR path: it is metadata over an entirely faithful runtime shape and ECMA-335 II.23.3 has nowhere to record it. One shape in this family is measured and left alone — a nested type inside a generic OUTER (typeof(Outer[Status].Inner)) still loses its enclosing argument, which needs a different vector and a decision about the nested TypeDef's declared arity; it is filed as issue #4095, and closed in this same release (above). A constructed generic DELEGATE —typeof(Pred[Status])— is fixed here too, and it failed one step further along than the others: a constructed delegate preserves its type parameters, so the arity suffix was already right and the name resolved, to the OPEN definition, silently dropping the argument; nested as an argument (typeof(Box[Pred[Status]])) it named an open generic in an instantiation slot, which reifies to a type with no full name at all. Two further kinds are measured and filed rather than fixed: a G# structural type (a map, a tuple, a function type, a channel) over a same-compilation component serialises its G# SPELLING, because the symbol has no CLR type and the fallback writes the display name — four kinds, each needing its own BCL projection decided, so repairing one would leave three undecodable (issue #4098, closed in this same release); and an attribute whose arguments match no constructor is still dropped from the assembly with no diagnostic, which is what kept theType[]half of this issue invisible (issue #4097, closed in this same release). -
A G# structural type over a same-compilation component now serialises its BCL projection into an attribute blob, not its G# spelling (issue #4098).
@Marker(typeof(Box[map[string, Status]]))over a same-compilation enum wrote the DISPLAY name of the structural type, qualified to the compilation's own assembly, so reading the attribute back threwCould not find type 'map' in assembly 'P.dll'; the tuple form failed asThe given assembly name was invalid, and the function and channel forms named(Status) -> boolandchan. Each structural symbol computes its own CLR type by closing an open BCL definition over its components, a same-compilation component has none while binding, so the symbol's CLR type came out null and the serialiser fell through to a baretype.Name. These operands are only reachable NESTED inside a generic argument: at top leveltypeof(map[string, Status])is rejected byGS0202, which gates on the top-level operand's CLR type, while an imported generic closed over the erased surrogate HAS one, so the component reached emit unchecked. Five kinds are repaired together rather than one at a time, each taking its projection from the symbol that already owns it: a map becomes aDictionary<K, V>, a sequence anIEnumerable<T>orIAsyncEnumerable<T>through the same shape probe the rest of the compiler uses, a channel theChannel<T>/ChannelReader<T>/ChannelWriter<T>its direction already selects, a tuple theValueTuplefamily with the tail nested intoTRestabove arity 7, and a function type anActionor aFuncby the same void rule its CLR builder applies. Every open definition is resolved through the COMPILATION's reference set rather than the emitting host's, so the assembly named is the one the emitted assembly actually references, and the components are closed over SYMBOLICALLY — never throughMakeGenericType, which is what has no answer here. The arms are deliberately not gated on a null CLR type, and that matters:map[string, List[Status]]has a component whose CLR type is non-null — aList<object>closed over the erasure surrogate — so the map's own CLR type resolved, and the old fallback wrote a name that RESOLVED, toDictionary<string, List<int>>. A row that reads back as a plausible wrong type is worse than one that throws, and a null-check guard would have left it in place. The existing wrapper arms for slices, arrays, rectangular arrays and nilables already recurse symbolically without such a guard, for the same reason. The same kinds over components that DO have a CLR type —map[string, int32],(int32, string),func(int32) bool,chan[int32]— are what identify the trigger, and they are asserted unchanged. A function type above the shippedFunc/Actionarities still has no spelling at all and is left as it was rather than given an invented name. -
An attribute whose arguments match no constructor now reports
GS0583instead of vanishing from the assembly (issue #4097).@Many([]object{1})— whereManyAttributedeclares onlyManyAttribute(Type[] values)— compiled with exit 0 and no diagnostic at all, IL-verified, ran, and the emitted assembly simply carried noManyAttributerow on the annotated class. The author asked for metadata and got silence. Constructor SELECTION is the emitter's own applicability rule, applied over the resolved constructor set including params-array expansion, and "no candidate matched" was being treated as "nothing to emit" rather than as an error. That silence is precisely what kept theType[]half of #4073 invisible for as long as it was: a widenedobject[]container failed aType[]parameter match, the whole attribute vanished, and the only symptom was a downstream framework not seeing an annotation that was plainly in the source. The new diagnostic names the attribute and the argument types it was given, the way C# spells the same rule as CS1729 and CS1503. It travels the channelGS0546already uses — an emit-time failure that carries its own diagnostic id and anchors at the annotation — because the emit pipeline has no diagnostic bag in scope; the consequence, and it is the same limitationGS0546has, is that the first offending attribute aborts emit, so a file with several reports one. Two neighbouring silent drops on the same path are closed with it. A user-defined attribute's PRIMARY constructor was accepted on arity alone, with no argument-type check at all, so@Note(1)atNoteAttribute(Text string)reached the blob writer with an int for a string slot and came out as the internal-compiler-errorGS9998; it now reportsGS0583like every other mismatch. And a user attribute whose constructor parameter is typed as a same-compilation enum — arguments correct, program legal — was dropped in silence because that parameter has no CLR type while the blob is built. It is now EMITTED: a G# enum's underlying type is alwaysint32, the bound value is already that constant rather than a symbol, and the constructor's token and signature come from the emitted method definition, so only the value's width was ever missing, and ECMA-335 II.23.3 writes an enum-typed fixed argument as its underlying primitive. The pinned Oahu corpus carries exactly this shape (@OahuCapability(CapabilityClass.Safe)), and an earlier draft that rejected it took four of that corpus's apps red. What remains of the second new diagnostic,GS0584, was then measured rather than assumed, over a probe comparinggscagainstcscon the same shapes: every surviving case — a same-compilation class, interface, delegate, or a structural type — is one C# rejects as CS0181, "not a valid attribute parameter type". There is no legal-but-unencodable residue, soGS0584says that rather than claiming an encoder limit. It was a backstop rather than the right place — the check belongs on the attribute's declaration — and G# validated no such thing at the time; #4143, in this same release, moves the check there asGS0585and retiresGS0584's reachable population for these shapes (below). The diagnostic then immediately earned its keep: it ran the pinned Oahu corpus red on@ToString(typeof(ToStringConverterPath)), againstToStringAttribute(Type type, string format = null)— a trailing OPTIONAL parameter, which no pass of the constructor resolver admitted. That program is legal C# and legal G#, so the diagnostic was the wrong answer for it and the attribute had in fact been dropped from every Oahu assembly that used it for as long as the corpus has been pinned, silently, which is exactly the failure this issue is about. Optional parameters are now a resolution pass of their own, placed before params-array expansion because normal form beats expanded form, and the omitted arguments' defaults are written into the blob. The two forms have to be told apart carefully: "fewer arguments than parameters" is true of an omitted optional AND of a params tail absorbing zero trailing elements, so filling defaults is gated on the omitted tail being genuinely optional — a params array is not, and conflating them wrotenilinto the array slot where the expanded form writes an empty array, which compiled and IL-verified while quietly leaving an xunit theory with no data rows — ECMA-335 II.23.3 gives the fixed-argument list one entry per constructor parameter, so a reader gets the defaulted values back rather than a malformed row. Attributes that DO match a constructor are untouched, including the widened[]Type{typeof(Status)}container #3684 introduced, a faithful[]stringat astring[]parameter, a scalartypeof, an explicitly supplied optional, and a matched user attribute. -
An attribute class's constructor parameter types are now validated at the DECLARATION, and an enum-array attribute argument is accepted (issues #4143 and #4144). Both were found while measuring #4097's
GS0584down to its final population: every survivingGS0584case is onecscrejects asCS0181("not a valid attribute parameter type"), which is a declaration-time defect that G# had no bind-time check for at all —class BoxedAttribute(Value Holder) : Attribute, whereHolderis an ordinary class, compiled clean and only reportedGS0584at each USE, or not at all if the attribute was never applied.GS0585now reports it once, on the attribute class's own declaration — primary constructor and every explicitinit(...)overload alike — the waycscreportsCS0181, and it shares its valid-parameter-type predicate withGS0202's argument check rather than each spelling out the list separately: a primitive,string,System.Type,object, an enum, or a 1-D array thereof.GS0584's reachable population for these shapes is retired as a consequence, surviving only in its own tests as a backstop that can no longer be reached. Separately,@E([]Status{Status.Active})againstEAttribute(Kinds []Status)reportedGS0202— "must be compile-time constants ... or 1-D array thereof" — rejecting a shape its own message says it permits, and measuring settled that this is not one bug but two, in different code paths: a same-compilation enum element's array type has noClrTypeuntil the enum is emitted (the same erasure shape #4097's scalar fix already had to look past, now extended to the 1-D array binder, which is checked symbolically instead of by gating onClrType), while an IMPORTED enum element's array (@Days([]DayOfWeek{...})) reached a real, non-nullClrTypeand still failed, because the constant-array coercion converted the boxed value to the enum's UNDERLYING primitive rather than to a genuine boxed enum instance, andArray.SetValuerefuses to store anintinto aDayOfWeek[]slot ("Object cannot be stored in an array of this type") — a plain coercion bug, unrelated to erasure, now fixed withEnum.ToObject. Both shapes are read back through aMetadataLoadContextas the enum array the source named, not merely accepted at compile time.object/object[]— part of C#'s real CS0181 list but absent from the issue's own summary of it — is included in the shared predicate; excluding it regressed #4097's[]object{...}-argument rows (anobject[]container assignable to aType[]/string[]parameter) toGS0202, which is how the omission was caught. -
A static compound assignment through a generic receiver over a same-compilation type argument emits verifiable IL (issue #4056).
Handler[MyOptions].Field += "z", where the importedHandler<TOptions>declareswhere TOptions : SchemeOptionsandMyOptionsis a class declared in the same compilation, compiled with no diagnostic, was rejected by ILVerify with[UnsatisfiedFieldParentInst] Field parent instantiation has unsatisfied class type parameter constraints, and threwTypeLoadException: GenericArguments[0], 'System.Object', on the open Handler definition violates the constraint of type parameter 'TOptions'— a constraintMyOptionssatisfies. A same-compilation class has no CLR type while binding, so the receiver closes over theSystem.Objectsurrogate and the real construction is recorded beside it; the read spelling and the simple-write spelling both carried that symbol onto the bound node, and the compound-assignment path dropped it, so the surrogate reached emit. Both halves of the compound needed it: repairing the write alone left the read'sldsfldstill parented atHandler<object>and ILVerify stayed red. The affected shapes are wider than the issue's static field — a static property, a non-+=operator such as*=, an unconstrained generic, a same-compilation type NESTED in the argument (Registry[List[Item]]), and an in-scope type-parameter receiver inside a generic function all emitted the surrogate the same way. A receiver over an IMPORTED type argument has a real CLR type, records no symbolic view, and is unchanged. This is wrong emission of a construction the language already accepts, so no diagnostic was added and none was suppressed. -
An object literal of an imported generic over a same-compilation type argument now binds (issue #4042).
Handler[MyOptions]{Tag: "z"}reportedGS0157: Cannot find type Handler. Are you missing an import?— not a message about the literal but the fall-through for a type that could not be named at all — while the constructor spellingHandler[MyOptions]()of the same instantiation compiled, IL-verified and ran. The literal branch was gated on the type argument having a FAITHFUL closed CLR type, and a same-compilation class has no CLR type at all while binding (its TypeDef is produced at emit), so the branch was skipped entirely. That predicate is right about what it says and was being used for the wrong thing: it decides the RESULT TYPE, not whether to enter the branch. The literal now closes over theobjectsurrogate and carries the symbolic vector beside it, exactly as the constructor path has since #671, so the emitter reifies the realHandler<MyOptions>— asserted as the runtime type, not merely as the printed value. An in-scope type parameter works the same way. The three lossy-but-real spellings that the predicate does admit —[]T(#4024),[N]T(#3962) and a named tuple (ADR-0172) — take the same path they always took. Widening the branch does not widen what is accepted:Handler[NotOptions]now reportsGS0152where it used to report the wrongGS0157. A member whose type IS the erased type parameter still reads as the surrogate — on the constructor spelling too, which is pre-existing and unchanged; parity with that spelling is what the issue asked for. -
A member on an element from a dictionary's
.Keys/.Valuesnow binds (issue #4033).for v in m.Valuesfollowed by a property read on the loop element —v.Length,lists.Count,b.Label— reportedGS0158, or the internal-compiler-errorGS9998when the element was a constructed generic, for both themapand theDictionaryspelling, while the same member on the same value reached throughm[k], throughfor k, v in m, or throughTryGetValuebound fine.Dictionary<,>.Valuesis declared[Nullable({1, 0, 0})], and the two zeroes sit at theTKey/TValuepositions: those are type parameters, so the byte is a placeholder for whatever is substituted, not an annotation. Read as concrete positions they made the elementV?, and because G# requires narrowing or?.before a property read on an explicitT?(but not before a method call), the element lost its whole CLR property and field surface. The receiver's own type arguments are now projected through the open property whenever it mentions a type parameter, which is what the openmap[K, V].Keysspelling already did. The issue names a constructed generic as the failing ingredient; measured, a plainstringvalue fails identically,.Keysis affected as much as.Values, a generic key is affected, and so isSortedDictionary[K, V]— while non-nested generic collections such asList,HashSet,Queue,StackandLinkedListwere never affected. -
A
map[K, V?]over a nullable value type emits verifiable IL (issue #4035).map[string, int32?]compiled clean and then threwInvalidProgramException, because its backingDictionarywas closed over the bareint32while the literal, the indexer'soutslot and the loop variable all carried aNullable<int32>— two ILVerifyStackUnexpectederrors in that repro, one or more in every affected shape. A nullable type symbol answers its underlying type's CLR type, since a nullable reference has no distinct runtime type, and the map's construction read that directly instead of theGetEffectiveClrTypecorrection itssequence[T]sibling already used. Every value-position operation was affected — the literal,m[k],m[k] = v,m[k] = nil,TryGetValue,ContainsValue,for k, v in mandfor v in m.Values— and so was the key position,map[int32?, V]andmap[DateTime?, V]alike. Over an imported underlying such asDateTimethe wrapper is now built inside that type's own reflection context, alongside the openDictionary, for the reason issue #4023 documents. TheDictionary[string, int32?]spelling was already correct, so the two spellings of one type disagreed and assigning one to the other failed to verify; they now agree. Nullable reference values such asmap[string, string?]were never affected and are unchanged. -
A DEPENDENT generic constraint is no longer answered after erasure has collapsed two distinct same-compilation classes (issue #4041). Against the imported
Coupled<T, U> where U : IList<T>, the programvar c Coupled[A, List[Bee]]— withAandBeeunrelated classes declared in the same compilation — compiled with no diagnostic and threw at run time:System.TypeLoadException: GenericArguments[1], 'System.Collections.Generic.List`1[P.Bee]',on 'HelperLib3.Coupled`2[T,U]' violates the constraint of type parameter 'U'.A same-compilation class has no CLR type while binding, so it projects to a
System.Objectplaceholder; bothAandBeetherefore arrived asobjectand the vector handed to the constraint check wasCoupled<object, List<object>>, whereList<object>genuinely does satisfyIList<object>. The check answered honestly on what it was given — the information that distinguishesAfromBeewas gone before it was asked — and emission then reified the real types. #4016/#4031'sNormaliseErasedTypeArgsForConstraintCheckis not the culprit and this was verified rather than assumed: it operates on the vector after the collapse, which happens earlier inProjectGenericArgument. The declared bound is now kept UNSUBSTITUTED, and when it mentions another type parameter whose argument arrived erased the question is put to the SYMBOLS instead — the expectedIList[A]is built from the symbolic vector and compared againstList[Bee]'s ownIList[Bee], recursing so a nested bound such asIList<List<T>>is answered at its leaf. The check is three-state on purpose: a definitive no reportsGS0152, a definitive yes accepts, and anything the symbols cannot settle — a concrete position, a missing symbol, a VARIANT parameter (whereIEnumerable[Derived]legitimately satisfiesIEnumerable[Base]), or a BARE dependent bound at the TOP of a constraint (where the relation is assignability rather than identity, soChain[ChBase, ChDerived]must keep binding) — falls back to the pre-existing CLR comparison rather than to a rejection, because a wrong “no” would be aGS0152on a legal program. That last exit is load-bearing and measured: with it disabled and nothing else changed, the legalChain[ChBase, ChDerived]fails with a falseGS0152. It left the imported spelling of a bare dependent bound over two UNRELATED erased classes still accepted, which needs symbolic assignability rather than identity — issue #4063, closed in this same release by asking that position the same predicate the G#-declared spelling of the bound already used. The matched spellingsCoupled[A, List[A]]andCoupled[string, List[string]], the covariantCovariant[CovBase, List[CovDerived]], an open forwarded instantiation, and #4031'sAddScheme[TOptions, THandler]shape all stay green. The asserting row #4032 left pinned for this gap has been moved intoConstraintViolations, not deleted. -
A
map[K, V]whose key or value is an imported type now has its wholeDictionarymember surface (issue #4023).m.Count,m.Clear(),m.Remove(k),m.ContainsKey(k),m.ContainsValue(v),m.Add(k, v),m.TryGetValue(k, out v),m.Keys,m.Valuesandfor k, v in mall reportedGS0158/GS0159/ the internal-compiler-errorGS9998on such a map, while theDictionary[K, V]spelling of the same type — which ADR-0104 says is the same type — kept every one of them. The backing dictionary was built by closing a hosttypeof(Dictionary<,>)over a key or value resolved through the compilation's reference context, which yields aTypeBuilderInstantiationthat answers no members; it is now built inside the key/value's own reflection context instead. The failing shapes were every imported type, not only classes: an imported struct, an imported generic such asList[int32], a same-compilation class extending an imported base, and the key position as well as the value position.m[k]andm[k] = vwere already fixed by #4015 and are unchanged, andlen(m)still reportsGS0566because ADR-0174 (D13) retiredlenas a built-in. -
await for v in snow iterates anasync sequence[T]whose element has no CLR backing (issue #4020). Anasync sequence[T]parameter with an open element reportedGS0134("cannot be iterated withawait for") while the closedasync sequence[int32]spelling iterated and the synchronousfor v in sover an equally opensequence[T]iterated too. The operand check recognised the shape only through its CLR type, which an in-scope type parameter or a same-compilation class element leaves null. A diagnostic naming an async sequence now readsasync sequence[T]rather thansequence[T], so it can no longer be mistaken for the synchronous sequence — whichawait forstill correctly refuses. -
A
nilat a reference-constrained[T class]slot emits verifiable IL (issue #4027). Anilliteral is legal at a[T class]slot — deliberately, since #2354, because such a slot is a reference in every instantiation — but nothing lowered the accepted literal, so emit produced a bareldnullagainst a signature slot typed!!T(or!T). ECMA-335 has no rule admitting a null reference at a generic-parameter slot, constraint or no constraint, so ILVerify rejected it:[StackUnexpected] [found Nullobjref 'NullReference'] [expected value 'T']. The program ran and printed the right answer, which is why it went unnoticed. It is now lowered todefault(T), which the emitter has materialised asldloca; initobj; ldlocsince #774 — the same three opcodescscemits forTakes<T>(null)underwhere T : class, measured. Six sinks were affected, not the one the issue names: a call argument, a local declaration, an assignment, areturn, and — on a generic CLASS, where the slot is!T— a field write and a memberreturn. Nothing about the VALUE changes:default(T)at a[T class]slot is the null reference in every instantiation, so thenilstill arrives and the callee'sx == nilstill observes it. An UNCONSTRAINEDTstill refusesnil(#4010). -
A
map[K, V]whose key or value is an ordinary CLR type no longer crashes the compiler (issue #4015).map[string, DateTime]{},map[string, TimeSpan]{},map[string, List[int32]]{}and every map over a type imported from another assembly reported the internal-compiler-errorGS9998(NotSupportedException: TypeBuilder generic instantiation does not support resolving members). The backing type is built astypeof(Dictionary<,>).MakeGenericType(key, value), and .NET returns aTypeBuilderInstantiation— which refuses to resolve members — whenever a type argument is not itself a host runtime type, as every type the compiler resolved through its reference context is. Only a handful of G# primitives (int32,float64,bool,string,object) escaped it, which is why the shape went unnoticed. The three emit sites that reflected on the closed dictionary — the literal's constructor andset_Item,m[k]'sTryGetValue, andm[k] = v'sset_Item— now fall through to the reified-TypeSpec MemberRefs already used for a map with an open element. The issue reported this as specific to an imported reference type in the value position; it was neither specific to imports nor to reference types nor to the value position. A same-compilation class, aDictionary[K, V]()spelled directly, and the sibling slice and tuple literals were never affected and are unchanged. A separate, pre-existing binding gap on the same types —m.Count,m.Remove(k),m.ContainsKey(k)andfor k, v in mover a map whose value is a class — is tracked as #4023. -
An inferred generic call over a
mapemits a MethodSpec over the real key and value (issue #4026, second face).Probes.CountAnyMap(entries)on amap[string, Derived]— no explicit type arguments, ordinary code — compiled, ran and did NOT IL-verify: the symbolic recovery that decides what the MethodSpec is closed over had no arm for amap, soKandVwere never recovered and the spec fell back to whatever the erasure presented (ImportedBasefor a same-compilation class with an imported base,objectfor one without) while the value pushed was the realDictionary<string, Derived>. Amapis now restated as the constructedDictionary[K, V]it is (ADR-0104) before unification, so it takes the same patterns theListand[]Tspellings always took — which is why those never had the bug — andIDictionary[K, V],IReadOnlyDictionary[K, V]andIEnumerable[KeyValuePair[K, V]]formals are covered with it. -
A same-compilation class that implements an imported interface now satisfies that interface's constraint (issue #4124). For
class D : IDisposable, bothtake[D]()overfunc take[T IDisposable]()andBox[D]()overopen class Box[TB IDisposable]reportedGS0152: Type argument 'D' for type parameter 'T' does not satisfy the 'System.IDisposable' constraint.— a false rejection of ordinary, idiomatic code, which is the worse of this rule's two failure modes.cscaccepts the C# equivalent and so does the CLR.Binder.SatisfiesConstraint's CLR-interface arm bottoms out in a reflective walk overtypeArgument.ClrType.GetInterfaces(), and a same-compilation class has no CLR type until emit, so the walk answered "no" without ever reading the interface list the symbol already holds. This is the FOURTH appearance of that one blindness — #4061 repaired it at the imported class-chain walk, #4068 at the dependent-bound path (whereSourceSymbolImplementsImportedInterfacewas written), and #4092's review round at the G#-declared forwarding rule, each at the site that happened to hit it. Rather than add a fourth caller-side patch, the fallback moves INTO the shared leaf: the reflective body is split out and the symbolic walk now wraps every exit of it, and the two copies sitting at #4068's and #4092's call sites are DELETED. All three symbolic askers now bottom out in one predicate, so a fifth site cannot appear. The widening is monotone in the satisfaction direction and only consulted for an argument with no CLR type, which is exactly what reflection cannot see, so nothing the reflective path already answers changes: a class implementing nothing, a class implementing a different imported interface, and a generic bound with the wrong symbolic argument are all still refused. The source base chain and a G#-declared interface that extends the imported one both count, and a self-referential generic bound now works too — flat ([T IComparable[T]]overclass Cmp : IComparable[Cmp]) and NESTED ([T IComparable[List[T]]]overclass C : IComparable[List[C]]), both red before, on both halves of the predicate, because the argument-for-parameter substitution the two halves share is now recursive rather than a whole-argument identity test. The blast radius named by the issue was measured rather than reasoned about:BoundScope.TryUnifyAndCheckConstraintsgates extension-method candidates through the same predicate, so a constrained generic-receiver extension over a source class went fromGS0159to binding. Exactly one overload winner moves, and it moves TOWARDcsc: with a same-namedDescribe[T IDisposable](T)andDescribe(object),D().Describe()picked the boxingobjectbefore (the constrained candidate was not applicable) and picks the constrained one now, which is whatcscpicks — verified by compiling and running the C# equivalent. It is this change's move rather than #4086's: re-measured against a parent carrying #4108's fix for #4086, the answer there is stillobject, because #4108 fixed inferred type-parameter identity during ranking while this fixes candidate applicability before ranking runs. The rankings that do not move were measured too: two same-name GENERIC extensions still tie (GS0266, both sides), the free-function pair still picks the generic one (both sides), and a receiver that fails the constraint still falls back to the unconstrained sibling. -
An imported generic method constrained to a BASE CLASS now binds when the type argument is a type parameter carrying that bound (issue #4083).
Probes.NeedsScheme[T]()insidefunc callIt[T SchemeOptions]()— overNeedsScheme<T> where T : SchemeOptions— reportedGS0159: Cannot find function NeedsScheme., and so did the same-compilation spellingclass MyScheme : SchemeOptionsand the dependent spellingfunc callIt[U SchemeOptions, T U]().cscaccepts all three. This is #4070's defect one bound-kind over, on the non-interface FALLTHROUGH every base-class constraint of every imported generic method takes: aTypeParameterSymbolargument matched none of the symbolic arms, so the erasedSystem.Objectplaceholder was asked whether it derives fromSchemeOptions, said no, and the candidate was silently FILTERED out of overload resolution — which is why the author saw "cannot find function" rather than a constraint message. The generic-TYPE construction path has walked the parameter's own class-constraint chain since #4037; that walk is now extracted and the generic-METHOD path calls the SAME one. It is deliberately not a call to its parent, whoseobject/ValueTypeearly-out would be a false ACCEPT here, since on this path aSystem.ValueTypebound is the metadata shadow ofwhere T : structand is settled by the special-constraint arms before the type-bound loop runs. The new arm carries #4070's guard — the unsubstituted bound must mention no type parameter — so a CRTP base bound cannot be "proved" on the erased vector, and it is monotone in the satisfaction direction: an unbound parameter and a class bound naming a different base are both still refused. -
A dependent bound now forwards the bounding parameter's interface and base-class constraints (issue #4084).
Probes.NeedsDisposable[TDerived]()insidefunc callIt[TBase DisposableBase, TDerived TBase]()reportedGS0159: Cannot find function NeedsDisposable., while the generic-type spellingclass Forwarded[TBase DisposableBase, TDerived TBase] : DisposableConstrained[TDerived]reportedGS0580— two different wrong answers to one question, on a programcscaccepts, sinceTDerived : TBase : DisposableBase : IDisposableholds in every instantiation. Both askers read onlyClassConstraintand never #4043's separateTypeParameterBoundslot. They now share #4067's existing symbol walk, which follows both slots and terminates on a visited set rather than a depth limit, so one chain answers the question on both paths. That walk's 32-element cap is removed with it: it was belt-and-braces on top of the visited set and it was lossy, so a 40-link dependent chain was truncated and its terminal bound reported unforwarded (GS0159at a method,GS0580at a type — measured). The deduplication already visits each distinct parameter at most once, so the walk terminates on any graph without it. The base-class half at an IMPORTED generic type was still open too and is closed here: #4102 taughtSatisfiesClassConstraintto follow the dependent bound, which covers a G#-DECLARED generic, butclass Fwd[TBase SchemeOptions, TDerived TBase] : SchemeConstrained[TDerived]over an importedSchemeConstrained<T>goes through the reflective path instead and still reportedGS0580. A dependent bound forwards the bounding parameter's constraints and nothing else, so a chain ending in a class that implements a different interface is still refused. -
A suppressed body-header identifier followed by a labeled body no longer mis-parses that body as a struct literal (issue #4189).
if flag { retry: break }, and the equivalentwhile/for-in/C-style-for-post shapes, reportedUnexpected token <BreakKeyword>, expected <IdentifierToken>.: the label's spelling (Identifier :) is byte-for-byte identical to a struct literal's first field, andStructLiteralAllowedInSuppressedHeadertreated any NON-empty brace content as unambiguously a struct literal — the same lookahead that #1575 already had to add for an EMPTYIdent{}colliding with an empty body, generalized here to non-empty content that happens to startIdentifier :or.... The predicate now scans (bounded) to the candidate brace's own matching close and admits the struct-literal reading only when what follows still lets it stand — a genuine second body brace (the existing two-brace shape,Numbers{X: 1} { … }), or a token under which the surrounding suppressed expression legitimately keeps going (a binary/postfix operator, a,betweenif letbindings, a ternary's:); otherwise this{ … }is the header's own body, since a suppressed header always requires one and none would otherwise be left to open it. A spread-led brace (Ident{...expr}) reaches the same check but can never actually collide with a body — no G# statement begins with a bare...— so it keeps resolving in the struct literal's favor exactly as before. Every non-empty struct literal that is genuinely followed by more expression content (if Pt{X: 1} == p { }) is unaffected. -
A native
let ref/var refalias local is now legal in an async function, an iterator, or an async iterator as long as it is never live across anawait/yieldsuspension point (issue #4222).{ var ref alias = values[0]; alias = 42 }before anawait(or ayield) used to reportGS0258unconditionally — the same blanket "no ref alias anywhere in this state machine" rule issue #2350 already replaced for by-ref-like (ref struct) locals with per-local liveness.RefStructAsyncLivenessAnalyzernow also tracks native alias locals (identified byLocalVariableSymbol.RefKind, since an alias keeps its pointee type onType) and treatsyieldas a suspension point alongsideawait, so it runs for iterator functions too; assigning THROUGH an alias (alias = 42) is correctly modeled as a use of the alias (it needs the address), not a redefinition, unlike overwriting a by-ref-like value outright. A local actually proven live across a suspension still reportsGS0258, now with a precise reason instead of a blanket one.AsyncCaptureWalkerand the iterator rewriter's hoist-local collector both exclude alias locals from state-machine fields (mirroring the existing by-ref-like exclusion), so a confined alias simply stays a plain state-machine-method local — the pre-existingRefKind-drivenldind/stindemission handles it exactly as it would in an ordinary function, with no managed-pointer field ever emitted. The existing low-level&/*pointer-reconstruction path (RefInitializationHoister) and by-ref-like-local liveness are unchanged. -
A top-level extension function can now name the CLR type its self-hosted
MethodDefshould be filed under, instead of always the package's synthesized<Program>(issue #4234). A receiver-clausefuncbinds only at top level (its receiver is not in scope inside ashared { }block), so cs2gs lowers a migrated C# static extension class's methods to package-level G# funcs — which the emitter has always hosted on<Program>, unlike the native C# class that declared them. That is invisible to ordinary G# code, but not to a self-hosted build of the SAME method: a reflection-based test (typeof(ChannelExtensions).GetMethods()) or an analyzer's owner-specific recognition (RendezvousBatchAnalyzer'sChannelBatchExtensionscheck) that key off the exact declaring type saw the migrated runtime's shape diverge from the native assembly's. The new compiler-intrinsic@ExtensionOwner(typeof(T))annotation, which cs2gs now synthesizes automatically wherever it lifts an extension method out of a static class, names a same-package non-generic class to host theMethodDefon instead, reusing the same static-owner routing an ordinary shared-block static method already gets; the owning class is emittedabstract sealedand[ExtensionAttribute]-stamped, exactly like<Program>already is, so C#/F# extension-method discovery is unaffected. A malformed use reports the newGS9306. This mechanism exists for cs2gs's own self-hosting; ordinary hand-authored G# extension functions are unaffected and keep landing on<Program>as before. -
A generic local function calling a sibling local function that captures outer state no longer crashes
gsc(issue #4221 follow-up to #4252, which removed the blanketGS0463rejection so a generic local function could capture ordinary outer state at all).let Second[U] = func(x U) int32 { return outer }/let First[T] = func(x T) int32 { return Second(0) }— whereFirstnever readsouteritself, only callsSecond— crashed emission withGS9998: InvalidOperationException: Variable 'outer' has no local slot or parameter index in the current method., regardless of whetherSecondwas declared beforeFirst(ordinary forward visibility) or after (forward reference), or the two called each other (a cycle) — and the same crash reached one level deeper, through a plain local function declared insideFirst's own body that calledSecondonFirst's behalf, since that nested literal's own captured-variable set was fixed at its bind time and the reconciliation pass originally only re-walked the group's top-level members. Root cause: a generic local function is called directly through itsFunctionSymbol, not through a delegate value, soLambdaBinder's existing transitive-capture folding — which already walks a PHYSICALLY NESTED function literal'sCapturedVariablesinto its enclosing literal's own set — had no equivalent for aBoundCallExpressionreferencing a SIBLING local function'sFunctionSymbol; nothing propagatedSecond's capture ofouterintoFirst's own environment, soMethodBodyEmitter.EmitGenericLocalClosureInstancehad no field to readouterfrom when rebuildingSecond's closure instance at theSecond(0)call site insideFirst's body.CapturedVariableCollectornow consults a per-binder map of every local function's already-known captures (keyed byFunctionSymbol) and folds a callee's captures into its caller exactly like the nested-literal case;LambdaBinder.ReconcileGenericLocalFunctionGroupCapturesre-converges a whole consecutive-declaration group to a fixed point afterward, covering both the forward-reference and the call-cycle shapes the in-order pass alone cannot see, and now also recomputes every function literal nested inside a group member's body (not just the member's own top-level literal), so a plain local function declared inside a member that calls a sibling on the member's behalf gets the same fixed-point treatment instead of keeping the stale captured-variable set it had at its own bind time. Multiple generic instantiations of either function continue to share one captured cell;this, a captured parameter, a mutable reference-type field, and a plain local function nested inside a generic local function's own body (reading the outer state directly) all compose correctly with this and were previously untested. -
A call to a native ref-returning function/method, or a read of a native ref-returning property/indexer, is now usable as storage — an alias source, a
return refoperand, and (when the getter is writable) an assignment target (issue #4224).var ref alias = At(values, 0)(func At(values []int32, i int32) ref int32) andvar ref alias = holder.Value(prop Value ref int32 { get { return ref slot } }) used to reportGS0256unconditionally —ExpressionBinder.IsLvalueandStatementBinder.IsLvalueForRefReturnaccepted only a variable, field, array element, or*pdereference, never a call/property result, even a ref-returning one. Both classifiers (andreturn ref At(...)'s equivalent, previouslyGS0253) now also accept a call to a same-compilationFunctionSymbol/instance method or a read of a same-compilation property/indexer whoseReturnRefKind != None, via a sharedRefCapabilities.IsNativeRefReturningCallclassifier so the two do not drift. An imported/CLR ref-returning member (e.g.Span[T]'s indexer) needed no change —ConversionClassifier.AutoDereferenceRefReturnalready wraps those in aBoundDereferenceExpression, which was already an lvalue. Forwarding is escape-checked, not merely permitted:RefCapabilities.TryGetRefReturnEscapeSourcesdecomposes a ref-returning call into its instance receiver and its non-scopedref/in/outargument storage, andHasFunctionLocalRefScopepropagates through them —return ref Fwd(ref x)from inside the SAME function that declaredxstill reportsGS0254, whilereturn ref Fwd(ref value)over a caller-suppliedrefparameter, andreturn ref At(values, 0)over a by-value slice parameter, both compile, matching C#'s ref-safe-scope rules for a ref-returning call. A writable (ref, notref readonly) getter with no setter now supports assignment without inventing one —holder.Value = 42andGetHolder().Value = Next()(receiver/RHS each evaluated exactly once) store through the getter's managed pointer, reusing the existing imported-indexer write-through shape (BoundIndirectAssignmentExpressionoverBoundAddressOfExpression); a native indexer's writable getter (prop this[i int32] ref int32 { get {...} }) gets the same treatment for bothbox[i] = vand an alias. A struct receiver that would need a defensive copy to call the getter (alet-bound or otherwise non-addressable struct value) is rejected for both the alias and the assignment form — alet ref readonlyview remains allowed, since a read-only view of a copy is still sound. cs2gs'sref exprtranslator, which previously refused any call operand outright (issue #1900's own follow-up), now translates it like any other lvalue and lets gsc's binder validate it. -
out/refof aT?pointee, whereTis an OPEN, unconstrained type parameter, no longer emits an invalid reference-slot store/load for a real value-type instantiation (issue #4236, found self-hostingCompiler.Tests's channel matrix).Gsharp.Concurrency.Chan[T].ReceiveOrPark'sout value T?parameter —Tcarrying nostruct/classconstraint — compiled and ILVerified cleanly, then threwInvalidProgramExceptionthe momentTwas JIT-instantiated as a genuine non-primitive struct; a CoreLib primitive element (int32, etc.) never exercised the faulty path, which is why the native, non-self-hosted test suite never caught it. Root cause:MethodBodyEmitter.EmitStoreIndirect/EmitLoadIndirectpickstobj/ldobjonly for a pointee that is PROVABLY a value type (NullableLifting.IsAnyValueTypeNullable) or a bare boundTypeParameterSymbol— aNullableTypeSymbolwrapping an OPEN, unconstrained type parameter satisfies neither check, so it fell through to the reference-slotstind.ref/ldind.refarm, which is invalid IL once the CLR resolvesTto a real struct (a gap ILVerify's abstract-over-open-Tchecking does not catch, but the runtime type loader does).ImportedMemberRefFactory.GetElementTypeTokenalready resolved this exact shape correctly (issue #814 / ADR-0084 §L5 —Nullable[T]whenTis struct-constrained, bareTotherwise);EmitStoreIndirect/EmitLoadIndirectsimply never routed into it for this case. Both now recognizeNullableTypeSymbolover an openTypeParameterSymboland route tostobj/ldobjwith that already-correct token. A minimal, non-self-hosted regression (Issue4236OpenNullableTypeParameterIndirectTests) reproduces the crash directly against nativegsc— a generic class method with anout value T?and aref value T?parameter, instantiated over a user struct — confirmed red before the fix and green after;ilverifyreports no new finding on the fixed self-hostedGsharp.Runtime.Channels.dll(the pre-existing, trackedReturnPtrToStackfalse positive onSelectRandom.Shuffleis the only remaining entry).
Known limitations
Translating the compiler from C# to G# lost some things, by decision
(owner decision D7). A !! assertion is a runtime check (see "!! density"
and the fail-fast breaking change above), so a violated non-null assumption now
throws where C#'s compile-time-only ! carried null onward. For the changes
that cs2gs makes to any C# it translates, see
What translation changes.
!!density. The translated source has many!!assertions where the G# compiler could not prove that a value is non-null. Reducing them is ongoing cleanup.- Conditional compilation. G# has no
#if. cs2gs reports#if/#elifas an error instead of silently choosing a branch, and the compiler source was free of them before translation (three test-only#if DEBUGsites were rewritten as runtime checks). - Performance of the G#-built compiler compared with 0.4.1270 (compile time, memory), against the agreed budget (owner decision D11: aim for parity, 1.5x acceptable). Measured on the cut-over candidate: about 1.04x time and 1.02x peak memory; to be re-measured on the released bits.
0.4
The fourth pre-1.0 line focuses on sound defaults, expressive control flow, and faithful CLR interop. Collection zero values are now usable without hidden nulls, pattern matching works directly in boolean and loop conditions, rectangular CLR arrays have native syntax, and explicit extension receivers preserve extension semantics for owned types and enums. Tooling adds synchronized-map support, clearer REPL display, and dotnet watch hot reload.
Highlights
- Sound collection zero values. Initializer-less maps, slices, fixed arrays, rectangular arrays, and sequences receive usable empty instances, including collection fields nested through structs. Channels remain explicit: globals and fields require
make(chan T), while locals use definite-assignment analysis and nullable channels use(chan T)?. - Richer conditions and blocks. Boolean
isaccepts the full pattern grammar, including constant, type, property, relational, list, and composed patterns.while letintroduces a narrowed, body-scoped binding that is re-evaluated before each iteration. General block expressions can contain declarations and statements before their trailing value. - Native rectangular arrays.
[,]T,[,,]T, and higher ranks preserve CLR type identity.[rows, columns]Tallocates storage, flat initializers use row-major order, anda[i, j]supports reads, writes, compound assignment, address-taking, null-conditional access, iteration, and interop. - Cleaner extension declarations.
func extension (receiver T) Name()explicitly declares an extension for an owned type or enum without turning it into an instance member. - Migration fidelity.
cs2gsnow emits native block expressions, rectangular arrays, multi-target storage assignment,if let/while letbindings, nativeispattern variables, explicit extensions, and value-position assignments instead of synthetic spill-heavy rewrites.
Added
- Full patterns in
value is patternandvalue !is pattern, with type-plus-property composition and narrowed right-handandpatterns. - Pattern variables in boolean
is(ADR-0166):value is string text && text.Length > 3,value is { Length: > 0 } text,box is { Value: Dog d },values is [1, ..rest], and the guard idiomif !(value is string text) { return }followed by uses oftext. Variables are scoped to the regions where the match is known to have happened;Type namedesignations are also accepted inswitcharms.cs2gspreserves C#ispattern syntax and names for these shapes instead of hoisting__spillNtemporaries. while let name = nullableExpression { ... }, including multiple bindings and normal labeledbreak/continuebehavior.- General value-producing block expressions such as
{ let x = compute(); x + 1 }. - Native rectangular array types, allocation, initialization, indexing, iteration, nullable forms, metadata, and expression-tree support.
- Explicit extension receiver clauses through
func extension. - Map iteration through
for key, value in maporfor entry in map. Gsharp.Extensions.Sync.SyncMap[K,V]for goroutine-safe shared maps with atomicUpdate.- Structural display of plain user values in the REPL while preserving their emitted CLR
ToStringbehavior. dotnet watchhot reload for SDK projects.
Changed
- The
asoperator now has nullable result typeT?; useif let, keep the nullable value, or apply!!when a prior check guarantees success. - The deprecated
name = valuenamed-argument spelling is removed. Usename: value;=in an argument is an ordinary assignment expression. - Multi-target assignment accepts all writable storage forms, including fields, properties, indexed elements, nested members, and pointer dereferences.
- Nil comparison is available for every reference-backed built-in type. Comparisons against bare non-null collection types are diagnosed as statically constant.
- Legacy
print,input, andrndbuilt-ins and thestring(T)conversion are removed; use CLR APIs and explicit formatting/conversion methods. - The website specification, guides, tutorials, feature matrix, diagnostics catalogue, bridges, and tooling pages now describe the complete 0.4 surface without implementation-tracker references outside the design-decision index.
- The Docusaurus site cuts a new
0.4snapshot from the live docs. The version dropdown lists0.4,0.3, andNext.
Fixed
- Generic delegate, enclosing-generic, function-pointer, method-group, map, imported override, XML documentation, channel capture, boxing, and tuple-return emission now preserve the source type and storage semantics across compilation boundaries.
- Null-conditional delegate invocation, nullable-flow analysis, rejected-call diagnostics, interpolation spans, and source-migration output are aligned with the emitted behavior.
cs2gsnow carries widened nullable array-element types through inferred local alias chains, so maybe-nil writes through an alias widen the owning allocation and reads through any alias receive the required!!assertion (issue #4507).
Known limitations
- A non-empty rectangular-array initializer requires constant non-negative dimensions and a flat row-major element list.
- Pattern variables introduced by a boolean
ispattern (value is string text, ADR-0166) are read-only and are in scope only where their match is known to have happened; C# forms that rely on full definite-assignment data flow (for example a variable read after awhilewhose exit depends on the pattern) reportGS0532.
0.3
The third pre-1.0 line is a breadth-and-interop release. The language gains a large batch of C#-parity expression and declaration constructs, an unsafe pointer surface, partial types, and anonymous-object literals. Tooling adds the cs2gs C#→G# migration tool and the gsgen Roslyn source-generator host for native G# projects. The language server gains incremental binding, an incremental semantic-model pipeline, and a cross-session cold-start cache. This release also cuts a fresh 0.3 docs snapshot from the live docs and retires the 0.2 snapshot.
Highlights
- Unsafe pointer surface. An
unsafecontext now supports unmanaged raw pointers*T,stackalloc [n]Tproducing either safeSpan[T]or unsafe*Tstorage, thefixedpinning statement, theunmanagedtype-parameter constraint,sizeof(T), and pointer compound-assignment and cast lowering. - New expression and statement forms. Throw expressions, value-producing increment and decrement expressions
++/--, from-end indexes^n, standaloneSystem.Rangevalues such as1..3, expression-bodied members via->, generalgoto/ labels, collection initializersList[T]{…}/HashSet[T]{…}/Dictionary[K,V]{…}, and inferred-type arrow lambdas with statement-block bodies. - New declaration forms.
partialclasses, structs, and interfaces; anonymous-object literalsobject { … }; nested type declarations; user-defined conversion operatorsoperator implicit/operator explicit; user indexer membersprop this[i int32] T { get; set }; theshared { init { … } }static-initializer block; static imports throughimport Ns.Type; and top-levelprivatemapping to ILassembly/ internal. cs2gsC#→G# migration. The new translator lowers C# source to canonical G#, with construct coverage, gap triage, and a build-time strategy that reproduces generated code rather than freezing it. See the new cs2gs tooling page.- Source generators for native G#. The
gsgenhost runs Roslyn analyzers and generators against native G# projects.gsc /analyzer:<asm>spawnsgsgenas a sibling before compiling. A shared resx codebehind generator emitsResources.Designer.gs. - Language-server performance. Incremental binding, instance-keyed semantic-model memoization, a cross-session cold-start cache, completion-as-you-type triggering, and unified member resolution reduce repeated work across binder and LSP flows.
- Diagnostics catalogue extended. v0.3 adds diagnostics through the
GS04xxrange. The Diagnostics reference is reconciled against the compiler source and lists the current per-ID cause and fix detail.
Added
- Null-coalescing operator respelled
??. The null-coalescing operator isa ?? b. The earlier?:spelling is retired in that role;cond ? a : bremains the ternary expression. - Runtime array allocation
[n]T. A length-bearing[n]Tallocates a zero-initialised array at runtime, complementing array literals. - Nullable array-element spelling.
[]T?is an array of nullable elements;[]?Tis a nullable array. - Nullable function-type spelling. Nullable function types are spelled and displayed with the appropriate parenthesisation.
- Expression-tree lambda conversions. A lambda converts to
Expression[TDelegate]where the target demands an expression tree. - Delegate return-type covariance. Delegate return types can be covariant, including lambda target-typing on CLR method calls.
- Predefined type aliases as static-member receivers. Friendly numeric aliases can be used as receivers for static member access.
- Assembly-attribute parity with C#. Assembly-level attributes are accepted with C#-equivalent behavior.
- Collection spreads. Array, slice, and CLR collection initializers accept
...source, preserving lexical evaluation order and applying ordinary element conversions. - Safe structural projections. Compatible public object shapes project into safely constructible concrete targets;
Target{ ...source, Member: override }provides explicit object-spread mapping. - Explicit interface qualifier clauses. Methods, properties, indexers, events, and static interface members can use
(IFace)to provide distinct implementations without source-visible mangled names. - User-defined compound-assignment operators. Classes and structs can declare in-place
operator +=and related one-operand, void-returning instance operators.
Changed
- C#-compatible numeric conversions. Numeric literal narrowing and widening, plus implicit numeric promotion at call sites, now align with C# behavior.
- Unannotated imported reference types are nullable by default. Imported reference types without nullable annotations bind as nullable.
charbitwise and shift operators promote toint32. Enum==/!=comparisons against the integer literal0are also permitted.- The website spec, feature matrix, diagnostics reference, CLR-interop reference, guides, tour, tutorials, and tooling docs were refreshed to match compiler ground truth for the 0.3 surface; a new
cs2gstooling page was added. - The Docusaurus site cuts a new
0.3snapshot from the live docs and retires the0.2snapshot. The version dropdown lists0.3andNext.
Fixed
- Extensive
cs2gstranslator hardening across nullability promotion, extension-call lowering, deconstruction and indexer targets, pattern binding, named-argument lowering, and source-generator-shaped constructs. - Numerous
gscbinder, emitter, and interpreter correctness fixes across imported generic interface methods, nullable value-tuple boxing,data classequality andwith, overload resolution, async lambda inference, and smart-cast narrowing.
Known limitations
gsc --helpadvertises/implicitimports[+|-]; the+/-suffix form is not currently accepted by the Release parser. Use/noimplicitimports.- Migration coverage in
cs2gsis still expanding. C# source generators are reproduced at build time rather than translated, and some constructs remain on the gap-triage backlog.
0.2
The second pre-1.0 line is a syntax-and-ergonomics release. The parser, binder, and emitter absorb substantial additions; several legacy Go-flavored spellings are retired in favour of canonical G# forms; and the native-interop and default-interface-method surfaces ship end-to-end. This release also formally introduces docs versioning: the 0.1 snapshot is removed and a fresh 0.2 snapshot is cut from the live docs.
Highlights
- New language surface.
while/do…whileloops with labeledbreak/continue;if let/guard let/while letsmart-cast bindings; null-coalescing compound assignment??=; null-conditional indexinga?[i]; arrow lambdasx => body; canonical(T1, T2) -> Rfunction-type clauses; lambda binding-type inference; Kotlin/Swift-style type-declaration grammar; if-as-expression completion; smart-cast extensions; discriminated-union enum payloads;default(T)and target-typed baredefault; variadic...Tparameters in function and anonymous function-type clauses;class/struct/init()constraint flag spellings; default-interface methods; reified generics;Gsharp.Extensions.OptionalandGsharp.Extensions.Sequences; friendly numeric type aliases; and the canonical map type clausemap[K,V]. - Removals and migrations. Legacy spellings now produce focused, span-accurate diagnostics with canonical replacements so IDE quick-fixes can patch most migrations in one edit.
typekeyword for type declarations (type Foo struct { … }→struct Foo { … }).recordkeyword, replaced bydata classordata struct.:=short variable declaration, replaced bylet/var, with diagnosticGS0305.name = valuenamed-argument separator, replaced byname: value, with diagnosticGS0315.func(T) Rlegacy function-type clause, replaced by(T) -> R, with diagnosticGS0303.- Go-flavored
map[K]Vtype clause, replaced bymap[K,V], with diagnosticGS0366. static funcon interface methods is removed. Static-virtual interface members now live inside the interfaceshared { … }block. A body-lessfuncinside that block is an abstract static-virtual slot; afuncwith a body is the default. Static private helpers also move into theshared { … }block asprivate func, while instance private helpers stay directly in the interface body. The oldstatic func …shape now produces a parser error, andGS0330fires when a non-funcmember appears inside an interfaceshared { … }block.
- Body-less
funcnow requires;. Afuncdeclaration without a{ … }block is terminated by the universal no-body marker;. This already held for P/Invoke (func getpid() int32;) and now also applies to abstract interface methods and abstract static-virtual slots inside an interfaceshared { … }block. A body-less interfacefuncmissing its;reportsGS0368; afunccarrying a body still takes no;. - Native interop end-to-end. P/Invoke via
@DllImport, source-generator-shaped@LibraryImport, struct and class marshalling,ref/out/inparameter marshalling, function-pointer marshalling, and@MarshalAsparameter overrides are supported. - Go-flavored concurrency moved behind an opt-in import.
go,chan,select, channel send and receive,make(chan T), and the built-inslen,cap,append,make, anddeletenow requireimport Gsharp.Extensions.Go. DiagnosticsGS0316/GS0317point at the missing import. - Tooling polish. LSP completion understands async-shaped types such as
async (T) -> Randasync sequence[T];textDocument/codeActionoffers nil-related quick fixes; andnullnow produces anil"did you mean" diagnosticGS0273. - Diagnostics catalogue extended. v0.2 introduces
GS0273andGS0288–GS0366. The Diagnostics reference has the per-ID cause and fix detail.
Added
- Friendly numeric type aliases.
int,uint,long,ulong,short,ushort,byte,sbyte,float, anddoubleare accepted everywhere a type name is accepted, as a strict superset on top of the canonical width-bearing names (int32,uint32, …). The alias resolves to the canonicalTypeSymbolat the binder, so diagnostics,typeof,nameof, hover, and emitted IL always print the canonical spelling. Canonical names remain preferred in documentation and public library APIs; aliases are appropriate inside function bodies and local code. Aliases are reserved type names, sotype int = stringand equivalents are rejected withGS0102. - Null-conditional indexing
a?[i].a?[i]evaluates receiveraexactly once. If it isnil, the whole expression yieldsnil; otherwise the result is the indexed value lifted to the nullable form of the indexer's return type. It works on arrays, slices, maps, and CLR indexers on both emit and interpreter paths. Chained forms (h?.Data?[i]?.c) short-circuit on the first nil. The new token?[is recognized only when[immediately follows?, preservingcond ? [arr] : [arr]ternary parses. DiagnosticsGS0300andGS0301cover non-nullable receivers and assignment left-hand sides. - Documentation comments. Markdown-authored
///documentation comments round-trip losslessly to CLR XML doc. Hover renders merged documentation for both G# declarations and imported CLR APIs. New warnings includeGS0227,GS0228,GS0229,GS0230, andGS0231. - Named delegate types.
delegate Name(...)declares a real CLRMulticastDelegate-derived type so C# consumers see a conventional handler type and G# events can carry first-class custom delegate types. DiagnosticsGS0233–GS0234cover invalid forms.; ref/out/inparameters. Declaration-site and call-site ref-kind modifiers are supported, including inlineout var/out let/out _declarations. DiagnosticsGS0235–GS0243cover the rules. Passing a value to aninparameter without writinginat the call site is warningGS0242rather than a silent spill.- Ref-aliasing locals.
let ref m = arr[i]andvar ref v = c.Fieldproduce locals whose IL slots areT&and alias another lvalue. DiagnosticsGS0256–GS0258cover invalid aliases. - Ref returns.
func f(...) ref T { return ref <expr> }is supported. DiagnosticsGS0248–GS0255cover escape rules, async and iterator bans, and override matching. - Conditional ref-arguments. The narrow
ref cond ? a : bform is supported inside ref-kind argument payloads. DiagnosticsGS0260–GS0262cover invalid forms. - Generalized ternary expression.
cond ? a : bis now a normal expression.GS0259is retired in value contexts;GS0263covers "no common type" failures. - Method overloading and optional parameters. User G# functions can carry overload sets that differ by parameter types or ref-kinds, and optional parameters can use compile-time-constant defaults. Diagnostics
GS0264–GS0267cover invalid overloads and defaults. - Named arguments at call sites.
Foo(timeout: 30, retries: 3)works for free functions, user methods, user constructors, extension functions, inherited CLR methods, and delegateInvoke. DiagnosticsGS0244–GS0247cover invalid usage. The legacyname = valueform is deprecated this release with diagnosticGS0315; migrate.copy(...)and attribute argument lists alongside ordinary call sites. scopedparameter modifier.scopedconstrains aref structor managed-pointer parameter from escaping, enforced byGS9004/GS9006.data structsynthesis completed. Everydata structsynthesizesEquals(object),Equals(T),GetHashCode(),ToString(),op_Equality,op_Inequality, andDeconstruct(...). Hand-written versions are rejected withGS0232.- Editor features. Hover for CLR XML docs, live pull-based diagnostics, CodeLens reference counts on members of structs, interfaces, and enums, implicit
thisfor properties, methods, and events, hover forthis, bare static-member access from instance methods, chained-member hover, and six VS Code color themes inspired by the G# logo: Ember, Magma, and Synthwave in dark and light variants. :=short variable declaration removed. Every binding site now requiresletfor immutable bindings orvarfor mutable bindings. The lexer still recognizes:=so the parser can emitGS0305with context-sensitive migration suggestions such asx := 1→let x = 1,for i := 0 ... 10→for i in 0 ... 10, andcase v := <-ch→case let v = <-ch.
Changed
- The website spec, feature matrix, FAQ, bridges page, guide pages, and design-decisions index were refreshed to match compiler ground truth. Outdated statements such as "Parameters do not have default-value syntax" and "Named arguments — Partial" were rewritten.
- The repo
docs/lexical.mdblock-comment paragraph is corrected, and a documentation-comments subsection was added. - The VS Code TextMate grammar adds contextual keywords (
data,inline,record,delegate,event,prop,init,shared,scoped, accessor namesget/set/add/remove/raise, and ref-kindsref/out), operators (:=,?.,??,?/:,!!,...,=>), an@Annotationscope, and a///documentation-comment scope with@taghighlighting. The VS Code snippet set was rewritten to match current grammar. - The Docusaurus site cuts a new
0.2snapshot from the live docs and retires the0.1snapshot. The version dropdown lists0.2andNext; the0.1URL space is no longer served.
Fixed
- Numerous IL-emit, determinism, language-server, and editor hardening rounds improve CLR verification, byte-for-byte reproducibility, property access, CodeLens accuracy, and stale-tree handling.
Known limitations
- Full ref-safe-to-escape analysis is partial;
GS0257is reserved for a future pass. - Unsupported async state-machine emit shapes continue to report
GS0190.
0.1
The 0.1 version base identifies the first pre-1.0 line. This is not a dated stable release announcement; it summarizes the major capabilities implemented in the repository at that point.
Language and libraries
- Packages, imports, import aliases, top-level declarations, and multi-file or multi-package compilation.
- Width-bearing primitive names such as
int32,uint64,float32, andfloat64, plusbool,char,string,object,decimal,nint,nuint, andvoid. - Nullable
T?types withnil,?.,??, and!!. - Structs, classes, interfaces, enums,
data struct,recordas adata structalias, andinline structvalue wrappers. - Generic functions and types with square-bracket type parameters and arguments, constraints, method inference, and CLR variance support where applicable.
- Fixed arrays, slices, maps, tuples, function values, delegates,
sequence[T],async sequence[T], and iteratoryieldsupport. - Control flow including
if,for,for inorrangeforms, switches, switch expressions,try,catch,finally,throw,using, anddefer. - Go-shaped concurrency with
go,scope, channels, channel send and receive,make(chan T),close, andselect. async func,await, async lambdas, awaitable-shape support, andawait forover async sequences.- CLR interop for imported constructors, methods, overload resolution, fields, properties, indexers, events, delegates, extension methods, optional CLR arguments, operators, conversions, attributes, and generic types.
Tooling
gsccompiler driver with immediate execution when no/out:is supplied and saved managed executables or libraries with/out:.- Managed PE and metadata emission without Roslyn, optional reference assemblies, target-framework-aware reference resolution, runtime configuration output, and Portable PDB support.
- MSBuild SDK support through
Gsharp.NET.Sdk,.gsprojprojects,dotnet build,dotnet run, templates, and SDK-side response-file invocation. - VS Code extension and language server support for diagnostics, hover, definitions, references, symbols, formatting, completions, signature help, rename, code actions, CodeLens, semantic tokens, inlay hints, and debugging integration.
- Stable diagnostic IDs in the
GS####form, with warning suppression and warning-as-error controls.
Pre-1.0 notes
- The language is still evolving; source compatibility may change before a stable release.
- Some surfaces are intentionally documented as current implementation behavior rather than final specification guarantees.
- The Playground page exists, but browser-hosted execution is deferred.
Future release-note format
Use reverse chronological order. Each version entry should identify the version and, when a real release process exists, its date. Do not invent dates or version numbers; derive versions from the repository's release process. Write for end users: describe what changed, what it means, and any migration steps they should take.
## X.Y.Z
Short summary of the release.
### Added
- New language, tooling, documentation, or interop capabilities users can try.
### Changed
- Behavior changes, breaking changes, renamed features, or migration notes.
### Fixed
- Short grouped quality notes for user-visible correctness, diagnostics, emit, interpreter, or tooling improvements.
### Known limitations
- Important limitations users should know before upgrading.