Domaines spécialisés › Écrire des programmes

Domaines spécialisés

Cette page n’est pas encore traduite : voici la version anglaise.

Programs

Extension — beta (program; the core)

A program is a set of modules. Each module is one TypeScript file: the model says its types and the signature of each function, and a body file holds the code. archec check reads both and says when they disagree. archec gen --target typescript writes the files. The extension exists for ADR 010: to write archec itself in arche-lang, one module at a time, with the compiler as the checker of its own source.

This page builds a word counter. The finished project is examples/program/.

1. A first module#

A module has a path, the file it is written to, and a code, the file its bodies are read from. Each function is a signature with no body.

/// Splitting a text into words.
module text "Text" {
  path "src/text.ts"
  code "text.body.ts"

  /// The words of a text, in order.
  /// @param s the text
  fn words(s: string) -> string[]
}

The body file, text.body.ts, is next to the model:

// Split on white space; empty pieces are dropped.
function words(s: string): string[] {
  return s.split(/\s+/).filter((w) => w.length > 0); // no empty word
}

Check it, generate it, and compile it with tsc:

$ archec check main.arche --strict
✓ no errors
$ archec gen main.arche --target typescript -o out
  out/src/text.ts
  out/src/count.ts
  out/src/main.ts

out/src/text.ts is the model's doc comment, the signature and your body, with a line that leads back to the model:

// Generated by archec from text.arche: edit the model, not this file.
// Splitting a text into words.

/**
 * The words of a text, in order.
 * @param s the text
 */
// Split on white space; empty pieces are dropped.
// @arche text.words text.arche:8
export function words(s: string): string[] {
  return s.split(/\s+/).filter((w) => w.length > 0); // no empty word
}

Edit the model or the body file, never the generated file: the next generation writes it again, with the same bytes if nothing changed.

2. Types#

A module declares its own types, written where they are used. Its names are its own, as a package's: two modules may each have a Span.

module count "Count" {
  path "src/count.ts"
  code "count.body.ts"

  /// A word and how many times it is there.
  struct Entry {
    word: string
    n:    int32
  }

  /// How many times each word is there, in lower case.
  fn tally(ws: string[]) -> map<string, int32>

  /// The counts, most frequent first; equal counts in alphabetical order.
  fn ranked(counts: map<string, int32>) -> Entry[]
}

A struct is an export interface. Beyond the usual types, a module has map<K, V>, function types (fn(x: int32) -> string), unknown, generics (struct Box<T>, fn first<T>(xs: T[]) -> optional T) and async fn. These are accepted inside a module only.

In the model In TypeScript
int32, uint32, float64, any number type number
bool boolean
string string
T[] T[]
T[3] (up to 16) [T, T, T]
optional T T | undefined
map<K, V> Map<K, V>
"Record<string, number>", quoted as written (info ts-type)
"any", quoted any (info any-type)
optional "'a' | 'b'", optional struct { … } a field x?: 'a' | 'b', a parameter = nil p?: …

A type the model cannot say yet is written quoted, in TypeScript, and kept as written. archec check counts each use (info ts-type), so that what is left to model is known. A quoted "any" stays any, and is said apart (info any-type): the model's own unknown is the checked choice.

A constant or a variable may have a TypeScript value, kept as written: `const UNITS: map<string, int32> = ts new Map([["ms", 1]]).

A parameter or a variable may be optional T, which is T | undefined. A parameter may have a default, in TypeScript, and one that is optional with the default nil may be left out:

fn shownPath(file: string, root: optional string = nil, cwd: string = ```ts process.cwd()```) -> string

is function shownPath(file: string, root?: string, cwd: string = process.cwd()): string, and the body file writes it so.

3. Bodies#

The body file has one function for each fn of the module, with the signature the model gives it: the same parameters, by name and TypeScript type, and the same result. count.body.ts has tally and ranked, and a helper of its own:

/** A word as it is counted. */
const norm = (w: string): string => w.toLowerCase();

function tally(ws: string[]): Map<string, number> {
  const out = new Map<string, number>();
  for (const w of ws) out.set(norm(w), (out.get(norm(w)) ?? 0) + 1);
  return out;
}

The helper, norm, is the module's own. It is written in the generated file and nothing outside the module can use it. A comment of the body file is never lost.

What archec check says when the body file and the model differ:

$ archec check main.arche        # words(s: number) in text.body.ts
text.body.ts:2:16 error Parameter s of words is string in the model (text.arche:8), not number … (archec explain ts-signature) [ts-signature]
✗ 1 error(s), 0 warning(s)

$ archec check main.arche        # no function ranked in count.body.ts
count.arche:16:6 error ranked has no function in count.body.ts … (archec explain ts-missing-body) [ts-missing-body]
  |   fn ranked(counts: map<string, int32>) -> Entry[]
  |      ^^^^^^
✗ 1 error(s), 0 warning(s)

A function that is short may have its body in the model, in a ```ts block, instead of the body file.

4. Other modules and packages#

use brings names of another module into this one: its types, constants, variables and functions. They are written bare. The generated file imports them.

module main "Main" {
  path "src/main.ts"
  code "main.body.ts"

  use text { words }
  use count { tally, ranked }

  /// Prints each word of a sentence with its count, most frequent first.
  fn main()
}

becomes, in src/main.ts:

import { tally, ranked } from './count';
import { words } from './text';

A name is imported when the file uses it. If the body writes words and the model has no use text { words }, archec check is silent and tsc says:

src/main.ts(9,32): error TS2304: Cannot find name 'words'.

native names a Node module or a package of the project's package.json:

module reader "Reader" {
  path "src/reader.ts"
  native "node:path" as path
  native "typescript" {
    type SourceFile
    fn createSourceFile(name: string, text: string) -> SourceFile
  }
}

as path is a namespace (import * as path from 'node:path'). A native may also name a file of the project, bring in types only, or give a name another (more forms). native "left-pad" default pad is the package's default export (import pad from 'left-pad'), and it may have a block too. The block names what the model takes from the package, with the types it gives them. A package that is neither Node's nor in dependencies or devDependencies is an error, and nothing is fetched:

text.arche:5:10 error left-pad is not a module of Node nor a package of the project (no package.json above the model) … (archec explain native-unknown) [native-unknown]
  |   native "left-pad" as pad
  |          ^^^^^^^^^^
✗ 1 error(s), 0 warning(s)

5. Generate#

archec gen main.arche --target typescript -o out

writes one file for each module, at its path under out. Each file has, in this order: the header and the module's doc comment, the imports, the types, the constants and variables, what the body file has of its own, and the functions. Code generation lists the rules.

layout source in a module writes the file in the body file's order instead. layout exact does the same and also writes the imports and re-exports in the order the model declares them (each native, use and export use where it is, a side-effect import too), not sorted: a module that must load its imports in a set order needs it. Nothing is guessed: the body file says where each member goes. A function the model declares goes where its function is. Every other member (a type, a constant, a variable, a fn with a ```ts body) goes where a place line names it, // @place NAME, on a line of its own between statements. The body's other statements and comments stay where they are written. The file runs in that order, and nothing checks it: a place line must come after every helper or member its value reads, through a function too. A doc comment keeps its lines as written, where the default joins a paragraph's lines into one. Use it for a file whose order matters, such as a value computed from another:

module i18n "Strings" {
  path "src/i18n.ts"
  code "i18n.body.ts"
  layout source
  union Lang { en; fr }
  /// The strings of a page,
  /// one for each language.
  type Strings = "typeof en"
  const STRINGS: "Record<Lang, Strings>" = ```ts { en, fr } ```
}

with i18n.body.ts:

// @place Lang
const en = { hello: 'Hello' };
const fr = { hello: 'Bonjour' };
// @place Strings
// @place STRINGS

archec check says body-place for a member with no place line, a place line that names no member, and a place line in a module without layout source.

The output is made to be read. Names are the model's, comments are kept, and each function has an // @arche <module>.<fn> <file>:<line> line to find its signature. It compiles under tsc --strict:

$ tsc --strict --target ES2022 --module commonjs --skipLibCheck --outDir js --rootDir src src/*.ts
$ node -e 'require("./js/main.js").main()'
the 3
cat 2
and 1
hat 1
ran 1
saw 1

6. Check#

archec check reads the body files with the TypeScript compiler's parser, offline. It says:

Code When
ts-signature A body function's parameters or result differ from the model's.
ts-missing-body A fn has no function in the body file; a class member is not in the body's class.
ts-class A class's body-file class differs from the model's: its header, a member's kind or words, a public member the model does not declare.
ts-extra-export A module uses a function its body file has and its model does not declare.
module-path A module has no path, or two modules have the same one.
use-unknown A use names a module or a name the model does not have.
native-unknown A native package is not Node's, nor in package.json; a native file of the project is not there.
hand-import A native names a file of the project, a hand-written one (info, counted).
module-type-outside A module uses a type declared outside every module.
program-type map, a function type, unknown, a generic or async outside a module.
unknown-type An unknown in a module (info, counted).
ts-type A quoted TypeScript type in a module (info, counted).
any-type A quoted "any" in a module (info, counted).
body-place Under layout source, a member with no place line, or a place line that names none.
param-order A parameter that is always given after one that may be left out (= nil).

archec explain <code> says more about each.

More forms (beta)#

These forms say what archec's own files need (phase 3b of ADR 010). Each is new: a model that does not use one is written as before.

Form In the model In TypeScript
A file of the project native "../ast.ts" { fn exprText(e: "Expr") -> string }, native "../ast.ts" as ast import { exprText } from '../ast', import * as ast from '../ast'
A JSON file native "../data/pins.json" default pins import pins from '../data/pins.json'
A value or a class native "events" { class EventEmitter; const VERSION: string; var count: int32 } import { EventEmitter, VERSION, count } from 'events'
Types only native type "typescript" as TS, native type "@anthropic-ai/sdk" default Anthropic, native type "x" { type A } import type * as TS from 'typescript', import type Anthropic from '@anthropic-ai/sdk', import type { A } from 'x'
Another name native "../ast.ts" { fn exprText as astText(…) -> string }, use codetraces { CODE_LANGS as LANG_OF } import { exprText as astText } from '../ast', import { CODE_LANGS as LANG_OF } from './codetraces'
What a file does native "../extensions.ts" import '../extensions';
A generator fn* entries(zip: "Buffer") -> "Generator<string>" function* entries(zip: Buffer): Generator<string>
A type parameter's bound fn first<T extends "{ name: string }">(xs: T[]) -> T function first<T extends { name: string }>(xs: T[]): T
An interface built on others struct Options extends AppOptions, ProjectOptions { … } export interface Options extends AppOptions, ProjectOptions { … }
An interface in TypeScript struct Ctx ```ts … ``` export interface Ctx { … }, its members as written
A type over several lines type Expr = """…""" export type Expr = and its lines as written
Comments between fields, under layout source // … lines in a struct, a: int32 // why the same comments, at their place
A value that holds three backticks a block fenced with four, ts … the value as written
A class class HttpError extends Error { constructor(readonly status: int32, message: string) }, its code in the body file's class HttpError export class HttpError extends Error { … }, the body's class as written (classes)
An abstract class, implements abstract class Shape implements "Iterable<number>" { abstract fn area() -> float64 } export abstract class Shape implements Iterable<number> { … }
A class's members static count: int32, protected readonly name: string, constructor(private x: T), async fn load(…) -> T, get size -> int32, tick: fn() (an arrow-function field) the body class's members, each with the model's doc comment
A re-export export use http { Router, HttpError as Err }, export use type http { Ctx } export { Router, HttpError as Err } from './http', export type { Ctx } from './http'
All of a module's names export use types, export use spec as spec export * from './types', export * as spec from './spec'
A re-export of a hand-written file export native "../emit.ts" { systemModelFile }, export native "./x.ts", export native type "./y.ts" { Shape } export { systemModelFile } from '../emit', export * from './x', export type { Shape } from './y'

For example:

module m "M" {
  path "src/app/m.ts"
  code "m.body.ts"
  native "../extensions.ts"
  native "../ast.ts" {
    fn exprText as astText(e: "Expr") -> string
    const ACTION_KEYWORDS: string[]
    class Parser
  }
  native type "typescript" as TS
  use codetraces { CODE_LANGS as LANG_OF }

  struct Options extends Base {
    // where it is read from
    root:  string
    depth: int32 // 0: no limit
  }
  type Expr = """
    | { t: 'num'; value: number }
    | { t: 'str'; value: string }
    """
  const FENCE: string = ````ts '```' ````
  fn* names(xs: "TS.Node[]") -> "Generator<string>"
  fn first<T extends "{ name: string }">(xs: T[]) -> optional T
}
  • A file of the project is a .ts or a .json file, written with its extension. Its path is relative to the module's file (its path), as an import's is: a module at src/app/m.ts names src/ast.ts as ../ast.ts. The import drops the .ts. The file must be there, in the folder of the package.json above the model (native-unknown). Each one is counted, info hand-import: once that file is a module too, use it instead.
  • A value or a class in a native block: const and var name values, with their type and no value; class names a class, a type of the module and a value of the file.
  • Types only. What a native type brings in is imported with import type. Its namespace or its default is written in quoted types: "TS.Node".
  • Another name. a as b, in a native block or a use: the other file's name is a, this module's is b. A name the module declares too is still a duplicate.
  • What a file does. A native with nothing after it (no as, no default, no block) is imported for what it does when it loads. These imports come first, in the model's order.
  • A generator is checked as the other functions are: the body file writes function* (ts-signature if not). Its result is written as it is, quoted ("Generator<T>", "Iterable<T>").
  • A bound is a type, quoted or of the model. The body file writes the same one (ts-signature if not).
  • declare needs no form: declare const ARCHEC_VERSION: string; is a statement of the body file, kept where it is written.
  • Comments. Under layout source, plain // lines between a struct's fields, and one after a field on its line, are kept in the interface at their place (a module laid out by kind leaves them out, as before); a /// line is still the field's doc. Under layout source, the plain // lines just above a place line (blank lines between them too) belong to that member: they are written above it, before its doc comment, not with the next statement. A place line inside a statement, or under a /** … */ comment, is still body-place.
  • $ in a module. A module's description, and the text of what is in it, is prose about code, not LaTeX: a $ there is a dollar (no latex-unbalanced).
  • A longer fence. Any block may open with four backticks or more and its language ( ts ````); it closes at the next run of as many. A value whose text holds three backticks uses it.

Classes (beta)#

A class is written twice, as a function is: its shape in the model, its code in the body file. The body file writes the class itself, with no export:

module counter "Counter" {
  path "src/counter.ts"
  code "counter.body.ts"
  class Counter {
    /// how many were made
    static made: int32
    constructor(private readonly step: int32, public name: string)
    /// the count so far
    get count -> int32
    /// adds one step
    tick: fn()
    static fn make(name: string) -> Counter
  }
}
class Counter {
  static made: number = 0;
  private n = 0;

  constructor(private readonly step: number, public name: string) { Counter.made++; }

  get count(): number { return this.n; }
  tick = (): void => { this.n += this.step; };

  static make(name: string): Counter { return new Counter(2, name); }
}

The generated file has the model's header (export class Counter {), then the body's class between its braces as written: its members in its order, its blank lines and comments. Above each member the model declares goes the model's doc comment. So the generated class is the hand-written one, member for member. The order matters: a field's value is computed when the object is made, in the class's order, and an arrow-function field keeps this. Both stay as written.

Why the body file holds the whole class, and not one function per method: the class is then read and written by TypeScript as it is, in one piece. A method written as function Counter_tick would need moving back into a class, and its this, its super and its order would be the generator's to get right. Here they are the body's, as they were by hand.

  • Checked. archec check reads the body's class with the compiler's parser and compares it with the model's: abstract, extends, implements, and each member by its name, static or not, its kind (a field, constructor, a method fn, a getter get) and its words (private, protected, readonly, abstract, optional; ts-class). Parameters and results are compared as a function's are (ts-signature); a constructor's parameter properties (private readonly step) too. A member the model declares and the body's class does not have is ts-missing-body.
  • What the model need not declare. A private member of the body's class, and one with a computed name ([Symbol.iterator]), are the class's own, as a body file's function is the module's. Any other member the model does not declare is ts-class. A class of the body file the model does not declare is the module's own: written as it is, not exported.
  • A field's type is written in the body's class too (static made: number = 0), so that the two are compared: a field the model gives a type and the body writes none is ts-class.
  • An arrow-function field is a field of a function type in the model, tick: fn(). The body writes the types of the arrow's parameters and result (tick = (): void => …), or the field's type.
  • Doc comments are the model's. A member's own /** … */ in the body's class is not written when the model gives that member a doc: one doc comment, the model's. Plain // comments are kept.
  • extends names a class of another module (use shape { Shape }), a class of a hand-written file (native "../base.ts" { class Base }), or one TypeScript has (Error, "Map<string, Entry>", quoted).
  • A class with no class in the body file is written from the model alone: its fields with their values (```ts 1 ), each method with a ts ```` body, or `abstract`. When the body file has the class, a value or a ```` ts ```` body in the model is ts-class: it is written there.
  • Where it goes. By default, a class whose class is in the body file goes among the body file's own statements, in their order; one the model writes alone after them. Under layout source, a class goes where its class is in the body file, or where // @place Name says for one the model writes alone.

Re-exports (beta)#

export use and export native say what a module exports from another file, as a barrel file does (src/app/index.ts):

module app "App" {
  path "src/app/index.ts"
  native "../extensions.ts"
  export use http { Router, HttpError, versionOf }
  export use type http { Ctx, Handler }
  export use types
  export use spec as spec
  export native "../emit.ts" { systemModelFile as modelFile }
}
import '../extensions';

export { Router, HttpError, versionOf } from './http';
export type { Ctx, Handler } from './http';
export * from './types';
export * as spec from './spec';
export { systemModelFile as modelFile } from '../emit';

The re-exports are written as one block after the imports, in the model's order: where they stood among the imports in a hand-written file is not kept (there is no form for that yet). Under layout source, the plain // lines just above one in the model are written above it. A re-export brings no name into the module: to use a name too, use it as well. type before a name in the braces is a type only, written back so: export use t { compile, type CompileResult } is export { compile, type CompileResult } from './t' (in a use too). Each name of export use is one its module declares (use-unknown); the file of export native is checked as a native's (native-unknown, hand-import). Another module uses a name from the module that declares it, not from the one that re-exports it.

Outside a module, fn*, a bound and a struct in TypeScript are program-type errors. (struct D extends Base outside a module is the language's own: the base's fields come first.)

Self-generation: more than modules#

archec's own model (model/, ADR 010) uses node tools/selfgen.mjs. Besides the modules, it runs the model's generator declarations. They are the project's own, so they run without approval (generators). A script names what it writes by its key:

Key What it writes
src/x.ts the whole file. The script writes its own first line, // Generated by archec from <model file>: edit the model, not this file.
docs/x.md#name the text between <!-- archec:begin name from <model file> --> and <!-- archec:end name --> (several model files: from a.arche, b.arche, each named by --check). The rest of the page stays.
package.json#/a/b the value at that JSON pointer. The file is written back with two spaces of indent and every other key in its place.

A page without the markers, or with them twice, stops selfgen: nothing is written. So does a file that one output writes whole and another in part (x.md and x.md#b).

--check compares a page's generated blocks, its other text as it is. A JSON file is parsed and written back whole, so a hand reformat of any part of it (a key moved, another indent) is a difference too. --check names the model each differing file is made from:

  • a whole file: the model file or folder its first line names (// Generated by archec from model/spec/diagnostics/:);
  • a block: the model files its begin marker names;
  • a JSON value, or a whole file with no first line to say it (a JSON file): the default of the generator's source option, else the file the generator is declared in.
generator editor "VS Code commands and their owners" {
  script "generators/editor.ts"
  output "."
  option source "The model file its outputs are made from" { type string; default "model/spec/editor.arche" }
}

--unmove is for modules only. A generator's output (a whole file, a block or a JSON value) is refused, naming its generator, and nothing changes: to hand-write it again, take the generator's declaration out of model/main.arche (and the spec files only it reads), then edit the file. A module that other modules use is refused too, naming them, and nothing changes: unmove its users first.

Moving a module from src/#

node tools/selfmove.mjs moves a hand-written TypeScript file into the model, and checks that nothing changed. It reads the file's syntax tree and writes the module (model/.../x.arche and, if there is a function, x.body.ts). Then it writes src/x.ts again from the model.

node tools/selfmove.mjs survey            # what can move: writes docs/superpowers/reports/self-hosting-survey.md
node tools/selfmove.mjs survey --json     # the same, for a script
node tools/selfmove.mjs survey --deep     # every refusal of every file, by construct
node tools/selfmove.mjs show src/ci.ts    # the module it would write, nothing written
node tools/selfmove.mjs move src/ci.ts --dry-run   # all the checks, nothing kept
node tools/selfmove.mjs move src/ci.ts src/sitepage.ts

A file is ready when the mover takes it, and blocked when it uses a form the model cannot say. The survey names the form and the line. A file is refused when the mover takes it but a check after the write refused it. move writes the check and why in tools/selfmove-refused.json, and takes the file out of it when it moves. Imports do not order the moves. An import of a hand-written file is written as a relative native (native "../ast.ts" { fn exprText(…) }). An import of a moved file is written as a use of the module that declares the name: a barrel (../index) is followed to it. A name a moved barrel takes from a hand-written file is a native of that file. When a file moves, the moved modules that import it by a native get a use instead, at the places archec reads (a block on one line, two modules in one file). A namespace (import * as x) and a side effect (import './x') have no use form: their native stays, said as kept native and counted.

move takes many files in one call, and each file stands alone. A file refused before the write is left out, with the form and the line:

$ node tools/selfmove.mjs move src/polarionrich.ts --dry-run
src/polarionrich.ts: blocked (description-quotes at line 1)
selfmove: moved 0, refused 1 (blocked: description-quotes 1); 0 attempts, 1.6 s
selfmove: dry run: nothing changed

The move keeps the order of the members and of the imports (layout exact, with // @place lines in the body file). Each import or re-export of the source is one native, use or export use line, in its order: the moved file starts its modules in the same order. A module moved before, layout source, stays as it is.

The checks come after the write. They are: archec check, with no native left to a file that is a module now; the generator run twice; the export shapes; the comments; tsc; and the runtime exports, on for every move, one file too (--no-check-exports leaves them out). The node bundles build.mjs makes of src/ (dist/cli.js, index.js, siteapi.js, app.js) export the same keys, typeof and arity as before, one level into an object. Its other node bundles are not required, and the output says so: server.js and fullworker.js start a server. A build.mjs that names none of the four stops the move. Each bundle also runs its modules in the same order: when each __esm init starts and when it ends, and where a module with no wrapper runs. Both ends count, because a module's body can run at another time while the modules start in the same order. --no-check-order leaves this out. When a check fails, the files it names are put back and refused; when it names none, the batch is cut in halves until the files at fault are found. Two halves fine apart and not together refuse the files at fault next to the other half, on each side. The checks then run again on the files kept. The halving makes 40 attempts at most (--max-attempts N): the files not cleared then are refused as bisect-budget. When the process is killed, every file is put back: the journal .selfmove-journal.json does it at the next run.

Large waves#

Move in chunks of about 50 files, and build and test between chunks. A chunk of 50 takes 30 s when nothing is refused and up to 7 minutes when the bisection has work to do. --max-attempts N caps the attempts (40 by default). A file left unresolved at the cap is refused as bisect-budget: try it again in a later chunk, with other files. The order and exports checks are on for every move, one file too. A wave commit may change these files: the moved src/ files, their model/ files, the survey page, and tools/selfmove-refused.json (the record of the files a check refused).

An accepted difference#

An exported const f = () => … is written as function f(…). The function is hoisted, has a prototype and can be called with new. A hoisted function can run before the line where the constant was set, and new f() no longer throws. Both used to throw. No working code changes. The exports and the init order are checked to stay the same.

Limits#

  • Beta. The words of module, use and native, and the generated TypeScript, may change in any edition.
  • Types live inside a module. A type declared outside every module cannot be imported by a module's file. Move it in. Program types and generics are refused outside a module.
  • Only TypeScript is written. No other target reads a module.
  • The bodies are TypeScript. A function with no TypeScript body, or with an ```arche body, is a note and its module is not written. The model's own bodies are not translated yet: they come with phase B of ADR 010.
  • A generic has type parameters only. A number parameter such as Ring<T, N: int> is refused in a module.
  • A missing use is tsc's to say, not archec check's.
  • Classes and re-exports are beta. A setter in the body's class is not checked. class and export use are not offered by the editor's completion or hover yet. A field of a class the model writes alone with no value is written with no initializer: under tsc --strict it needs one (TS2564), or a constructor that sets it.
  • A constant that is a range, or a quantity other than a duration, is a note and its module is not written.