agentleFS
gepheumgepheum/skir/skills/add-language/SKILL.md

add-language

Skill319 starsChanged 6 months agoMITView on GitHub

Complete architectural guide, wire-format specification, design decision matrix, bug prevention checklist, and monorepo integration runbook for adding support for a new programming language (code generator + runtime client library + E2E/golden tests + example + docs) to Skir. Activate this skill whenever creating, auditing, or extending a Skir language code generator or runtime client library.

7 other projects use a version of this.

Adopted by

Most recently taken up by

  • Other versions7 projects use a version of this.

    Word for word · 0

    None found.

    Edited · 0

    None found.

    Wrote their own version · 7

    1. ZoneMinder/zmNinjaNg★ 104same name
    2. DailybotHQ/deepworkplan-website★ 16same name
    3. madeinoz67/madeinoz-knowledge-system★ 3same name
    4. ku5ic/claude-kit★ 2same name
    5. GeoffMillerAZ/fathom★ 1same name
    6. Locker-Room-Tools/synapse★ 1same name
    7. Phygital-Brain/phygital-brain★ 1same name

    How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.

  • In this repositoryOne other file it gives its agents.

The file

Show its rules and text

We split this skill into the rules it gives an agent

64 rules. 0 are common, 6 are distinctive, and 58 are very specific to this project.

  • 0

    Common

    Most of the 6 edited versions we read keep these.

  • 6

    Distinctive

    This author's own choices. Worth a look.

  • 58

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Wait: collisions *can* still happen after case conversion or suffixing in target languages!

    line 65
  2. Very specific:

    Every intermediate step in type.key.path is guaranteed to be a non-optional, non-recursive (field.isRecursive !== "hard") struct field …

    line 71
  3. Distinctive:

    Before writing a new generator, answer these 9 design questions for the target language:

    line 88
  4. Very specific:

    Collision Warning for Flattened Names: If struct Foo_Bar exists at top-level and struct Foo { struct Bar } is nested, or if an enum Status …

    line 110
  5. Very specific:

    Every generated Skir struct must support:

    line 114
  6. Very specific:

    Every Skir enum has:

    line 136
  7. Very specific:

    Never make Kind a raw string or int!: When Ruby's generator was first created, SubscriptionStatus::Kind::FREE was just the plain …

    line 148
  8. Very specific:

    When a wrapper variant wraps a struct (e.g., trial: struct { start_time: timestamp.

    line 151
  9. Very specific:

    Every Skir struct and enum represents a value, not an object identity.

    line 154
  10. Very specific:

    When field.isRecursive === "hard", RecA.DEFAULT.a is RecA.DEFAULT.

    line 166
  11. Very specific:

    If hashCode or equals reads this.a, calling RecA.DEFAULT.hashCode evaluates this.a $\rightarrow$ RecA.DEFAULT $\rightarrow$ …

    line 182
  12. Very specific:

    Every language's runtime client library must implement these exact rules to pass @gepheum/skir-golden-tests.

    line 194
  13. Very specific:

    JSON Decoding: If JSON token is null $\rightarrow$ None.

    line 225
  14. Very specific:

    When deserializing "0" or wire byte 0 as bool?, fromJson and decode must return Some(false)—NEVER check if (inner.isDefault(result)) return …

    line 235
  15. Very specific:

    If s._unrecognized is present and matches the target format (Dense JSON for Dense JSON output.

    line 254
  16. Very specific:

    All known fields in 0 ..< record.numSlots are encoded (even if default, because non-default unrecognized fields follow them!), removed …

    line 255
  17. Very specific:

    If no field is non-default, activeSlots = 0 (encodes as [] in Dense JSON, {} in Readable JSON, wire 246 in Binary).

    line 258
  18. Very specific:

    Wait: what if a schema had removed numbers at the end (e.g.

    line 262
  19. Very specific:

    If keepUnrecognizedValues == false, simply skip any slots $\ge \text{numSlots}$ without storing them.

    line 264
  20. Very specific:

    If 1 <= variant.number <= 4 $\rightarrow$ single wire byte 250 + variant.number (251, 252, 253, or 254) + payloadAdapter.encode(e.value).

    line 283
  21. Very specific:

    If variant.number >= 5 $\rightarrow$ wire byte 248 (0xF8) + encodeInt32(variant.number) + payloadAdapter.encode(e.value).

    line 284
  22. Very specific:

    If num == 0 or "unknown" / "UNKNOWN" $\rightarrow$ E.UNKNOWN.

    line 287
  23. Very specific:

    If num is in removedNumbers $\rightarrow$ E.UNKNOWN (do not keep as unrecognized!).

    line 288
  24. Very specific:

    If num (or "name", accepting both lower_case and UPPER_CASE for constant variants) matches a constant variant $\rightarrow$ return that …

    line 289
  25. Very specific:

    If num (or "name") matches a wrapper variant (schema evolved from constant to wrapper!) $\rightarrow$ decode/construct the wrapper variant …

    line 290
  26. Very specific:

    If num is unrecognized: if keepUnrecognizedValues is true (and input is Dense JSON or Binary), return E.UNKNOWN wrapping the raw JSON/bytes.

    line 291
  27. Very specific:

    If num is in removedNumbers $\rightarrow$ in Binary, skip the payload value (skipValue(stream)) so the stream position stays valid, and …

    line 293
  28. Very specific:

    If num (or name) matches a wrapper variant $\rightarrow$ decode val with payloadAdapter (passing keepUnrecognizedValues) and wrap it.

    line 294
  29. Very specific:

    If num matches a constant variant (schema evolved from wrapper to constant!) $\rightarrow$ in Binary, skip the payload value …

    line 296
  30. Very specific:

    If num is unrecognized: in Binary, slice the raw bytes of the wire tag + number + skipped payload value.

    line 297
  31. Distinctive:

    When skipping an unrecognized struct field or a removed/unrecognized enum wrapper payload in binary:

    line 300
  32. Very specific:

    Every Serializer<T> exposes .typeDescriptor returning a TypeDescriptor that can be serialized to pretty-printed JSON (2-space indentation) …

    line 316
  33. Very specific:

    Consider enum JsonValue in enums.skir, which has array: [JsonValue] and object: [JsonValue.Pair|name] where struct Pair has value: …

    line 352
  34. Very specific:

    When collecting the "records" list for TypeDescriptor, do not only check direct self-recursion (vType.key === currentRecord.key)!

    line 353
  35. Very specific:

    Instead, traverse record dependencies using a visited: Set<string> of record IDs:

    line 354
  36. Very specific:

    Before recursing into a struct's fields or an enum's wrapper variant types, check if (visited.has(recordId)) return;, add recordId to …

    line 355
  37. Very specific:

    Ensure that both RecA and RecB appear in "records" when RecA.serializer.typeDescriptor is inspected.

    line 356
  38. Very specific:

    Every runtime client library implements Method<Req, Resp>, Service<Meta>, and ServiceClient:

    line 362
  39. Very specific:

    If "method" is an integer (or numeric string), look up by number.

    line 379
  40. Very specific:

    If response status is 200, parses body with method.responseSerializer.fromJsonCode(respBody).

    line 389
  41. Distinctive:

    Before declaring a new language generator or client library complete, verify every item in this list:

    line 395
  42. Very specific:

    If using a nullable backing field _rec_a with getter a => _rec_a ??

    line 401
  43. Very specific:

    When Recursive<T> has no value (!HasValue), emit "[]" / "{}" / wire 246 directly.

    line 403
  44. Very specific:

    Never bind local variables inside generated serializer/decoder functions using raw unprefixed field names (let ${fieldName}_serializer = ...

    line 407
  45. Very specific:

    If a struct has a field named user in the same module as struct User, let user_serializer = user_serializer() shadows the module-level …

    line 408
  46. Very specific:

    If a struct has a field named arr, bits, keep, stream, offset, json, or slots_to_fill, unprefixed local bindings will shadow the decoder …

    line 409
  47. Very specific:

    If wrapper variants add a Wrapper suffix in KindType (foo: T $\rightarrow$ FooWrapper) while constant variants do not (foo_wrapper.

    line 411
  48. Very specific:

    If an enum is named Kind and its .Kind property is renamed to .Kind_ to avoid colliding with the enclosing class name, ensure Kind_ is …

    line 413
  49. Very specific:

    Always guard if (&other != this) before calling destroy() or freeing buffers in custom operator=.

    line 415
  50. Very specific:

    When unescaping JSON strings containing \u0000, never push an extra C-string '\0' terminator into the middle of a length-delimited …

    line 416
  51. Very specific:

    Rule: When encoding a string to binary (encode / toBytes) or decoding a string from binary (decode / fromBytes), any invalid UTF-8 byte …

    line 420
  52. Very specific:

    When a variant evolved from wrapper to constant, a readable JSON object {"kind": "variant_name", "value": ...} must ignore "value" and …

    line 430
  53. Very specific:

    When isDefault is called on a struct or enum, always verify that _unrecognized is also null/empty (getUnrecognized(value) == null), and …

    line 431
  54. Very specific:

    When adding a new language <lang>, create and update all of the following locations:

    line 437
  55. Very specific:

    Create packages/compiler/src/generators/<lang>/index.ts (plus naming.ts, type_speller.ts, etc.).

    line 440
  56. Very specific:

    Add unit tests in packages/compiler/src/generators/<lang>/index.test.ts.

    line 442
  57. Very specific:

    Create e2e-tests/<lang>/skir.yml referencing @gepheum/skir-fantasy-game-example and the latest @gepheum/skir-golden-tests tag.

    line 446
  58. Very specific:

    Create examples/<lang>/ (skir.yml, skir-src/service.skir, skirout/, snippets, server, client, README.md, .github/workflows/ci.yml).

    line 455
  59. Very specific:

    Add <lang> to .github/workflows/ci.yml and .github/workflows/sync-examples.yml.

    line 456
  60. Very specific:

    Create .github/workflows/publish-client-<lang>.yml (if mirrored to a GitHub repo, use a release_version input with default: "patch", not an …

    line 457
  61. Distinctive:

    Update packages/website/.vitepress/config.mts and

    line 460
  62. Distinctive:

    Update packages/website/public/llms.txt and regenerate

    line 461
  63. Very specific:

    Update README.md and skills/skir/SKILL.md.

    line 462
  64. Very specific:

    Run ./pre_commit.sh --lang <lang> (and full ./pre_commit.sh) and verify zero warnings, zero lint errors, and 100% passing unit, E2E, and …

    line 464

“Common” is measured: kept by at least 6 in 10 of the 6 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Adding a New Programming Language to Skir

This guide contains everything an AI agent needs to design, implement, test, document, and wire up a new programming language target in the Skir monorepo—with zero prior context required.


1. High-Level Architecture of a Language Target

Adding a language <lang> to Skir involves 6 deliverables in the monorepo:

  1. Runtime Client Library (client-libraries/<lang>/)
    • Provides primitive serializers (bool, int32, int64, hash64, float32, float64, timestamp, string, bytes), composite serializers (optional, array / keyed_array, struct, enum, recursive), reflection (TypeDescriptor + JSON serialization/parsing), and SkirRPC (Method, Service, ServiceClient).
    • Note: Languages sharing a virtual machine can share a runtime client library (e.g., Java, Kotlin, and Scala all share client-libraries/kotlin; C# and F# both share client-libraries/csharp).
  2. Code Generator (packages/compiler/src/generators/<lang>/)
    • A TypeScript module inside packages/compiler implementing CodeGenerator<Config> from skir-internal and registered in packages/compiler/src/config_parser.ts under STATIC_GENERATORS["skir-<lang>-gen"].
    • Note: Built-in generators do not need runtime reflection value-transformation capabilities (ReflectiveTransformer / mapFields as in Kotlin/Dart)—only TypeDescriptor metadata (asJson / parseFromJson) is required by the golden tests.
  3. End-to-End & Golden Test Suite (e2e-tests/<lang>/)
    • Compiles all schemas in e2e-tests/<lang>/skir-src/ plus external dependencies @gepheum/skir-fantasy-game-example and @gepheum/skir-golden-tests.
    • Runs every golden test in UNIT_TESTS (goldens.readonly.skir) plus language-specific tests for structs, enums, keyed arrays, recursive types, constants, methods, and Service / ServiceClient.
    • Wired into e2e-tests/format-all.sh, e2e-tests/test.sh, and pre_commit.sh.
  4. Starter Example Project (examples/<lang>/)
    • Self-contained starter project (skir.yml, skir-src/service.skir, skirout/, snippets, start_service, call_service, README.md, .github/workflows/ci.yml), synced to https://github.com/gepheum/skir-<lang>-example via .github/workflows/sync-examples.yml.
  5. Documentation & Website (docs/languages/<lang>.md & packages/website/)
    • Comprehensive user guide in docs/languages/<lang>.md, sidebar & homepage integration in packages/website/, and LLM bundle updates (llms.txt, llms-full.txt, README.md, skills/skir/SKILL.md).
  6. Publishing Workflow (.github/workflows/publish-client-<lang>.yml)
    • Manual workflow_dispatch GitHub Actions workflow that publishes to the language's package registry (npm, PyPI, crates.io, NuGet, Maven Central, Hex.pm, RubyGems, pub.dev) or mirrors client-libraries/<lang> to https://github.com/gepheum/skir-<lang>-client.git with a release_version input (default: "patch").

2. Compiler IR & Invariants (What the Code Generator Can Assume)

Your generator in packages/compiler/src/generators/<lang>/index.ts implements CodeGenerator<Config> from skir-internal (packages/compiler-internal/src/types.ts):

export interface CodeGenerator<Config = unknown> {
  readonly id: string; // e.g. "skir-<lang>-gen"
  readonly configType: z.ZodType<Config>;
  generateCode(input: CodeGenerator.Input<Config>): CodeGenerator.Output;
}

input provides:

  • modules: readonly Module[] — Every .skir module in skir-src/ and skir-external/.
  • recordMap: ReadonlyMap<RecordKey, RecordLocation> — Lookup table from RecordKey to RecordLocation (record, recordAncestors, modulePath).
  • config: Config — Parsed and Zod-validated generator configuration from skir.yml.

Crucial Compiler Guarantees (Do Not Re-Validate or Write Dead Code for These!)

The Skir compiler frontend (packages/compiler/src/module_set.ts) enforces the following invariants before generateCode is ever called:

  1. Strict Casing in .skir Source:
    • Record names (struct and enum) and method names are strictly UpperCamel (PascalCase).
    • Struct field names and enum variant names (both constant and wrapper variants) are strictly lower_underscore (snake_case).
    • Top-level const names are strictly UPPER_UNDERSCORE (UPPER_SNAKE_CASE).
  2. No "unknown" or "UNKNOWN" Enum Variant Names:
    • The Skir compiler forbids naming any enum variant unknown or UNKNOWN.
    • Because every enum implicitly has an unknown variant (field number 0), you never have to worry about a user-defined variant named unknown colliding with the built-in Unknown variant, KindType.Unknown, or Visitor.onUnknown!
  3. Case-Insensitive Uniqueness Within a Scope:
    • Because all fields and variants are enforced lower_underscore (and record names are UpperCamel), a record can never contain both a variant named "FOO" and one named "foo".
    • Wait: collisions can still happen after case conversion or suffixing in target languages! For example:
      • A struct or enum can have a field/variant whose name matches a target-language keyword (if, class, type, match, fn, val, end, whole), a base Object method (equals, hash_code, to_string, clone), a generated class member (default, serializer, kind, unknown, accept, visitor), or an enclosing type name (e.g. a field foo inside struct Foo, or enum Kind).
      • An enum can have a wrapper variant foo: string; and a constant variant foo_wrapper;. If your generator appends Wrapper to wrapper variant names in KindType (e.g. Foo $\rightarrow$ FooWrapper) while converting constant variants to UpperCamel (foo_wrapper $\rightarrow$ FooWrapper), those two will collide unless you disambiguate the constant variant (e.g. FooWrapper_)!
  4. Keyed Array ([Item|key_path]) Path Invariants:
    • In ArrayType, if type.key (FieldPath) is present:
      • type.item is guaranteed to be a struct (ResolvedRecordRef with recordType === "struct").
      • Every intermediate step in type.key.path is guaranteed to be a non-optional, non-recursive (field.isRecursive !== "hard") struct field (kind === "record").
      • The final step in type.key.path is guaranteed to be either a primitive field (type.key.keyType.kind === "primitive") OR .kind on an enum field (type.key.keyType.kind === "record" with recordType === "enum", and the last path item's name.text === "kind").
      • Important Consequence: Both optional (T?) fields and hard recursive (field.isRecursive === "hard") struct fields are rejected by validateArrayKeys in module_set.ts and can never appear anywhere in a keyed-array key path!
      • Because via-optional fields are also optional (T?) at the top level, no recursive indirection (Recursive<T>, Box<T>, or getter unwrapping) or optional unwrapping is ever needed when generating key extractors along type.key.path!
      • The only special case a key-extractor generator must handle along type.key.path is the final .kind accessor (including when the enum itself is named Kind and renames its .Kind property to .Kind_, as in C#).
  5. Recursion Classification (field.isRecursive):
    • false: The field's type does not depend on the enclosing record.
    • "hard": The enclosing struct's default instance (S.DEFAULT) contains S.DEFAULT through this field (direct self-recursion struct A { a: A; } or mutual struct recursion struct A { b: B; } struct B { a: A; } without passing through an array [...], optional T?, or enum).
    • "via-optional": The field's top-level type is T? (optional), T is a struct, and T.DEFAULT reaches S.DEFAULT (e.g. struct Node { next: Node?; }).
    • "soft": Reaches the enclosing record through an array [...] or an enum wrapper variant.
  6. Depth-First Record Ordering in module.records:
    • module.records lists all top-level and nested records in depth-first post-order (Foo.Bar appears before Foo).

3. Core Design Questions & How Existing Languages Answer Them

Before writing a new generator, answer these 9 design questions for the target language:

Q1: Can the language share an existing runtime client library?

  • Yes (Shared VM):
    • JVM (client-libraries/kotlin): Shared by Kotlin, Java, and Scala. The runtime is written in Kotlin with @JvmStatic / @JvmName annotations so Java and Scala call it natively.
    • .NET (client-libraries/csharp): Shared by C# and F#. Serializers.OptionalCustom allows F# to use native F# 'T option (None / Some) instead of C# Nullable<T> while reusing 100% of SkirClient.
  • No (Standalone runtime in client-libraries/<lang>):
    • TypeScript (packages/typescript-client), Python, Ruby, C++, Go, Rust, Dart, Swift, Zig, Gleam, MoonBit, OCaml.

Q2: How should .skir modules map to generated output files?

  • Pattern A: 1 output file per .skir file (foo/bar.skir $\rightarrow$ skirout/foo/bar.<ext>):
    • Used by: TypeScript, Python, Ruby, C++, C#, Dart, Swift, Zig, Gleam, OCaml.
    • External package modules @owner/pkg/foo.skir map to skirout/@owner/pkg/foo.<ext> (or skirout/external/owner/pkg/foo.<ext> in languages where @ or - is illegal in module paths, like Ruby, Python, Go, OCaml).
  • Pattern B: 1 single combined output file (skirout/Skirout.fs, skirout/base.rs, skirout/skirout.mbt):
    • Why F# uses a single skirout/Skirout.fs: F# requires every .fs file to be listed manually in strict dependency order inside .fsproj and forbids circular dependencies across files unless combined via module ... and .... Emitting one topologically sorted skirout/Skirout.fs lets the user add <Compile Include="skirout/Skirout.fs" /> to .fsproj once and never touch .fsproj again when .skir files are added or removed.
    • Why MoonBit uses a single package skirout/: MoonBit compiles all .mbt files in a package directory together into one namespace.

Q3: How should nested records (struct User { struct Pet { ... } }) be represented?

  • True Lexical Nesting (Class/Module inside Class/Module):
    • Used when the language supports nested types inside classes or companion modules: Java (User.Pet), Kotlin (User.Pet), Scala (User.Pet), C++ (user::pet), Python (User.Pet), Ruby (User::Pet), Swift (User.Pet), OCaml (User.Pet), Zig (User.Pet).
  • Flattened Top-Level Types (User_Pet or UserPet):
    • Used when the language does not allow nested types inside struct/record types: C# (User_Pet), F# (User_Pet), Dart (User_Pet), Go (User_Pet), MoonBit (User_Pet), Gleam (UserPet).
    • Collision Warning for Flattened Names: If struct Foo_Bar exists at top-level and struct Foo { struct Bar } is nested, or if an enum Status has a nested struct Trial (StatusTrial) AND a variant constructor StatusTrial(StatusTrial), you must deterministically disambiguate collisions!
      • Example (C#/F#): Escape literal underscores in .skir record names before joining with _, or track used type names in breadth-first depth order (shallowest first) and suffix collisions (e.g., Gleam appends "X" to colliding variant constructors: SubscriptionStatusTrial for the struct, SubscriptionStatusTrialX(SubscriptionStatusTrial) for the variant constructor).

Q4: How should structs be represented (Immutability, Construction, Partial Initialization, and Copying)?

Every generated Skir struct must support:

  1. Deep immutability (or value semantics where let/const bindings cannot be mutated).
  2. A default instance (User.DEFAULT / User.default / User.defaultInstance / user_default) with all fields initialized to their Skir defaults.
  3. Full construction and partial construction (omitted fields default to their Skir defaults).
  4. Non-destructive copying / updating (creating a modified copy from an existing instance).

How existing languages achieve this idiomatically:

  • Languages with built-in record copy / with expressions & optional/default arguments:
    • C#: public readonly record struct User with public required T Field { get; init; } + User.Default. Partial init and updates both use C#'s native with expression: User.Default with { UserId = 42, Name = "John" } and john with { Name = "Jane" }.
    • F#: Immutable F# record { UserId: int64; Name: string; ... } + User.Default + User.Create(?userId, ?name, ...) static method with optional parameters defaulting to Default, plus native { john with Name = "Jane" }.
    • Scala: final case class User(userId: Long = 0L, name: String = "", ...) with default parameters and native .copy(...).
    • OCaml: Immutable record type t = { user_id : int64; name : string; ... } + User.default + User.make ?user_id ?name () + functional update { john with name = "Jane" }.
    • Gleam: Single-constructor custom type pub type User { User(user_id: Int, ...) } + user_new(...) + user_default + native record update User(..user_default, name: "John").
    • Rust / MoonBit / Zig / Swift: Native struct with default constructor/constant and field initializers.
  • Languages using a Frozen Class + Mutable Builder Class (User + User.Mutable):
    • Kotlin, Dart, Python, Ruby, C++:
      • User is deeply immutable (toMutable() returns a shallow mutable copy User.Mutable).
      • User.Mutable has mutable properties and mutable<Field> copy-on-write getters for nested structs/arrays, and .toFrozen() returns an immutable User.
      • In Python and Ruby, User(...) keyword arguments are all optional and default to the field's default value (User(user_id=42, name="John")), while User.Partial(...) / partial initialization is supported directly by the constructor.
    • Java: Uses a compile-time step builder (User.builder().setFieldA(...).setFieldB(...).build()) that enforces setting all fields in alphabetical order at compile time, plus User.partialBuilder() where all fields are optional and pre-populated with defaults, and user.toBuilder() for modifying an existing instance.

Q5: How should enums be represented (Pattern Matching, Kind, and Type Safety)?

Every Skir enum has:

  • The built-in unknown variant (field number 0, default value of the enum).
  • Zero or more constant variants (free;, premium;).
  • Zero or more wrapper variants (trial: Trial;, error: string;) carrying a payload value.

Two Proven Representations:

  1. Native Algebraic Data Types (ADTs) / Sealed Class Hierarchies (Preferred whenever the language supports them!):
    • Rust, OCaml, Gleam, MoonBit, F#, Scala 3, Swift: Native enum / discriminated union / variant type with an Unknown(UnrecognizedVariant) case, constant cases, and payload-carrying wrapper cases. Exhaustive pattern matching is checked directly by the host compiler!
    • Kotlin & Dart: sealed interface / sealed class hierarchy where each wrapper variant is a final subclass (SubscriptionStatus.TrialWrapper(val value: Trial) / SubscriptionStatus_trialWrapper(this.value)) and constant variants are singleton instances, paired with a Kind enum so users can either switch/when on the sealed type (with smart casting / pattern destructuring) or switch on .kind.
  2. Single Sealed Class + Kind Enum + wrap_* / as_* + Visitor (For languages without native ADTs):
    • Java, C#, C++, Go, TypeScript, Python, Ruby:
    • CRITICAL LESSON ON Kind TYPE SAFETY (From Ruby Audit Feedback):
      • Never make Kind a raw string or int! When Ruby's generator was first created, SubscriptionStatus::Kind::FREE was just the plain String "free". That was bad for type safety (and Sorbet typing) because any arbitrary string could be passed where a Kind was expected.
      • Even in dynamic languages (or languages with gradual typing like Ruby + Sorbet or Python), Kind should be a dedicated typed enum/class (e.g., T::Enum or a dedicated frozen class in Ruby; enum.Enum in Python; public enum KindType in C#; public enum Kind in Java), and in statically typed languages it must be a distinct enum type!
    • Convenience create_<variant> constructors for struct payloads:
      • When a wrapper variant wraps a struct (e.g., trial: struct { start_time: timestamp; }), generate both wrap_trial(trial_struct) AND create_trial(start_time: ...) (as in Dart, Kotlin, Java, Python, Ruby, TypeScript). Users love create_trial(...) because they don't have to import or construct the nested struct type manually.

Q6: How should Value Equality (==) and Hashing (hashCode) work?

Every Skir struct and enum represents a value, not an object identity.

  1. Arrays/Lists inside structs AND inside enum wrapper variants:
    • Many languages have list/array types that use reference equality by default:
      • Java (array arrays — use List), C# (ImmutableArray<T> compares the backing T[] pointer!), F# ('T array inside discriminated unions or records), Dart (List<T> uses identical(a, b)!), Go (slices cannot use ==).
    • Rule: Two structs—or two enum wrapper variants (such as JsonValue.wrapArray([JsonValue.null]))—constructed separately or deserialized from identical JSON/bytes must compare equal under the language's standard equality check and produce equal hash codes!
    • In Dart, Python, and Ruby, array fields are frozen into an immutable value-equated collection (_FrozenListImpl in Dart, tuple in Python, .freeze in Ruby). Do not forget to apply the exact same freezing/copying in enum wrap_* constructors and array deserializers (Dart Bug #2)!
    • Notice that in C#, we intentionally skipped generating custom Equals/GetHashCode on readonly record struct to keep the generated code concise, whereas in F# we emit custom structural Equals and GetHashCode using a recursive structural helper.
  2. Unrecognized fields (_unrecognized) and Unknown enum variants:
    • Enums: Two Unknown enum instances must always compare equal (a == b is true) and have the same hash code, regardless of whether one was constructed via MyEnum.UNKNOWN and the other was decoded from an unrecognized variant number with keepUnrecognizedValues = true!
    • Structs: _unrecognized must never be included in equals or hashCode, and must never be a required parameter in the public struct constructor.

Q7: How should "hard" Recursive Structs (struct RecA { a: RecA; b: RecB; }) be handled?

When field.isRecursive === "hard", RecA.DEFAULT.a is RecA.DEFAULT. If RecA.DEFAULT eagerly allocates RecA.DEFAULT in its constructor, or if RecA is an unboxed value type (struct), initialization or type layout will infinite-loop!

There are two proven solutions—pick the one that fits the target language:

  • Solution 1: Transparent Nullable Backing Field (_rec_a: RecA?) + Non-Null Public Getter (a => _rec_a ?? RecA.DEFAULT)
    • Used in: Java, Kotlin, Scala, Dart, Python, Ruby.
    • How it works:
      • RecA.DEFAULT initializes _rec_a = null.
      • The public getter rec.a returns _rec_a ?? RecA.DEFAULT, so RecA.DEFAULT.a.a.a works seamlessly with zero wrapper noise in user code!
    • CRITICAL BUG PREVENTION (Dart Bug #1 — StackOverflowError in hashCode / equals):
      1. In the private constructor of RecA, normalize default values to null:
        this._rec_a = (_rec_a == null || _rec_a == RecA.defaultInstance) ? null : _rec_a
        (Note: check _rec_a == null first so constructing defaultInstance = RecA._(null) short-circuits without referencing RecA.defaultInstance before defaultInstance finishes initializing!)
      2. In equals and hashCode (e.g. _equality_proxy), always read this._rec_a, NEVER the public getter this.a! If hashCode or equals reads this.a, calling RecA.DEFAULT.hashCode evaluates this.a $\rightarrow$ RecA.DEFAULT $\rightarrow$ RecA.DEFAULT.hashCode $\rightarrow$ infinite recursion (StackOverflowError)!
  • Solution 2: Explicit Indirection Wrapper (Recursive<T> / Box<T> / Pointer)
    • Used in: C# (Recursive<T>), F# (Recursive<'T>), C++ (std::unique_ptr<T> / recursive<T>), Rust (Box<T>), Zig (*const T / Recursive(T)), Gleam (recursive.Recursive(a)), MoonBit (Recursive[T]), OCaml (t Lazy.t or recursive record).
    • CRITICAL BUG PREVENTION (C# Bug #3 & Gleam Bug #6):
      1. When Recursive<T> is in its unset/default state (!HasValue / Recursive.Default), ToJson must directly output "[]" (dense) or "{}" (readable) and Encode must directly output wire byte 246. Never construct a zero-initialized value-type default(T) in C# and pass it to _inner.ToJson(default(T))—its reference fields (string, enum) and ImmutableArray fields will be null/uninitialized and crash with NullReferenceException!
      2. On FromJson and Decode, if Recursive<T> is an explicit enum (Default | Some(T) as in Gleam/MoonBit) that participates in structural ==, normalize decoded default values (if inner.is_default(val) -> Default else -> Some(val)) so round-tripping RecStruct preserves ==.

4. Complete Wire Format & Serialization Specification

Every language's runtime client library must implement these exact rules to pass @gepheum/skir-golden-tests.

4.1 Forward/Backward Compatibility Contract

  • Dense JSON and Binary guarantee forward and backward compatibility across all safe schema evolutions.
  • Readable JSON is for human debugging only and does not guarantee schema evolution compatibility (do notpersist readable JSON).
  • However, every fromJson implementation must accept both Dense JSON and Readable JSON inputs automatically.

4.2 Binary Header ("skir")

  • Serializer.toBytes(value) must start with the 4 ASCII bytes "skir" (0x73, 0x6B, 0x69, 0x72), followed immediately by adapter.encode(value).
  • Serializer.fromBytes(bytes) must verify that bytes has length $\ge 5$ and starts with "skir", then decode starting at byte offset 4.

4.3 Primitive Wire Formats

PrimitiveDefaultDense JSONReadable JSONBinary EncodingBinary & JSON Decoding Rules
boolfalse0 or 1false or truefalse $\rightarrow$ 0x00<br>true $\rightarrow$ 0x01JSON: false, 0, 0.0, -0.0, "0", "false" $\rightarrow$ false; true, non-zero numbers, "1", "true" $\rightarrow$ true.<br>Binary: Any numeric wire tag 0..241 where decoded number $\ne 0$ $\rightarrow$ true; 0 $\rightarrow$ false.
int320integerinteger0..231: 1 byte v<br>232..65535: 232 + u16_le<br>65536..2147483647: 233 + u32_le<br>-256..-1: 235 + u8(v + 256)<br>-65536..-257: 236 + u16_le(v + 65536)<br>-2147483648..-65537: 237 + i32_le(v)JSON: integer, float (truncated), or quoted number string.<br>Binary: Any numeric wire tag 0..241. Guard against NaN/±Infinity when converting float wire tags 240/241 to int!
int640number if in [-9007199254740991, 9007199254740991] ($\pm(2^{53}-1)$); quoted string "..." outside!Same as Dense JSONIf in int32 range [-2147483648, 2147483647], use int32 encoding; else 238 + i64_le(v) (8 bytes LE).JSON: number or quoted string.<br>Binary: Any numeric wire tag 0..241.
hash64 (uint64)0number if $\le 9007199254740991$ ($2^{53}-1$); quoted string "..." if $> 9007199254740991$Same as Dense JSON0..231: 1 byte v<br>232..65535: 232 + u16_le<br>65536..4294967295: 233 + u32_le<br>>= 4294967296: 234 + u64_le (8 bytes LE)JSON: number or quoted string.<br>Binary: Any numeric wire tag 0..241.<br>BigInt Warning (Dart Bug #3): In languages where hash64 is BigInt, check if (v <= 0) encode(0) before checking if v fits in a signed 64-bit int, and clamp v > maxHash64 to 8 bytes of 0xFF after wire 234!
float320.0number if finite; "NaN", "Infinity", "-Infinity" if non-finiteSame as Dense JSONv == 0.0 $\rightarrow$ 0x00<br>else $\rightarrow$ 240 + 4-byte IEEE-754 float32 LEJSON: number or "NaN", "Infinity", "-Infinity".<br>Binary: Any numeric wire tag 0..241.
float640.0number if finite; "NaN", "Infinity", "-Infinity" if non-finiteSame as Dense JSONv == 0.0 $\rightarrow$ 0x00<br>else $\rightarrow$ 241 + 8-byte IEEE-754 float64 LEJSON: number or "NaN", "Infinity", "-Infinity".<br>Binary: Any numeric wire tag 0..241.
timestampUnix epoch 0 msinteger unix_millis (clamped to ±8_640_000_000_000_000){\n "unix_millis": <ms>,\n "formatted": "<ISO-8601 UTC Z>"\n}unix_millis == 0 $\rightarrow$ 0x00<br>else $\rightarrow$ 239 + i64_le(unix_millis)Always clamp unix_millis to [-8_640_000_000_000_000, +8_640_000_000_000_000].<br>JSON: accepts integer, float, quoted string, or object with "unix_millis".<br>Binary: wire 239 (or any numeric wire tag 0..241).
string""JSON string "..."JSON string "...""" $\rightarrow$ 242 (0xF2)<br>non-empty $\rightarrow$ 243 (0xF3) + encodeUint32(utf8_len) + UTF-8 bytes (invalid UTF-8 & lone surrogates replaced with U+FFFD)JSON: string, or 0 $\rightarrow$ "".<br>Binary: wire 0 or 242 $\rightarrow$ ""; wire 243 $\rightarrow$ decode length + UTF-8 bytes (replace invalid UTF-8 with U+FFFD). Reject other wire tags!
bytesempty b""Base64 string "...""hex:<lowercase-hex>"empty $\rightarrow$ 244 (0xF4)<br>non-empty $\rightarrow$ 245 (0xF5) + encodeUint32(len) + raw bytesJSON: string starting with "hex:" (hex) or Base64 string, or 0 $\rightarrow$ empty.<br>Binary: wire 0 or 244 $\rightarrow$ empty; wire 245 $\rightarrow$ decode length + bytes. Reject other wire tags!

4.4 Composite Wire Formats

1. optional (T?)

  • Default: null / None.
  • isDefault(v): true iff v is null / None.
  • JSON Encoding: null if None; inner.toJson(v) if Some(v).
  • JSON Decoding: If JSON token is null $\rightarrow$ None; otherwise Some(inner.fromJson(json)).
  • Binary Encoding:
    • None $\rightarrow$ single wire byte 255 (0xFF).
    • Some(v) $\rightarrow$ inner.encode(v) directly with NO prefix tag byte!
  • Binary Decoding:
    • Peek next byte: if it is 255 (0xFF), consume 1 byte and return None.
    • Otherwise, do not consume a tag byte—pass the stream directly to inner.decode(stream) and wrap the result in Some(...)!
  • CRITICAL INVARIANT (Caught in C# Bug #2 & Gleam Bug #1 by Golden Tests #1038 and #1101):
    • Some(default_value) (for example Some(false), Some(0), Some(""), Some([]), Some(MyStruct.DEFAULT)) is a present non-null value!
    • In Dense JSON, Some(false) serializes to "0", and in Binary it serializes to hex:736b697200 (wire byte 0).
    • When deserializing "0" or wire byte 0 as bool?, fromJson and decode must return Some(false)—NEVER check if (inner.isDefault(result)) return None; and NEVER treat wire byte 0 as None! Only JSON null and binary wire 255 represent None.

2. array ([T] and [T|key])

  • Default: [] (empty array).
  • isDefault(v): v.isEmpty.
  • JSON: [item_0, item_1, ...]. On fromJson, also accept 0 as [].
  • Binary:
    • len == 0 $\rightarrow$ wire 246 (0xF6)
    • len == 1 $\rightarrow$ wire 247 (0xF7) + element 0
    • len == 2 $\rightarrow$ wire 248 (0xF8) + elements 0, 1
    • len == 3 $\rightarrow$ wire 249 (0xF9) + elements 0, 1, 2
    • len >= 4 $\rightarrow$ wire 250 (0xFA) + encodeUint32(len) + len elements.
    • On decode, also accept wire 0 as []. Validate 0 <= len and remaining buffer capacity before allocating!

3. struct

  • Default: S.DEFAULT (all fields have their default values and _unrecognized is empty/null).
  • isDefault(s): true iff every field satisfies fieldAdapter.isDefault(s.field) AND s._unrecognized is null/empty.
  • Slot Layout & Unrecognized Field Preservation:
    • Let totalSlots be the active prefix length when serializing:
      • If s._unrecognized is present and matches the target format (Dense JSON for Dense JSON output; Binary for Binary output) and s._unrecognized.totalSlots > record.numSlotsInclRemovedNumbers:
        • All known fields in 0 ..< record.numSlots are encoded (even if default, because non-default unrecognized fields follow them!), removed slots in 0 ..< record.numSlotsInclRemovedNumbers are encoded as 0, and then the raw unrecognized tail elements/bytes for slots record.numSlotsInclRemovedNumbers ..< s._unrecognized.totalSlots are appended!
      • Otherwise (no unrecognized tail for this format):
        • Find the highest field number maxNonDefaultSlot whose value is not default (!fieldAdapter.isDefault(val)).
        • If no field is non-default, activeSlots = 0 (encodes as [] in Dense JSON, {} in Readable JSON, wire 246 in Binary).
        • Otherwise, activeSlots = maxNonDefaultSlot + 1, and encode slots 0 .. maxNonDefaultSlot in order (writing 0 for removed slots or default slots before maxNonDefaultSlot).
    • When Deserializing with keepUnrecognizedValues:
      • A sender with a newer schema may have added fields at slot numbers $\ge$ your record.numSlotsInclRemovedNumbers.
      • Wait: what if a schema had removed numbers at the end (e.g. field 0 is x, and slot 1 is removed;, so numSlots = 1 and numSlotsInclRemovedNumbers = 2), and a payload arrives with 2 slots [10, 99]?
        • Slot 1 is a known removed slot, NOT an unrecognized future slot! You must skip/drop slots < numSlotsInclRemovedNumbers and only preserve unrecognized slots at indices $\ge \text{numSlotsInclRemovedNumbers}$! (Tested by golden tests #1053–#1058 and #1067–#1068!)
      • If keepUnrecognizedValues == false, simply skip any slots $\ge \text{numSlots}$ without storing them.

4. enum

  • Default: E.UNKNOWN (with no unrecognized variant payload).
  • isDefault(e): true iff e is UNKNOWN AND carries no unrecognized variant payload.
  • Dense JSON Encoding:
    • UNKNOWN with preserved Dense JSON unrecognized payload $\rightarrow$ emit raw preserved JSON verbatim.
    • UNKNOWN without unrecognized payload $\rightarrow$ 0.
    • Constant variant $\rightarrow$ integer variant.number.
    • Wrapper variant $\rightarrow$ [variant.number, payloadAdapter.toDenseJson(e.value)].
  • Readable JSON Encoding:
    • UNKNOWN (even if it has unrecognized payload!) $\rightarrow$ "unknown".
    • Constant variant $\rightarrow$ "<variant.name>" (in lower_underscore).
    • Wrapper variant $\rightarrow$ {\n "kind": "<variant.name>",\n "value": <payloadAdapter.toReadableJson(e.value)>\n}.
  • Binary Encoding:
    • UNKNOWN with preserved Binary unrecognized payload $\rightarrow$ emit raw preserved bytes verbatim.
    • UNKNOWN without unrecognized payload $\rightarrow$ 0x00.
    • Constant variant $\rightarrow$ encodeInt32(variant.number) (always wire $< 242$).
    • Wrapper variant:
      • If 1 <= variant.number <= 4 $\rightarrow$ single wire byte 250 + variant.number (251, 252, 253, or 254) + payloadAdapter.encode(e.value).
      • If variant.number >= 5 $\rightarrow$ wire byte 248 (0xF8) + encodeInt32(variant.number) + payloadAdapter.encode(e.value).
  • Deserialization & Schema Evolution Rules for Enums (Tested by Golden Tests #1059–#1070, #1087–#1100):
    1. Constant representation in input (Dense JSON integer num / Readable JSON string "name" / Binary wire < 242):
      • If num == 0 or "unknown" / "UNKNOWN" $\rightarrow$ E.UNKNOWN.
      • If num is in removedNumbers $\rightarrow$ E.UNKNOWN (do not keep as unrecognized!).
      • If num (or "name", accepting both lower_case and UPPER_CASE for constant variants) matches a constant variant $\rightarrow$ return that constant variant.
      • If num (or "name") matches a wrapper variant (schema evolved from constant to wrapper!) $\rightarrow$ decode/construct the wrapper variant wrapping its payload type's default value (payloadAdapter.fromJson(0) / payloadAdapter.default)!
      • If num is unrecognized: if keepUnrecognizedValues is true (and input is Dense JSON or Binary), return E.UNKNOWN wrapping the raw JSON/bytes; else return E.UNKNOWN.
    2. Wrapper representation in input (Dense JSON [num, valJson] / Readable JSON {"kind": name, "value": valJson} / Binary wire 248 or 251..254):
      • If num is in removedNumbers $\rightarrow$ in Binary, skip the payload value (skipValue(stream)) so the stream position stays valid, and return E.UNKNOWN!
      • If num (or name) matches a wrapper variant $\rightarrow$ decode val with payloadAdapter (passing keepUnrecognizedValues) and wrap it.
        • CRITICAL (Dart Bug #5): In Readable JSON {"kind": "opt_field", "value": null}, "value" is present with value null. Check obj.containsKey("value"), not obj["value"] != null!
      • If num matches a constant variant (schema evolved from wrapper to constant!) $\rightarrow$ in Binary, skip the payload value (skipValue(stream)), and return the constant variant!
      • If num is unrecognized: in Binary, slice the raw bytes of the wire tag + number + skipped payload value; if keepUnrecognizedValues is true, wrap in E.UNKNOWN, else return E.UNKNOWN.

4.5 Skipping Unused Binary Values (skipValue / decodeUnused)

When skipping an unrecognized struct field or a removed/unrecognized enum wrapper payload in binary:

  • 0..231, 242 (empty string), 244 (empty bytes), 246 (empty array/struct), 255 (null): 0 additional bytes (1 byte total).
  • 235: skip 1 byte.
  • 232, 236: skip 2 bytes.
  • 233, 237, 240 (float32): skip 4 bytes.
  • 234, 238, 239 (timestamp), 241 (float64): skip 8 bytes.
  • 243 (non-empty string), 245 (non-empty bytes): decode number len = decodeNumber(stream), validate len >= 0 and remaining bytes $\ge \text{len}$, then advance len bytes.
  • 247, 251, 252, 253, 254: recursively call skipValue(stream) 1 time.
  • 248: recursively call skipValue(stream) 2 times (works for both 2-element array/struct AND enum wrapper 248 + number + payload because number is itself a valid single Skir value!).
  • 249: recursively call skipValue(stream) 3 times.
  • 250: decode number count = decodeNumber(stream), validate count >= 0, and recursively call skipValue(stream) count times.

5. TypeDescriptor & Reflection JSON Format

Every Serializer<T> exposes .typeDescriptor returning a TypeDescriptor that can be serialized to pretty-printed JSON (2-space indentation) via asJsonCode() / asJson() and parsed via TypeDescriptor.parseFromJsonCode(json):

{
  "type": {
    "kind": "record",
    "value": "user.skir:User"
  },
  "records": [
    {
      "kind": "struct",
      "id": "user.skir:User",
      "doc": "...",
      "fields": [
        {
          "name": "user_id",
          "number": 0,
          "type": {
            "kind": "primitive",
            "value": "int64"
          },
          "doc": "..."
        }
      ],
      "removed_numbers": [2]
    }
  ]
}

TypeDescriptor Rules & Bug Prevention:

  1. Omit empty optional properties in record descriptors:
    • "doc" on a struct, enum, field, or variant is only included in the JSON object when doc is non-empty (doc.length > 0)!
    • "removed_numbers" on a struct or enum is only included when removedNumbers.length > 0!
    • "key_extractor" on an "array" type signature ({"kind": "array", "value": {"item": ..., "key_extractor": "..."}}) is only included when the array is a keyed array! And its value is the original snake_case path from .skir (e.g. "sub_item.weekday.kind"), not the target language's camelCase property names!
  2. Preventing Infinite Recursion on Recursive Enums/Structs (Gleam Bug #2):
    • Consider enum JsonValue in enums.skir, which has array: [JsonValue] and object: [JsonValue.Pair|name] where struct Pair has value: JsonValue, or mutually recursive structs RecA and RecB.
    • When collecting the "records" list for TypeDescriptor, do not only check direct self-recursion (vType.key === currentRecord.key)!
    • Instead, traverse record dependencies using a visited: Set<string> of record IDs:
      • Before recursing into a struct's fields or an enum's wrapper variant types, check if (visited.has(recordId)) return;, add recordId to visited, and use a lazy thunk (() => Serializer) for record references so mutually recursive serializers don't infinite-loop during static initialization or TypeDescriptor construction!
      • Ensure that both RecA and RecB appear in "records" when RecA.serializer.typeDescriptor is inspected.

6. SkirRPC Service & ServiceClient Specification

Every runtime client library implements Method<Req, Resp>, Service<Meta>, and ServiceClient:

  1. Method<Req, Resp>:
    • Holds name: string, number: uint32 (int64), requestSerializer: Serializer<Req>, responseSerializer: Serializer<Resp>, doc: string.
  2. Service<Meta> (Server Router):
    • Built via builder/registration pattern mapping Method<Req, Resp> to an async/sync handler (req: Req, meta: Meta) -> Resp.
    • handleRequest(rawBody: string, meta: Meta) -> RawResponse(data: string, statusCode: int, contentType: string):
      • Built-in Studio / Discovery bodies:
        • rawBody == "" or rawBody == "studio" $\rightarrow$ HTTP 200, text/html; charset=utf-8, HTML page loading Skir Studio JS from studioAppJsUrl (default "https://cdn.jsdelivr.net/npm/skir-studio-app@latest/dist/skir-studio-app.js").
        • rawBody == "list" $\rightarrow$ HTTP 200, application/json, JSON object {"methods": [ { "method": "...", "number": 123, "request": <TypeDescriptor>, "response": <TypeDescriptor>, "doc": "..." } ]}.
      • Two RPC Request Formats:
        1. Colon-separated format (<methodName>:<methodNumber>:<format>:<requestJson>):
          • Split on : into at most 4 parts (split(':', 4) so colons inside <requestJson> are preserved!).
          • Lookup method by <methodNumber> (or by <methodName> if <methodNumber> is empty).
          • <format> is "readable" (respond with readable JSON) or "" / "dense" (respond with dense JSON).
        2. JSON object format (starts with { or whitespace before {):
          • Parse JSON object {"method": <string or int>, "request": <any JSON value>}.
          • If "method" is an integer (or numeric string), look up by number; if string, look up by name.
          • CRITICAL BUG PREVENTION (C# Bug #6, Dart Bug #6): A method's request type can be an optional T?, so {"method": "MyMethod", "request": null} is a 100% valid request! Check that the "request" key exists in the JSON object (obj.containsKey("request")), NOT obj["request"] != null! When its value is JSON null, pass "null" (or JsonNull) to requestSerializer.fromJson.
          • JSON-object requests always serialize their response in readable JSON (readable = true).
      • Error Handling & errorLogger (Gleam Bug #7):
        • Bad request format / unknown method / request JSON parse failure $\rightarrow$ HTTP 400 (text/plain; charset=utf-8, "bad request: ...").
        • Handler throws/returns ServiceError(statusCode, message) $\rightarrow$ invoke errorLogger and return HTTP statusCode (400..599, text/plain; charset=utf-8, message).
        • Handler throws unexpected exception $\rightarrow$ invoke errorLogger and return HTTP 500 (text/plain; charset=utf-8, message if canSendUnknownErrorMessage is true, else "internal server error").
  3. ServiceClient (HTTP Client):
    • Validates serviceUrl (must be a valid http:// or https:// URL without a query string ?).
    • Sends POST to serviceUrl with body <method.name>:<method.number>::<requestDenseJson>, plus custom headers and deadline/timeout support.
    • If response status is 200, parses body with method.responseSerializer.fromJsonCode(respBody). Otherwise throws/returns RpcError(statusCode, body).

7. Hall of Fame of Subtle Bugs to Avoid

Before declaring a new language generator or client library complete, verify every item in this list:

  1. Optional Some(default) vs None (C# Bug #2, Gleam Bug #1):
    • optional_serializer must encode None as wire 255 and Some(x) as inner.encode(x) with no tag prefix.
    • On decode/fromJson, only wire 255 / JSON null returns None. Wire 0 / JSON 0 on bool? or int32? must return Some(false) / Some(0), never None.
  2. "hard" Recursive Struct hashCode / equals Stack Overflow (Dart Bug #1):
    • If using a nullable backing field _rec_a with getter a => _rec_a ?? Default, normalize _rec_a == Default to null in the constructor and reference _rec_a (never this.a) in equals and hashCode.
  3. Value-Type default(T) vs T.Default in Recursive<T> (C# Bug #3):
    • When Recursive<T> has no value (!HasValue), emit "[]" / "{}" / wire 246 directly.
  4. Enum Wrapper Variants Wrapping Lists or Timestamps (Dart Bug #2):
    • Apply toFrozenExpression (freezing lists into value-equated immutable lists and converting timestamps to UTC) inside enum wrap_* factory methods as well as struct constructors, and ensure the array deserializer returns the value-equated frozen list type.
  5. Variable Shadowing in Generated *_serializer() Functions (Gleam Bug #3):
    • Never bind local variables inside generated serializer/decoder functions using raw unprefixed field names (let ${fieldName}_serializer = ... or let ${fieldName} = ...).
    • If a struct has a field named user in the same module as struct User, let user_serializer = user_serializer() shadows the module-level user_serializer() function and breaks compilation if another field in the same struct also has type User!
    • If a struct has a field named arr, bits, keep, stream, offset, json, or slots_to_fill, unprefixed local bindings will shadow the decoder function's own parameters! Always prefix generated local variables (e.g. _f_${fieldName}, _ser_${fieldName}).
  6. Enum KindType Collisions Between foo: T; and foo_wrapper; (C# Bug #5):
    • If wrapper variants add a Wrapper suffix in KindType (foo: T $\rightarrow$ FooWrapper) while constant variants do not (foo_wrapper; $\rightarrow$ FooWrapper), reserve all wrapper variant KindType names first and disambiguate colliding constant variants as FooWrapper_.
  7. Enum Named Kind Used as a Key in a Keyed Array ([Item|kind_enum.kind]) (C# Bug #4):
    • If an enum is named Kind and its .Kind property is renamed to .Kind_ to avoid colliding with the enclosing class name, ensure Kind_ is public (not internal) and that keyed-array key extractors check enumTypeName === "Kind" and emit .Kind_.
  8. C++ Union/Enum Self-Assignment & CopyUtf8String Embedded NUL (C++ Bugs #1, #2, #3):
    • Always guard if (&other != this) before calling destroy() or freeing buffers in custom operator=.
    • When unescaping JSON strings containing \u0000, never push an extra C-string '\0' terminator into the middle of a length-delimited std::string buffer.
  9. Binary String Encoding & Decoding Must Always Produce Valid UTF-8 With U+FFFD Replacement (Never Invalid UTF-8, Lone Surrogates, or ?):
    • In languages where in-memory strings are UTF-16 code units (TypeScript, Java/Kotlin/Scala, C#/F#, Dart, MoonBit) or Unicode code points that permit surrogate code points (Python), an input string can contain an unpaired surrogate (U+D800..U+DFFF).
    • In languages where in-memory strings are arbitrary byte arrays (C++, Go, Zig, OCaml, Ruby), an input string can contain invalid UTF-8 byte sequences or UTF-8-encoded surrogates (0xED 0xA0..0xBF 0x80..0xBF).
    • Rule: When encoding a string to binary (encode / toBytes) or decoding a string from binary (decode / fromBytes), any invalid UTF-8 byte sequence or unpaired surrogate must be replaced with U+FFFD (0xEF 0xBF 0xBD).
    • Beware of standard-library defaults that use '?' (0x3F) instead of U+FFFD during UTF-8 encoding:
      • On the JVM (Kotlin/Java/Scala), String.toByteArray(Charsets.UTF_8) replaces unpaired surrogates with '?' (0x3F). Always sanitize unpaired surrogates in String to \uFFFD before calling toByteArray(Charsets.UTF_8) in encode!
      • In Python, str.encode("utf-8", errors="replace") replaces unpaired surrogates with '?' (0x3F). Always replace code points in 0xD800..0xDFFF with "\ufffd" before calling .encode("utf-8") in encode!
  10. Corrupted Binary Inputs, Negative/Huge Lengths, and Trailing Bytes:
    • Serializer.fromBytes(bytes) must fall back to JSON parsing when bytes does not start with "skir", and when it does start with "skir", must verify that all bytes were consumed (offset == bytes.length) after decoding the root value—rejecting trailing bytes.
    • When decoding a length or slot count in string (wire 243), bytes (wire 245), array (wire 250), struct (wire 250), or skipValue, decodeNumber can return a negative number (via wires 235..241) or a huge number exceeding remaining input bytes. Always validate 0 <= count <= remainingBytes before allocating arrays or advancing pointers!
  11. Enum Readable JSON Schema Evolution & Case-Insensitive Variant Lookup:
    • Register both lower_case and UPPER_CASE aliases for both constant variants and wrapper variants.
    • When a variant evolved from constant to wrapper, a readable JSON string "variant_name" (or "VARIANT_NAME") or a readable JSON object with omitted "value" ({"kind": "variant_name"}) must decode to the wrapper variant wrapping its payload's default value (note: for an optional payload type T?, the default value is null/None / wire 255, not 0!).
    • When a variant evolved from wrapper to constant, a readable JSON object {"kind": "variant_name", "value": ...} must ignore "value" and return the constant variant.
    • When isDefault is called on a struct or enum, always verify that _unrecognized is also null/empty (getUnrecognized(value) == null), and ensure UNKNOWN enums with unrecognized payloads still serialize to "unknown" in readable JSON.

8. Complete Monorepo Integration Checklist

When adding a new language <lang>, create and update all of the following locations:

  1. Compiler Generator (packages/compiler/):
    • Create packages/compiler/src/generators/<lang>/index.ts (plus naming.ts, type_speller.ts, etc.).
    • Register skir-<lang>-gen in STATIC_GENERATORS in packages/compiler/src/config_parser.ts.
    • Add unit tests in packages/compiler/src/generators/<lang>/index.test.ts.
  2. Runtime Client Library (client-libraries/<lang>/):
    • Implement serializers, reflection TypeDescriptor, Service, ServiceClient, and comprehensive unit tests.
  3. End-to-End & Golden Tests (e2e-tests/<lang>/):
    • Create e2e-tests/<lang>/skir.yml referencing @gepheum/skir-fantasy-game-example and the latest @gepheum/skir-golden-tests tag.
    • Symlink or copy e2e-tests/<lang>/skir-src/ (constants.skir, enums.skir, full_name.skir, methods.skir, quest_collection.skir, schema_change.skir, structs.skir, user.skir, vehicles/car.skir).
    • Implement goldens_test running all UNIT_TESTS from goldens.readonly.skir (including reserialize_value, reserialize_large_string, reserialize_large_array, bytes_equal, bytes_in, string_equal, string_in, enum_a_from_json_is_constant, enum_a_from_bytes_is_constant, enum_b_from_json_is_wrapper_b, enum_b_from_bytes_is_wrapper_b, expected_type_descriptor, alternative_jsons, alternative_bytes, and verifying that every expected_bytes payload can be skipped as an unrecognized slot in Point).
    • Wire <lang> into:
      • e2e-tests/format-all.sh
      • e2e-tests/test.sh
      • pre_commit.sh
      • pre_commit_setup.sh
  4. Example Project (examples/<lang>/) & CI Workflows (.github/workflows/):
    • Create examples/<lang>/ (skir.yml, skir-src/service.skir, skirout/, snippets, server, client, README.md, .github/workflows/ci.yml).
    • Add <lang> to .github/workflows/ci.yml and .github/workflows/sync-examples.yml.
    • Create .github/workflows/publish-client-<lang>.yml (if mirrored to a GitHub repo, use a release_version input with default: "patch", not an input named tag, because GitHub's workflow_dispatch web UI rejects inputs named tag!).
  5. Documentation & Website (docs/, packages/website/, README.md, skills/skir/SKILL.md):
    • Write docs/languages/<lang>.md.
    • Update packages/website/.vitepress/config.mts and packages/website/.vitepress/theme/HomePage.vue (including the language count badge).
    • Update packages/website/public/llms.txt and regenerate packages/website/public/llms-full.txt.
    • Update README.md and skills/skir/SKILL.md.
  6. Final Verification:
    • Run ./pre_commit.sh --lang <lang> (and full ./pre_commit.sh) and verify zero warnings, zero lint errors, and 100% passing unit, E2E, and golden tests.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.