Compiler architecture
G# has a shared front end and one execution backend: the emit pipeline used by every command-line driver, including the interactive REPL.
End-to-end pipeline
.gs source → Lexer → Parser → Syntax tree → Binder → BoundProgram → Lowerer → Backend
The front end lives under src/Core/CodeAnalysis. The lexer and parser produce syntax trees, the binder resolves names and types into symbols and bound nodes, and lowering rewrites higher-level constructs into forms that the backends can execute or emit.
Emit backend
The production compiler path writes managed PE metadata directly with ReflectionMetadataEmitter and System.Reflection.Metadata.Ecma335.
BoundProgram (lowered) → ReflectionMetadataEmitter → PE assembly
│
└→ PortablePdbEmitter → sidecar or embedded PDB
gsc owns command-line parsing, response-file expansion, output stream creation, optional reference-assembly output, Portable PDB stream selection, and .runtimeconfig.json generation for executable outputs. Gsharp.NET.Sdk wraps the same driver from MSBuild by building a response file and invoking dotnet gsc.dll during CoreCompile.
The compiler is written in G#
From 0.5, gsc, the language server, the formatter and the other G# tools are written in G#. An earlier released version of the G# compiler compiles each new version. The Visual Studio extension is written in C#.
No Roslyn dependency in the emit path
G# stays on the bespoke emitter and does not use Roslyn to write assemblies at runtime. The motivation is practical: NuGet-distributable assemblies and cross-language debugging require standard ECMA-335 metadata and Portable PDBs, and those are available directly through System.Reflection.Metadata.
Roslyn is used only by sibling tooling. cs2gs uses Roslyn to read C# projects for migration, and gsgen hosts Roslyn source generators out of process, projects G# declarations to C# stubs, translates generator output back to G#, and then hands generated .g.gs files to gsc. The compiler process itself remains Roslyn-free.
Unified emitted execution
Every command-line driver uses the emitter, including the interactive gsi REPL. /out:<path> controls whether gsc saves the assembly or runs the emitted program immediately. The legacy tree-walking evaluator, its Compilation.Evaluate API, and the --engine evaluator / GSI_ENGINE=evaluator escape hatches have been removed.
Lowering and generated code
Lowering prepares language constructs for execution and emit. Examples include top-level entry-point synthesis, defer and cleanup lowering, for in patterns, async state machines, and sync/async iterator state machines. Async and iterator lowering synthesize state-machine types and hidden scaffolding while preserving source sequence points for debugging.
Top-level statements are lowered to a synthesized entry point unless an explicit func Main() takes precedence. Mixing explicit and synthesized entry points is diagnosed.
Packages, namespaces, and assemblies
G# package declarations map to CLR namespaces. G# uses a .NET-style multi-package-per-project model: one .gsproj produces one assembly, and that assembly may contain multiple packages/namespaces. The assembly name comes from project metadata such as AssemblyName, RootNamespace, or the project file name, not from whichever source file the compiler sees first.
The emitter produces separate namespace/type metadata for each package. The package containing top-level statements owns the synthesized entry point for executable assemblies.
References and target frameworks
gsc can run on .NET 10 while emitting for other target frameworks. The compiler routes user and SDK references through ReferenceResolver and an isolated metadata load context. User-supplied target-framework reference assemblies shadow the compiler host assemblies, so emitted type references carry the target framework's identity.
This is why SDK builds pass the complete reference assembly closure through /r:<path> arguments and why direct gsc usage should do the same for non-trivial projects.
Thread safety and lifetime for library hosts
A host that uses GSharp.Core as a library must obey these rules (ADR-0223 D5, #6273, #6275):
- Concurrent read-only queries on
CompilationandSemanticModel. Configure compilation options before the first semantic query. After configuration, concurrent threads can callGetDiagnostics,GetDeclarationDiagnostics,GetBodyDiagnostics,GetTypeByMetadataName,GetSemanticModel,GlobalScope,BoundProgram, and every read-onlySemanticModelquery (GetSymbolInfo,GetTypeInfo,GetDeclaredSymbol,GetBoundNode,GetEnclosingSymbol,LookupSymbols,LookupMembers,GetMemberGroup,GetReceiverTypeInfo,GetReferencedExpression,GetExpectedType,GetSpeculativeTypeInfo) on the same compilation and its semantic models. First-use declaration binding, body binding, and semantic-model index construction run single-flight under the compilation build gate; lazy symbol substitution caches (StructSymbol,InterfaceSymbol,DelegateTypeSymbol) andSyntaxTreeindexes publish atomically. Do not callEmit,Dispose, or mutate compilation options concurrently with semantic queries. - Immutable syntax inputs.
SyntaxTreeandSourceTextobjects do not change afterParseandFrom. Threads can share them across compilations. - Shared
ReferenceResolverconcurrency. ConcurrentCompilationobjects — including compilations with differentAssemblyNamevalues — can share oneReferenceResolver(#6068, #6070). Each compilation passes its own consumer assembly name explicitly into binding and emit instead of mutatingReferenceResolver.CurrentAssemblyName. Do not mutateCurrentAssemblyNameor callTryUseMetadataIndexwhile compilations use the resolver. - Ownership and disposal of
ReferenceResolverandMetadataLoadContext. The caller that invokesReferenceResolver.WithReferences,ReferenceResolver.ForReferencePack,ReferenceResolver.WithRuntimeReferences, orReferenceResolver.Default(runtimeDirectory)owns the returned resolver and its underlyingMetadataLoadContextor collectibleAssemblyLoadContext. Share one resolver across compilations with the same reference closure and callReferenceResolver.Dispose()when finished. Alternatively, passownsReferences: truetoCompilation(references, ownsReferences: true, syntaxTrees)to transfer resolver disposal to that compilation. Do not callReferenceResolver.Dispose()while any compilation uses the resolver or runs in the process. - Compilation disposal and process-wide caches.
CompilationimplementsIDisposable. CallCompilation.Dispose()to release bound trees, diagnostics, and semantic model caches immediately; a borrowed resolver stays open and usable for subsequent compilations. Type-symbol interning caches and CLR reflection/conversion caches are weakly keyed (ConditionalWeakTable/ weak intern tries), so dropped or disposed compilations release their symbols and syntax trees automatically without clearing a sharedReferenceResolver. Long-lived hosts can also callCompilation.ClearProcessCaches()when no compilation is active to release bounded process-wide reference byte and metadata-name index caches. - Process-wide environment. Do not change process-wide state, such as the
GSHARP_SDK_TOOLS_DIRvariable, while a compilation runs. - In-process analyzer execution and load-context reuse.
CompilationWithAnalyzers(Compilation.WithAnalyzers,CompilationWithAnalyzers.FromAnalyzerPaths,CompilationWithAnalyzers.FromProjectConfiguration) runs configuredGSharpDiagnosticAnalyzerinstances against an in-memoryCompilationwith build-equivalentDiagnosticSeverityOptions(.editorconfig,/gsdiag:,/nowarn:,/warnaserror,/warnaserror+:,/warnaserror-:).GetAnalyzerDiagnosticsandGetAllDiagnosticsare safe for concurrent read-only calls across threads and return deterministically ordered diagnostics.AnalyzerAssemblyLoadercaches collectibleAssemblyLoadContextinstances per canonical path, file size, and UTC last-write timestamp (loading from memory bytes so on-disk DLLs stay unlocked for rebuilds); callClear()orDispose()to unload cached contexts (#6277). - Non-retiring incremental forks and member-level reuse.
Compilation.Fork(oldTree, newTree)andCompilation.Fork(oldTrees, newTrees)create incremental successor compilations without mutating or retiring the base compilation (#6269, #6270). Multiple sequential or concurrent forks can share one base compilation while keeping the base's diagnostics, semantic models, and emitted output byte-identical, and disposing a fork leaves the base and any sharedReferenceResolverintact. InspectCompilation.IncrementalReuse(IncrementalReuseReport) on any forked orReplaceSyntaxTreesuccessor to observe the selected tier (BodyOnlyReuse,MemberLevelReuse, orFullRebind), exact fallback reason (IncrementalReuseMissReasonandMissDetail), and reused versus rebound body counts.BodyOnlyReusesupports single- and multi-file body edits across ordinary andpartialtypes as well as files carrying declaration-level warnings (relocating warning spans automatically; only declaration-level errors disqualify reuse).MemberLevelReusesupports adding, removing, or changing signatures of ordinary instance/static methods and top-level functions (binding only the changed member signatures, edited trees, and dependent bodies — scoped to the owning type and its partial/nested parts forprivatemembers, or using a lazy base-owned identifier index for non-private members — while falling back cleanly toFullRebindfor package/import changes, type-hierarchy or field/layout changes, interface/override/extension/operator changes, or edits referenced by external declaration initializers).
In-process bind performance and host reuse
For large in-process hosts (such as binding src/Core: 833 files, 176 references, 13,781 methods), the compiler performance suite tracks a dedicated core-inprocess-bind benchmark row in build/compiler-bench.py --inprocess-bind backed by gsc.dll --bench-inprocess-bind (#6274).
- Baseline profile (
0.6.11): One full in-process bind ofsrc/Coretakes ~22.6 s cold (1 worker,TieredPGO=0) / ~29.4 s cold (1 worker, host defaultTieredPGO=1) / ~17.2 s warm (reused resolver) and retains ~1,149 MiB live managed heap (~1,296 MiB peak managed): ~493 MiB inSyntaxTrees (42.9%), ~426 MiB inBoundProgram(37.1%), ~138 MiB inBoundGlobalScope(12.0%), and ~91 MiB inReferenceResolver(7.9%). Body binding accounts for ~80% of wall time (~18 s) and ~84% of allocations (~16.5 GiB). - Reduction targets: Near-term targets are
<= 8 scold /<= 6 swarm full bind at 4 workers (driven by #5141 body workers, #5131 walker fusion, and #5144 handle-backed metadata) and<= 650 MiBlive retained managed memory per compilation (long-term<= 450 MiBvia syntax compaction and on-demand body binding). - Host reuse today: Share one
ReferenceResolveracross compilations with the same reference closure, callCompilation.Dispose()when done, share oneCompilationacross concurrent read-only threads (#6273, #6275), useCompilation.ForkandCompilation.IncrementalReusefor body-only and member-level incremental rebinding (#6269, #6270), preferGlobalScope/GetDeclarationDiagnostics()when bodies are not required, and consider<TieredPGO>false</TieredPGO>in dedicated compiler hosts (-23% cold bind wall time). For upstream project references in multi-project hosts, pass deterministic/refout:reference assemblies rather than re-binding upstream bodies. - Planned cross-process reuse:
ReferenceResolver.ExportMetadataIndex/TryUseMetadataIndex(ADR-0107, #5167) persists reference type-name indexes across processes. Cross-processBoundGlobalScopedeclaration snapshots are planned on top of member-level incremental reuse (#6270) once handle-backed metadata (#5144) lands, using fail-closed content-fingerprinted keys over compiler version, compilation options, ordered reference fingerprints, and ordered source hashes. See section 12 of the compiler architecture and performance study for full tables and reproduction commands.
Portable PDBs
When debug information is enabled, ReflectionMetadataEmitter collaborates with PortablePdbEmitter. The PDB records document rows, SHA-256 hashes of raw source bytes, sequence points, local scopes, local variables, embedded source, Source Link, compilation options, and PE debug-directory data.
Reified generics model
G# generics are emitted as CLR reified generics, end-to-end. A user-declared generic type (data struct Box[T], class Pair[A, B], etc.) becomes a TypeDef with GenericParam rows; backtick-arity is part of the name (Box`1). Generic methods carry their own MVar slots; field, parameter, return, and local signatures over an in-scope T encode Var(idx) / MVar(idx). Closed CLR generics that mention an in-scope type parameter (List[T], Dictionary[string, T]) emit as honest GenericInstantiation blobs. Open-bearing delegate shapes (func(T) U) emit as a constructed Func<!T, !U> (or Action<…>) and dispatch through normal callvirt FuncN::InvokeMemberRefs parented at the constructedTypeSpec`.
Constraints (any, comparable, sealed-interface bounds) round-trip as GenericParamConstraint rows. Variance markers (in/out) on interface type parameters are emitted as the matching GenericParam variance flags. C# / F# consumers see the same shape they would see from a C#-defined equivalent: GetGenericArguments() returns the type parameters, GetField("Value").FieldType returns the parameter type, and there is no box/unbox.any boundary at member access.
Source layout
| Area | Representative paths |
|---|---|
| CLI driver | src/Compiler/Program.gs |
| Lexer/parser/syntax | src/Core/CodeAnalysis/Syntax/ |
| Binding and symbols | src/Core/CodeAnalysis/Binding/, src/Core/CodeAnalysis/Symbols/ |
| Lowering | src/Core/CodeAnalysis/Lowering/ |
| Interactive emitted sessions | src/Repl/Engine/EmittedSessionEngine.gs, src/Repl/ (gsi REPL host) |
| PE emit | src/Core/CodeAnalysis/Emit/ReflectionMetadataEmitter.gs |
| Portable PDB emit | src/Core/CodeAnalysis/Emit/PortablePdbEmitter.gs |
| SDK integration | src/Sdk/Gsharp.NET.Sdk/ |
| Source-generator host | src/GeneratorHost/, tools/gsgen/ |
| C# migration tooling | tools/cs2gs/ |
| Language server | src/LanguageServer/ |