# Fin# (Financial Sharp) v0.1.0 — Complete Technical Reference (llms-full.txt) > Linear-type double-entry financial programming language, conservation-of-capital type checker (FIN0001-FIN0005), and .NET compiler blueprint born in The Eleventh Child (/books/aubrie). ================================================================================ TOPIC: Welcome to Fin# (Financial Sharp) [welcome] (Getting Started) ================================================================================ # Welcome to Fin# (`Financial Sharp` / `finsc`) {#welcome} **Fin# (`Financial Sharp`, `.fin`)** is RaggieSoft Labs' open-source (**MIT License**), linear-type double-entry financial programming language and `.NET` compiler blueprint where **the First Law of Thermodynamics is enforced on money at compile time**. > [!TIP] Press `Ctrl+K` (or `/`) anywhere on **finsharp.raggiesoft.dev** to search every linear type (`Capital`, `Account`), standard library function, `finsc` CLI command, and `FIN0001`–`FIN0005` diagnostic, or browse the [Master A–Z API Index](api-index.html). Curious how a novel chapter inspired a real compiler? Read [Origin Story: From `/books/aubrie` Plot Device to Real Language](origin-in-aubrie.html). ## Why Imperative Languages Fail Accounting {#why-imperative-fails} In mainstream imperative languages—C#, Java, C++, Python, TypeScript, and imperative spreadsheet macros—monetary balances are represented as ordinary unconstrained scalar numbers (`decimal`, `BigDecimal`, or worse, binary `double`). In an unconstrained scalar language, the following line compiles with **zero warnings and zero errors**: ```csharp // Standard imperative code: compiles cleanly even though $500,000,000.00 // just materialized out of thin air without debiting any counterparty account! companyRevenue += 500_000_000.00m; ``` Even when engineering teams apply strict code reviews and Sarbanes-Oxley (`SOX` Sections 302 and 404) controls, scalar languages only discover unbalanced postings, dropped sub-cent rounding remainders, or accidental cross-currency additions **at runtime or months later during a forensic audit**. **Fin# catches them in milliseconds at compile time.** ## The Five Compile-Time Conservation Laws of Fin# {#five-laws} | Invariant | Compiler Diagnostic | What `finsc` Proves Before Emitting Code | | :--- | :--- | :--- | | **1. No Thin-Air Mutation** | `FIN0001` | Scalar `+=`, `-=`, `=`, or un-paired account writes outside an atomic `transaction` block are rejected immediately. | | **2. Balanced Double-Entry** | `FIN0002` | Every `transaction` block proves Luca Pacioli's 1494 identity (`∑ Debits ≡ ∑ Credits`) per currency. | | **3. Zero Binary Floating-Point** | `FIN0003` | IEEE 754 `float` and `double` cannot touch `Capital`, `Rate`, or `Account`; all math is 128-bit scaled fixed-point. | | **4. Dimension-Typed Currencies** | `FIN0004` | `Capital` and `Capital` cannot be mixed without an explicit `fx.convert(...)` clearing bridge. | | **5. Linear Remainder Safety** | `FIN0005` | `Capital` is a linear resource (`Move`-only: no `Copy`, no silent `Drop`). Unallocated split remainders fail compilation! | ## 60-Second Tour: Your First `.fin` Ledger {#quick-tour} Here is the real-world scene from *The Eleventh Child*—recording a $30.00 annual aquatic center keytag pass on Geneva Street—written in idiomatic **Fin#**: ```rssc // geneva_household.fin — Every cent is conserved at compile time! ledger GenevaHousehold412 [currency: USD, audit_standard: Z_SOX_302] { account OperatingChecking : Account; account WellnessPassPool : Account; account HouseholdEquity : Account; // Explicit external boundary ingress: pairs Asset against Equity opening_balance( debit: OperatingChecking, credit: HouseholdEquity, amount: 1_250.00_USD, memo: "August 2015 Fall Semester Opening Balance" ); // Atomic double-entry transaction: Sum(Debits) == Sum(Credits) == $30.00 USD transaction PurchaseAquaticKeytag [audit: Z_SOX_302, date: "2015-10-09"] { let keytagFee : Capital = credit OperatingChecking -> 30.00_USD; debit WellnessPassPool <- keytagFee; } } ``` Try deleting `debit WellnessPassPool <- keytagFee;` in `PurchaseAquaticKeytag`: - First, `finsc check` raises **`FIN0005` (`UnconsumedLinearCapitalError`)** because `keytagFee` (`Capital`) reached the end of its scope without being consumed into a destination account. - Second, `finsc check` raises **`FIN0002` (`UnbalancedJournalEntryError`)** because the transaction has `30.00_USD` in credits and `0.00_USD` in debits! ## Open-Source Licensing & RaggieSoft Ecosystem {#licensing} - **Compiler, SDK & Tooling Code**: **100% Open Source under the MIT License** (`https://raggiesoft.dev` & [GitHub `@raggiesoft`](https://github.com/raggiesoft)). - **Documentation & Literary Origins**: Licensed under **Creative Commons Attribution-ShareAlike 4.0 International (`CC BY-SA 4.0`)**. - **RaggieSoft Reference Portal (`v0.8.0`)**: Just like [raggiescript.raggiesoft.dev](https://raggiescript.raggiesoft.dev), **finsharp.raggiesoft.dev** is a three-column **RaggieSoft Reference Portal** compiled from plain-text `.rshp` + Markdown sources by **RaggieSoft Help Studio (`rshbuild.exe`)**—generating this searchable web reference, its `Ctrl+K` instant API index, its offline `FinSharpHelp.exe` viewer, `llms-full.txt`, and its WCAG 2.2 AA VPAT 2.5 report from one build! > [!NOTE] **Fictitious Persons & Entities Disclaimer**: *Zoë Wren Brooks*, *Jordan Fuller*, *Daniel Brooks*, *Aubrie Jean Kelly*, *Mark Anderson*, *Commonwealth Polytechnic Institute (CPI)*, and *Vectron Energy Corp.* referenced in Fin#'s origin documentation are works of fiction from RaggieSoft's *Ocean View Archives* literary series ([*The Eleventh Child*](https://books.raggiesoft.com/aubrie)). Any resemblance to actual persons, living or dead, or actual corporate entities is purely coincidental. In real life, **RaggieSoft**, **RaggieSoft Studio**, and **RaggieSoft Media** are unincorporated personal creative and software imprints of Michael P. Ragsdale (not registered corporations or LLCs). ================================================================================ TOPIC: Origin Story: From /books/aubrie Plot Device to Real Language [origin-in-aubrie] (Getting Started) ================================================================================ # Narrative Origin: From `/books/aubrie` Plot Device to Real Language {#origin-story} Most programming languages start in a corporate compiler lab or a university thesis committee. **Fin# (`Financial Sharp`)** started as a plot device around a fictional oak dining table in Christiansburg, Virginia—inside Michael P. Ragsdale's novel [***The Eleventh Child: The Story of Jordan***](https://books.raggiesoft.com/aubrie). Long before Antigravity made it possible to architect full multi-target compilers and Help Studio documentation portals locally in `Y:\desktop-apps\`, Michael was co-developing the world of *The Eleventh Child* with Gemini on the Web. What began as an authentic, character-driven capstone idea for an autistic Computer Science and Finance double major turned out to have such a clean mathematical core—**applying linear resource types to Luca Pacioli's 1494 double-entry accounting identity**—that RaggieSoft Labs promoted `Fin#` into a real MIT-licensed language specification and `.NET` compiler project! ![Around the oak dining table on Geneva Street in Christiansburg, Zoë Wren Brooks and Jordan Fuller in his S.S. Freedom power wheelchair co-design the linear-type compiler for Fin# to enforce the First Law of Thermodynamics on double-entry accounting, while Daniel Brooks stands proudly behind Zoë and Aubrie Jean Kelly and Mark look on.](https://assets.raggiesoft.com/raggiesoft-books/images/scenes/aubrie/e007/c001/p003/birth-of-finsharp.jpg) ## August 26, 2015: *"Question The Rules"* on Geneva Street {#question-the-rules} In [**Part 3: Question The Rules: The Birth of Fin#**](https://books.raggiesoft.com/aubrie/fall-semester-2015/the-5-45-am-problem-the-birth-of-fin-home-on-geneva-street/part-3-question-the-rules-the-birth-of-fin) (`books/aubrie/e007/c001/p003.md`), sophomore double-major **Zoë Wren Brooks** sits at the Geneva Street dining table enrolled simultaneously in two courses at **Commonwealth Polytechnic Institute (CPI)**: 1. **CS 3214** — *Compiler Design & Programming Languages* 2. **ACIS 3115** — *Intermediate Financial Accounting & Corporate Governance* Alongside her father **Daniel Brooks, CPA**, Zoë reviews a forensic accounting case study on the fictional December 2001 collapse of Houston-based **Vectron Energy Corp.**, whose late-1990s television commercials famously dared viewers to *"Question The Rules"* while executives hid debt off balance sheet—forcing the passage of the Sarbanes-Oxley Act (`SOX`). Sitting beside Zoë in his *S.S. Freedom* power wheelchair with his Engineering Thermodynamics textbook open, **Jordan Fuller** types the insight that sparks the entire language on his AAC device: > *"In physics, you can question the rules of who owns the power lines, but you cannot question the First Law of Thermodynamics! Energy in a closed system cannot be created out of nothing or destroyed—it can only be transferred from one place to another."* > > *"Because rules made by monopolies can be questioned. The laws of conservation cannot."* Zoë immediately connects Jordan's thermodynamics law to quantum no-cloning linear types and double-entry bookkeeping: if a programming language treats `Capital` as a **conserved linear state** rather than an overwriteable scalar number, an unbalanced off-balance-sheet entry cannot even compile (`FIN0001` / `FIN0002`). ## Bidirectional Reading Map: Follow Fin# Across *The Eleventh Child* {#reading-map} Every milestone in `Fin#`'s type system maps directly to chapters and behind-the-scenes dossiers you can read free in the **RaggieSoft Book Reader** (`CC BY-SA 4.0`): | Literary Chapter or Backstage Dossier | In-Story Date | Connection to `Fin#` & `Z-SOX-302` | | :--- | :--- | :--- | | [**The Eleventh Child — Series Landing Page**](https://books.raggiesoft.com/aubrie) | `2014–2016` | Complete novel overview, character arcs, free EPUB/PDF editions, and companion albums in The Listening Room. | | [**Part 3: Question The Rules: The Birth of Fin#**](https://books.raggiesoft.com/aubrie/fall-semester-2015/the-5-45-am-problem-the-birth-of-fin-home-on-geneva-street/part-3-question-the-rules-the-birth-of-fin) | `2015-08-26` | The exact scene where Jordan's First Law of Thermodynamics insight and Zoë's compiler notebook give birth to `Fin#` and `FIN0001`. | | [**Part 7: The Blue Ridge Regional Aquatic Center**](https://books.raggiesoft.com/aubrie/the-eleventh-child-off-to-college/jordan-s-independence-day-the-fall-break-relay/part-7-mark-s-hometown-trail-the-blue-ridge-regional-aquatic-center-a-neighbor-s-wave-on-the-huckleberry-trail) | `2015-10-09` | Zoë logs Jordan's $30.00 annual aquatic center keytag pass under her `Fin#` / `Z-SOX-302` household conservation protocol. | | [**Backstage Dossier: ZOË.Systems.Logs, Fin# & Z-SOX-302**](https://backstage.raggiesoft.com/books/aubrie/zoe-logging-architecture) | `2015-07-18+` | Deep dive into Zoë's five cognitive runtime log streams, five concurrency threads, and how `Z-SOX-302` brings deterministic calm. | | [**RaggieSoft Labs — Fin# Architecture Blueprint**](https://raggiesoft.dev/labs/finsharp) | Present Day | Real-world open-source `.NET` compiler strategy (`FinSharp.Compiler`) on `raggiesoft.dev`. | ## How Fictional Ideas Become Real MIT Code at RaggieSoft {#fiction-to-code} Across the RaggieSoft creative and engineering network: - **Stories stay 100% chronological and human**: Inside `/books/aubrie`, August 2015 stays August 2015—free of fourth-wall breaks or future spoilers. - **Code lives openly on `*.raggiesoft.dev`**: Here on **finsharp.raggiesoft.dev** and [**raggiesoft.dev**](https://raggiesoft.dev), we take the ideas sparked in those stories and engineer real, tested, **MIT-licensed** compilers, SDKs, and developer tools! > [!IMPORTANT] **Fictitious Persons & Entities Disclaimer**: *Zoë Wren Brooks*, *Jordan Fuller*, *Daniel Brooks*, *Aubrie Jean Kelly*, *Mark Anderson*, *Commonwealth Polytechnic Institute (CPI)*, *Blue Ridge Transit (BRT)*, and *Vectron Energy Corp.* are works of fiction created for *Ocean View Archives*. In real life, **Fin#** is an unincorporated open-source software project by Michael P. Ragsdale released under the **MIT License**. ================================================================================ TOPIC: Linear Resource Types (Capital, Account & Move Semantics) [linear-capital-types] (Language Specification) ================================================================================ # Linear Resource Types (`Capital`, `Account` & Move Semantics) {#capital-type} The heart of **Fin#** is its **Linear Flow Analyzer** (`LinearFlowAnalyzer` in `FinSharp.Compiler`). Inspired by substructural linear logic (Girard, 1987) and quantum no-cloning / no-deleting theorems in `Q#`, Fin# splits data types into two worlds: 1. **Ordinary Unrestricted Value Types** (`Int64`, `String`, `Date`, `Bool`, `DecimalQuantity`): Can be copied, inspected, and dropped freely—just like values in C# or F#. 2. **Linear Monetary Resource Types** (`Capital`): Represent conserved units of purchasing power or commodity obligation. Every `Capital` binding **must be consumed exactly once** along every control-flow path! ## Rules of `Capital` {#linear-rules} A binding of type `Capital` obeys three compile-time substructural laws: 1. **No Implicit `Copy`**: Passing `payment` to `debit RentExpense <- payment;` *moves* ownership into the posting and marks `payment` as **Consumed**. Referencing `payment` a second time fails compilation! 2. **No Silent `Drop` (`FIN0005`)**: Allowing a `Capital` variable—including an `if`/`else` branch or a `0.01_USD` split remainder—to go out of scope unconsumed fails compilation with **`FIN0005` (`UnconsumedLinearCapitalError`)**. 3. **No Unpaired Literal Minting (`FIN0001`)**: Outside a `transaction` credit leg or an explicit `opening_balance(...)` boundary declaration, code cannot conjure `Capital` out of a bare integer or string. ```rssc transaction SplitRentThreeWays [audit: Z_SOX_302, date: "2015-09-01"] { // Source $1,000.00 linearly from Checking: let totalRent : Capital = credit OperatingChecking -> 1_000.00_USD; // $1,000.00 / 3 = $333.33 * 3 + $0.01 remainder! // FloorWithRemainder returns BOTH the 3 equal shares AND the 1-cent linear remainder: let (shares, remainder) = capital.splitEqual(totalRent, 3, RoundingPolicy.FloorWithRemainder); debit RoommateShareA <- shares[0]; // $333.33 debit RoommateShareB <- shares[1]; // $333.33 debit RoommateShareC <- shares[2]; // $333.33 // REQUIRED: If we forget this line, finsc halts with FIN0005 because $0.01 was dropped! debit RoundingAdjustmentPool <- remainder; // $0.01 -> Total Debits == $1,000.00! } ``` ## Strongly Typed T-Accounts (`Account`) {#account-kinds} Every ledger account carries two compile-time type parameters: | `TKind` Marker Type | Normal Balance | Accounting Equation Side | Increases On | Decreases On | | :--- | :--- | :--- | :--- | :--- | | `Asset` | Debit | Left (`Assets + Expenses`) | `debit` | `credit` | | `Expense` | Debit | Left (`Assets + Expenses`) | `debit` | `credit` | | `Liability` | Credit | Right (`Liabilities + Equity + Revenue`) | `credit` | `debit` | | `Equity` | Credit | Right (`Liabilities + Equity + Revenue`) | `credit` | `debit` | | `Revenue` | Credit | Right (`Liabilities + Equity + Revenue`) | `credit` | `debit` | Because `TKind` is part of the static type signature, a helper function expecting an `Account` will never accidentally post into an `Account`! ## 128-Bit Scaled Fixed-Point Arithmetic (`FIN0003`) {#fixed-point-math} In binary IEEE 754 floating-point (`float` / `double`), `0.1 + 0.2` evaluates to `0.30000000000000004`. Across millions of ledger rows, binary rounding drift corrupts trial balances. - **Compile-Time Float Ban (`FIN0003`)**: Attempting to multiply, divide, or compare `Capital`, `Account`, or `Rate` with `float` or `double` is a hard compile error (`FIN0003`). - **Exact `Int128` Fixed-Point Representation**: Internally, `FinSharp.Runtime` represents monetary amounts as signed 128-bit integers (`System.Int128` on `.NET 10 / 11`) scaled by `10⁸` (`100,000,000` atomic ticks per major currency unit—supporting sub-basis-point interest and FX math while guaranteeing exact cent reconciliation at posting boundaries). - **Explicit `RoundingPolicy` Enum**: - `RoundingPolicy.HalfEven` / `RoundingPolicy.Bankers` — Round half to even, returning `(roundedShare, adjustmentDelta)` inside settlement combinators. - `RoundingPolicy.FloorWithRemainder` — Deterministic floor division returning `(shares, exactRemainder)` as linear `Capital` values. ## ISO 4217 Dimension-Typed Currencies (`FIN0004`) {#currency-dimensions} Just as an aerospace compiler prevents adding meters to foot-pounds, Fin# treats every ISO 4217 currency (`USD`, `EUR`, `GBP`, `CAD`, `JPY`, `SGD`) and custom commodity unit (`MWh`, `TreasuryBill`) as a distinct phantom type dimension: ```rssc // COMPILE ERROR FIN0004: Cannot combine Capital and Capital without fx.convert! // let invalidTotal = usdPayment + eurPayment; ``` To settle across currencies, see [`fx.convert(...)` in Ledgers & Transactions](ledgers-and-transactions.html#fx-settlement). ================================================================================ TOPIC: Ledgers, Accounts, Atomic Transactions & Z-SOX-302 Proofs [ledgers-and-transactions] (Language Specification) ================================================================================ # Ledgers, Accounts, Atomic Transactions & `Z-SOX-302` Proofs {#ledger-declarations} In 1494, Franciscan mathematician **Luca Pacioli** formalized double-entry bookkeeping around a single conservation equation: > **`Assets + Expenses = Liabilities + Equity + Revenue`** Every valid state transition in a closed accounting system preserves that equality because **the sum of debits in every journal entry equals the sum of credits** (`∑ Debits ≡ ∑ Credits`). Fin# promotes Pacioli's 530-year-old equation directly into its grammar. ## Declaring a Closed `ledger` {#ledger-syntax} A `ledger` block establishes a closed chart of accounts, its functional reporting currency, and its audit-attestation profile (`Z_SOX_302` or custom policy tags): ```rssc ledger CampusAccessibilityFund [currency: USD, audit_standard: Z_SOX_302] { account GrantCashChecking : Account; account EquipmentReceivable : Account; account AdaptiveGearExpense : Account; account VendorPayable : Account; account DonorNetAssets : Account; account WorkshopRevenue : Account; } ``` > [!IMPORTANT] **Zero Mutation Outside `transaction` (`FIN0001`)**: An `Account` exposes read-only query properties (`.id`, `.kind`, `.currency`, `.normalBalance`) in general functions, but **no `.Balance = ...` setter and no `+=` operator**. The *only* grammatical construct permitted to mutate account state is an atomic `transaction` (or boundary `opening_balance`) block! ## Boundary Ingress: `opening_balance(...)` {#boundary-ingress} How does money enter a closed ledger when migrating an existing business or opening a fiscal year? Even at the boundary, capital never appears one-sided—`opening_balance` requires an explicit Asset/Liability pair balanced against an `Equity` (or Opening Balance Equity) account: ```rssc opening_balance( debit: GrantCashChecking, credit: DonorNetAssets, amount: 25_000.00_USD, memo: "FY2016 Opening Endowment Balance" ); ``` ## Atomic `transaction` Blocks {#atomic-transactions} Every `transaction` block compiles to: 1. A **compile-time symbolic conservation check** (`FIN0002` + `FIN0005`), AND 2. A **runtime all-or-nothing atomic commit record** with deterministic SHA-256 hash chaining (`Z-SOX-302`). ### `debit` and `credit` Flow Arrows {#debit-and-credit} Notice the directional visual symmetry of Fin#'s posting arrows: - `credit -> ` **sources** linear `Capital` from the credited leg. - `debit <- ` **sinks** (consumes) linear `Capital` into the debited leg. ```rssc transaction InvoiceAndPayRampSupplier [audit: Z_SOX_302, date: "2015-09-14"] { // Leg 1: Accrue vendor invoice ($1,800.00) let invoiceObligation : Capital = credit VendorPayable -> 1_800.00_USD; debit AdaptiveGearExpense <- invoiceObligation; // Leg 2: Settle half ($900.00) immediately from checking let cashDisbursement : Capital = credit GrantCashChecking -> 900.00_USD; debit VendorPayable <- cashDisbursement; } ``` In `InvoiceAndPayRampSupplier`, `finsc` verifies: - Total `USD` Credits = `1,800.00 + 900.00 = 2,700.00_USD` - Total `USD` Debits = `1,800.00 + 900.00 = 2,700.00_USD` - Unconsumed linear bindings at `}` = `0` (`PASS`)! ## Multi-Currency FX Settlement Bridges (`fx.convert`) {#fx-settlement} During the Summer 2015 Singapore arc of [*The Eleventh Child*](https://books.raggiesoft.com/aubrie), household expenses in Singapore Dollars (`SGD`) had to reconcile cleanly against `USD` accounts without breaking single-currency conservation (`FIN0004`). In Fin#, `fx.convert` routes cross-currency transfers through dual-currency FX clearing accounts so **both the `USD` sub-ledger AND the `SGD` sub-ledger remain 100% independently balanced**: ```rssc transaction ReimburseSingaporeTransitCard [audit: Z_SOX_302, date: "2015-07-18"] { let quote = fx.quote(1.3685_0000, "2015-07-18T09:00:00Z", "MAS-Spot-Ref"); let usdOutflow : Capital = credit UsdTravelChecking -> 100.00_USD; // Credits SgdFxClearing in SGD and debits UsdFxClearing in USD atomically: let (sgdProceeds, fxReceipt) = fx.convert(usdOutflow, quote, FxClearingBridge); debit SgdTransitCardAsset <- sgdProceeds; // Exact 136.85_SGD! audit.attach(fxReceipt); } ``` ================================================================================ TOPIC: finsc CLI, Standard Library (capital.*, fx.*, audit.*) & .NET Architecture [stdlib-and-cli] (Compiler & Standard Library) ================================================================================ # `finsc` CLI, Standard Library & `.NET` Compiler Architecture {#finsc-cli} **Fin# (`FinSharp.Compiler` / `finsc`)** is architected as a clean, fast, 100%-readable self-hosted C# compiler frontend ("Mini-Roslyn" design) targeting **`.NET 10 / 11` CoreCLR and NativeAOT**—interoperating seamlessly with every `.NET` NuGet library while keeping build times under `3 seconds`. ## `finsc` Command-Line Interface Reference {#finsc-commands} | Command | Flags & Arguments | Purpose | | :--- | :--- | :--- | | `finsc check ` | `--diagnostics=json`, `--strict` | Runs `Lexer` -> `Parser` -> `Binder` -> `LinearFlowAnalyzer` (`FIN0001`–`FIN0005`) in milliseconds without writing binaries. | | `finsc build ` | `-o `, `--aot`, `--pdb` | Verifies all conservation proofs and lowers verified syntax trees via `Microsoft.CodeAnalysis.CSharp` (`Roslyn`) into deterministic `.dll` / `.exe` assemblies. | | `finsc audit ` | `--standard=Z_SOX_302`, `--json` | Executes ledger transactions deterministically and emits a SHA-256 Merkle trial-balance attestation report. | | `finsc fmt ` | `--write`, `--check` | Comment-preserving source formatter that aligns `account`, `debit`, and `credit` columns cleanly. | | `finsc lsp` | `--stdio` | Launches the JSON-RPC 2.0 Language Server providing real-time red squiggles for `FIN0001`–`FIN0005` and live T-account hover cards. | ## Standard Library Reference (`FinSharp.StdLib`) {#stdlib-overview} ### `capital.*` — Linear Allocation & Remainder Combinators {#capital-namespace} | Function Signature | Return Type | Description | | :--- | :--- | :--- | | `capital.splitEqual(amount: Capital, ways: Int32, policy: RoundingPolicy)` | `(Capital[], Capital)` | Consumes `amount` and returns `ways` equal shares plus an explicit linear `remainder` so zero sub-cents ever vanish (`FIN0005`). | | `capital.allocateByWeights(amount: Capital, weights: Int64[])` | `Capital[]` | Consumes `amount` using deterministic Largest-Remainder (Hamilton) allocation guaranteed to sum to `amount` with zero leftover cents. | | `capital.combine(left: Capital, right: Capital)` | `Capital` | Consumes two same-currency bindings (`FIN0004` checked) and returns their exact 128-bit fixed-point sum. | | `capital.assertZero(value: Capital)` | `Unit` | Safely consumes a linear binding proven to equal `0.00` (for example, an exhausted loop accumulator). Traps in audit mode if non-zero. | ### `fx.*` — Multi-Currency Conservation Bridges {#fx-namespace} | Function Signature | Return Type | Description | | :--- | :--- | :--- | | `fx.quote(scaledRate: Fixed128, timestampUtc: String, providerId: String)` | `Rate` | Creates an immutable, timestamped foreign-exchange quote using 8-decimal-place scaled fixed-point math (`FIN0003` float-free). | | `fx.convert(source: Capital, quote: Rate, bridge: FxBridge)` | `(Capital, FxAuditReceipt)` | Consumes `source` into `bridge`'s `TFrom` clearing leg and sources balanced `Capital` from `bridge`'s `TTo` leg. | ### `audit.*` — `Z-SOX-302` Deterministic Attestation {#audit-namespace} | Function Signature | Return Type | Description | | :--- | :--- | :--- | | `audit.trialBalance(ledger: Ledger)` | `TrialBalanceSnapshot` | Computes immutable period totals and asserts `Assets + Expenses ≡ Liabilities + Equity + Revenue` per currency. | | `audit.attestZsox302(ledger: Ledger, periodId: String)` | `ZsoxAttestation` | Emits SHA-256 hash-chained journal digest inspired by Zoë Wren Brooks's `Z-SOX-302` governance protocol in [*The Eleventh Child*](https://books.raggiesoft.com/aubrie). | | `audit.attach(receipt: AuditArtifact)` | `Unit` | Attaches structured FX, invoice, or external bank-feed evidence metadata to the enclosing `transaction` journal record. | ### `report.*` — Accessible Financial Statements {#report-namespace} | Function Signature | Return Type | Description | | :--- | :--- | :--- | | `report.exportTaggedPdfUa(snapshot: TrialBalanceSnapshot, outputPath: String)` | `ReportResult` | Exports an ISO 14289-1 **Tagged `PDF/UA-1`** accessible trial balance and income statement compatible with screen readers and **RaggieSoft Document Studio**. | | `report.exportCsv(snapshot: TrialBalanceSnapshot, outputPath: String)` | `ReportResult` | Exports RFC 4180 UTF-8 CSV ledger schedules with exact fixed-point decimal strings. | ## Compiler Pipeline Architecture ("Mini-Roslyn" on `.NET`) {#compiler-pipeline} Why build `FinSharp.Compiler` as a standalone immutable C# syntax tree lowering to Roslyn rather than forking all 4+ million lines of `dotnet/roslyn`? 1. **Sub-3-Second Cold Builds**: Developers and contributors can clone, read, and compile the entire `Fin#` toolchain in seconds without a 30 GB compiler build environment. 2. **100-Level Read-Along Clarity**: Every pass—`FinLexer` -> `FinParser` -> `FinBinder` -> **`LinearFlowAnalyzer`** -> `CSharpRoslynEmitter`—fits cleanly in well-commented C# files. 3. **Full `.NET` & Studio Ecosystem Integration**: Emits standard signed `.NET` IL + PDBs and powers a candidate **RaggieSoft Fin# / Ledger Studio** workstation (`WebView2 + Monaco + Live T-Account Visualizer`, honoring `Community == 100% Architect Feature Parity`!). ================================================================================ TOPIC: Compiler Diagnostics Reference (FIN0001 – FIN0005) [diagnostics-reference] (Diagnostics & Proofs) ================================================================================ # Compiler Diagnostics Reference (`FIN0001` – `FIN0005`) {#diagnostics-overview} Every conservation violation in **Fin#** is caught deterministically during `finsc check` and `finsc build`—long before code can touch a production database or ledger file. All diagnostics support `--diagnostics=json` and SARIF 2.1.0 output for CI/CD gates. --- ## `FIN0001`: `ConservationOfCapitalViolationException` {#fin0001} - **Severity**: `Error` (Fatal Compile-Time Conservation Failure) - **Named In**: [*Part 3: Question The Rules: The Birth of Fin#*](https://books.raggiesoft.com/aubrie/fall-semester-2015/the-5-45-am-problem-the-birth-of-fin-home-on-geneva-street/part-3-question-the-rules-the-birth-of-fin) (`books/aubrie/e007/c001/p003.md`) - **Cause**: Code attempted to mutate an `Account` via scalar assignment (`=`, `+=`, `-=`), conjure an unpaired `Capital` literal outside a boundary/credit leg, or mutate ledger state outside an atomic `transaction` block. ### Failing Example (`FIN0001`) ```rssc // ERROR FIN0001: Unpaired scalar mutation outside an atomic transaction! // Capital cannot be created out of thin air without a counterparty credit leg. OperatingRevenue += 500_000_000.00_USD; ``` ### Passing Fix ```rssc transaction RecordVerifiedEnergyDelivery [audit: Z_SOX_302, date: "2015-08-26"] { let settledReceivable : Capital = credit OperatingRevenue -> 500_000_000.00_USD; debit AccountsReceivable <- settledReceivable; } ``` --- ## `FIN0002`: `UnbalancedJournalEntryError` {#fin0002} - **Severity**: `Error` - **Cause**: Inside a `transaction` block, the symbolic or concrete sum of `debit` postings does not equal the sum of `credit` postings for one or more currencies (`∑ Debits ≠ ∑ Credits`). ### Failing Example (`FIN0002`) ```rssc transaction BrokenUtilitySplit [audit: Z_SOX_302] { let cash : Capital = credit OperatingChecking -> 120.00_USD; // Suppose a buggy custom helper tried to debit $125.00 against a $120.00 credit: debit ElectricUtilityExpense <- cash; debit InternetUtilityExpense <- credit OperatingChecking -> 5.00_USD; // Wait: if only one side posted -> FIN0002! } ``` ### Passing Fix Ensure every `credit -> ` leg is paired 1-for-1 (or via conservation-preserving `capital.splitEqual` / `capital.combine` combinators) with `debit` legs summing to the exact same `Int128` scaled total. --- ## `FIN0003`: `BinaryFloatingPointForbiddenOnCapitalError` {#fin0003} - **Severity**: `Error` - **Cause**: An IEEE 754 binary floating-point type (`float` / `Single` or `double` / `Double`) was passed to or combined with `Capital`, `Rate`, or `Account`. ### Failing Example (`FIN0003`) ```rssc let badTaxRate : float64 = 0.053; // IEEE 754 binary float! // ERROR FIN0003: Binary floating-point is banned from touching Capital. let taxAmount = subtotal * badTaxRate; ``` ### Passing Fix Use exact 128-bit fixed-point `BasisPoints` / `Fixed128` literals (`5.30_pct` or `530_bps`) with an explicit `RoundingPolicy` so both the rounded tax share and sub-cent remainder are accounted for linearly! --- ## `FIN0004`: `CrossCurrencyConservationMismatchError` {#fin0004} - **Severity**: `Error` - **Cause**: Two `Capital` or `Account` operands with different ISO 4217 currency type arguments (such as `Capital` and `Capital`) were combined directly without an auditable `fx.convert(...)` clearing bridge. ### Failing Example (`FIN0004`) ```rssc // ERROR FIN0004: Cannot post Capital into Account! let sgdReceipt : Capital = credit SingaporeCashWallet -> 42.00_SGD; debit UsdDiningExpense <- sgdReceipt; ``` ### Passing Fix Route `sgdReceipt` through `fx.convert(sgdReceipt, quote, FxClearingBridge)` so both the `SGD` and `USD` sub-ledgers remain independently balanced. --- ## `FIN0005`: `UnconsumedLinearCapitalError` {#fin0005} - **Severity**: `Error` - **Cause**: A variable or tuple element of linear type `Capital` (most commonly the `remainder` element returned by `capital.splitEqual`) reached the end of a lexical scope or conditional branch without being consumed by a `debit` posting or `capital.*` combinator. ### Failing Example (`FIN0005`) ```rssc transaction DropPennyBug [audit: Z_SOX_302] { let dues : Capital = credit OperatingChecking -> 100.00_USD; // _ ignores the $0.01 remainder -> ERROR FIN0005! let (shares, _) = capital.splitEqual(dues, 3, RoundingPolicy.FloorWithRemainder); debit MemberA <- shares[0]; debit MemberB <- shares[1]; debit MemberC <- shares[2]; } ``` ### Passing Fix Bind `(shares, remainder)` and explicitly post `debit RoundingAdjustmentPool <- remainder;` before closing the `transaction` block.