[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7ARC290RYRH7E82VQ2GXB4Q":3,"skill-same:01M7ARC290RYRH7E82VQ2GXB4Q":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M7ARC290RYRH7E82VQ2GXB4Q","language-design-parsing-and-types",null,"Use when designing a language or building a compiler front end: the questions that determine everything else, the design principles that hold up, syntax; lexing, parsing approaches (recursive descent, Pratt, LR, generators), error recovery, CST vs AST; name resolution and modules; and type systems — the design space, inference (Hindley–Milner, bidirectional), unification and the occurs check, traits, type classes, and interfaces, generics (monomorphize or erase), ownership, borrowing, and linearity, the other static analyses, compile-time execution and metaprogramming, and effects. Includes the router for the whole programming-language-development reference.","the-vibey-project\u002Fvibey","the-vibey-project","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F329298758?v=4","01M7AJHGZ9722CTJ4JNQZVRH0Q","the vibey project","01M7AJHGZVMG2K7TGXQ6XFHVG3",5,"MIT","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fprogramming-language-development\u002Fskills\u002Flanguage-design-parsing-and-types\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: language-design-parsing-and-types\ndescription: \"Use when designing a language or building a compiler front end: the questions that determine everything else, the design principles that hold up, syntax; lexing, parsing approaches (recursive descent, Pratt, LR, generators), error recovery, CST vs AST; name resolution and modules; and type systems — the design space, inference (Hindley–Milner, bidirectional), unification and the occurs check, traits, type classes, and interfaces, generics (monomorphize or erase), ownership, borrowing, and linearity, the other static analyses, compile-time execution and metaprogramming, and effects. Includes the router for the whole programming-language-development reference.\"\n---\n\n# Programming Language Development: Language Design, Lexing and Parsing, Names and Modules, and Type Systems\n\n> **Part 1 of 5** of the *Programming Language Development* reference (plugin `programming-language-development`), covering §0–§4. Sibling skills: `language-irs-optimization-and-backends` (§5–§7), `language-runtimes-interpreters-and-jits` (§8–§9), `language-diagnostics-tooling-and-evolution` (§10–§14), `language-development-reference` (§15–§20). Section numbers are shared across the set; a reference written as §N → `skill` points into that sibling skill.\n>\n> **Currency:** Verified August 2026. See §17 → `language-development-reference` for the currency snapshot and what goes stale first.\n\n> **How to read this.** Reference, not tutorial. Sections are independent. Three markers:\n> - **[DURABLE]** — theory, algorithms, or a lesson every language implementation has\n>   independently learned. Does not expire.\n> - **[VERSIONED]** — depends on a specific toolchain, standard, or project's current\n>   state. Verify against its docs.\n> - **[CONTESTED]** — competent language designers disagree, publicly and permanently.\n>   Both cases given.\n>\n> **⚠️ GOTCHA** boxes mark the design mistakes that are cheap to make on day one and\n> impossible to undo on day one thousand.\n>\n> **The framing that organizes everything below: a language is a set of promises you can\n> never take back.** Syntax you can deprecate. Semantics you cannot. Every hard decision\n> in this document is really the question *\"what am I willing to be permanently\n> responsible for?\"* — and the languages people love and the languages people resent are\n> distinguished mostly by how carefully their designers answered it early.\n\n---\n\n## §0. Routing\n\n### 0.1 The pipeline\n\n```\nSOURCE TEXT\n  │  LEXER ─────────── tokens (+ trivia, spans)                            §2\n  │  PARSER ────────── CST\u002FAST (+ error recovery)                          §2\n  ▼\nFRONT END\n  │  NAME RESOLUTION ─ bind identifiers to declarations; modules, scopes   §3\n  │  TYPE CHECKING ─── inference, coercion, trait\u002Fclass resolution         §4\n  │  SEMANTIC ANALYSIS ─ borrow\u002Feffect\u002Fexhaustiveness\u002Fdefinite-assignment  §4.7\n  ▼\nMIDDLE END\n  │  LOWER to IR ───── SSA \u002F CPS \u002F ANF; desugar; monomorphize              §5\n  │  OPTIMIZE ──────── inline, constant-fold, DCE, GVN, LICM, vectorize    §6\n  ▼\nBACK END\n  │  INSTRUCTION SELECTION ─ IR → target instructions                      §7\n  │  REGISTER ALLOCATION ─── virtual → physical registers                  §7.3\n  │  SCHEDULING \u002F EMISSION ─ object code, debug info                       §7\n  ▼\nRUNTIME + LINK ───── GC, scheduler, FFI, unwinding, dynamic loading        §8\n```\n\n**[DURABLE] The two most consequential structural decisions are made before you write a\nline of the pipeline:**\n1. **What is your IR, and how many do you have?** (§5 → `language-irs-optimization-and-backends`) Every serious compiler ends up with\n   at least three levels. Deciding this late means rewriting everything.\n2. **Is the front end reusable by an IDE?** (§11 → `language-diagnostics-tooling-and-evolution`) A compiler designed as a batch\n   source-to-binary pipeline cannot be turned into a responsive language server without\n   substantial rearchitecture. Design for incrementality from day one or accept that you\n   will do it twice.\n\n### 0.2 The question router\n\n| Asked about... | Go to |\n|---|---|\n| Should this be a language at all? Design philosophy, trade-offs | §1 |\n| Lexing, parsing, grammars, error recovery, syntax design | §2 |\n| Scopes, modules, imports, name resolution | §3 |\n| Type systems, inference, generics, traits, effects, ownership | §4 |\n| IR design — SSA, CPS, ANF, MLIR, lowering | §5 → `language-irs-optimization-and-backends` |\n| Optimization passes and where they belong | §6 → `language-irs-optimization-and-backends` |\n| Code generation, instruction selection, register allocation, backends | §7 → `language-irs-optimization-and-backends` |\n| Runtime: memory management, GC, concurrency, FFI, exceptions | §8 → `language-runtimes-interpreters-and-jits` |\n| Interpreters, bytecode VMs, JIT | §9 → `language-runtimes-interpreters-and-jits` |\n| Error messages and diagnostics | §10 → `language-diagnostics-tooling-and-evolution` |\n| Incremental compilation, IDE, LSP | §11 → `language-diagnostics-tooling-and-evolution` |\n| Testing, fuzzing, formal verification | §12 → `language-diagnostics-tooling-and-evolution` |\n| Standard library, ecosystem, tooling | §13 → `language-diagnostics-tooling-and-evolution` |\n| Evolution, versioning, governance, deprecation | §14 → `language-diagnostics-tooling-and-evolution` |\n| \"Don't do this\" | §15 → `language-development-reference` |\n| \"Which approach is better?\" | §16 → `language-development-reference` (contested) |\n| \"Is this still current?\" | §17 → `language-development-reference` |\n| Books, papers, people | §18 → `language-development-reference` |\n\n---\n\n## §1. Language Design\n\n### 1.1 The questions that determine everything else\n\nAnswer these before implementation; each one propagates through the whole pipeline.\n\n| Question | Options | Downstream consequences |\n|---|---|---|\n| **Static or dynamic typing?** | Static, dynamic, gradual | Determines whether the type checker is a phase or a runtime |\n| **Memory management?** | Manual, RAII\u002Fownership, refcount, tracing GC, region\u002Farena | The single largest runtime-design driver (§8.1 → `language-runtimes-interpreters-and-jits`) |\n| **Compiled or interpreted?** | AOT, JIT, bytecode VM, tree-walk, transpile | Determines the whole back end |\n| **Generics: monomorphize or erase?** | Monomorphize (C++, Rust), erase (Java, Go pre-1.18), dictionary-pass (Haskell, Swift) | Code size vs. compile time vs. runtime cost (§4.5) |\n| **Concurrency model?** | Threads+locks, async\u002Fawait, actors, CSP, STM, structured concurrency | Colours your entire function type system (§8.3 → `language-runtimes-interpreters-and-jits`) |\n| **Mutability default?** | Mutable, immutable, controlled | Affects optimization opportunity enormously |\n| **Nullability?** | Nullable-by-default, option types, non-null-by-default | Tony Hoare's \"billion-dollar mistake.\" Option types are the settled answer for new languages |\n| **Error handling?** | Exceptions, result types, error returns, panics | Interacts with every ABI and FFI decision (§8.4 → `language-runtimes-interpreters-and-jits`) |\n| **Metaprogramming?** | None, macros (hygienic or not), reflection, compile-time execution, templates | Determines whether your compiler is also an interpreter (§4.8) |\n\n### 1.2 The design principles that hold up\n\n- **[DURABLE] Simplicity is a budget, not a virtue.** You get a fixed complexity budget;\n  every feature spends it. The question is never \"is this feature good?\" but \"is this\n  feature worth what it costs in interaction with everything else?\" Feature *interactions*\n  are superlinear, which is why languages get harder to learn faster than they get bigger.\n- **Orthogonality**: features should compose without special cases. Every special case is\n  a thing to learn, a thing to implement, and a source of bugs at the seams.\n- **The principle of least astonishment** applies to *the population you're targeting*, not\n  to language theorists.\n- **Make the right thing easy and the wrong thing hard.** Rust's success is mostly this\n  principle applied to memory.\n- **Errors should be impossible, then caught at compile time, then caught at runtime, then\n  documented — in that order of preference.**\n- **[CONTESTED] \"Worse is Better\" (Richard Gabriel, 1989)** — the New Jersey school\n  (simplicity of *implementation* beats completeness; ship it) versus the MIT\u002FStanford\n  school (correctness and completeness first). C and Unix won with the first; the second\n  produced better artifacts that fewer people used. This tension is unresolved and shows\n  up in every language committee.\n- **Hyrum's Law**: with enough users, every observable behaviour of your implementation\n  becomes a promise, whether or not you specified it. **Specify aggressively, and\n  deliberately randomize what you refuse to promise** (Go randomizes map iteration order\n  precisely to prevent people depending on it — a technique worth stealing).\n\n### 1.3 Syntax\n\n**[DURABLE] Syntax is the least important part of a language and the part people argue\nabout most.** That said, it is the interface, and interfaces matter:\n- **Familiarity has enormous value.** Jakob's Law applies to languages: users arrive with\n  expectations from every other language they know. Novel syntax is a tax paid on every\n  reader forever, and it should buy something real.\n- **Readability > writability.** Code is read far more than written. Perl and APL optimized\n  the wrong one.\n- **Prefer unambiguous grammars.** If your grammar needs unbounded lookahead or a \"lexer\n  hack,\" your tooling — formatters, highlighters, IDEs, other implementations — will\n  suffer forever. C's `(a)*b` ambiguity (cast or multiply? depends on whether `a` is a\n  type) is the canonical example.\n- **Design for tooling from the start**: a formatter, a syntax highlighter, and an IDE all\n  want a *lossless* CST with trivia preserved (§2.4).\n\n> **⚠️ GOTCHA — significant whitespace and tabs.** If you choose indentation-sensitive\n> syntax, you must specify the tab\u002Fspace interaction exactly, at the lexer level, in\n> version one. Python took until Python 3 to make mixing an error, and it caused real bugs\n> for a decade.\n\n> **⚠️ GOTCHA — reserve keywords generously.** Adding a keyword later breaks every program\n> using it as an identifier. Languages handle this with contextual keywords (complexity),\n> editions (Rust — §14.2 → `language-diagnostics-tooling-and-evolution`), or just breaking people. Reserve more than you need on day one.\n\n---\n\n## §2. Lexing and Parsing\n\n### 2.1 Lexing\n\nConvert characters to tokens. The parts people underestimate:\n- **Unicode.** Identifiers (UAX #31), normalization (NFC — decide and enforce it, or `é`\n  and `é` are different identifiers), and **bidirectional-override characters, which are a\n  security issue**: the \"Trojan Source\" attack uses them to make source read differently\n  to a human than to the compiler. Reject or warn on bidi control characters in source.\n- **Spans\u002Flocations on every token.** Byte offsets plus a line-index side table is the\n  standard efficient design — computing line\u002Fcolumn lazily from a precomputed line table\n  beats tracking it per character.\n- **Trivia** (whitespace, comments) — either preserve them attached to tokens or you cannot\n  build a formatter or a lossless refactoring tool later (§2.4).\n- **Interpolated strings, raw strings, and nested comments** are where hand-written lexers\n  earn their keep; regex-based lexer generators struggle with them.\n\n### 2.2 Parsing — choosing an approach\n\n| Approach | Notes |\n|---|---|\n| **Recursive descent + Pratt** | **The overwhelming choice of production compilers** (GCC, Clang, rustc, Go, TypeScript, V8). Hand-written, readable, arbitrary lookahead, and — decisively — *excellent error recovery and error messages* |\n| LL(k) generators (ANTLR) | Good tooling, good for DSLs; less control over errors |\n| LALR generators (yacc\u002Fbison) | Compact, fast; conflicts are famously painful to debug; poor error messages |\n| GLR \u002F Earley | Handle ambiguous grammars; slower; useful for language *research* and for parsing C++ |\n| PEG \u002F packrat | Unambiguous by construction (ordered choice), linear with memoization; **ordered choice silently hides ambiguity, which is a footgun** |\n| Combinators | Elegant, great for prototypes; error messages and performance need work |\n\n**[DURABLE] Essentially every widely-used production compiler uses hand-written recursive\ndescent, and the reason is error recovery.** A generated parser gives up or produces a\ngeneric message; a hand-written one can say \"you forgot a semicolon here\" and continue.\nSince the parser's output feeds an IDE that sees broken code 100% of the time, this is not\na minor consideration.\n\n**Pratt parsing (top-down operator precedence)** is the right technique for expressions:\neach token gets a binding power, and precedence and associativity fall out of comparing\nthem. It's about 50 lines and handles prefix, infix, postfix, and mixfix cleanly.\n\n### 2.3 Error recovery\n\n**[DURABLE] The parser's job is not to reject bad programs. It is to produce a usable tree\nfrom bad programs**, because that is the input it receives most of the time.\n- **Error nodes \u002F poison nodes**: represent \"something was here but it was wrong\" in the\n  tree so later phases can continue and produce *their* errors too.\n- **Panic-mode recovery with synchronization tokens**: on error, skip to the next `;`, `}`,\n  or start-of-declaration and resume.\n- **Insertion\u002Fdeletion repair**: hypothesize a missing token and continue.\n- **Never cascade.** One missing brace producing 400 errors is the classic failure. Suppress\n  errors within a short distance of a previous one, and suppress errors *derived from*\n  poison nodes.\n\n### 2.4 CST vs. AST\n\n- **CST (concrete syntax tree)**: every token, every space, every comment. Required for\n  formatters, refactoring tools, and IDEs. Rust-analyzer's **rowan** and the\n  **Roslyn** \"red-green tree\" design are the reference implementations: a persistent,\n  immutable \"green\" tree of shared nodes plus a lightweight \"red\" layer providing parent\n  pointers and absolute positions.\n- **AST**: semantic structure, trivia discarded.\n- **[DURABLE] Build the CST and derive the AST from it.** Going the other direction is\n  impossible. This is the single most common regret in compiler front-end design, because\n  the IDE requirement always arrives later than the compiler requirement.\n\n---\n\n## §3. Names, Scopes, and Modules\n\n### 3.1 Name resolution\n\nBind every identifier to a declaration. Sounds simple; is not.\n- **Scoping**: lexical (almost always correct) vs. dynamic (almost always a mistake).\n- **Shadowing**: allowed, warned, or forbidden. Rust allows and uses it heavily; many\n  languages warn.\n- **Forward references**: can a function call something declared later? At top level,\n  usually yes (requiring a separate declaration-collection pass); inside a block, usually\n  no. **This decision determines whether name resolution is one pass or two.**\n- **Namespaces**: are types, values, macros, and labels in the same namespace? (C has\n  separate struct\u002Fordinary namespaces; Rust separates types and values; Lisp-2 vs. Lisp-1\n  is the oldest version of this argument.)\n- **Overloading** multiplies resolution complexity by type checking — now name resolution\n  and type checking are mutually dependent, and you may need to interleave them.\n\n### 3.2 Modules\n\n**[DURABLE] Module systems are where languages accrete the most regret**, because module\nsemantics touch compilation units, linking, versioning, packaging, and the file system all\nat once. The decisions:\n\n| Decision | Options |\n|---|---|\n| Unit of modularity | File, directory, explicit declaration, package |\n| Import granularity | Whole module, selected names, glob |\n| Visibility | Public\u002Fprivate, `pub(crate)`-style graded, explicit export lists |\n| Cyclic imports | Allowed (complicates compilation order), forbidden (simplifies everything) |\n| Name-to-file mapping | Implicit (Java, Python) or explicit (Rust `mod`, C++ modules) |\n| Separate compilation | Per-file, per-module, per-package, whole-program |\n\n**[DURABLE] Forbid cyclic module dependencies if you possibly can.** They force\nwhole-program analysis, complicate incremental compilation, and are almost always a design\nsmell in user code. Go forbids them; the ecosystem is measurably healthier for it.\n\n> **⚠️ GOTCHA — C++ modules are the cautionary tale.** Standardized in C++20; **GCC 16.1\n> (April 2026) still describes its C++20 modules support as experimental, requiring\n> `-fmodules`.** Six years from standardization to \"still experimental\" in a major\n> implementation is what happens when a module system must interoperate with a\n> textual-inclusion legacy. **Design modules before you have a legacy, not after.**\n\n---\n\n## §4. Type Systems\n\n### 4.1 The design space\n\n| Axis | Options |\n|---|---|\n| Checked when | Static, dynamic, gradual, optional |\n| Inference | None, local, bidirectional, global (HM) |\n| Polymorphism | Parametric (generics), ad-hoc (overloading\u002Ftraits), subtype, row |\n| Subtyping | None, nominal, structural, both |\n| Variance | Invariant, co\u002Fcontravariant, declaration-site or use-site |\n| Higher-kinded | No, yes (Haskell, Scala) |\n| Dependent | No, limited (const generics, refinement), full (Idris, Lean, Agda) |\n| Effects | Implicit, checked exceptions, monadic, algebraic effect handlers |\n| Linearity | None, affine (Rust ownership), linear, uniqueness |\n\n### 4.2 Inference\n\n**Hindley–Milner (Algorithm W)** — full inference for the let-polymorphic lambda calculus.\nUnification-based, principal types, and no annotations required anywhere. The catch:\n**HM does not survive contact with subtyping, higher-rank types, or type classes without\nsignificant extension**, and its error messages are notoriously bad — unification fails at\nsome arbitrary point far from the actual mistake.\n\n**Bidirectional type checking** — the modern default. Split into two mutually recursive\njudgments: *checking* (`Γ ⊢ e ⇐ T`, \"does `e` have type `T`?\") and *synthesis*\n(`Γ ⊢ e ⇒ T`, \"what type does `e` have?\"). Annotations at the boundaries.\n- **Why it won**: it scales to subtyping, higher-rank polymorphism, dependent types, and\n  GADTs, where HM does not; it needs fewer annotations than you'd think; and — the reason\n  practitioners care — **error messages are dramatically better**, because when checking\n  fails you know the *expected* type and can report both sides.\n- Used in some form by Rust, Swift, TypeScript, Scala 3, Agda, Idris.\n\n**Local type inference** (C#, Java, Go, C++ `auto`) — infer variable types from\ninitializers and generic instantiations from arguments; require annotations on function\nsignatures. **[DURABLE] Requiring signature annotations is a feature, not a limitation**:\nit makes the code self-documenting, keeps errors local, makes separate compilation\ntractable, and makes the IDE's job possible.\n\n> **⚠️ GOTCHA — global inference and error locality are in direct tension.** With full\n> inference, an error in one function can surface as a type error in an unrelated one.\n> Every language with global inference eventually adds a \"please annotate your top-level\n> definitions\" lint. Consider just requiring them.\n\n### 4.3 Unification and the occurs check\n\n```\nunify(a, b):\n  a, b = resolve(a), resolve(b)          # follow substitutions (union-find)\n  match (a, b):\n    (Var x, Var y) if x == y  -> ok\n    (Var x, t) | (t, Var x)   -> occurs_check(x, t); bind(x, t)   ← DON'T SKIP THIS\n    (Con(c1, as), Con(c2, bs)) if c1 == c2 && len equal -> zip-unify\n    _                          -> type error (report BOTH sides and the location)\n```\n**The occurs check** prevents binding `x := List\u003Cx>`, which creates an infinite type. Skip\nit and your compiler hangs or stack-overflows on a program like `let f = fun x -> x x`.\nUse **union-find with path compression** for the substitution or unification is\naccidentally quadratic.\n\n**Levels\u002Franks for generalization**: the naive \"generalize all free variables not in the\nenvironment\" is O(n) in environment size at every `let`. The standard fix is Rémy's\nlevel-based generalization — tag each type variable with the `let`-depth at which it was\ncreated and generalize only those deeper than the current level. Every efficient HM\nimplementation does this.\n\n### 4.4 Traits, type classes, and interfaces\n\nThe mechanism for ad-hoc polymorphism, and it comes in three flavours:\n- **Nominal interfaces** (Java, C#): a type explicitly declares it implements an interface.\n  Simple, but you cannot retrofit an interface onto a type you don't own.\n- **Structural** (Go, TypeScript): if it has the methods, it satisfies the interface. Fixes\n  retrofitting; loses the ability to distinguish two interfaces with the same shape and\n  different meaning.\n- **Type classes \u002F traits** (Haskell, Rust, Swift): implementations are declared\n  *separately* from both the type and the interface. Solves retrofitting *and* keeps\n  nominality — at the cost of needing **coherence** rules.\n\n**Coherence and the orphan rule.** If two crates can both implement `Trait` for `Type`,\nwhich one applies? Incoherence breaks type-directed dispatch and can break soundness.\nHaskell and Rust enforce coherence via the **orphan rule**: you may implement a trait for\na type only if you own the trait or the type. It is the single most-complained-about rule\nin Rust and it is load-bearing.\n\n**Implementation strategies**: dictionary passing (pass a vtable of the implementation —\nHaskell, Swift), monomorphization (generate a specialized copy — Rust static dispatch), or\nvtables at runtime (`dyn Trait`, Go interfaces).\n\n**⚠️ Trait resolution is a solver, and solvers have performance and termination problems.**\nRust's trait system is expressive enough that resolution can loop or blow up exponentially.\n**[VERSIONED]** rustc has been building a **next-generation trait solver** for years\nprecisely to fix long-standing soundness bugs, unblock features (implied bounds, negative\nimpls), and improve compile times; it reached production use in coherence checking and, as\nof 2026, stabilization work continues alongside **Polonius** (the next-generation borrow\nchecker). The lesson for a language designer: **an expressive trait\u002Finstance-resolution\nsystem is a Prolog interpreter in your compiler. Budget accordingly.**\n\n### 4.5 Generics: monomorphize or erase?\n\n**[CONTESTED, and one of the genuinely load-bearing decisions.]**\n\n| | **Monomorphization** (C++, Rust) | **Erasure \u002F dictionaries** (Java, Haskell, Swift) |\n|---|---|---|\n| Runtime cost | **Zero** — specialized code, inlinable | Indirection: boxing, vtables, dictionaries |\n| Code size | **Explodes** — one copy per instantiation | One copy |\n| Compile time | **Slow** — the dominant cost in large Rust and C++ builds | Fast |\n| Separate compilation | Hard — need the generic body available | Clean |\n| Reflection on type args | Available | Erased (Java's `List\u003CT>` doesn't know `T` at runtime) |\n| Error messages | Instantiation-time errors, often terrible (C++ templates pre-concepts) | Declaration-time errors |\n\nGo's 1.18 generics chose a **middle path (GC shape stenciling)**: monomorphize by\n*representation class* rather than by exact type, so all pointer-shaped types share one\ninstantiation. This bounds code growth while keeping most of the performance.\n\n**[DURABLE] Whichever you choose, define errors at the *declaration* site.** C++ templates\nfamously deferred all checking to instantiation, producing the pathological error messages\nthat concepts (C++20) exist to fix. Rust's trait bounds check the generic body against its\nbounds up front. This is worth real implementation effort.\n\n### 4.6 Ownership, borrowing, and linearity\n\nRust's contribution is proving that **affine types plus region inference can eliminate\nmemory-safety bugs at compile time with no runtime cost**, in a language people actually\nship. The machinery:\n- **Ownership**: each value has one owner; drop at scope end (RAII).\n- **Borrowing**: `&T` (shared, many) \u002F `&mut T` (unique, one). The XOR rule — aliasing xor\n  mutation — is what makes the whole thing sound *and* is what makes it hard to learn.\n- **Lifetimes**: regions inferred by the borrow checker; annotations only where inference\n  can't decide.\n\n**[VERSIONED] NLL (non-lexical lifetimes) shipped in 2018; Polonius** is the next-generation\nformulation, designed to accept currently-rejected patterns (notably \"lending iterators\").\nRust's own 2026 project-goal updates describe an \"alpha\" Polonius being tested on CI\nalongside the next-gen trait solver, with worst-case slowdowns still being tracked. **The\nhonest read: borrow checking is a research area with a shipped product on top of it, and\nthe shipped product's rules are still being refined eight years in.**\n\n**Alternatives worth knowing**: linear types (must use exactly once — Linear Haskell),\nuniqueness types (Clean), region\u002Farena inference (MLKit, Cyclone — the direct ancestor of\nRust's design), and Swift's ARC with `~Copyable`\u002Fborrowing annotations retrofitted.\n\n### 4.7 The other static analyses\n\nThese aren't \"type checking\" but live in the same phase and are equally load-bearing:\n- **Exhaustiveness checking for pattern matching.** [DURABLE] **This is one of the highest\n  value-per-implementation-effort features in language design.** Maranget's algorithm\n  (\"Warnings for pattern matching,\" 2007) is the standard reference and is genuinely\n  implementable in a few hundred lines. It converts a whole class of runtime bugs into\n  compile errors and it is what makes sum types pleasant instead of tedious.\n- **Definite assignment** — is this variable initialized on every path?\n- **Reachability \u002F dead code**, **unused variables and imports**.\n- **Effect checking** (§4.9).\n\n### 4.8 Compile-time execution and metaprogramming\n\nThe spectrum, in increasing order of power and danger:\n1. **Constant folding** — the compiler evaluates `2+2`.\n2. **`constexpr`\u002F`comptime`** — arbitrary evaluation at compile time (C++, **Zig's\n   `comptime`**, which is also how Zig does generics).\n3. **Hygienic macros** — syntax-to-syntax transforms that respect scope (Scheme, Rust).\n4. **Procedural macros \u002F compiler plugins** — arbitrary code running in the compiler.\n5. **Full reflection** — programs inspecting and generating themselves.\n\n**[VERSIONED, and a genuinely big deal] C++26 shipped static reflection**, which Herb\nSutter called \"the biggest upgrade since templates\" and \"C++'s decade-defining rocket\nengine.\" **The ISO committee completed technical work on C++26 on 28 March 2026** in\nLondon; the headline features are **static reflection, contracts, `std::execution`\n(sender\u002Freceiver), and a hardened standard library**. **GCC 16.1 (30 April 2026) already\nships reflection and contracts.** Note the syntax churn as a lesson: the reflection\noperator changed from `^` to `^^` during standardization, so early adopter code needed\nmigration.\n\n> **⚠️ GOTCHA — compile-time execution means your compiler contains an interpreter, and\n> that interpreter is a security boundary and a performance cliff.** You need: a step\n> limit (or programs won't terminate), determinism (or builds aren't reproducible), a\n> decision about whether it can do I\u002FO (**it should not**), and an answer for what it means\n> to debug it. Zig's community discussions consistently name `comptime` as both its best\n> feature and a significant pain point — that's the shape of this trade-off.\n\n### 4.9 Effects\n\nAn active research frontier that is reaching production:\n- **Checked exceptions** (Java) — the first mainstream effect system, and widely considered\n  a partial failure because it lacked polymorphism: you couldn't write a higher-order\n  function generic over what its argument throws.\n- **Monadic effects** (Haskell) — expressive, composes badly (monad transformers).\n- **Algebraic effects and handlers** (Koka, Eff, OCaml 5's effect handlers) — the current\n  best answer. Effects are operations; handlers interpret them. This is what makes OCaml 5's\n  concurrency work without colouring functions.\n- **Function colouring** (§8.3 → `language-runtimes-interpreters-and-jits`): async\u002Fawait is an *ad-hoc, unprincipled effect system*.\n  This is the strongest argument for doing effects properly.\n","# Programming Language Development: Language Design, Lexing and Parsing, Names and Modules, and Type Systems\n\n> **Part 1 of 5** of the *Programming Language Development* reference (plugin `programming-language-development`), covering §0–§4. Sibling skills: `language-irs-optimization-and-backends` (§5–§7), `language-runtimes-interpreters-and-jits` (§8–§9), `language-diagnostics-tooling-and-evolution` (§10–§14), `language-development-reference` (§15–§20). Section numbers are shared across the set; a reference written as §N → `skill` points into that sibling skill.\n>\n> **Currency:** Verified August 2026. See §17 → `language-development-reference` for the currency snapshot and what goes stale first.\n\n> **How to read this.** Reference, not tutorial. Sections are independent. Three markers:\n> - **[DURABLE]** — theory, algorithms, or a lesson every language implementation has\n>   independently learned. Does not expire.\n> - **[VERSIONED]** — depends on a specific toolchain, standard, or project's current\n>   state. Verify against its docs.\n> - **[CONTESTED]** — competent language designers disagree, publicly and permanently.\n>   Both cases given.\n>\n> **⚠️ GOTCHA** boxes mark the design mistakes that are cheap to make on day one and\n> impossible to undo on day one thousand.\n>\n> **The framing that organizes everything below: a language is a set of promises you can\n> never take back.** Syntax you can deprecate. Semantics you cannot. Every hard decision\n> in this document is really the question *\"what am I willing to be permanently\n> responsible for?\"* — and the languages people love and the languages people resent are\n> distinguished mostly by how carefully their designers answered it early.\n\n---\n\n## §0. Routing\n\n### 0.1 The pipeline\n\n```\nSOURCE TEXT\n  │  LEXER ─────────── tokens (+ trivia, spans)                            §2\n  │  PARSER ────────── CST\u002FAST (+ error recovery)                          §2\n  ▼\nFRONT END\n  │  NAME RESOLUTION ─ bind identifiers to declarations; modules, scopes   §3\n  │  TYPE CHECKING ─── inference, coercion, trait\u002Fclass resolution         §4\n  │  SEMANTIC ANALYSIS ─ borrow\u002Feffect\u002Fexhaustiveness\u002Fdefinite-assignment  §4.7\n  ▼\nMIDDLE END\n  │  LOWER to IR ───── SSA \u002F CPS \u002F ANF; desugar; monomorphize              §5\n  │  OPTIMIZE ──────── inline, constant-fold, DCE, GVN, LICM, vectorize    §6\n  ▼\nBACK END\n  │  INSTRUCTION SELECTION ─ IR → target instructions                      §7\n  │  REGISTER ALLOCATION ─── virtual → physical registers                  §7.3\n  │  SCHEDULING \u002F EMISSION ─ object code, debug info                       §7\n  ▼\nRUNTIME + LINK ───── GC, scheduler, FFI, unwinding, dynamic loading        §8\n```\n\n**[DURABLE] The two most consequential structural decisions are made before you write a\nline of the pipeline:**\n1. **What is your IR, and how many do you have?** (§5 → `language-irs-optimization-and-backends`) Every serious compiler ends up with\n   at least three levels. Deciding this late means rewriting everything.\n2. **Is the front end reusable by an IDE?** (§11 → `language-diagnostics-tooling-and-evolution`) A compiler designed as a batch\n   source-to-binary pipeline cannot be turned into a responsive language server without\n   substantial rearchitecture. Design for incrementality from day one or accept that you\n   will do it twice.\n\n### 0.2 The question router\n\n| Asked about... | Go to |\n|---|---|\n| Should this be a language at all? Design philosophy, trade-offs | §1 |\n| Lexing, parsing, grammars, error recovery, syntax design | §2 |\n| Scopes, modules, imports, name resolution | §3 |\n| Type systems, inference, generics, traits, effects, ownership | §4 |\n| IR design — SSA, CPS, ANF, MLIR, lowering | §5 → `language-irs-optimization-and-backends` |\n| Optimization passes and where they belong | §6 → `language-irs-optimization-and-backends` |\n| Code generation, instruction selection, register allocation, backends | §7 → `language-irs-optimization-and-backends` |\n| Runtime: memory management, GC, concurrency, FFI, exceptions | §8 → `language-runtimes-interpreters-and-jits` |\n| Interpreters, bytecode VMs, JIT | §9 → `language-runtimes-interpreters-and-jits` |\n| Error messages and diagnostics | §10 → `language-diagnostics-tooling-and-evolution` |\n| Incremental compilation, IDE, LSP | §11 → `language-diagnostics-tooling-and-evolution` |\n| Testing, fuzzing, formal verification | §12 → `language-diagnostics-tooling-and-evolution` |\n| Standard library, ecosystem, tooling | §13 → `language-diagnostics-tooling-and-evolution` |\n| Evolution, versioning, governance, deprecation | §14 → `language-diagnostics-tooling-and-evolution` |\n| \"Don't do this\" | §15 → `language-development-reference` |\n| \"Which approach is better?\" | §16 → `language-development-reference` (contested) |\n| \"Is this still current?\" | §17 → `language-development-reference` |\n| Books, papers, people | §18 → `language-development-reference` |\n\n---\n\n## §1. Language Design\n\n### 1.1 The questions that determine everything else\n\nAnswer these before implementation; each one propagates through the whole pipeline.\n\n| Question | Options | Downstream consequences |\n|---|---|---|\n| **Static or dynamic typing?** | Static, dynamic, gradual | Determines whether the type checker is a phase or a runtime |\n| **Memory management?** | Manual, RAII\u002Fownership, refcount, tracing GC, region\u002Farena | The single largest runtime-design driver (§8.1 → `language-runtimes-interpreters-and-jits`) |\n| **Compiled or interpreted?** | AOT, JIT, bytecode VM, tree-walk, transpile | Determines the whole back end |\n| **Generics: monomorphize or erase?** | Monomorphize (C++, Rust), erase (Java, Go pre-1.18), dictionary-pass (Haskell, Swift) | Code size vs. compile time vs. runtime cost (§4.5) |\n| **Concurrency model?** | Threads+locks, async\u002Fawait, actors, CSP, STM, structured concurrency | Colours your entire function type system (§8.3 → `language-runtimes-interpreters-and-jits`) |\n| **Mutability default?** | Mutable, immutable, controlled | Affects optimization opportunity enormously |\n| **Nullability?** | Nullable-by-default, option types, non-null-by-default | Tony Hoare's \"billion-dollar mistake.\" Option types are the settled answer for new languages |\n| **Error handling?** | Exceptions, result types, error returns, panics | Interacts with every ABI and FFI decision (§8.4 → `language-runtimes-interpreters-and-jits`) |\n| **Metaprogramming?** | None, macros (hygienic or not), reflection, compile-time execution, templates | Determines whether your compiler is also an interpreter (§4.8) |\n\n### 1.2 The design principles that hold up\n\n- **[DURABLE] Simplicity is a budget, not a virtue.** You get a fixed complexity budget;\n  every feature spends it. The question is never \"is this feature good?\" but \"is this\n  feature worth what it costs in interaction with everything else?\" Feature *interactions*\n  are superlinear, which is why languages get harder to learn faster than they get bigger.\n- **Orthogonality**: features should compose without special cases. Every special case is\n  a thing to learn, a thing to implement, and a source of bugs at the seams.\n- **The principle of least astonishment** applies to *the population you're targeting*, not\n  to language theorists.\n- **Make the right thing easy and the wrong thing hard.** Rust's success is mostly this\n  principle applied to memory.\n- **Errors should be impossible, then caught at compile time, then caught at runtime, then\n  documented — in that order of preference.**\n- **[CONTESTED] \"Worse is Better\" (Richard Gabriel, 1989)** — the New Jersey school\n  (simplicity of *implementation* beats completeness; ship it) versus the MIT\u002FStanford\n  school (correctness and completeness first). C and Unix won with the first; the second\n  produced better artifacts that fewer people used. This tension is unresolved and shows\n  up in every language committee.\n- **Hyrum's Law**: with enough users, every observable behaviour of your implementation\n  becomes a promise, whether or not you specified it. **Specify aggressively, and\n  deliberately randomize what you refuse to promise** (Go randomizes map iteration order\n  precisely to prevent people depending on it — a technique worth stealing).\n\n### 1.3 Syntax\n\n**[DURABLE] Syntax is the least important part of a language and the part people argue\nabout most.** That said, it is the interface, and interfaces matter:\n- **Familiarity has enormous value.** Jakob's Law applies to languages: users arrive with\n  expectations from every other language they know. Novel syntax is a tax paid on every\n  reader forever, and it should buy something real.\n- **Readability > writability.** Code is read far more than written. Perl and APL optimized\n  the wrong one.\n- **Prefer unambiguous grammars.** If your grammar needs unbounded lookahead or a \"lexer\n  hack,\" your tooling — formatters, highlighters, IDEs, other implementations — will\n  suffer forever. C's `(a)*b` ambiguity (cast or multiply? depends on whether `a` is a\n  type) is the canonical example.\n- **Design for tooling from the start**: a formatter, a syntax highlighter, and an IDE all\n  want a *lossless* CST with trivia preserved (§2.4).\n\n> **⚠️ GOTCHA — significant whitespace and tabs.** If you choose indentation-sensitive\n> syntax, you must specify the tab\u002Fspace interaction exactly, at the lexer level, in\n> version one. Python took until Python 3 to make mixing an error, and it caused real bugs\n> for a decade.\n\n> **⚠️ GOTCHA — reserve keywords generously.** Adding a keyword later breaks every program\n> using it as an identifier. Languages handle this with contextual keywords (complexity),\n> editions (Rust — §14.2 → `language-diagnostics-tooling-and-evolution`), or just breaking people. Reserve more than you need on day one.\n\n---\n\n## §2. Lexing and Parsing\n\n### 2.1 Lexing\n\nConvert characters to tokens. The parts people underestimate:\n- **Unicode.** Identifiers (UAX #31), normalization (NFC — decide and enforce it, or `é`\n  and `é` are different identifiers), and **bidirectional-override characters, which are a\n  security issue**: the \"Trojan Source\" attack uses them to make source read differently\n  to a human than to the compiler. Reject or warn on bidi control characters in source.\n- **Spans\u002Flocations on every token.** Byte offsets plus a line-index side table is the\n  standard efficient design — computing line\u002Fcolumn lazily from a precomputed line table\n  beats tracking it per character.\n- **Trivia** (whitespace, comments) — either preserve them attached to tokens or you cannot\n  build a formatter or a lossless refactoring tool later (§2.4).\n- **Interpolated strings, raw strings, and nested comments** are where hand-written lexers\n  earn their keep; regex-based lexer generators struggle with them.\n\n### 2.2 Parsing — choosing an approach\n\n| Approach | Notes |\n|---|---|\n| **Recursive descent + Pratt** | **The overwhelming choice of production compilers** (GCC, Clang, rustc, Go, TypeScript, V8). Hand-written, readable, arbitrary lookahead, and — decisively — *excellent error recovery and error messages* |\n| LL(k) generators (ANTLR) | Good tooling, good for DSLs; less control over errors |\n| LALR generators (yacc\u002Fbison) | Compact, fast; conflicts are famously painful to debug; poor error messages |\n| GLR \u002F Earley | Handle ambiguous grammars; slower; useful for language *research* and for parsing C++ |\n| PEG \u002F packrat | Unambiguous by construction (ordered choice), linear with memoization; **ordered choice silently hides ambiguity, which is a footgun** |\n| Combinators | Elegant, great for prototypes; error messages and performance need work |\n\n**[DURABLE] Essentially every widely-used production compiler uses hand-written recursive\ndescent, and the reason is error recovery.** A generated parser gives up or produces a\ngeneric message; a hand-written one can say \"you forgot a semicolon here\" and continue.\nSince the parser's output feeds an IDE that sees broken code 100% of the time, this is not\na minor consideration.\n\n**Pratt parsing (top-down operator precedence)** is the right technique for expressions:\neach token gets a binding power, and precedence and associativity fall out of comparing\nthem. It's about 50 lines and handles prefix, infix, postfix, and mixfix cleanly.\n\n### 2.3 Error recovery\n\n**[DURABLE] The parser's job is not to reject bad programs. It is to produce a usable tree\nfrom bad programs**, because that is the input it receives most of the time.\n- **Error nodes \u002F poison nodes**: represent \"something was here but it was wrong\" in the\n  tree so later phases can continue and produce *their* errors too.\n- **Panic-mode recovery with synchronization tokens**: on error, skip to the next `;`, `}`,\n  or start-of-declaration and resume.\n- **Insertion\u002Fdeletion repair**: hypothesize a missing token and continue.\n- **Never cascade.** One missing brace producing 400 errors is the classic failure. Suppress\n  errors within a short distance of a previous one, and suppress errors *derived from*\n  poison nodes.\n\n### 2.4 CST vs. AST\n\n- **CST (concrete syntax tree)**: every token, every space, every comment. Required for\n  formatters, refactoring tools, and IDEs. Rust-analyzer's **rowan** and the\n  **Roslyn** \"red-green tree\" design are the reference implementations: a persistent,\n  immutable \"green\" tree of shared nodes plus a lightweight \"red\" layer providing parent\n  pointers and absolute positions.\n- **AST**: semantic structure, trivia discarded.\n- **[DURABLE] Build the CST and derive the AST from it.** Going the other direction is\n  impossible. This is the single most common regret in compiler front-end design, because\n  the IDE requirement always arrives later than the compiler requirement.\n\n---\n\n## §3. Names, Scopes, and Modules\n\n### 3.1 Name resolution\n\nBind every identifier to a declaration. Sounds simple; is not.\n- **Scoping**: lexical (almost always correct) vs. dynamic (almost always a mistake).\n- **Shadowing**: allowed, warned, or forbidden. Rust allows and uses it heavily; many\n  languages warn.\n- **Forward references**: can a function call something declared later? At top level,\n  usually yes (requiring a separate declaration-collection pass); inside a block, usually\n  no. **This decision determines whether name resolution is one pass or two.**\n- **Namespaces**: are types, values, macros, and labels in the same namespace? (C has\n  separate struct\u002Fordinary namespaces; Rust separates types and values; Lisp-2 vs. Lisp-1\n  is the oldest version of this argument.)\n- **Overloading** multiplies resolution complexity by type checking — now name resolution\n  and type checking are mutually dependent, and you may need to interleave them.\n\n### 3.2 Modules\n\n**[DURABLE] Module systems are where languages accrete the most regret**, because module\nsemantics touch compilation units, linking, versioning, packaging, and the file system all\nat once. The decisions:\n\n| Decision | Options |\n|---|---|\n| Unit of modularity | File, directory, explicit declaration, package |\n| Import granularity | Whole module, selected names, glob |\n| Visibility | Public\u002Fprivate, `pub(crate)`-style graded, explicit export lists |\n| Cyclic imports | Allowed (complicates compilation order), forbidden (simplifies everything) |\n| Name-to-file mapping | Implicit (Java, Python) or explicit (Rust `mod`, C++ modules) |\n| Separate compilation | Per-file, per-module, per-package, whole-program |\n\n**[DURABLE] Forbid cyclic module dependencies if you possibly can.** They force\nwhole-program analysis, complicate incremental compilation, and are almost always a design\nsmell in user code. Go forbids them; the ecosystem is measurably healthier for it.\n\n> **⚠️ GOTCHA — C++ modules are the cautionary tale.** Standardized in C++20; **GCC 16.1\n> (April 2026) still describes its C++20 modules support as experimental, requiring\n> `-fmodules`.** Six years from standardization to \"still experimental\" in a major\n> implementation is what happens when a module system must interoperate with a\n> textual-inclusion legacy. **Design modules before you have a legacy, not after.**\n\n---\n\n## §4. Type Systems\n\n### 4.1 The design space\n\n| Axis | Options |\n|---|---|\n| Checked when | Static, dynamic, gradual, optional |\n| Inference | None, local, bidirectional, global (HM) |\n| Polymorphism | Parametric (generics), ad-hoc (overloading\u002Ftraits), subtype, row |\n| Subtyping | None, nominal, structural, both |\n| Variance | Invariant, co\u002Fcontravariant, declaration-site or use-site |\n| Higher-kinded | No, yes (Haskell, Scala) |\n| Dependent | No, limited (const generics, refinement), full (Idris, Lean, Agda) |\n| Effects | Implicit, checked exceptions, monadic, algebraic effect handlers |\n| Linearity | None, affine (Rust ownership), linear, uniqueness |\n\n### 4.2 Inference\n\n**Hindley–Milner (Algorithm W)** — full inference for the let-polymorphic lambda calculus.\nUnification-based, principal types, and no annotations required anywhere. The catch:\n**HM does not survive contact with subtyping, higher-rank types, or type classes without\nsignificant extension**, and its error messages are notoriously bad — unification fails at\nsome arbitrary point far from the actual mistake.\n\n**Bidirectional type checking** — the modern default. Split into two mutually recursive\njudgments: *checking* (`Γ ⊢ e ⇐ T`, \"does `e` have type `T`?\") and *synthesis*\n(`Γ ⊢ e ⇒ T`, \"what type does `e` have?\"). Annotations at the boundaries.\n- **Why it won**: it scales to subtyping, higher-rank polymorphism, dependent types, and\n  GADTs, where HM does not; it needs fewer annotations than you'd think; and — the reason\n  practitioners care — **error messages are dramatically better**, because when checking\n  fails you know the *expected* type and can report both sides.\n- Used in some form by Rust, Swift, TypeScript, Scala 3, Agda, Idris.\n\n**Local type inference** (C#, Java, Go, C++ `auto`) — infer variable types from\ninitializers and generic instantiations from arguments; require annotations on function\nsignatures. **[DURABLE] Requiring signature annotations is a feature, not a limitation**:\nit makes the code self-documenting, keeps errors local, makes separate compilation\ntractable, and makes the IDE's job possible.\n\n> **⚠️ GOTCHA — global inference and error locality are in direct tension.** With full\n> inference, an error in one function can surface as a type error in an unrelated one.\n> Every language with global inference eventually adds a \"please annotate your top-level\n> definitions\" lint. Consider just requiring them.\n\n### 4.3 Unification and the occurs check\n\n```\nunify(a, b):\n  a, b = resolve(a), resolve(b)          # follow substitutions (union-find)\n  match (a, b):\n    (Var x, Var y) if x == y  -> ok\n    (Var x, t) | (t, Var x)   -> occurs_check(x, t); bind(x, t)   ← DON'T SKIP THIS\n    (Con(c1, as), Con(c2, bs)) if c1 == c2 && len equal -> zip-unify\n    _                          -> type error (report BOTH sides and the location)\n```\n**The occurs check** prevents binding `x := List\u003Cx>`, which creates an infinite type. Skip\nit and your compiler hangs or stack-overflows on a program like `let f = fun x -> x x`.\nUse **union-find with path compression** for the substitution or unification is\naccidentally quadratic.\n\n**Levels\u002Franks for generalization**: the naive \"generalize all free variables not in the\nenvironment\" is O(n) in environment size at every `let`. The standard fix is Rémy's\nlevel-based generalization — tag each type variable with the `let`-depth at which it was\ncreated and generalize only those deeper than the current level. Every efficient HM\nimplementation does this.\n\n### 4.4 Traits, type classes, and interfaces\n\nThe mechanism for ad-hoc polymorphism, and it comes in three flavours:\n- **Nominal interfaces** (Java, C#): a type explicitly declares it implements an interface.\n  Simple, but you cannot retrofit an interface onto a type you don't own.\n- **Structural** (Go, TypeScript): if it has the methods, it satisfies the interface. Fixes\n  retrofitting; loses the ability to distinguish two interfaces with the same shape and\n  different meaning.\n- **Type classes \u002F traits** (Haskell, Rust, Swift): implementations are declared\n  *separately* from both the type and the interface. Solves retrofitting *and* keeps\n  nominality — at the cost of needing **coherence** rules.\n\n**Coherence and the orphan rule.** If two crates can both implement `Trait` for `Type`,\nwhich one applies? Incoherence breaks type-directed dispatch and can break soundness.\nHaskell and Rust enforce coherence via the **orphan rule**: you may implement a trait for\na type only if you own the trait or the type. It is the single most-complained-about rule\nin Rust and it is load-bearing.\n\n**Implementation strategies**: dictionary passing (pass a vtable of the implementation —\nHaskell, Swift), monomorphization (generate a specialized copy — Rust static dispatch), or\nvtables at runtime (`dyn Trait`, Go interfaces).\n\n**⚠️ Trait resolution is a solver, and solvers have performance and termination problems.**\nRust's trait system is expressive enough that resolution can loop or blow up exponentially.\n**[VERSIONED]** rustc has been building a **next-generation trait solver** for years\nprecisely to fix long-standing soundness bugs, unblock features (implied bounds, negative\nimpls), and improve compile times; it reached production use in coherence checking and, as\nof 2026, stabilization work continues alongside **Polonius** (the next-generation borrow\nchecker). The lesson for a language designer: **an expressive trait\u002Finstance-resolution\nsystem is a Prolog interpreter in your compiler. Budget accordingly.**\n\n### 4.5 Generics: monomorphize or erase?\n\n**[CONTESTED, and one of the genuinely load-bearing decisions.]**\n\n| | **Monomorphization** (C++, Rust) | **Erasure \u002F dictionaries** (Java, Haskell, Swift) |\n|---|---|---|\n| Runtime cost | **Zero** — specialized code, inlinable | Indirection: boxing, vtables, dictionaries |\n| Code size | **Explodes** — one copy per instantiation | One copy |\n| Compile time | **Slow** — the dominant cost in large Rust and C++ builds | Fast |\n| Separate compilation | Hard — need the generic body available | Clean |\n| Reflection on type args | Available | Erased (Java's `List\u003CT>` doesn't know `T` at runtime) |\n| Error messages | Instantiation-time errors, often terrible (C++ templates pre-concepts) | Declaration-time errors |\n\nGo's 1.18 generics chose a **middle path (GC shape stenciling)**: monomorphize by\n*representation class* rather than by exact type, so all pointer-shaped types share one\ninstantiation. This bounds code growth while keeping most of the performance.\n\n**[DURABLE] Whichever you choose, define errors at the *declaration* site.** C++ templates\nfamously deferred all checking to instantiation, producing the pathological error messages\nthat concepts (C++20) exist to fix. Rust's trait bounds check the generic body against its\nbounds up front. This is worth real implementation effort.\n\n### 4.6 Ownership, borrowing, and linearity\n\nRust's contribution is proving that **affine types plus region inference can eliminate\nmemory-safety bugs at compile time with no runtime cost**, in a language people actually\nship. The machinery:\n- **Ownership**: each value has one owner; drop at scope end (RAII).\n- **Borrowing**: `&T` (shared, many) \u002F `&mut T` (unique, one). The XOR rule — aliasing xor\n  mutation — is what makes the whole thing sound *and* is what makes it hard to learn.\n- **Lifetimes**: regions inferred by the borrow checker; annotations only where inference\n  can't decide.\n\n**[VERSIONED] NLL (non-lexical lifetimes) shipped in 2018; Polonius** is the next-generation\nformulation, designed to accept currently-rejected patterns (notably \"lending iterators\").\nRust's own 2026 project-goal updates describe an \"alpha\" Polonius being tested on CI\nalongside the next-gen trait solver, with worst-case slowdowns still being tracked. **The\nhonest read: borrow checking is a research area with a shipped product on top of it, and\nthe shipped product's rules are still being refined eight years in.**\n\n**Alternatives worth knowing**: linear types (must use exactly once — Linear Haskell),\nuniqueness types (Clean), region\u002Farena inference (MLKit, Cyclone — the direct ancestor of\nRust's design), and Swift's ARC with `~Copyable`\u002Fborrowing annotations retrofitted.\n\n### 4.7 The other static analyses\n\nThese aren't \"type checking\" but live in the same phase and are equally load-bearing:\n- **Exhaustiveness checking for pattern matching.** [DURABLE] **This is one of the highest\n  value-per-implementation-effort features in language design.** Maranget's algorithm\n  (\"Warnings for pattern matching,\" 2007) is the standard reference and is genuinely\n  implementable in a few hundred lines. It converts a whole class of runtime bugs into\n  compile errors and it is what makes sum types pleasant instead of tedious.\n- **Definite assignment** — is this variable initialized on every path?\n- **Reachability \u002F dead code**, **unused variables and imports**.\n- **Effect checking** (§4.9).\n\n### 4.8 Compile-time execution and metaprogramming\n\nThe spectrum, in increasing order of power and danger:\n1. **Constant folding** — the compiler evaluates `2+2`.\n2. **`constexpr`\u002F`comptime`** — arbitrary evaluation at compile time (C++, **Zig's\n   `comptime`**, which is also how Zig does generics).\n3. **Hygienic macros** — syntax-to-syntax transforms that respect scope (Scheme, Rust).\n4. **Procedural macros \u002F compiler plugins** — arbitrary code running in the compiler.\n5. **Full reflection** — programs inspecting and generating themselves.\n\n**[VERSIONED, and a genuinely big deal] C++26 shipped static reflection**, which Herb\nSutter called \"the biggest upgrade since templates\" and \"C++'s decade-defining rocket\nengine.\" **The ISO committee completed technical work on C++26 on 28 March 2026** in\nLondon; the headline features are **static reflection, contracts, `std::execution`\n(sender\u002Freceiver), and a hardened standard library**. **GCC 16.1 (30 April 2026) already\nships reflection and contracts.** Note the syntax churn as a lesson: the reflection\noperator changed from `^` to `^^` during standardization, so early adopter code needed\nmigration.\n\n> **⚠️ GOTCHA — compile-time execution means your compiler contains an interpreter, and\n> that interpreter is a security boundary and a performance cliff.** You need: a step\n> limit (or programs won't terminate), determinism (or builds aren't reproducible), a\n> decision about whether it can do I\u002FO (**it should not**), and an answer for what it means\n> to debug it. Zig's community discussions consistently name `comptime` as both its best\n> feature and a significant pain point — that's the shape of this trade-off.\n\n### 4.9 Effects\n\nAn active research frontier that is reaching production:\n- **Checked exceptions** (Java) — the first mainstream effect system, and widely considered\n  a partial failure because it lacked polymorphism: you couldn't write a higher-order\n  function generic over what its argument throws.\n- **Monadic effects** (Haskell) — expressive, composes badly (monad transformers).\n- **Algebraic effects and handlers** (Koka, Eff, OCaml 5's effect handlers) — the current\n  best answer. Effects are operations; handlers interpret them. This is what makes OCaml 5's\n  concurrency work without colouring functions.\n- **Function colouring** (§8.3 → `language-runtimes-interpreters-and-jits`): async\u002Fawait is an *ad-hoc, unprincipled effect system*.\n  This is the strongest argument for doing effects properly.\n",{"name":5,"description":7},"develop","ae32736a1aabddabca5d2c96d665aa0ebc7d8700","src\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fprogramming-language-development\u002Fskills\u002Flanguage-design-parsing-and-types",3,"https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey","https:\u002F\u002Fthe-vibey-project.github.io\u002Fvibey\u002F","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project","https:\u002F\u002Fvibewithadam.matthewsteinberger.com","freedom for software engineers","2026-11-15 05:47:42",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add the-vibey-project\u002Fvibey --skill language-design-parsing-and-types",{"tool":40,"command":41},"bunx","bunx skills add the-vibey-project\u002Fvibey --skill language-design-parsing-and-types",{"tool":43,"command":44},"pnpm","pnpm dlx skills add the-vibey-project\u002Fvibey --skill language-design-parsing-and-types","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fprogramming-language-development\u002Fskills\u002Flanguage-design-parsing-and-types\u002FSKILL.md",true,[],[49,56,63,70,77,84],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":19},"01M7AT1FQJAE1FQYAMDTF490Y4","white-paper-writing","Use when writing white papers, technical reports, policy documents, thought leadership pieces, or any long-form authoritative document. Triggers on requests to write, structure, outline, or review white papers, technical reports, position papers, policy briefs, or evidence-driven arguments. Also use for B2B content marketing strategy, technical documentation requiring authority, academic-style reports, or any document that must educate while persuading. Use when someone asks \"how should I structure this\" for a long-form document.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Fwhite-paper-writing\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":59,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":60,"categories":61,"keywords":62,"publishedAt":19},"01M7AT16BJRJJKK2MASXRZS76G","prose-technical-mechanics","Use when editing or writing prose at a technical\u002Fmechanical level: choosing between Anglo-Saxon and Latinate diction, placing information in topic vs stress positions, writing periodic vs cumulative sentences, handling sentence rhythm, punctuation as logic, transitions, paragraph structure, or phonesthetics. Use when someone wants to understand WHY prose works or doesn't, not just surface-level style advice. Triggers on word choice, sentence structure, emphasis, rhythm, diction, or any deep writing mechanics question.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Fprose-technical-mechanics\u002FSKILL.md",[],[],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":19},"01M7AT0W9HT0ZZ9Y287NW99MR3","prose-mechanics","Use when writing, editing, or analyzing prose style; when trying to avoid generic AI-sounding writing; when applying specific prose styles such as journalistic, academic, narrative, KJV biblical, Hemingway plain, Latinate\u002FJamesian, Orwellian, Augustan, Victorian, Early Modern (Bacon, Browne, Milton), or free indirect discourse; or when coaching someone on writing voice and mechanics. Triggers on any request to improve, analyze, or write in a specific prose style, to fix \"AI-sounding\" writing, to make prose more vivid or concrete, to vary sentence rhythm, or to understand how a particular writer achieves their effects.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Fprose-mechanics\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M7AT0KR635JX66X2X6F3E2CP","narrative-structure","Use when structuring stories, pitches, presentations, white papers, or any persuasive narrative; analyzing the hero's journey in fiction or non-fiction; applying StoryBrand for business communication; designing narrative arcs for thought leadership; or understanding Vogler, Snyder, Propp, or Campbell frameworks. Triggers on any narrative structure, storytelling, pitch structure, StoryBrand, hero's journey, three-act structure, Freytag, Save the Cat, narrative arc, or \"how should I structure this story\u002Fpitch\u002Fpresentation\" request.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Fnarrative-structure\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":19},"01M7AT0AKGW09NKKZDYBT8VRDE","legal-brief-writing","Use when writing legal briefs, motions, or any court filing; when analyzing judicial cognition and persuasion; when applying elite brief-writing techniques from Roberts, Clement, Kagan, Garner; or when structuring legal arguments for maximum persuasion. Also use for autistic\u002Fneurodivergent advocates who need to understand how their natural communication style maps to elite legal advocacy. Triggers on any legal writing, brief drafting, motion preparation, or legal argument structuring request.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Flegal-brief-writing\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M7AT00VWPS4Q8B5VEMXX9NQT","journal-publishability-criteria","Use whenever a research paper, article or preprint is being written, revised, reviewed or published, and specifically before every publication of docs\u002Fpaper.md. Covers what legitimate journals actually gate on, in order of gating — the editor's desk screen (scope, novelty, package problems), what reviewers judge (methodological soundness, claims the evidence can carry, statistical and qualitative reporting), EQUATOR reporting guidelines, the ICMJE authorship criteria, COPE's view of text recycling, the near-universal generative-AI policy (no AI author, disclosure, author responsibility), TOP 2025 transparency standards, how to verify a journal is legitimate, submitting without an institution, and a pre-submission checklist. Triggers on requests to evaluate, review, prepare or submit a paper, to judge publishability, to write a declarations or data-availability section, to disclose AI use, or to check a journal.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Fjournal-publishability-criteria\u002FSKILL.md",[],[]]