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
- ku5ic/claude-kittheir own version, first seen Nov 29, 2026
- Phygital-Brain/phygital-braintheir own version, first seen Nov 15, 2026
- GeoffMillerAZ/fathomtheir own version, first seen Nov 8, 2026
- Locker-Room-Tools/synapsetheir own version, first seen Oct 11, 2026
- DailybotHQ/deepworkplan-websitetheir own version, first seen Oct 9, 2026
- madeinoz67/madeinoz-knowledge-systemtheir own version, first seen Jan 18, 2026
Other versions7 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 7
- ZoneMinder/zmNinjaNg★ 104same name
- DailybotHQ/deepworkplan-website★ 16same name
- madeinoz67/madeinoz-knowledge-system★ 3same name
- ku5ic/claude-kit★ 2same name
- GeoffMillerAZ/fathom★ 1same name
- Locker-Room-Tools/synapse★ 1same name
- 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.
- skirSkill
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
- Distinctive: line 65
Wait: collisions *can* still happen after case conversion or suffixing in target languages!
- Very specific: line 71
Every intermediate step in type.key.path is guaranteed to be a non-optional, non-recursive (field.isRecursive !== "hard") struct field …
- Distinctive: line 88
Before writing a new generator, answer these 9 design questions for the target language:
- Very specific: line 110
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 …
- Very specific: line 114
Every generated Skir struct must support:
- Very specific: line 136
Every Skir enum has:
- Very specific: line 148
Never make
Kinda rawstringorint!: When Ruby's generator was first created, SubscriptionStatus::Kind::FREE was just the plain … - Very specific: line 151
When a wrapper variant wraps a struct (e.g., trial: struct { start_time: timestamp.
- Very specific: line 154
Every Skir struct and enum represents a value, not an object identity.
- Very specific: line 166
When field.isRecursive === "hard", RecA.DEFAULT.a is RecA.DEFAULT.
- Very specific: line 182
If hashCode or equals reads this.a, calling RecA.DEFAULT.hashCode evaluates this.a $\rightarrow$ RecA.DEFAULT $\rightarrow$ …
- Very specific: line 194
Every language's runtime client library must implement these exact rules to pass @gepheum/skir-golden-tests.
- Very specific: line 225
JSON Decoding: If JSON token is null $\rightarrow$ None.
- Very specific: line 235
When deserializing "0" or wire byte 0 as bool?, fromJson and decode must return Some(false)—NEVER check if (inner.isDefault(result)) return …
- Very specific: line 254
If s._unrecognized is present and matches the target format (Dense JSON for Dense JSON output.
- Very specific: line 255
All known fields in 0 ..< record.numSlots are encoded (even if default, because non-default unrecognized fields follow them!), removed …
- Very specific: line 258
If no field is non-default, activeSlots = 0 (encodes as [] in Dense JSON, {} in Readable JSON, wire 246 in Binary).
- Very specific: line 262
Wait: what if a schema had removed numbers at the end (e.g.
- Very specific: line 264
If keepUnrecognizedValues == false, simply skip any slots $\ge \text{numSlots}$ without storing them.
- Very specific: line 283
If 1 <= variant.number <= 4 $\rightarrow$ single wire byte 250 + variant.number (251, 252, 253, or 254) + payloadAdapter.encode(e.value).
- Very specific: line 284
If variant.number >= 5 $\rightarrow$ wire byte 248 (0xF8) + encodeInt32(variant.number) + payloadAdapter.encode(e.value).
- Very specific: line 287
If num == 0 or "unknown" / "UNKNOWN" $\rightarrow$ E.UNKNOWN.
- Very specific: line 288
If num is in removedNumbers $\rightarrow$ E.UNKNOWN (do not keep as unrecognized!).
- Very specific: line 289
If num (or "name", accepting both lower_case and UPPER_CASE for constant variants) matches a constant variant $\rightarrow$ return that …
- Very specific: line 290
If num (or "name") matches a wrapper variant (schema evolved from constant to wrapper!) $\rightarrow$ decode/construct the wrapper variant …
- Very specific: line 291
If num is unrecognized: if keepUnrecognizedValues is true (and input is Dense JSON or Binary), return E.UNKNOWN wrapping the raw JSON/bytes.
- Very specific: line 293
If num is in removedNumbers $\rightarrow$ in Binary, skip the payload value (skipValue(stream)) so the stream position stays valid, and …
- Very specific: line 294
If num (or name) matches a wrapper variant $\rightarrow$ decode val with payloadAdapter (passing keepUnrecognizedValues) and wrap it.
- Very specific: line 296
If num matches a constant variant (schema evolved from wrapper to constant!) $\rightarrow$ in Binary, skip the payload value …
- Very specific: line 297
If num is unrecognized: in Binary, slice the raw bytes of the wire tag + number + skipped payload value.
- Distinctive: line 300
When skipping an unrecognized struct field or a removed/unrecognized enum wrapper payload in binary:
- Very specific: line 316
Every Serializer<T> exposes .typeDescriptor returning a TypeDescriptor that can be serialized to pretty-printed JSON (2-space indentation) …
- Very specific: line 352
Consider enum JsonValue in enums.skir, which has array: [JsonValue] and object: [JsonValue.Pair|name] where struct Pair has value: …
- Very specific: line 353
When collecting the "records" list for TypeDescriptor, do not only check direct self-recursion (vType.key === currentRecord.key)!
- Very specific: line 354
Instead, traverse record dependencies using a visited: Set<string> of record IDs:
- Very specific: line 355
Before recursing into a struct's fields or an enum's wrapper variant types, check if (visited.has(recordId)) return;, add recordId to …
- Very specific: line 356
Ensure that both RecA and RecB appear in "records" when RecA.serializer.typeDescriptor is inspected.
- Very specific: line 362
Every runtime client library implements Method<Req, Resp>, Service<Meta>, and ServiceClient:
- Very specific: line 379
If "method" is an integer (or numeric string), look up by number.
- Very specific: line 389
If response status is 200, parses body with method.responseSerializer.fromJsonCode(respBody).
- Distinctive: line 395
Before declaring a new language generator or client library complete, verify every item in this list:
- Very specific: line 401
If using a nullable backing field _rec_a with getter a => _rec_a ??
- Very specific: line 403
When Recursive<T> has no value (!HasValue), emit "[]" / "{}" / wire 246 directly.
- Very specific: line 407
Never bind local variables inside generated serializer/decoder functions using raw unprefixed field names (let ${fieldName}_serializer = ...
- Very specific: line 408
If a struct has a field named user in the same module as struct User, let user_serializer = user_serializer() shadows the module-level …
- Very specific: line 409
If a struct has a field named arr, bits, keep, stream, offset, json, or slots_to_fill, unprefixed local bindings will shadow the decoder …
- Very specific: line 411
If wrapper variants add a Wrapper suffix in KindType (foo: T $\rightarrow$ FooWrapper) while constant variants do not (foo_wrapper.
- Very specific: line 413
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 …
- Very specific: line 415
Always guard if (&other != this) before calling destroy() or freeing buffers in custom operator=.
- Very specific: line 416
When unescaping JSON strings containing \u0000, never push an extra C-string '\0' terminator into the middle of a length-delimited …
- Very specific: line 420
Rule: When encoding a string to binary (encode / toBytes) or decoding a string from binary (decode / fromBytes), any invalid UTF-8 byte …
- Very specific: line 430
When a variant evolved from wrapper to constant, a readable JSON object {"kind": "variant_name", "value": ...} must ignore "value" and …
- Very specific: line 431
When isDefault is called on a struct or enum, always verify that _unrecognized is also null/empty (getUnrecognized(value) == null), and …
- Very specific: line 437
When adding a new language <lang>, create and update all of the following locations:
- Very specific: line 440
Create packages/compiler/src/generators/<lang>/index.ts (plus naming.ts, type_speller.ts, etc.).
- Very specific: line 442
Add unit tests in packages/compiler/src/generators/<lang>/index.test.ts.
- Very specific: line 446
Create e2e-tests/<lang>/skir.yml referencing @gepheum/skir-fantasy-game-example and the latest @gepheum/skir-golden-tests tag.
- Very specific: line 455
Create examples/<lang>/ (skir.yml, skir-src/service.skir, skirout/, snippets, server, client, README.md, .github/workflows/ci.yml).
- Very specific: line 456
Add <lang> to .github/workflows/ci.yml and .github/workflows/sync-examples.yml.
- Very specific: line 457
Create .github/workflows/publish-client-<lang>.yml (if mirrored to a GitHub repo, use a release_version input with default: "patch", not an …
- Distinctive: line 460
Update packages/website/.vitepress/config.mts and
- Distinctive: line 461
Update packages/website/public/llms.txt and regenerate
- Very specific: line 462
Update README.md and skills/skir/SKILL.md.
- Very specific: line 464
Run ./pre_commit.sh --lang <lang> (and full ./pre_commit.sh) and verify zero warnings, zero lint errors, and 100% passing unit, E2E, and …
“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.
Files
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:
- 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 shareclient-libraries/csharp).
- Provides primitive serializers (
- Code Generator (
packages/compiler/src/generators/<lang>/)- A TypeScript module inside
packages/compilerimplementingCodeGenerator<Config>fromskir-internaland registered inpackages/compiler/src/config_parser.tsunderSTATIC_GENERATORS["skir-<lang>-gen"]. - Note: Built-in generators do not need runtime reflection value-transformation capabilities (
ReflectiveTransformer/mapFieldsas in Kotlin/Dart)—onlyTypeDescriptormetadata (asJson/parseFromJson) is required by the golden tests.
- A TypeScript module inside
- 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-exampleand@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, andService/ServiceClient. - Wired into
e2e-tests/format-all.sh,e2e-tests/test.sh, andpre_commit.sh.
- Compiles all schemas in
- 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 tohttps://github.com/gepheum/skir-<lang>-examplevia.github/workflows/sync-examples.yml.
- Self-contained starter project (
- Documentation & Website (
docs/languages/<lang>.md&packages/website/)- Comprehensive user guide in
docs/languages/<lang>.md, sidebar & homepage integration inpackages/website/, and LLM bundle updates (llms.txt,llms-full.txt,README.md,skills/skir/SKILL.md).
- Comprehensive user guide in
- Publishing Workflow (
.github/workflows/publish-client-<lang>.yml)- Manual
workflow_dispatchGitHub Actions workflow that publishes to the language's package registry (npm, PyPI, crates.io, NuGet, Maven Central, Hex.pm, RubyGems, pub.dev) or mirrorsclient-libraries/<lang>tohttps://github.com/gepheum/skir-<lang>-client.gitwith arelease_versioninput (default: "patch").
- Manual
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.skirmodule inskir-src/andskir-external/.recordMap: ReadonlyMap<RecordKey, RecordLocation>— Lookup table fromRecordKeytoRecordLocation(record,recordAncestors,modulePath).config: Config— Parsed and Zod-validated generator configuration fromskir.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:
- Strict Casing in
.skirSource:- Record names (
structandenum) andmethodnames are strictlyUpperCamel(PascalCase). - Struct field names and enum variant names (both constant and wrapper variants) are strictly
lower_underscore(snake_case). - Top-level
constnames are strictlyUPPER_UNDERSCORE(UPPER_SNAKE_CASE).
- Record names (
- No
"unknown"or"UNKNOWN"Enum Variant Names:- The Skir compiler forbids naming any enum variant
unknownorUNKNOWN. - Because every enum implicitly has an
unknownvariant (field number0), you never have to worry about a user-defined variant namedunknowncolliding with the built-inUnknownvariant,KindType.Unknown, orVisitor.onUnknown!
- The Skir compiler forbids naming any enum variant
- Case-Insensitive Uniqueness Within a Scope:
- Because all fields and variants are enforced
lower_underscore(and record names areUpperCamel), 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 baseObjectmethod (equals,hash_code,to_string,clone), a generated class member (default,serializer,kind,unknown,accept,visitor), or an enclosing type name (e.g. a fieldfooinsidestruct Foo, orenum Kind). - An enum can have a wrapper variant
foo: string;and a constant variantfoo_wrapper;. If your generator appendsWrapperto wrapper variant names inKindType(e.g.Foo$\rightarrow$FooWrapper) while converting constant variants toUpperCamel(foo_wrapper$\rightarrow$FooWrapper), those two will collide unless you disambiguate the constant variant (e.g.FooWrapper_)!
- A struct or enum can have a field/variant whose name matches a target-language keyword (
- Because all fields and variants are enforced
- Keyed Array (
[Item|key_path]) Path Invariants:- In
ArrayType, iftype.key(FieldPath) is present:type.itemis guaranteed to be astruct(ResolvedRecordRefwithrecordType === "struct").- Every intermediate step in
type.key.pathis guaranteed to be a non-optional, non-recursive (field.isRecursive !== "hard")structfield (kind === "record"). - The final step in
type.key.pathis guaranteed to be either aprimitivefield (type.key.keyType.kind === "primitive") OR.kindon anenumfield (type.key.keyType.kind === "record"withrecordType === "enum", and the last path item'sname.text === "kind"). - Important Consequence: Both
optional(T?) fields andhardrecursive (field.isRecursive === "hard") struct fields are rejected byvalidateArrayKeysinmodule_set.tsand can never appear anywhere in a keyed-array key path! - Because
via-optionalfields are alsooptional(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 alongtype.key.path! - The only special case a key-extractor generator must handle along
type.key.pathis the final.kindaccessor (including when the enum itself is namedKindand renames its.Kindproperty to.Kind_, as in C#).
- In
- 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) containsS.DEFAULTthrough this field (direct self-recursionstruct A { a: A; }or mutual struct recursionstruct A { b: B; } struct B { a: A; }without passing through an array[...], optionalT?, or enum)."via-optional": The field's top-level type isT?(optional),Tis a struct, andT.DEFAULTreachesS.DEFAULT(e.g.struct Node { next: Node?; })."soft": Reaches the enclosing record through an array[...]or an enum wrapper variant.
- Depth-First Record Ordering in
module.records:module.recordslists all top-level and nested records in depth-first post-order (Foo.Barappears beforeFoo).
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/@JvmNameannotations so Java and Scala call it natively. - .NET (
client-libraries/csharp): Shared by C# and F#.Serializers.OptionalCustomallows F# to use native F#'T option(None/Some) instead of C#Nullable<T>while reusing 100% ofSkirClient.
- JVM (
- No (Standalone runtime in
client-libraries/<lang>):- TypeScript (
packages/typescript-client), Python, Ruby, C++, Go, Rust, Dart, Swift, Zig, Gleam, MoonBit, OCaml.
- TypeScript (
Q2: How should .skir modules map to generated output files?
- Pattern A: 1 output file per
.skirfile (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.skirmap toskirout/@owner/pkg/foo.<ext>(orskirout/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.fsfile to be listed manually in strict dependency order inside.fsprojand forbids circular dependencies across files unless combined viamodule ... and .... Emitting one topologically sortedskirout/Skirout.fslets the user add<Compile Include="skirout/Skirout.fs" />to.fsprojonce and never touch.fsprojagain when.skirfiles are added or removed. - Why MoonBit uses a single package
skirout/: MoonBit compiles all.mbtfiles in a package directory together into one namespace.
- Why F# uses a single
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).
- Used when the language supports nested types inside classes or companion modules: Java (
- Flattened Top-Level Types (
User_PetorUserPet):- 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_Barexists at top-level andstruct Foo { struct Bar }is nested, or if an enumStatushas a nested structTrial(StatusTrial) AND a variant constructorStatusTrial(StatusTrial), you must deterministically disambiguate collisions!- Example (C#/F#): Escape literal underscores in
.skirrecord 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:SubscriptionStatusTrialfor the struct,SubscriptionStatusTrialX(SubscriptionStatusTrial)for the variant constructor).
- Example (C#/F#): Escape literal underscores in
- Used when the language does not allow nested types inside struct/record types: C# (
Q4: How should structs be represented (Immutability, Construction, Partial Initialization, and Copying)?
Every generated Skir struct must support:
- Deep immutability (or value semantics where
let/constbindings cannot be mutated). - A default instance (
User.DEFAULT/User.default/User.defaultInstance/user_default) with all fields initialized to their Skir defaults. - Full construction and partial construction (omitted fields default to their Skir defaults).
- Non-destructive copying / updating (creating a modified copy from an existing instance).
How existing languages achieve this idiomatically:
- Languages with built-in record copy /
withexpressions & optional/default arguments:- C#:
public readonly record struct Userwithpublic required T Field { get; init; }+User.Default. Partial init and updates both use C#'s nativewithexpression:User.Default with { UserId = 42, Name = "John" }andjohn with { Name = "Jane" }. - F#: Immutable F# record
{ UserId: int64; Name: string; ... }+User.Default+User.Create(?userId, ?name, ...)static method with optional parameters defaulting toDefault, 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 updateUser(..user_default, name: "John"). - Rust / MoonBit / Zig / Swift: Native
structwith default constructor/constant and field initializers.
- C#:
- Languages using a Frozen Class + Mutable Builder Class (
User+User.Mutable):- Kotlin, Dart, Python, Ruby, C++:
Useris deeply immutable (toMutable()returns a shallow mutable copyUser.Mutable).User.Mutablehas mutable properties andmutable<Field>copy-on-write getters for nested structs/arrays, and.toFrozen()returns an immutableUser.- In Python and Ruby,
User(...)keyword arguments are all optional and default to the field's default value (User(user_id=42, name="John")), whileUser.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, plusUser.partialBuilder()where all fields are optional and pre-populated with defaults, anduser.toBuilder()for modifying an existing instance.
- Kotlin, Dart, Python, Ruby, C++:
Q5: How should enums be represented (Pattern Matching, Kind, and Type Safety)?
Every Skir enum has:
- The built-in
unknownvariant (field number0, 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:
- 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 anUnknown(UnrecognizedVariant)case, constant cases, and payload-carrying wrapper cases. Exhaustive pattern matching is checked directly by the host compiler! - Kotlin & Dart:
sealed interface/sealed classhierarchy 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 aKindenum so users can eitherswitch/whenon the sealed type (with smart casting / pattern destructuring) orswitchon.kind.
- Rust, OCaml, Gleam, MoonBit, F#, Scala 3, Swift: Native
- Single Sealed Class +
KindEnum +wrap_*/as_*+Visitor(For languages without native ADTs):- Java, C#, C++, Go, TypeScript, Python, Ruby:
- CRITICAL LESSON ON
KindTYPE SAFETY (From Ruby Audit Feedback):- Never make
Kinda rawstringorint! When Ruby's generator was first created,SubscriptionStatus::Kind::FREEwas just the plainString"free". That was bad for type safety (and Sorbet typing) because any arbitrary string could be passed where aKindwas expected. - Even in dynamic languages (or languages with gradual typing like Ruby + Sorbet or Python),
Kindshould be a dedicated typed enum/class (e.g.,T::Enumor a dedicated frozen class in Ruby;enum.Enumin Python;public enum KindTypein C#;public enum Kindin Java), and in statically typed languages it must be a distinct enum type!
- Never make
- Convenience
create_<variant>constructors for struct payloads:- When a wrapper variant wraps a
struct(e.g.,trial: struct { start_time: timestamp; }), generate bothwrap_trial(trial_struct)ANDcreate_trial(start_time: ...)(as in Dart, Kotlin, Java, Python, Ruby, TypeScript). Users lovecreate_trial(...)because they don't have to import or construct the nested struct type manually.
- When a wrapper variant wraps a
Q6: How should Value Equality (==) and Hashing (hashCode) work?
Every Skir struct and enum represents a value, not an object identity.
- Arrays/Lists inside structs AND inside enum wrapper variants:
- Many languages have list/array types that use reference equality by default:
- Java (
arrayarrays — useList), C# (ImmutableArray<T>compares the backingT[]pointer!), F# ('T arrayinside discriminated unions or records), Dart (List<T>usesidentical(a, b)!), Go (slices cannot use==).
- Java (
- 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 (
_FrozenListImplin Dart,tuplein Python,.freezein Ruby). Do not forget to apply the exact same freezing/copying in enumwrap_*constructors and array deserializers (Dart Bug #2)! - Notice that in C#, we intentionally skipped generating custom
Equals/GetHashCodeonreadonly record structto keep the generated code concise, whereas in F# we emit custom structuralEqualsandGetHashCodeusing a recursive structural helper.
- Many languages have list/array types that use reference equality by default:
- Unrecognized fields (
_unrecognized) andUnknownenum variants:- Enums: Two
Unknownenum instances must always compare equal (a == bistrue) and have the same hash code, regardless of whether one was constructed viaMyEnum.UNKNOWNand the other was decoded from an unrecognized variant number withkeepUnrecognizedValues = true! - Structs:
_unrecognizedmust never be included inequalsorhashCode, and must never be a required parameter in the public struct constructor.
- Enums: Two
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.DEFAULTinitializes_rec_a = null.- The public getter
rec.areturns_rec_a ?? RecA.DEFAULT, soRecA.DEFAULT.a.a.aworks seamlessly with zero wrapper noise in user code!
- CRITICAL BUG PREVENTION (Dart Bug #1 —
StackOverflowErrorinhashCode/equals):- In the private constructor of
RecA, normalize default values tonull:
(Note: checkthis._rec_a = (_rec_a == null || _rec_a == RecA.defaultInstance) ? null : _rec_a_rec_a == nullfirst so constructingdefaultInstance = RecA._(null)short-circuits without referencingRecA.defaultInstancebeforedefaultInstancefinishes initializing!) - In
equalsandhashCode(e.g._equality_proxy), always readthis._rec_a, NEVER the public getterthis.a! IfhashCodeorequalsreadsthis.a, callingRecA.DEFAULT.hashCodeevaluatesthis.a$\rightarrow$RecA.DEFAULT$\rightarrow$RecA.DEFAULT.hashCode$\rightarrow$ infinite recursion (StackOverflowError)!
- In the private constructor of
- 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.tor recursive record). - CRITICAL BUG PREVENTION (C# Bug #3 & Gleam Bug #6):
- When
Recursive<T>is in its unset/default state (!HasValue/Recursive.Default),ToJsonmust directly output"[]"(dense) or"{}"(readable) andEncodemust directly output wire byte246. Never construct a zero-initialized value-typedefault(T)in C# and pass it to_inner.ToJson(default(T))—its reference fields (string,enum) andImmutableArrayfields will benull/uninitialized and crash withNullReferenceException! - On
FromJsonandDecode, ifRecursive<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-trippingRecStructpreserves==.
- When
- Used in: C# (
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
fromJsonimplementation 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 byadapter.encode(value).Serializer.fromBytes(bytes)must verify thatbyteshas length $\ge 5$ and starts with"skir", then decode starting at byte offset4.
4.3 Primitive Wire Formats
| Primitive | Default | Dense JSON | Readable JSON | Binary Encoding | Binary & JSON Decoding Rules |
bool | false | 0 or 1 | false or true | false $\rightarrow$ 0x00<br>true $\rightarrow$ 0x01 | JSON: 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. |
int32 | 0 | integer | integer | 0..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! |
int64 | 0 | number if in [-9007199254740991, 9007199254740991] ($\pm(2^{53}-1)$); quoted string "..." outside! | Same as Dense JSON | If 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) | 0 | number if $\le 9007199254740991$ ($2^{53}-1$); quoted string "..." if $> 9007199254740991$ | Same as Dense JSON | 0..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! |
float32 | 0.0 | number if finite; "NaN", "Infinity", "-Infinity" if non-finite | Same as Dense JSON | v == 0.0 $\rightarrow$ 0x00<br>else $\rightarrow$ 240 + 4-byte IEEE-754 float32 LE | JSON: number or "NaN", "Infinity", "-Infinity".<br>Binary: Any numeric wire tag 0..241. |
float64 | 0.0 | number if finite; "NaN", "Infinity", "-Infinity" if non-finite | Same as Dense JSON | v == 0.0 $\rightarrow$ 0x00<br>else $\rightarrow$ 241 + 8-byte IEEE-754 float64 LE | JSON: number or "NaN", "Infinity", "-Infinity".<br>Binary: Any numeric wire tag 0..241. |
timestamp | Unix epoch 0 ms | integer 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! |
bytes | empty b"" | Base64 string "..." | "hex:<lowercase-hex>" | empty $\rightarrow$ 244 (0xF4)<br>non-empty $\rightarrow$ 245 (0xF5) + encodeUint32(len) + raw bytes | JSON: 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):trueiffvisnull/None.- JSON Encoding:
nullifNone;inner.toJson(v)ifSome(v). - JSON Decoding: If JSON token is
null$\rightarrow$None; otherwiseSome(inner.fromJson(json)). - Binary Encoding:
None$\rightarrow$ single wire byte255(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 returnNone. - Otherwise, do not consume a tag byte—pass the stream directly to
inner.decode(stream)and wrap the result inSome(...)!
- Peek next byte: if it is
- CRITICAL INVARIANT (Caught in C# Bug #2 & Gleam Bug #1 by Golden Tests
#1038and#1101):Some(default_value)(for exampleSome(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 tohex:736b697200(wire byte0). - When deserializing
"0"or wire byte0asbool?,fromJsonanddecodemust returnSome(false)—NEVER checkif (inner.isDefault(result)) return None;and NEVER treat wire byte0asNone! Only JSONnulland binary wire255representNone.
2. array ([T] and [T|key])
- Default:
[](empty array). isDefault(v):v.isEmpty.- JSON:
[item_0, item_1, ...]. OnfromJson, also accept0as[]. - Binary:
len == 0$\rightarrow$ wire246(0xF6)len == 1$\rightarrow$ wire247(0xF7) + element 0len == 2$\rightarrow$ wire248(0xF8) + elements 0, 1len == 3$\rightarrow$ wire249(0xF9) + elements 0, 1, 2len >= 4$\rightarrow$ wire250(0xFA) +encodeUint32(len)+lenelements.- On
decode, also accept wire0as[]. Validate0 <= lenand remaining buffer capacity before allocating!
3. struct
- Default:
S.DEFAULT(all fields have their default values and_unrecognizedis empty/null). isDefault(s):trueiff every field satisfiesfieldAdapter.isDefault(s.field)ANDs._unrecognizedis null/empty.- Slot Layout & Unrecognized Field Preservation:
- Let
totalSlotsbe the active prefix length when serializing:- If
s._unrecognizedis present and matches the target format (Dense JSON for Dense JSON output; Binary for Binary output) ands._unrecognized.totalSlots > record.numSlotsInclRemovedNumbers:- All known fields in
0 ..< record.numSlotsare encoded (even if default, because non-default unrecognized fields follow them!), removed slots in0 ..< record.numSlotsInclRemovedNumbersare encoded as0, and then the raw unrecognized tail elements/bytes for slotsrecord.numSlotsInclRemovedNumbers ..< s._unrecognized.totalSlotsare appended!
- All known fields in
- Otherwise (no unrecognized tail for this format):
- Find the highest field number
maxNonDefaultSlotwhose value is not default (!fieldAdapter.isDefault(val)). - If no field is non-default,
activeSlots = 0(encodes as[]in Dense JSON,{}in Readable JSON, wire246in Binary). - Otherwise,
activeSlots = maxNonDefaultSlot + 1, and encode slots0 .. maxNonDefaultSlotin order (writing0for removed slots or default slots beforemaxNonDefaultSlot).
- Find the highest field number
- If
- 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
removednumbers at the end (e.g. field0isx, and slot1isremoved;, sonumSlots = 1andnumSlotsInclRemovedNumbers = 2), and a payload arrives with 2 slots[10, 99]?- Slot
1is a known removed slot, NOT an unrecognized future slot! You must skip/drop slots< numSlotsInclRemovedNumbersand only preserve unrecognized slots at indices $\ge \text{numSlotsInclRemovedNumbers}$! (Tested by golden tests#1053–#1058and#1067–#1068!)
- Slot
- If
keepUnrecognizedValues == false, simply skip any slots $\ge \text{numSlots}$ without storing them.
- A sender with a newer schema may have added fields at slot numbers $\ge$ your
- Let
4. enum
- Default:
E.UNKNOWN(with no unrecognized variant payload). isDefault(e):trueiffeisUNKNOWNAND carries no unrecognized variant payload.- Dense JSON Encoding:
UNKNOWNwith preserved Dense JSON unrecognized payload $\rightarrow$ emit raw preserved JSON verbatim.UNKNOWNwithout 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>"(inlower_underscore). - Wrapper variant $\rightarrow$
{\n "kind": "<variant.name>",\n "value": <payloadAdapter.toReadableJson(e.value)>\n}.
- Binary Encoding:
UNKNOWNwith preserved Binary unrecognized payload $\rightarrow$ emit raw preserved bytes verbatim.UNKNOWNwithout unrecognized payload $\rightarrow$0x00.- Constant variant $\rightarrow$
encodeInt32(variant.number)(always wire $< 242$). - Wrapper variant:
- If
1 <= variant.number <= 4$\rightarrow$ single wire byte250 + variant.number(251,252,253, or254) +payloadAdapter.encode(e.value). - If
variant.number >= 5$\rightarrow$ wire byte248(0xF8) +encodeInt32(variant.number)+payloadAdapter.encode(e.value).
- If
- Deserialization & Schema Evolution Rules for Enums (Tested by Golden Tests
#1059–#1070,#1087–#1100):- Constant representation in input (Dense JSON integer
num/ Readable JSON string"name"/ Binary wire< 242):- If
num == 0or"unknown"/"UNKNOWN"$\rightarrow$E.UNKNOWN. - If
numis inremovedNumbers$\rightarrow$E.UNKNOWN(do not keep as unrecognized!). - If
num(or"name", accepting bothlower_caseandUPPER_CASEfor 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
numis unrecognized: ifkeepUnrecognizedValuesistrue(and input is Dense JSON or Binary), returnE.UNKNOWNwrapping the raw JSON/bytes; else returnE.UNKNOWN.
- If
- Wrapper representation in input (Dense JSON
[num, valJson]/ Readable JSON{"kind": name, "value": valJson}/ Binary wire248or251..254):- If
numis inremovedNumbers$\rightarrow$ in Binary, skip the payload value (skipValue(stream)) so the stream position stays valid, and returnE.UNKNOWN! - If
num(orname) matches a wrapper variant $\rightarrow$ decodevalwithpayloadAdapter(passingkeepUnrecognizedValues) and wrap it.- CRITICAL (Dart Bug #5): In Readable JSON
{"kind": "opt_field", "value": null},"value"is present with valuenull. Checkobj.containsKey("value"), notobj["value"] != null!
- CRITICAL (Dart Bug #5): In Readable JSON
- If
nummatches a constant variant (schema evolved from wrapper to constant!) $\rightarrow$ in Binary, skip the payload value (skipValue(stream)), and return the constant variant! - If
numis unrecognized: in Binary, slice the raw bytes of the wire tag + number + skipped payload value; ifkeepUnrecognizedValuesistrue, wrap inE.UNKNOWN, else returnE.UNKNOWN.
- If
- Constant representation in input (Dense JSON integer
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 numberlen = decodeNumber(stream), validatelen >= 0and remaining bytes $\ge \text{len}$, then advancelenbytes.247,251,252,253,254: recursively callskipValue(stream)1 time.248: recursively callskipValue(stream)2 times (works for both 2-element array/struct AND enum wrapper248 + number + payloadbecausenumberis itself a valid single Skir value!).249: recursively callskipValue(stream)3 times.250: decode numbercount = decodeNumber(stream), validatecount >= 0, and recursively callskipValue(stream)counttimes.
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:
- Omit empty optional properties in record descriptors:
"doc"on a struct, enum, field, or variant is only included in the JSON object whendocis non-empty (doc.length > 0)!"removed_numbers"on a struct or enum is only included whenremovedNumbers.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 originalsnake_casepath from.skir(e.g."sub_item.weekday.kind"), not the target language's camelCase property names!
- Preventing Infinite Recursion on Recursive Enums/Structs (Gleam Bug #2):
- Consider
enum JsonValueinenums.skir, which hasarray: [JsonValue]andobject: [JsonValue.Pair|name]wherestruct Pairhasvalue: JsonValue, or mutually recursive structsRecAandRecB. - When collecting the
"records"list forTypeDescriptor, 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;, addrecordIdtovisited, and use a lazy thunk (() => Serializer) for record references so mutually recursive serializers don't infinite-loop during static initialization orTypeDescriptorconstruction! - Ensure that both
RecAandRecBappear in"records"whenRecA.serializer.typeDescriptoris inspected.
- Before recursing into a struct's fields or an enum's wrapper variant types, check
- Consider
6. SkirRPC Service & ServiceClient Specification
Every runtime client library implements Method<Req, Resp>, Service<Meta>, and ServiceClient:
Method<Req, Resp>:- Holds
name: string,number: uint32(int64),requestSerializer: Serializer<Req>,responseSerializer: Serializer<Resp>,doc: string.
- Holds
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 == ""orrawBody == "studio"$\rightarrow$ HTTP200,text/html; charset=utf-8, HTML page loading Skir Studio JS fromstudioAppJsUrl(default"https://cdn.jsdelivr.net/npm/skir-studio-app@latest/dist/skir-studio-app.js").rawBody == "list"$\rightarrow$ HTTP200,application/json, JSON object{"methods": [ { "method": "...", "number": 123, "request": <TypeDescriptor>, "response": <TypeDescriptor>, "doc": "..." } ]}.
- Two RPC Request Formats:
- 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).
- Split on
- 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")), NOTobj["request"] != null! When its value is JSONnull, pass"null"(orJsonNull) torequestSerializer.fromJson. - JSON-object requests always serialize their response in readable JSON (
readable = true).
- Parse JSON object
- Colon-separated format (
- 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$ invokeerrorLoggerand return HTTPstatusCode(400..599,text/plain; charset=utf-8,message). - Handler throws unexpected exception $\rightarrow$ invoke
errorLoggerand return HTTP500(text/plain; charset=utf-8, message ifcanSendUnknownErrorMessageis true, else"internal server error").
- Bad request format / unknown method / request JSON parse failure $\rightarrow$ HTTP
- Built-in Studio / Discovery bodies:
- Built via builder/registration pattern mapping
ServiceClient(HTTP Client):- Validates
serviceUrl(must be a validhttp://orhttps://URL without a query string?). - Sends
POSTtoserviceUrlwith body<method.name>:<method.number>::<requestDenseJson>, plus custom headers and deadline/timeout support. - If response status is
200, parses body withmethod.responseSerializer.fromJsonCode(respBody). Otherwise throws/returnsRpcError(statusCode, body).
- Validates
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:
- Optional
Some(default)vsNone(C# Bug #2, Gleam Bug #1):optional_serializermust encodeNoneas wire255andSome(x)asinner.encode(x)with no tag prefix.- On decode/fromJson, only wire
255/ JSONnullreturnsNone. Wire0/ JSON0onbool?orint32?must returnSome(false)/Some(0), neverNone.
"hard"Recursive StructhashCode/equalsStack Overflow (Dart Bug #1):- If using a nullable backing field
_rec_awith gettera => _rec_a ?? Default, normalize_rec_a == Defaulttonullin the constructor and reference_rec_a(neverthis.a) inequalsandhashCode.
- If using a nullable backing field
- Value-Type
default(T)vsT.DefaultinRecursive<T>(C# Bug #3):- When
Recursive<T>has no value (!HasValue), emit"[]"/"{}"/ wire246directly.
- When
- 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 enumwrap_*factory methods as well as struct constructors, and ensure the array deserializer returns the value-equated frozen list type.
- Apply
- 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 = ...orlet ${fieldName} = ...). - If a struct has a field named
userin the same module asstruct User,let user_serializer = user_serializer()shadows the module-leveluser_serializer()function and breaks compilation if another field in the same struct also has typeUser! - If a struct has a field named
arr,bits,keep,stream,offset,json, orslots_to_fill, unprefixed local bindings will shadow the decoder function's own parameters! Always prefix generated local variables (e.g._f_${fieldName},_ser_${fieldName}).
- Never bind local variables inside generated serializer/decoder functions using raw unprefixed field names (
- Enum
KindTypeCollisions Betweenfoo: T;andfoo_wrapper;(C# Bug #5):- If wrapper variants add a
Wrappersuffix inKindType(foo: T$\rightarrow$FooWrapper) while constant variants do not (foo_wrapper;$\rightarrow$FooWrapper), reserve all wrapper variantKindTypenames first and disambiguate colliding constant variants asFooWrapper_.
- If wrapper variants add a
- Enum Named
KindUsed as a Key in a Keyed Array ([Item|kind_enum.kind]) (C# Bug #4):- If an enum is named
Kindand its.Kindproperty is renamed to.Kind_to avoid colliding with the enclosing class name, ensureKind_ispublic(notinternal) and that keyed-array key extractors checkenumTypeName === "Kind"and emit.Kind_.
- If an enum is named
- C++ Union/Enum Self-Assignment &
CopyUtf8StringEmbedded NUL (C++ Bugs #1, #2, #3):- Always guard
if (&other != this)before callingdestroy()or freeing buffers in customoperator=. - When unescaping JSON strings containing
\u0000, never push an extra C-string'\0'terminator into the middle of a length-delimitedstd::stringbuffer.
- Always guard
- Binary String Encoding & Decoding Must Always Produce Valid UTF-8 With
U+FFFDReplacement (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 withU+FFFD(0xEF 0xBF 0xBD). - Beware of standard-library defaults that use
'?'(0x3F) instead ofU+FFFDduring UTF-8 encoding:- On the JVM (
Kotlin/Java/Scala),String.toByteArray(Charsets.UTF_8)replaces unpaired surrogates with'?'(0x3F). Always sanitize unpaired surrogates inStringto\uFFFDbefore callingtoByteArray(Charsets.UTF_8)inencode! - In
Python,str.encode("utf-8", errors="replace")replaces unpaired surrogates with'?'(0x3F). Always replace code points in0xD800..0xDFFFwith"\ufffd"before calling.encode("utf-8")inencode!
- On the JVM (
- In languages where in-memory strings are UTF-16 code units (
- Corrupted Binary Inputs, Negative/Huge Lengths, and Trailing Bytes:
Serializer.fromBytes(bytes)must fall back to JSON parsing whenbytesdoes 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(wire243),bytes(wire245),array(wire250),struct(wire250), orskipValue,decodeNumbercan return a negative number (via wires235..241) or a huge number exceeding remaining input bytes. Always validate0 <= count <= remainingBytesbefore allocating arrays or advancing pointers!
- Enum Readable JSON Schema Evolution & Case-Insensitive Variant Lookup:
- Register both
lower_caseandUPPER_CASEaliases 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 anoptionalpayload typeT?, the default value isnull/None/ wire255, not0!). - 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
isDefaultis called on astructorenum, always verify that_unrecognizedis also null/empty (getUnrecognized(value) == null), and ensureUNKNOWNenums with unrecognized payloads still serialize to"unknown"in readable JSON.
- Register both
8. Complete Monorepo Integration Checklist
When adding a new language <lang>, create and update all of the following locations:
- Compiler Generator (
packages/compiler/):- Create
packages/compiler/src/generators/<lang>/index.ts(plusnaming.ts,type_speller.ts, etc.). - Register
skir-<lang>-geninSTATIC_GENERATORSin packages/compiler/src/config_parser.ts. - Add unit tests in
packages/compiler/src/generators/<lang>/index.test.ts.
- Create
- Runtime Client Library (
client-libraries/<lang>/):- Implement serializers, reflection
TypeDescriptor,Service,ServiceClient, and comprehensive unit tests.
- Implement serializers, reflection
- End-to-End & Golden Tests (
e2e-tests/<lang>/):- Create
e2e-tests/<lang>/skir.ymlreferencing@gepheum/skir-fantasy-game-exampleand the latest@gepheum/skir-golden-teststag. - 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_testrunning allUNIT_TESTSfromgoldens.readonly.skir(includingreserialize_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 everyexpected_bytespayload can be skipped as an unrecognized slot inPoint). - Wire
<lang>into:- e2e-tests/format-all.sh
- e2e-tests/test.sh
- pre_commit.sh
- pre_commit_setup.sh
- Create
- 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 arelease_versioninput withdefault: "patch", not an input namedtag, because GitHub'sworkflow_dispatchweb UI rejects inputs namedtag!).
- Create
- 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.
- Write
- 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.
- Run
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
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.

