The Erlang target-language layer for Skmtc generators (@skmtc/lang-erlang). It covers the projection base factories, ErlangSnippet, the register shape with no imports, the three identifier kinds, one file as one module, the file as the owner of the module order and the export attributes, absent and null values, and the producers for types, functions, calls, maps and names. Use ALONGSIDE skmtc-generator whenever a generator writes Erlang.
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 Erlang?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/skmtc-skmtc-lang-erlang)
---
name: skmtc-lang-erlang
version: 0.1.0
description: >
The Erlang target-language layer for Skmtc generators
(@skmtc/lang-erlang). It covers the projection base factories,
ErlangSnippet, the register shape with no imports, the three identifier
kinds, one file as one module, the file as the owner of the module
order and the export attributes, absent and null values, and the
producers for types, functions, calls, maps and names. Use ALONGSIDE
skmtc-generator whenever a generator writes Erlang.
metadata:
internal: true
---
# The Erlang layer (@skmtc/lang-erlang)
Read `skmtc-generator` first. The two worked examples are
`@skmtc/gen-erlang-json` (a model generator) and
`@skmtc/gen-erlang-httpc` (an SDK: a module for each tag, with a function
for each operation). Generated code targets Erlang/OTP 27 or later, and
needs no package outside OTP. The style of both follows `erlef/oidcc`
(section 13).
Import each module by its own path (`@skmtc/lang-erlang/ErlangAtom`).
Do not import the root of the package.
## 1. Declare the language
The import graph declares the language. `src/base.ts` imports a factory,
and each snippet extends `ErlangSnippet`.
```ts fragment
import { toModelName } from '@skmtc/core/refFns'
import { ErlangName } from '@skmtc/lang-erlang/ErlangName'
import { toErlangModelProjectionBase } from '@skmtc/lang-erlang/toErlangModelProjectionBase'
export const ErlangJsonBase = toErlangModelProjectionBase<EnrichmentSchema>({
id: denoJson.name,
toIdentifierName({ ref }) {
return `${new ErlangName(toModelName(ref)).toAtom()}_model`
},
toIdentifierType: () => ({ type: 'module' }),
toExportPath({ ref, enrichments, variant }) {
return `@/${this.toIdentifierName({ ref, enrichments, variant })}.erl`
},
})
```
The factories are `toErlangModelProjectionBase` and
`toErlangOasOperationProjectionBase`.
## 2. A file is a module
One `.erl` file is one module, and the name of the file is the name of
the module.
- **Make the path from the name.** `toExportPath` returns
`@/<module name>.erl`. `toModuleName(path)` reads the module name back
from a path. A path that is not a plain atom and `.erl` stops the run.
- **Set `settings.generatedSuffix` to `""`.** The default suffix gives
`pet_model.generated.erl`, and a module name has no dot. The first
step of each generator README must say so.
- **A module name is one name in the whole Erlang system.** Modules have
no package and no folder. A generator adds a suffix (`_model`, `_api`)
so that a model named `Lists` does not replace `lists` of OTP.
`erlang.toNameScope` gives one scope (`MODULE_SCOPE`) for every model.
- **A module reads another module through its name.** `pet_model:t()`
and `pet_model:from_json(Json)` need no import. `ErlangImport` renders
nothing, and `register` has no `imports` field.
- **Put every generated file in one folder**: the `src` folder of the
application. `'@/'` is the project's `basePath`.
## 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 |
| Any code with a context | `register(context, { ...args, destinationPath })` | The file you name |
`args` is `{ definitions?, custom? }`. There is no `imports` and no
`reExports`.
- A definition is `new ErlangDefinition({ context, identifier, value,
description? })`. `defineAndRegister(context, …)` makes one and
registers it.
- A file keeps the first definition of one kind, name and arity. So each
function of a service can register the module of the service, and the
file has it one time.
- With no `custom`, a file starts with
`%% Code generated by Skmtc. DO NOT EDIT.`.
## 4. Identifier kinds
| Kind | Factory | Renders |
|---|---|---|
| `module` | `createModule(name)` | Nothing. The value renders the attributes of the module, such as `-moduledoc` |
| `type` | `createType(name)` | `-type name() :: ` + value + `.` |
| `function` | `createFunction(name, { arity, exported? })` | Nothing. The value is an `ErlangFunction` |
- Erlang knows a function by its name and its arity. The arity is the
`typeName` of the identifier, as text. In `toIdentifierType`, return
`{ type: 'function', typeName: '2' }`. A function with no arity stops
the run.
- A type and two functions of different arity can share a name. The key
of a declaration is its kind, its name and its arity.
- `exported` says whether the file lists the type or the function in its
export attribute. The default is `true`.
## 5. Head and value
The identifier renders the head of a declaration, and the value renders
all that follows. `ErlangDefinition` puts a `-doc` attribute above them
when it has a `description`.
```erlang
-doc "The id of an order.". the description
-type order_id() :: binary(). the head, the value, and the period
```
The value of a `function` is an `ErlangFunction`. It renders its own
`-doc`, its `-spec` and its clause, because the name is in both. Its
`identifier` has the name and the number of the parameters:
```ts fragment
const decode = new ErlangFunction({ name: 'decode', parameters, result, expressions })
new ErlangDefinition({ context, identifier: decode.identifier, value: decode })
```
## 6. A function is a member of a module
The file is the module, so the file owns its order and its export
attributes. `ErlangFile` renders, in this order:
1. `custom`, or the notice of a generated file.
2. `-module(name).`, from the name of the file.
3. Each `module` definition: the `-moduledoc`.
4. `-export([…]).` with each exported `function`, and `-export_type([…]).`
with each exported `type`. More than one signature is one on each
line, between the brackets.
5. Each `type` definition.
6. Each `function` definition.
So a generator registers types and functions, and writes no export
attribute. Erlang needs no Index for a module of functions:
- **A model** is a `module` projection. Its constructor registers the
type `t` and its functions in its own file, and its `toString()`
renders the `-moduledoc` (`ErlangJsonProjection`).
- **An operation** is a `function` projection whose `toExportPath` is the
file of its service. Each function registers a `module` definition for
the `-moduledoc` of the service (`ServiceFunction`, `ServiceModule`).
A `module` definition whose name is not the name of its file stops the
run.
## 7. Absent and null
Erlang has no `undefined` value in JSON. The `json` module of OTP gives a
JSON `null` as the atom `null`, and writes that atom back as `null`.
| The schema says | The map type has |
|---|---|
| Required | `key := T` (`ErlangExactAssociation`) |
| Optional | `key => T` (`ErlangAssociation`). An absent key is not in the map |
| Nullable | `T \| null` |
| Optional and nullable | `key => T \| null` |
- Do not use `undefined` as a value in a model: `json:encode/1` writes it
as the string `"undefined"`.
- Decide `null` in one class (`ErlangJsonNull` for the type and
`ErlangJsonNullable` for the decoder, in `gen-erlang-json`).
- A JSON number is `number()`: `json:decode/1` gives `1` as an integer
and `1.5` as a float.
## 8. Indentation
`erlfmt` writes four spaces for each level. A producer renders its own
lines from column 0. `ErlangIndented` is the only code that writes the
spaces, so blocks nest to any depth. Do not write the spaces of a nested
part in a template.
A producer does not wrap a long line. A project runs `erlfmt` on the
output.
## 9. Producers
| Producer | Renders |
|---|---|
| `ErlangList.toArguments(items)`, `.toUnion`, `.toSequence`, `.toClauses`, `.toLines`, `.toParagraphs` | `a, b`, `a \| b`, a comma or a semicolon and a line break, one item on each line, a blank line between items |
| `ErlangIndented(content)` | The content one level deeper |
| `ErlangLocalType(name)`, `ErlangRemoteType({ module, name, parameters? })` | `t()`, `binary()`, `pet_model:t()`, `api_client:error(problem_model:t())` |
| `ErlangCall({ function, arguments })`, `ErlangRemoteCall({ module, function, arguments })` | `from_json(Json)`, `pet_model:from_json(Value)` |
| `ErlangFunRef({ name, arity })`, `ErlangRemoteFunRef({ module, name, arity })` | `fun from_json/1`, `fun pet_model:from_json/1` |
| `ErlangTuple(items)` | `{ok, pet_model:t()}` |
| `ErlangMap(associations)` | `#{ … }` with one association on each line: a map type, and a map expression. With no association, `#{}` |
| `ErlangAssociation({ key, value })`, `ErlangExactAssociation` | `key => value`, `key := value` |
| `ErlangMapUpdate({ map, association })` | `Map#{id => Value}` |
| `ErlangClause({ head, body })` | `head ->` and the body one level deeper |
| `ErlangCase({ subject, clauses })` | `case Subject of … end` |
| `ErlangFun(clauses)` | `fun … end` with a clause for each case |
| `ErlangFunction({ name, description?, parameters, result, expressions, exported? })`, `ErlangParameter({ name, type })` | A `-doc`, a `-spec` with a `when` part, and one clause |
| `ErlangDoc({ text, attribute? })` | `-doc "…".` or `-moduledoc "…".`, or nothing |
| `ErlangComment(text)` | `%% text` on each line, or nothing |
| `ErlangVariable({ name, depth })` | `Value`, and `Value1` one level deeper |
An item that is `undefined` or `null` is absent. `ErlangFunction` needs
one parameter or more.
**A variable at each depth.** A `fun` and a comprehension bind variables
of their own. Erlang warns about an inner variable that has the name of
an outer one. So a producer that binds a variable takes a `depth`, makes
`new ErlangVariable({ name: 'Value', depth })`, and gives `depth + 1` to
the producers inside it.
## 10. Names and literals
- `new ErlangName(text).toAtom()` for a module, a function and a type:
`PetStatus` gives `pet_status`. It is a plain atom in ASCII for any
text. A reserved word gets an underscore at its end (`end_`). A name
that would start with a digit starts with `x`.
- `new ErlangName(text).toVariable()` for a variable with the name
of a part of the document: `petId`, a path parameter, gives
`PetId`. A name that would start with a digit starts with `X`.
- **Two texts can give one name.** `pet-id` and `pet_id` give `pet_id`,
and `Segment` and `SEGMENT` give `segment`. See the pitfalls.
- `new ErlangAtom(text)` for a key of a map and a value of an enum. The
atom is the text itself, with quotes where Erlang needs them
(`'in-progress'`, `'end'`). Thus `json:encode/1` writes the same text
back. Do not change the case of a key.
- **An atom holds 255 characters.** `ErlangAtom` stops the run for a
longer text. An emoji is one character, as Erlang counts it, and two
units in `text.length`. `ErlangAtom.MAX_LENGTH` is the limit and
`ErlangAtom.toLength(text)` is the count, for a generator that chooses
another form.
- `new ErlangBinary(text)` for a JSON key or a JSON string in a pattern:
`<<"status">>`. Text outside ASCII gets the type `utf8`.
- `new ErlangString(text)` for an Erlang string: `"A \"pet\"."`.
- **Never make an atom from text of a response.** Write each atom in the
generated source, and match its binary: `<<"pending">> -> pending`.
`binary_to_atom/1` on data from outside fills the atom table.
- **The atoms `true`, `false` and `null` are not strings in JSON.**
`json:encode/1` writes them as the JSON booleans and `null`. An enum
value with one of these texts stays a binary.
## 11. A declaration and a type position differ
In Erlang they do not differ: a map type has one form in a `-type`, in a
field of another map and in a `-spec`. One router serves each position.
What a schema has two renders of is its type and the code that reads its
JSON. `gen-erlang-json` solves this as follows:
- `toErlangJsonValue` is the one router. Each producer renders the type
in `toString()`, and holds the code that reads the same schema as its
`decoder`. The router reads a schema one time.
- A `decoder` is an expression over a variable (`subject`). Its
`identity` says that the value is the same in JSON and in Erlang.
The producer that holds it then writes the variable and no code
around it.
- A generator that only sends a schema (parameters, a body) makes
`new ErlangJsonType({ context, destinationPath, schema, fallbackName })`.
It renders `pet_model:t()` for a `$ref`. For a schema with no name,
it renders the name of a type in the file of the generator.
- A generator that reads a schema (a response) makes
`new ErlangJsonReader(…)` with the same arguments. Its `type` is the
type. Its `decoder` is a function as a value:
`fun pet_model:from_json/1`, or `fun get_pets_response_from_json/1` for
a schema with no name. The function is beside the type, and the module
does not export it.
## 12. Pitfalls
| Symptom | Fix |
|---|---|
| `cannot be an Erlang module … 'pet.generated'` | Set `settings.generatedSuffix` to `""` in `skmtc.config.json` |
| `The module 'segment_model2' cannot be in '@/segment_model.erl'` | Two schemas give one module name (`Segment` and `SEGMENT`), and the run gave the second a counter. The counter is in the name and not in the path, so no file can hold the module. The `DUPLICATE_NAME` warning of the run names both. Give one another name in the document or with an overlay, or change `toIdentifierName` in a clone of the generator |
| `Registered definition mismatch: 'create_api_orders'` | Two paths give one function name. Core's `toEndpointName` gives `/orders` and `/orders.` one name. `ErlangName` also gives `/application.changeStage` and `/application.change_stage` one name, and `{envelope_id}` and `{envelopeID}` one name. Change one path with an overlay, or the name in `base.ts` of a clone |
| `illegal atom` from `erlc`, or `cannot be an Erlang atom: an atom holds at most 255 characters` | A key or an enum value is too long for an atom. Keep an enum value as a binary. A key of this length needs another document |
| An enum value `"true"` is sent as the JSON boolean | The value was made an atom. Keep `true`, `false` and `null` as binaries (section 10) |
| `variable 'Value' shadowed in 'fun'` | A nested producer got the depth of its parent. Give it `depth + 1` (section 9) |
| `function f/1 is unused` | A function that the module does not export has no caller. Register it only with the code that calls it |
| A type or a function is not in the file | Another definition with the same kind, name and arity was registered first. The file keeps the first |
| `syntax error before: '.'` after `when` | An `ErlangFunction` has no parameter. Give it one or more |
| A caller crashes with `case_clause` or `badmap` | Code that reads a response failed outside a `try`. Read the response inside the client's protected part, and return `{error, {invalid_response, Body}}` |
## 13. The reference SDK
The style of the output follows `erlef/oidcc`
(https://github.com/erlef/oidcc), read at commit
`720f82666ee4470344eb79e85f20c82510ad8fc7`. It is hand-written, the Erlang
Ecosystem Foundation maintains it, and it uses the same libraries: the
`json` module and `httpc` of OTP 27.
What the generators take from it:
1. **Layout.** All modules are flat in `src/`, and a prefix or a suffix
of the name is the namespace.
2. **One module for each resource.** A module holds the types of one
thing and the functions that work on it.
3. **Module order.** `-module`, `-moduledoc`, `-export`, `-export_type`,
types, then functions.
4. **Names.** Modules, functions and types are `snake_case` atoms.
Variables are `CamelCase`. The main type of a module is `t()`.
5. **Types field by field.** Each field of a model has a name and a
type. A known shape is never `map()` or `any()`.
6. **Required and optional.** `:=` is a key that the map must have, and
`=>` is one that it can have.
7. **Enums are atoms, read by clauses.** Each known binary gives its
atom. No code calls `binary_to_atom/1` on data from a response.
8. **Strings, lists and maps.** A JSON string is `binary()`, an array is
`[T]`, and a free-form object is a map with binary keys.
9. **Dates stay the value on the wire.** A `date-time` is `binary()`.
10. **Documentation.** `-moduledoc` and `-doc` attributes of OTP 27,
above the type or the `-spec`.
11. **No client process.** No process holds the state of a client, and
a call takes what it needs as arguments.
12. **The spec of a function** names each argument as the clause does,
and gives the types in its `when` part.
13. **Results.** A function returns `{ok, Value}` or `{error, Reason}`,
and does not raise for an answer of the server. An answer with a
status of an error is `{http_error, Status, Body}`. `Body` is the
decoded JSON when it is JSON, and the bytes when it is not.
14. **The client decodes JSON inside `try … catch`**, so a bad body is
an error value and not a crash. Erlang deprecates a bare `catch`.
15. **Runtime apart from the code of one API.** The request function,
the status check and the JSON decode are hand-written
(`base-files/api_client.erl`). The generated code is the types and
one function for each operation.
Where the generators differ from it, and why:
- **Typed maps, not records.** A model is a map type in its own module,
with no `.hrl` file.
- **Nullable is `T | null`.** oidcc has no nullable field. The map does
not have an absent key, and the key is not `undefined`.
- **An enum keeps a value that it does not have, as a binary**
(`active | inactive | binary()`). oidcc refuses it. An API can add a
value, and a client from an earlier run still reads the
response.
- **Keys are the names of the document** (`petId`, and not `pet_id`).
Thus `json:encode/1` writes a value of the type as it is.
- **A client value.** oidcc has no client: it has no base URL and no
API key to keep. The client of the generators is a plain map, and it
is the first argument of each function.
- **The transport error has a tag**: `{transport_error, Reason}`. In
oidcc it is a term with no tag (`httpc_error() :: term()`). That term
takes the place of every other member of the error type.
- **The arguments of an operation.** oidcc has no path parameter. A
function takes one argument for each path parameter, and then the
body. The last argument is one map with the query parameters and the
headers. When each key
of that map is optional, a second function with one argument less
passes `#{}`. The pair of arities is the form of `aws-beam/aws-erlang`.
- **The schema of an error reads its body**, when the operation
documents one. oidcc has one shape for the body of each error.
- **The client calls `httpc` directly**, with no adapter behavior, no telemetry,
no retry and no cache.