strict-script strict-script

JavaScript without null, exceptions or any.

strict-script is a small language that compiles to plain JavaScript. What can go wrong is written in the types, and the compiler makes you deal with it before the program runs, not in production.

A first kernel runs. It is not a release, and it is not proven. →

main.sts:5:3 type-mismatch This is `Result<unknown, JsonError>`, and `Invoice` is asked for.
  help: the call may fail: read it with `match`, or hand the error on with `?`

JSON.parse may fail, and so may reading an invoice out of what it gives. Both are in the type of the function, and ? hands them on.

Open in the playground →

Does it work? We try to break it. We keep a list of small TypeScript programs that compile without a warning and go wrong when they run: a value that is not what its type says, a forgotten null, a crash nobody expected. Then we try to write each one in strict-script.

84
Programs on the listEach compiles in TypeScript, and goes wrong when it runs.
83
Stopped by strict-scriptThey cannot be written in it: the compiler refuses them.
1
Still possibleA function that calls itself forever.

Stopping every program of a list does not prove there is no other. Known limits says what is left.

How it works

Write it, let the compiler check, ship JavaScript

1

Write

It reads like TypeScript, with fewer words: no null, no undefined, no throw, no any, no cast, no class.

2

The compiler checks

A function that may fail says so in its type. Forget an error, a missing value or a case, and the compiler refuses, with a line that says what to write instead.

3

Ship plain JavaScript

Each file becomes a .js module and its .d.ts. TypeScript, Vite, React and Node import it as any module.

What you get

The bugs that no longer exist

No forgotten null

There is no null and no undefined. What may be missing is an Option, and each use says what happens when it is.

Errors you cannot ignore

Nothing is thrown. A function that may fail returns a Result, and ? hands the error on in one character.

Types that tell the truth

No any and no cast. What comes from npm, the DOM or Node is read against its type as the program runs.

One module at a time

It compiles to plain JavaScript with TypeScript declarations: put one file of it in a project you already have.

Fewer words

What you can no longer write

Each of these is a way a JavaScript program goes wrong. None is a word of strict-script: write one, and the compiler says what to write instead. Five words are new.

What has no word →

  • any
  • as
  • null
  • undefined
  • throw
  • try
  • catch
  • class
  • this
  • new
  • typeof
  • instanceof
  • in
  • delete
  • var
  • switch
  • enum
  • match
  • mut
  • resource
  • extern
  • ?

A tour

The language, in six ideas

Six short samples. Each links to the page « The language », which says the rest.

Errors are values

A function that may fail says so in its type. ? hands the error on, and nothing is thrown.

Errors are values →
errors-are-values.sts
function quarter(n: number): Result<number, "odd" | "negative"> {
  if (n < 0) return Err("negative")
  Ok(half(half(n)?)?)
}

match covers every case

It gives what it found a name that cannot change. Nothing is narrowed by a test.

match →
match.sts
function area(shape: Shape): number {
  match shape {
    { kind: "circle", radius } => 3.14 * radius * radius,
    { kind: "rect", width, height } => width * height,
  }
}

match parseInvoice(text) {
  Ok(invoice) => total(invoice),
  Err({ kind: "json", message }) => 0,
  Err(_) => -1,
}

Read-only, unless it says mut

What can be changed has one owner: its name. Given away, it is a value nobody changes any more.

Values that can be changed →
values-that-can-be-changed.sts
const mut basket: Item[] = []
basket.push(pen)

const mut counts: Map<string, number> = Map.from([])
counts.set("pen", 1)

const mut state = { sum: 0, count: 0 }
state.sum = state.sum + 5

A resource is ended by its scope

On every way out of it, return, ? and break among them, with no line written for the paths that fail.

Resources →
resources.sts
export resource Transaction { entries: string[] } end rollback

export function begin(): Transaction { { entries: [] } }
export function debit(mut tx: Transaction, account: string, cents: number) { … }
export function commit(tx: Transaction): string[] { … }
export function rollback(tx: Transaction) { … }

The outside is declared

npm, the DOM and Node are named in an extern. Every call to them gives a Result.

The outside →
the-outside.sts
extern "node:http" {
  type Server
  type IncomingMessage
  type ServerResponse
  function createServer(handler: (request: IncomingMessage, response: ServerResponse) => void): Server
  function Server.listen(port: number): Server
  const IncomingMessage.url: Option<string>
  function ServerResponse.end(body: string): ServerResponse
}

extern {
  type URL
  function URL.new(href: string): URL
  function fetch(url: string): Promise<Response>
}

A promise never rejects

What may fail gives a Promise<Result<T, E>>, and await hands back a value.

async →
async.sts
async function size(path: string): Promise<Result<number, Thrown>> {
  const text = await readFile(path, "utf8")?
  Ok(text.length)
}

const sizes = await Promise.all(paths.map(path => size(path)))

What comes out

One file in, plain JavaScript and its types out

This is what the compiler wrote for the file on the left when this page was built. The checks of what comes from outside are in the JavaScript: nobody writes a schema.

invoice.sts
type Line = { label: string, quantity: number, unitPrice: number }
export type Invoice = { id: string, lines: Line[] }

export function total(invoice: Invoice): number {
  invoice.lines.sum(line => line.quantity * line.unitPrice)
}

export function parseInvoice(json: string): Result<Invoice, JsonError | ParseError> {
  Invoice.parse(JSON.parse(json)?)
}
invoice.js
import * as $std from "@strict-script/std";
const $take_Invoice = /*#__PURE__*/ $std.check.lazy(() => $std.check.record({ id: $std.check.string, lines: $std.check.array($std.check.lazy(() => $take_Line)) }));
const $take_Line = /*#__PURE__*/ $std.check.lazy(() => $std.check.record({ label: $std.check.string, quantity: $std.check.number, unitPrice: $std.check.number }));
const $check_Invoice = /*#__PURE__*/ $std.check.lazy(() => $std.check.record({ id: $std.check.string, lines: $std.check.array($std.check.lazy(() => $check_Line)) }));
const $check_Line = /*#__PURE__*/ $std.check.lazy(() => $std.check.record({ label: $std.check.string, quantity: $std.check.number, unitPrice: $std.check.number }));

function total(invoice) {
  return $std.sumBy(invoice.lines, (line) => line.quantity * line.unitPrice);
}
const $out_total = /*#__PURE__*/ $std.entry("total", total, () => [[$std.check.lazy(() => $take_Invoice)], $std.give.same]);
export { $out_total as total, total as $total };
function parseInvoice(json) {
  const $t1 = $std.parseJson(json);
  if (!$t1.ok) return $t1;
  return $std.parse($std.check.lazy(() => $check_Invoice), $t1.value);
}
const $out_parseInvoice = /*#__PURE__*/ $std.entry("parseInvoice", parseInvoice, () => [[$std.check.string], $std.give.data]);
export { $out_parseInvoice as parseInvoice, parseInvoice as $parseInvoice };
invoice.d.ts
import type { Result, ParseError, JsonError } from "@strict-script/std";
type Line = { readonly label: string; readonly quantity: number; readonly unitPrice: number };
export type Invoice = { readonly id: string; readonly lines: readonly Line[] };
export declare function total(invoice: Invoice): number;
export declare function parseInvoice(json: string): Result<Invoice, JsonError | ParseError>;

Adopt it one module at a time

A .sts file built beside the TypeScript sources is imported as any module, with its types. An Option and a Result are plain data that if narrows.

What TypeScript hands to that module is not checked when the program runs: in a project says what that means.

app.ts
import { parseInvoice, total } from './invoice.js';

const read = parseInvoice(text);
if (read.ok) console.log(total(read.value));
else console.log(read.error.kind);

The scoreboard

The five promises, and where each stands

They are the four of strict-ts, plus memory, which the engine gives. This table is the project's scoreboard.

PromiseIn strict-scriptStatus
Memory safetyThe engine's garbage collectorGiven by the engine
Safe typingNo any, cast, declare or narrowing by a test; a record is closed; what comes from outside is read against its type as the program runsNo way known: 31 attacks, none gets through, a test each
No null, errors in the typesOption, Result, ?, a match that covers every case; a call to the outside gives a Result; a promise never rejectsNo way known but one: 29 attacks, a test each; a recursion without end is accepted
Explicit mutabilityRead-only unless it says mut, at the declaration and at the callNo way known: 24 attacks, none gets through, a test each
OwnershipWhat can be changed has one owner; a resource is ended by its scope, on every way outBuilt and tested, with no list of attacks. Not built: state shared by several parts of a program

« No way known » has a narrow meaning here: no way is known to write, in the kernel, a value that differs from its type or a failure that its type does not announce. The measure is the 84 files of strict-ts that compile under strict TypeScript and break a promise when they are run: 83 cannot be written or are refused, each by a test (packages/compiler/test/attacks.test.ts); 1 is accepted, a recursion without end, which stops the program. It is a list and not a proof, each row is the attack written again in this language by who wrote the compiler, and the only others who tried to break it are two agents and a fuzzer, not a person. The kernel is fuzzed: a machine writes programs and runs the ones that compile, and a run of 1,200,000 found nothing after the three holes it had found were closed. What is taken on trust is in Known limits.

Asked

Frequently asked questions

Is it TypeScript with more rules?

No, and it is not a superset of TypeScript: a TypeScript file is not a strict-script file. It reads like one, with fewer words and a few more (match, mut, resource, extern, ?). The checker for standard TypeScript is its sibling, strict-ts, which is released and is the one to use on existing code.

Can I use it in a TypeScript project?

One module at a time: a .sts file becomes a .js and a .d.ts that TypeScript imports as any module. What TypeScript hands to a function of that module is read against its type when the program runs, and refused in the caller when it is something else: see In a project.

How do I use a package from npm, the DOM or Node?

By declaring what it has in an extern. Every call to it gives a Result, and what comes back is read against the declared type: a declaration that is wrong is an Err where the call is made.

How do I silence a refusal?

You cannot. There is no any, no cast, no comment that turns a rule off and no unsafe directory: the unsafe part is the runtime library, which is not written in the language.

Is my program proven safe once it compiles?

No. The promises rest on a list of attacks, not on a proof, and nobody but its author has tried to break the kernel. What is taken on trust, the JavaScript that is written, the engine, each extern, is in Known limits.

Is there an editor?

Colours, in VS Code and the editors that read a TextMate grammar. A language server says what is refused where it is typed, gives the type under the cursor and offers what may be written there, in VS Code and in the editors that speak its protocol: In the editor.

What is the compiler written in?

In strict-script: the lexer, the parser, the checker and what writes the JavaScript are 7,300 lines of the language they compile (packages/self). The compiler compiles itself, and the tests pass on what it wrote. The runtime library and the command line are TypeScript.

Try to make it crash.

Write a program that compiles and fails in a way its types do not say. The compiler is in the page, and nothing is sent anywhere.

Esc

    Type a word of the language, a rule, a command: mut, extern, match-not-covered.