The Rust target-language layer for Skmtc generators (@skmtc/lang-rust). It covers the projection base factories, RsSnippet, the register shape with `use` imports and modules, the seven identifier kinds, a file as a module and a folder as a module, the `mod.rs` that declares each file, the head and value render model, functions as members of an `impl` block, `Option` and `Box`, the producers for structs, enums, functions, blocks and names, and the conventions of the reference SDK. Use ALONGSID...
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Skmtc Lang Rust?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/skmtc-skmtc-lang-rust)
---
name: skmtc-lang-rust
version: 0.2.0
description: >
The Rust target-language layer for Skmtc generators (@skmtc/lang-rust).
It covers the projection base factories, RsSnippet, the register shape
with `use` imports and modules, the seven identifier kinds, a file as a
module and a folder as a module, the `mod.rs` that declares each file,
the head and value render model, functions as members of an `impl`
block, `Option` and `Box`, the producers for structs, enums, functions,
blocks and names, and the conventions of the reference SDK. Use
ALONGSIDE skmtc-generator whenever a generator writes Rust.
metadata:
internal: true
---
# The Rust layer (@skmtc/lang-rust)
Read `skmtc-generator` first. The two worked examples are
`@skmtc/gen-rust-serde` (a model generator) and `@skmtc/gen-rust-reqwest`
(an SDK: one Index that holds a method for each operation). Generated
code targets the 2021 edition of Rust or later.
## 1. Declare the language
The import graph declares the language. `src/base.ts` imports a factory,
and each snippet extends `RsSnippet`.
```ts fragment
import { RsName } from '@skmtc/lang-rust/RsName'
import { toRsModelProjectionBase } from '@skmtc/lang-rust/toRsModelProjectionBase'
export const RsSerdeBase = toRsModelProjectionBase<EnrichmentSchema>({
id: denoJson.name,
toIdentifierName({ ref }) {
return new RsName(toModelName(ref)).toPascal()
},
toIdentifierType(ref, context) { … },
toExportPath({ ref, enrichments, variant }) {
const name = this.toIdentifierName({ ref, enrichments, variant })
return `@/types/${new RsName(name).toModuleName()}.rs`
},
})
```
The factories are `toRsModelProjectionBase`,
`toRsOasOperationProjectionBase` and `toRsOasOperationIndexBase`.
Each module of the package has an export path of its own
(`@skmtc/lang-rust/RsStruct`). Import from that path, and not from the
root of the package. Do the same for core: `@skmtc/core/Stringable`,
and not `@skmtc/core`.
## 2. A file is a module
Rust compiles a file only when another file declares it as a module. A
file is a module, and a folder is a module too: its `mod.rs` declares
each file and each folder in it.
- **Each base declares its file.** A projection with a file of its own
adds two lines to the `mod.rs` of its folder: `pub mod order;` and
`pub use order::Order;`. The base also declares the folder in the
`mod.rs` of the folder above (`pub mod types;`). It does this up to
the root of the generated files. A member of an Index adds nothing.
You write no code for this.
- **An import is a path from one file to the other.** The engine
registers an import for a definition in another file. `RsFile` renders
it with `RsModulePath`: `use super::order::Order;` in the same folder,
and `use super::types::order::Order;` from the folder above. The path
goes up with `super` and never names the root of the crate, which the
engine does not know.
- **A name is one definition in a folder.** The `mod.rs` makes each name
public from the folder, so `toNameScope` is the folder of the file.
Put the models in a folder of their own (`types`). A model can then
have the name of something beside the folder.
- **The engine adds `.generated` to the name of a file.** Rust looks for
the module `order` in `order.rs`. So the `mod.rs` then says where the
file is: `#[path = "order.generated.rs"]`. A project sets
`settings.generatedSuffix` to `""` to get plain names.
- **A hand-written file is a module too.** A generator that needs one
declares it: register
`modules: [{ path: '@/client.rs', names: ['Client', 'Error'] }]` into
the `mod.rs` (`'@/mod.rs'`). To read it, import the module, and not
its names: `imports: { '@/mod.rs': ['client'] }` is
`use super::client;`, and the code writes `client::Client`. A model
named `Client` or `Error` then clashes with nothing.
- **The crate declares the root folder once, by hand:** `pub mod api;`.
## 3. Register
| Caller | Call | File |
|---|---|---|
| Projection | `this.register(args)` | Its own export file |
| Projection | `this.registerInto(path, args)` | The file you name |
| Snippet | `this.register({ ...args, destinationPath })` | The file you name |
`args` is `{ imports?, modules?, definitions?, custom? }`.
- A `use` names the items of a module:
`imports: { serde: ['Serialize', 'Deserialize'] }`. The key is a Rust
path (`'std::collections'`), or the export path of a file of the
project (`'@/types/order.rs'`).
- **Rust warns about a name that a file imports and does not read.** So
the producer that writes `HashMap` registers `'std::collections'`, in
its constructor. A producer that no code builds registers nothing.
- The file renders its `use` lines in three sorted groups. They are the
standard library, the other crates, and the modules of the project.
- With no `custom`, a file starts with
`// @generated by Skmtc. Do not edit.`.
- `registerModule(context, { path, names })` declares a file in the
`mod.rs` of its folder, and each folder above it. The bases call it.
## 4. Identifier kinds
| Kind | Factory | Renders |
|---|---|---|
| `struct` | `createStruct(name)` | `pub struct Pet ` + value |
| `enum` | `createEnum(name)` | `pub enum Status ` + value |
| `type` | `createAlias(name)` | `pub type Tags = ` + value + `;` |
| `const` | `createConst(name, { typeName })` | `pub const LIMIT: u32 = ` + value + `;` |
| `fn` | `createFunction(name)` | `pub fn list_pets` + value |
| `asyncFn` | `createAsyncFunction(name)` | `pub async fn list_pets` + value |
| `impl` | `createImpl(name, { typeName })` | `impl client::Client ` + value |
- `exported` on the identifier is Rust's `pub`. The package does not read `noExport`.
- The `typeName` of a `const` is its type. The `typeName` of an `impl`
is the type that gets the methods. No other kind reads it.
- An `impl` block has no name in Rust. Its `name` is only what the
engine keeps the definition under.
- The kind does not change an import: `use` names an item of any kind.
## 5. Head and value
The identifier renders the head of a declaration, and the value renders
all that follows. The value of a `struct` is an `RsStruct`, and the
value of an `enum` is an `RsEnum`. The value of a `fn` or an `asyncFn`
is an `RsFunctionValue`, and the value of an `impl` is an `RsBlock`. A
projection holds one and renders it.
**A comment and the attributes are above the declaration, and a trait
that the type implements by hand is after it.** The value cannot write
them there. A definition reads three fields of its value:
```ts fragment
export class RsSerdeProjection extends RsSerdeBase {
value: TypeSystemValue
description: string | undefined
attributes: RsListItem<Stringable>[]
implementations: RsListItem<RsTraitImpl>[]
…
}
```
- `description` is a string, or a producer that the comment reads when
it renders. Use a producer when the comment has more than one part.
- `attributes` holds a producer for each line: an `RsDerive`, an
`RsAttribute`.
- `implementations` holds an `RsTraitImpl` for each block. The
definition writes the name of the type into the head of the block:
`impl<'de> Deserialize<'de> for Pet { … }`.
## 6. A method is a member of a type
Rust declares the functions of a type in an `impl` block. The block can
be in another file than the type. So an Index is the block, and its
members are the functions:
```ts fragment
const ClientMethodsBase = toRsOasOperationIndexBase<EnrichmentSchema>({
id: denoJson.name,
toIdentifierName: () => 'ClientMethods',
toIdentifierType: () => ({ type: 'impl', typeName: 'client::Client' }),
toExportPath: () => '@/operations.rs',
})
export class ClientMethods extends ClientMethodsBase {
methods: RsBlock
constructor(args: OasOperationIndexConstructorArgs<EnrichmentSchema>) {
super(args)
this.methods = new RsBlock(this.definitions, { separator: '\n\n' })
}
override toString(): string {
return `${this.methods}`
}
}
```
Give `RsBlock` the `definitions` array of the Index itself: the functions
arrive after the constructor, and the block reads the array when it
renders. A member projection states `toIndex: () => TheIndex` and no
`toExportPath`. The block holds the kinds `fn` and `asyncFn`. Any other
kind stops the run. The first parameter of a method is an `RsReceiver`
(`&self`).
Both bases are in `base.ts`, as each name and each path of a generator
is. `base.ts` then imports the class of the Index for `toIndex`, and the
file of the Index imports its base from `base.ts`. `toIndex` reads the
class late, but the class extends its base when its file loads. So the
file of the Index must load before `base.ts`: import it first in
`src/mod.ts`, as `gen-rust-reqwest` does. If `base.ts` loads first, the
run stops with `Cannot access 'ClientMethodsBase' before initialization`.
An attribute of the block is a field of the Index:
`attributes = [new RsAttribute({ name: 'allow', arguments: ['clippy::too_many_arguments'] })]`
renders `#[allow(clippy::too_many_arguments)]` above `impl`.
## 7. Option and Box
Rust has no `null`. A value that can be absent or `null` is an
`Option`, and `None` is the absent value.
- `new RsOption({ type, modifiers })` decides the `Option`, from the
`required` and the `nullable` of the place. Each class of a type
position holds one.
- A struct cannot hold itself: its size would have no end. A reference
inside a cycle (`modelRef.suspended || modelRef.inCycle`) is an
`RsBox`. An item of an `RsVec` and a value of a `HashMap` are on the
heap, and need no `Box`.
## 8. Indentation
`rustfmt` writes four spaces for each level. A producer renders its own
lines from column 0. `RsBlock` and `RsIndented` are the only code that
writes the spaces, so blocks nest to any depth. Do not write an indent
in a template for a part that is a producer.
A producer does not wrap a long line. A project sets
`settings.formatter` to `"rustfmt --edition 2021"`.
## 9. Producers
| Producer | Renders |
|---|---|
| `RsList.toArguments(items)`, `.toLines`, `.toParagraphs`, `.toSequence` | `a, b`, one item on each line, a blank line between items, items with nothing between |
| `RsBlock(items, { separator? })` | `{`, the items one level deeper, `}`. `{}` for none |
| `RsStruct(fields)` | `{ … }`, the body of a struct |
| `RsField({ name, type, attributes?, description?, exported? })` | `pub name: Type,` with its comment and attributes above. `exported: false` gives a private field |
| `RsEnum(variants)`, `RsUnitVariant`, `RsTupleVariant` | The body of an enum: `Sold,`, `Text(String),` |
| `RsDerive(traits)` | `#[derive(Debug, Clone)]`, with a line break |
| `RsAttribute({ name, arguments })` | `#[serde(untagged)]`, with a line break. Nothing with no arguments |
| `RsNameValue({ name, value })` | `rename = "shipTo"` |
| `RsOption({ type, modifiers })` | `Option<String>`, or `String` for a value that is always there |
| `RsVec(item)`, `RsBox(type)`, `RsUnit()` | `Vec<String>`, `Box<Node>`, `()` |
| `RsGeneric({ name, arguments })` | `HashMap<String, i64>`, `client::Result<Pet>` |
| `RsFunctionValue({ parameters, result?, statements })` | `(&self, pet_id: i64) -> Pet { … }` |
| `RsReceiver()`, `RsParameter({ name, type })` | `&self`, `pet_id: i64` |
| `RsChain({ receiver, links })`, `RsAwait()` | A chain of calls, one on each line, and `.await` |
| `RsTraitImpl({ generics?, trait, body })` | `impl<'de> Deserialize<'de>`. The definition adds ` for Pet` and the body |
| `RsUse({ path, names, exported? })` | `use serde::{Deserialize, Serialize};` |
| `RsModulePath({ from, to })` | `super::types::pet`, the path from one generated file to another |
| `RsStringLiteral(value)` | `"a \"b\""`, a text of the document as a Rust string |
| `RsDocComment(text)` | `/// text` on each line, or nothing. A code block with no language, or a block that has `rust` or an attribute of a doc test (also beside other words, as in `rust,json`), gets the language `text`, so that `cargo test` does not compile it |
An item that is `undefined` or `null` is absent. `RsBlock` and `RsStruct`
read their array when they render.
A constructor stores producers and facts: a name, a path, a flag. Only
`toString()` writes Rust syntax. For a sign such as `&self`,
`.await` or `()`, hold the producer, and not the text.
## 10. Names and literals
- `new RsName(text).toPascal()` for a struct, an enum and an alias:
`petId` gives `PetId`. `.toVariant()` for a variant of an enum.
`.toSnake()` for a field, a function and a parameter: `pet_id`.
`.toModuleName()` for a module and its file. Each form is a valid
Rust name for any text.
- **A name that Rust keeps gets an underscore at its end.** A keyword is
`type_` as a field, and serde gets `rename = "type"`. Rust code reads
some names with no path: `Option`, `Result`, `String`, `HashMap`,
`Serialize`. A type with such a name is `Result_`. The lists are
`rustKeywords` and `rustReservedTypeNames`.
- A name that would start with a digit starts with a letter. `2nd line`
is the field `x2nd_line` and the type `X2ndLine`. An underscore at the
start says that no code reads the name.
- A script with no case gives one form for a type and for a module.
`toModuleName()` then adds `_mod`, because Rust refuses a module and a
type of one name in one place.
- `new RsNameScope(reserved).claim(name)` makes the names of one list
unique: the fields of a struct, the parameters of a function. Two keys
can give one Rust name (`user-id` and `user_id`), and the second one
gets a number. Put the names that a function declares itself in
`reserved`.
- `new RsStringLiteral(value)` writes a string of the document as a
Rust string, with the escapes of Rust. Hold it in a field. The package
exports no function that returns the literal as text, so a field
cannot hold Rust code.
## 11. A declaration and a type position differ
An object with properties is a struct in its declaration, and only a
name in a type position. The router contract has no argument for
the position. `gen-rust-serde` solves this as follows:
- `toRsSerdeDeclaration` is the router for the value of a declaration.
`toRsSerdeType` is the router for a type position.
- In a type position, an inline object, enum or union declares a type
beside the definition that uses it. It renders the name of that type.
Call
`defineInlineType(context, { stackTrail, destinationPath,
createIdentifier, value })` and read `identifier.name` from the
result. The name is `toInlineTypeName` of the schema's `stackTrail`:
`OrderShipTo`.
- A second walk of one schema gets the definition of the first. Two
schemas whose places give one name get two types, and the second one
has a number (`MessageType2`). The file keeps the name of each place.
- Another generator can need the type of a schema in a type position (a
parameter of a method, a response). It calls the exported
`toRsSerdeType`.
## 12. Pitfalls
| Symptom | Fix |
|---|---|
| `unused import: HashMap`, with warnings as errors | An import was registered by a producer that does not write the name. Register it in the producer that does |
| `cannot find type Pet in this scope` | A string held the name of a model. Take the name from an insert, or from the peer's router |
| `file not found for module order` | The file has the suffix `.generated`, and a hand-written `mod` line names it. Let the base declare the file, or set `settings.generatedSuffix` to `""` |
| The file is not compiled, and no error names it | No `mod` line declares it. A projection base declares its own file. Declare a hand-written file with `modules` |
| `recursive type has infinite size` | A struct holds itself by value. Make a reference inside a cycle an `RsBox` |
| `the name Pet is defined multiple times` | A file imports two things of one name, or declares one and imports the other. Read a hand-written module by its name (`client::Error`), and keep the models in a folder of their own |
| `missing field kind` when a union with `#[serde(tag = "kind")]` is read | serde takes the tag out of the value before the member reads it. Write `Deserialize` by hand, as `RsSerdeTagDecode` of `gen-rust-serde` does |
| `Index rule: … does not hold that kind of declaration` | A member of an Index is not a `fn` or an `asyncFn` |
## The reference SDK
The style of the Rust output follows Progenitor, the OpenAPI client
generator of Oxide Computer. It uses the same libraries: `serde` for the
models and an async `reqwest` client.
- Repository: `https://github.com/oxidecomputer/progenitor`
- Commit: `182025b0d1855af5238dd0983d445ffa652580a7` (2026-11-29)
- The code that the authors read: its committed output
(`progenitor-impl/tests/output/src/*_positional.rs`), and its runtime
crate `progenitor-client`.
### Conventions that the generators follow
1. One module for the API, with the models in a `types` submodule. One
`Client` struct gets a method for each operation.
2. A small hand-written runtime (the client, the error, the request).
The generators write all other code from the document.
3. A type name is in upper camel case. A field and a method are in
snake case.
4. `#[serde(rename = "…")]` only where the Rust name is not the name on
the wire. A keyword gets an underscore at its end and a rename.
5. Each model derives `Debug`, `Clone`, `PartialEq`, `Serialize` and
`Deserialize`, and each field is `pub`. An enum of strings adds
`Copy`, `Eq` and `Hash`.
6. An optional field is `Option<T>` with
`skip_serializing_if = "Option::is_none"`. A required field is the
bare type.
7. An array is `Vec<T>`, a map is `HashMap<String, V>`, and JSON with no
schema is `serde_json::Value`.
8. An enum of strings is a Rust enum with a `rename` on each variant.
The enum has no other variant: a value that the document does not
list fails to decode.
9. A `oneOf` is a Rust enum. With no discriminator it is
`#[serde(untagged)]`. With a discriminator, the value of that
property names the variant.
10. A doc comment comes from the document. The comment of a method has
the summary, the description, the line
``Sends a `GET` request to `/path`.`` and a list of the arguments
that the document describes.
11. The client holds a base URL and a `reqwest::Client`. `Client::new`
takes the base URL, and `Client::new_with_client` takes a
`reqwest::Client` too. The caller sets authentication as default
headers of that `reqwest::Client`.
12. One `pub async fn` for each operation, with the arguments in this
order: path, query, header, body. An optional parameter is an
`Option`.
13. A request sends a JSON body with its media type, and asks for
`application/json`.
14. One error enum in the runtime, with a variant for each way that a
call fails.
15. A type that refers to itself is in a `Box` at the point of the
cycle. An item of a `Vec` needs no `Box`.
16. The output has paths as a person writes them. A `use` is at the top
of the file, and the code then has `String`, `Vec<T>` and
`Option<T>`. A doc comment
has a space after `///`. A method has no lifetime parameter.
### Where the generators differ, and why
| Progenitor | The generators | Reason |
|---|---|---|
| One file | `client.rs`, `operations.rs`, and a file for each model in `types/` | A file for each definition is the Skmtc model |
| The method name is the `operationId` | The name is from the method and the path | `operationId` is the document author's, and changes without notice |
| Strings and models are borrowed (`&str`, `&types::X`) | Each argument is owned, and the method gives it to the request | One form for every type. A borrow needs a rule for each kind of schema |
| `Result<ResponseValue<T>, Error<E>>` | `client::Result<T>` | The error body is text in `Error::ErrorResponse`. A typed error body needs a comparison of the error responses |
| `chrono` and `uuid` types for `format` | `String` for every format | The crate then needs only `serde`, `serde_json` and `reqwest` |
| A named schema of one primitive is a newtype | It is an alias (`pub type Tags = Vec<String>;`) | An alias needs no conversion where the value is used |
| A field with a `default` is the bare type with `#[serde(default)]` | It is an `Option` | The default stays the server's |
| The tagging of a `oneOf` is read from the shape of its members | It is read from `discriminator` | The parser gives the discriminator. A generator does not compare schemas |
| `Error<E>`, generic over the error body, with six variants | `client::Error` with four: `InvalidRequest`, `Communication`, `ErrorResponse { status, body }` and `InvalidResponsePayload` | The error body is text, so there is no `E`. A status outside 2xx is `ErrorResponse`, so there is no `UnexpectedResponse` |
| `nullable` is the same `Option<T>` with `skip_serializing_if`, also for a required field | A field that is required and nullable is `Option<T>` with no `skip_serializing_if` | The document says that the key is always there, so `None` is sent as `null` |
| No form for a field that is optional and nullable | One `Option<T>` with `skip_serializing_if`: `None` is left out, and `null` cannot be sent | `Option<Option<T>>` needs the `serde_with` crate |
| An optional array is `Vec<T>` with `#[serde(default, skip_serializing_if = "Vec::is_empty")]` | It is `Option<Vec<T>>` | One rule for each field that is not required. An empty array and no array stay different |
| A response that is not JSON is a byte stream | The operation gets no method | The request of the client reads JSON only. The manifest lists the operation as `notSupported` |
| `Client::new` returns `Result<Self, reqwest::Error>`, with a timeout of 15 seconds | `Client::new` returns `Self`, with no timeout | `client.rs` is a hand-written file of the project, which can change it. `Client::new_with_client` takes a `reqwest::Client` with any setting |
| An enum of strings adds `Ord`, `PartialOrd`, `Display` and `FromStr` | It adds `Copy`, `Eq` and `Hash` only, and each model adds `PartialEq` | The request writes an enum through serde, so it needs no `Display`. `PartialEq` lets a test compare two values |
### Not for a default generator
- Pagination streams, hooks and telemetry, and retries.
- The builder interface, and validation in types.
- Extra conversions on each type (`From`, `Deref`, `TryFrom`).
- A default timeout.
- The other outputs of the tool (a CLI, mock helpers, `schemars`
derives).