Bundled languages¶
Audience: everyone · ~10 min read · Prerequisites: IDE tour
struktJS ships with 59 plugin folders (plugins/lang-*/) defining 74 languages. Most are small demonstrations of one
idea; a few are the foundation everything else builds on. This page groups them by what they are for.
For the exhaustive, generated list of every language and concept, see
Languages (generated reference); for the example programs, see
Samples.

Plugins that ship an example program expose it under File > Samples (also Load Sample… on the start page) (see
Projects and models). Some samples need no plugin of their own and live in the
top-level samples/ folder; those are listed at the end.
Writing your own
Everything below is built with the same tools you have. To make a language of your own, see the developer guide.
General-purpose languages¶
These are the languages you write real programs in.
| Plugin | What it is |
|---|---|
lang-core |
Core, the default language: a Python-flavoured general-purpose language (variables, functions, loops, conditionals, collections, exceptions, pattern matching, modules). Most samples and most other plugins build on it. It is bundled as a devkit (core) that groups its sibling pieces into one installable language. |
lang-stdlib |
The standard library for Core: strings, collections, math, I/O, and a JS Interop escape hatch (js(path, ...args)) that calls vetted JavaScript globals such as Math.*. Sample: JS Interop Demo. |
lang-ts |
The language used to edit a concept's own .tsx source in the Language pane. You rarely use it directly. |
Persistence grammars¶
A model file is real source text. Core uses Python syntax by default; these plugins let a language use a
different surface syntax instead. Formats with no comment syntax (JSON, XML) have no # key: value header at all:
the model's package, model imports and language version are kept in the sibling model.json instead.
| Plugin | What it is |
|---|---|
lang-python |
Not a language: it owns the tree-sitter grammars for Python, JavaScript and TypeScript and registers them with the engine. |
lang-jsgrammar |
A language whose models are saved as real JavaScript (.model.js). Sample: JS Grammar Demo. |
lang-js |
Not a language of its own: every JavaScript construct (switch, labels, optional chaining, classes with fields, imports/exports, …) as a concept, imported by lang-jsgrammar and lang-jstest. Sample: JavaScript tour. See JavaScript as structure. |
lang-typescript |
A language whose models are saved as real TypeScript, with type annotations understood by the editor's type checker. Sample: TypeScript Grammar Demo. |
lang-sexpr |
A small Lisp-style S-expression language saved with its own hand-written parser, with no tree-sitter involved. Sample: S-Expression Demo. |
lang-json |
JSON documents saved as plain JSON text (.model.json, no header lines); evaluates to its native value and also works as a generator target. Sample: JSON Walkthrough. |
lang-xml |
XML documents saved as plain XML text (.model.xml): elements, attributes, text, CDATA, comments and processing instructions. Sample: XML Walkthrough. |
lang-kernelf-test |
Test suites for KernelF models (suite, test, assert … equals …, confail), run from the Tests pane. Sample: KernelF Tests. |
lang-kernelf |
KernelF — a functional, statically typed expression language (see KernelF below), saved as KernelF text (.model.kf). Sample: KernelF Tour (three roots, one per tier: Core: KernelF Tour, Advanced: Data, Tables and Time and Stateful: State Machines). It is one installable language assembled from three tiers (core, advanced, stateful); the tiers are not offered on their own. |
Demo and domain languages¶
Each of these is a compact language that shows one way a language can be shaped.
| Plugin | What it shows | Sample |
|---|---|---|
lang-simplest |
The smallest possible language: one concept, one property, one editor rule, one generator rule. | The Simplest Language |
lang-shapes, lang-shapes3d |
Language extension: Shapes adds a Circle to Core; Shapes3D extends Shapes with a Sphere. |
Shapes, Shapes3D |
lang-dbscript, lang-sql |
Language embedding: DbScript is a Python-syntax host language whose RunQuery holds a real select(...) node from the SQL mini-language, each with its own structural editor. lang-sql is the embedded language and is not opened on its own. |
DbScript |
lang-entities |
Entity and property declarations with a scoped, type-checked reference, plus an enum-typed property you can cycle with Alt+Enter. | Entities, Enum Types |
lang-libcall |
References that survive renaming: a call is linked to its function by an internal id, not by name. | LibCall |
lang-money |
Currency-typed arithmetic: adding amounts in different currencies is flagged instead of summed. | Money |
lang-changelog |
Release notes in the Keep a Changelog layout: releases with semantic or month-year versions, categorized changes, and entries that point at model nodes by fully-qualified name. Generates Markdown. | Release Notes |
lang-lambda |
Untyped lambda calculus with real beta reduction. | Lambda Calculus |
lang-agreement |
Structuring business-agreement clauses and party obligations, generating readable contract text. | Agreement |
lang-markup |
An XML-like markup authoring language (elements, attributes, text) that generates markup text. | Markup Authoring |
lang-fixedreader |
A fixed-width record schema plus sample lines parsed against it. | Fixed-Width Reader |
lang-dslbook |
A toy access-control DSL (people, compartments, owners, members) after the DSL Engineering book. | Secret Compartment |
lang-heating |
A thermostat control language rendered as a decision table, checked against sample readings. Also demonstrates opt-in hover tooltips. | Heating, Hover Tooltips |
lang-devices |
A fictional office printer in real units (mm, in, gsm, dpi, ppm): trays, a duplex unit, resolution and speed, with print jobs checked against them. One quantity concept per dimension, so the editor does not accept a weight where a paper size belongs (and reports one that arrives by file); inches and millimetres convert exactly. A print job's lifecycle is a small state machine you can simulate. Its generator writes a plain-text device sheet. | Aurora C500 |
lang-robot |
A grid-world robot scripting language (move, turn, pick up, sense walls). Its generator produces a self-contained HTML page that Open Preview runs in a sandboxed frame. | Maze Explorer |
lang-vibro |
A pile-driving equipment selector: declare a pile, soil profile and equipment catalog, rank hammer combinations, and export a report. | VibroSelect |
lang-genplan |
A generator-plan showcase: one model produces two outputs (the program itself and a documentation view extracted from its comments). | Generator plan showcase |
lang-testlang |
Test assertions for the editor itself, such as asserting what a simulated keypress does, what an expression evaluates to, that a condition becomes true (assert wait for), or that two model fragments have the same structure. Open the Tests pane and run all tests. |
Test Language |
lang-exercises |
Interactive lessons: an exercise of tasks whose requirements (uses a concept, never uses one, prints, evaluates to, passes the checks) check the learner's own code, shown in the Tests pane with a hint per unmet requirement. |
Exercises Walkthrough |
Notation and diagram languages¶
These change how a model looks, not what it means.
| Plugin | What it is | Sample |
|---|---|---|
lang-formula |
Mathematical notation rendered as genuine 2D layout: fractions, powers, roots, sums, integrals, limits, matrices, plus floor, ceiling, angle, brace and square brackets and over/under scripts. A formula can read named values defined above it (rate = 0.004). |
Math Notation |
lang-notations |
One state machine shown three ways (text, table, diagram). Click the badge next to the node to cycle notations. | Notation switching demo |
lang-diagram |
Reusable flowchart node vocabulary that renders as a diagram. Other languages import it. | see flow-diagram, dependency-graph, ci-pipeline-diagram below |
lang-core-decision-table |
First-match decision tables (with row groups that nest rows under a shared guard), kept separate so models that do not import it do not see it in completion. | see decision-table below |
lang-richdoc |
Opt-in doc comments with inline bold, italic, code and links, authored as Markdown. | see rich-doc-comments below |
lang-quotation |
Embeds real Core expressions as quoted values; switch the notation (Mod+Alt+V) to see the constructor form. | Quotation demo |
lang-uikit |
A live roster table beside a showcase of every interactive widget a concept editor can use (switches, sliders, date pickers, dialogs). | UI Kit demo |
Tooling languages¶
These languages are used to define languages and rules, not to write programs.
| Plugin | What it is |
|---|---|
lang-pattern |
A projectional editor for structural patterns, used in checks and elsewhere. |
lang-scopeflow |
A projectional editor for scope and data-flow descriptions (what a concept introduces, reads and writes). |
lang-typerules, lang-genrules, lang-surfacerules, lang-cells, lang-evalrules, lang-evalbuilder, lang-flowrules, lang-listrules |
Hidden notation languages. They let the Language Editor show a rule body (type rules, generator rules, surface mappings, editor cells, grammar, evaluation, flow, lists) as concepts instead of JavaScript. You never open them directly. |
Samples not tied to a plugin¶
The top-level samples/ folder holds generic Core programs: hello, guess-the-number,
console-cookbook (for the Model Console), python-tour,
generator-demo,
multi-root-demo, pattern-matching-demo, decision-table, flow-diagram, dependency-graph,
ci-pipeline-diagram, rich-doc-comments, css-styling-demo, ruff-lint-demo, stub-loading and
tricky-syntax. Each has a short description when you open it from Load Sample….
KernelF¶
lang-kernelf is an independent implementation of the core of KernelF (itemis,
Apache-2.0): a functional, statically typed expression language whose values are immutable. Its models are saved as KernelF
text in .model.kf files, and the editor shows the same notation.
// arithmetic is exact: 0.1 + 0.2 is 0.3
val tenth = 0.1 + 0.2
fun double(n) = n * 2
val evens = 0.upto(10).where(|it mod 2 == 0|)
val label = alt | total > 100 => "big" | total > 10 => "medium" otherwise "small"
What is in this version:
| Area | Forms |
|---|---|
| Numbers | Exact decimals (no floating-point error); range types such as number[0\|100]{0} (lower bound, upper bound, decimal places), with int and real as shorthand. A value's type tracks its range: hovering 1 + 2 shows the type number<3, 3, 0> (lower bound, upper bound, decimal places), and a function that expects number[0\|10]{0} is checked against it at each call. |
| Options | none, some<e>, a ?: b (a default for none). Operators work through an option: none + 1 is none, and so is x == none. if c then a without an else is none when c is false. |
| Names and functions | val x = e, const x = e (a named constant), fun f(a, b: int) = e, lambdas \|a, b => a + b\|, and the implicit-it short form \|it > 2\|. Parameters may declare a type, and calls are checked against it. |
| Collections | list(…), set(…), map(k => v, …), tuple(…); members size, isEmpty, first, last, sum, reverse, distinct, sort, flatten, keys, values, contains(x), get(k), upto(n) (the end is excluded), where, map, any, all, count, sortBy, groupBy, fold(init, f); indexing xs[i] and tuple positions t.0. |
| Built-in operations | Numbers: abs, sqrt, pow(n), floor, ceil, round, sin, cos, tan, inRange(lo, hi), limit(lo, hi) (clamp), oneOf(a, b, …). Strings: length, toUpper, toLower, trim, startsWith(s), endsWith(s), contains(s), split(sep), matches(regex) (the whole string must fit), replace(a, b), indexOf(s), isBlank, isNumeric; on a list of strings join(sep). Lists: min, max, take(n), drop(n). Options: x.isSome (false for none and for an error). Functions: f.exec(a, b) calls, f.bind(a) fixes the first arguments. Booleans: a implies b and a iff b (KernelF writes => and <=>, which here already separate lambda parameters and alt arms). Like size, these names are members: a record field called length or min is written with backticks. |
| Dates and times | date("2026-10-15") and datetime("2026-10-15T12:30:00") (UTC); members year, month, day, dayOfWeek (1 is Monday), hour, minute, second, toDate, plusDays(n), plusMonths(n) (a day missing from the target month moves to its last day), plusSeconds(n), daysBetween(d), secondsBetween(t). Dates compare with <, >, == and sort; a date and a datetime do not compare. An impossible date is a failure when it runs. |
Data types and match |
data Shape { Circle(r: int), Rect(w: int, h: int), Empty() } declares a type with variants; Circle(2) builds a value and s.r reads a field. match s { Circle(r) => r * r, Rect(w, h) if w > 0 => w * h, _ => 0 } takes the first arm whose pattern fits (a constructor with sub-patterns, a name that binds, _, a literal, or == expr) and whose optional if guard holds; no arm matching stops the run with a failure. A pattern naming a variant of another type, or with the wrong number of fields, is an error, and a match whose arms leave variants uncovered gets a warning naming them. |
| Decision tables | table price(age: int, member: bool) { \| < 18, any => 5 \| between(65, 120), any => 8 \| any, true => 9 \| otherwise => 10 } is a function (price(30, true)) whose rows are tried in order; the first row whose cells all hold gives the result. A cell is any, a comparison (< e, <= e, > e, >= e, != e; numbers, dates, strings), between(lo, hi) (both ends included) or a value the argument must equal; otherwise is a row of any cells. No row matching stops the run with a failure. The checker judges the rows exactly over their numbers, values and ranges: it reports a row that earlier rows already cover (table row 2 is unreachable: row 1 already covers every case it matches), and for a table without an otherwise row either stays silent (the rows cover every argument — an int parameter has nothing between 3 and 4) or names the first argument no row matches (no row matches age = 18, member = false). A cell that is not a plain value (a variable, a call) is not analysed, so the checker only claims a gap that no row could cover. It also reports a row with the wrong number of cells. Switch the rows to a grid (⊞ badge or Mod+Alt+V on the rows): a column per parameter, every cell editable in place, with + Add row and a delete button per row. |
| Small expressions | xs.pick(list(2, 0)) is the elements at those indices (an index outside the list stops the run); x.bounds(0, 10) clamps a number into the bounds, none leaving an end open (x.bounds(none, 10)); x == 3 ± 0.1 is true when x is within 0.1 of 3 (only == / != read a tolerance); :add is the function add itself, so xs.fold(0, :add) works; if isSome(maybe(x)) as v then v + 1 else 0 unwraps an option into v (only visible in then; several tests join with &&; no else means none); and alt | c => v without otherwise gives none when no arm matches. |
| Rational numbers | rat(1) / rat(3) is the exact fraction 1/3: + - * / and the comparisons never round (rat(1)/rat(3) + rat(1)/rat(6) is 1/2), a plain number mixes in exactly (rat(1)/4 + 0.25 is 1/2), rat(0.25) is 1/4. Members: .toInt (toward zero), .toReal (a decimal), .numerator, .denominator. rat is also a type: fun half(r: rat) = r / rat(2). |
^ cells and split |
In a decision table a ^ cell repeats the cell above it in the same column (\| < 1, false => 3 \| ^, true => 6 — the second row is also < 1); the checker sees through it, and a ^ in the first row is an error. split t \| < 10 => "low" \| between(10, 20) => "mid" \| otherwise => "high" cuts one value into ranges with the same cells as a table: the first arm that holds gives the result, none when no arm does (end with otherwise to cover everything), and an arm that earlier arms already cover is reported. A multi-valued row is a tuple result (=> tuple(a, b)). |
| State machine details | The initial state's entry actions run when M() starts the instance (outermost state first). if guard => target (no event) is an automatic transition: taken whenever its guard holds — before and after every fire, and on m.poke() (which says whether one was taken); a cycle of them is reported as a failure. var n = 0 / observable var n = 0 give each instance its own box (n.current, n.update(…) in guards and actions); an observable variable and an observable query many = n.current > 1 are readable from outside as m.n / m.many. A composite state with history resumes in the substate it was left in. newtx(e) is a transaction like atomic(e); intx(e) must run inside one. rate 2 per 10 among a machine's items is an interceptor: at most that many events are accepted in any window of that many seconds (by the run's clock); further events are discarded and fire says false until the window moves on. |
| More about units | unit nmi = 1852 m and unit knot = 1852/3600 m/s declare your own units as an exact multiple of one already known (a built-in or one declared above); they work in quantity<…>, convert<…> and quantity types for the rest of the file. degC and degF are temperature scales with an offset: convert<K>(quantity<degC>(20)) is 293.15 K, comparisons use the absolute temperature, quantity<degC>(30) - quantity<degC>(10) is 20 K (a difference), quantity<degC>(30) + quantity<K>(5) is 35 degC; adding two temperatures, multiplying, dividing or negating one is refused (convert to K first), and an offset unit stands alone (no degC/s). quantity<m>[0|100] is a quantity type with a range on the magnitude (in that unit), enforced by cast / check. |
| Block libraries and state | A block declared in another model is used after import "that-model": it runs like a local one, the graph view shows its ports, and the checker does not call it unknown. A block call is a pure function from inputs to outputs, so a block that must remember something takes a box as an input: block Counter { in n: box<int>, out next: int = n.update(\|it + 1\|) } — Counter{n = c} called twice with the same box c counts 1, then 2. box<T> is a type. In the graph view the toolbar adds an input port, an output port or an instance (of the block declared just before). |
| Ordered tags and taint rules | tag level { low < mid < high } declares an ordered tag: tagged<level.mid>("x") tags a value with one of its values, and in a type level.mid- means every value up to mid — fun f(s: tagged<string, level.mid->) accepts a value tagged level.low or level.mid but not level.high. untag<level.mid->(e) drops all of them. level.mid+ is the mirror: mid and every higher value (fun f(s: tagged<string, level.mid+>) takes level.mid or level.high, not level.low). tag hashed clears secret is a taint rule: tagging a value with hashed removes secret from its type. |
| Function types and effects | (int, int => int) is the type of a function; ( => int) takes nothing. An effect may follow the arrow — (int =>/R int) — and is then judged like fun f/R: calling such a parameter has the effect (so the function must declare it), and a function passed for it must stay within it (a /M function is refused where /R is declared). Parameters without a declared effect are not judged. |
| Decision tree graph | A tree { … } can be switched to its graph view (Mod+Alt+V, or Alt+Enter): the tree is the root box, every branch and leaf is a box (x > 10 ?, y > 5 => "a") and an edge runs from the branch it sits in. The graph is a view; edit the text form. |
| Joining with an operator | xs.join<+>, join<*>, join<&&>, join<\|\|>, join<min>, join<max> combine a list left to right with the operator (strings concatenate under +); an empty list gives none. The separator form xs.join(", ") is unchanged. This is struktJS's own reading of the name — KernelF has no join<op>. |
| Documentation | doc "text" is a statement that carries documentation and evaluates to nothing. (KernelF's doc is IDE tooling; this keeps the text.) |
| Terms: parent and ancestors | Values have no parent pointer, so ask the root: root.parentOf(t) is the term of root that directly holds t (none for the root itself or a value not inside it); root.ancestorsOf(t) lists the terms containing t, nearest first, ending with root. |
| π, ∫ and lim | pi() is π to the working precision; integral(f, a, b) is the definite integral by Simpson's rule on 200 intervals (exact up to cubics, rounded to 12 places); lim(f, a) is the value f approaches at a (sampled on both sides; it fails when the sides disagree; rounded to 6 places). All three have a math notation (π, ∫ₐᵇ f dx, lim under x → a). These are struktJS's own numeric concepts. |
| Query | query xs filter \|it > 1\| transform \|it * 2\| group by \|it mod 2\| build \|it.size\| — a source list, then optional clauses in this order: filter keeps elements whose function gives true, transform maps them, group by makes a map from each key to its elements and build maps each group's list (it needs a group by). |
| Decision trees | tree { \| x > 10 { \| y > 5 => "a" \| y > 0 => "b" } \| x > 0 => "c" otherwise "d" } — the first top-level node whose condition holds decides: a leaf (=>) gives its value, a branch ({ … }) lets its own nodes decide and, if none does, the result is none — the search does not go on with the branch's siblings — and otherwise is the value when nothing gave one. otherwise as a condition means always. The nested view is the editor's own indentation. |
| Metafunctions | metafun price(x) "doubles it" = x * 2 is a function that carries a description (shown with the function); it behaves like fun. |
| Quoted expressions | quote(e) holds the expression e as a value without evaluating it (type quoted<T>); unquote(q) evaluates it where it was written, so val q = quote(n * 10) then unquote(q) uses the n that was in scope at the quote. |
| Algebraic values as terms | For a data value t: t.traverse("top-down") lists every sub-term (itself included), parents first ("bottom-up": last), t.termSize counts them, t.copy is a deep copy, and t.replaceWith(old, new) is a copy in which every sub-term equal to old is replaced (values are immutable, so it returns the new tree where KernelF edits the model). |
| Effects | fun bump/M() = counter.update(\|it + 1\|) declares the function's effect: /R reads state (a box, the clock), /M modifies it (set / update a box, fire / poke a machine, set the clock), /RM both. A function that declares an effect must cover what its body does, and any function that calls one with a declared effect must declare it too (an error otherwise). A function with no declaration and no such call is not judged. |
| Phrases | natlang "add $a to $b" = add gives a function a phrase of words and operands: from then on add 3 to 4 means add(3, 4), anywhere in the file (an operand is one operand: add 1 to 2 + 10 is (add 1 to 2) + 10; a phrase must fit on one line). The program is stored — and prints back — as the plain call. |
| Lookup tables | lookup rate(country, year) { \| "DE", 2025 => 19 \| "FR", 2025 => 20 } is a function from exact keys to a value; a key with no row gives none (so rate("FR", 2026) ?: 0 supplies a fallback) instead of stopping the run. Every cell is a plain value (a comparison, any or between is an error), and a key listed twice is a warning. |
| Type tags | tag secret declares a tag; tagged<secret>(e) attaches it to a value's type (tagged<string, secret>) and untag<secret>(e) removes it. Tags flow through every operation: key.length + 1 is tagged<number, secret>, an operation over two tagged operands carries both tags, and a branch carries the tags of both. A tagged value is rejected where the plain type is expected (send(key) for a parameter s: string is an error); a plain value is accepted where a tagged one is. untag is the only way through (a warning when the value does not carry the tag). Tags exist only while checking: the running program sees the plain value. A parameter can ask for tags (s: tagged<string, secret>). |
| Messages | message("warning", "disk almost full") is a value with a severity (info, warning or error) and a text, read with .severity and .text; a severity that is not one of the three is an error (a failure when it is computed). |
| State: boxes and transactions | box(0) is a mutable cell: b.current reads it, b.set(e) stores a value, b.update(\|n => n + 1\|) applies a function; a box is shared, not copied. atomic(e) evaluates e as one transaction: if it fails, or its value is an error, every change made inside is undone (an inner transaction that succeeded is still undone by an outer failure). Without atomic, changes before a failure stay. |
| Clocks | now() is the current date and time (UTC). setClock(datetime("2026-01-01T09:00:00")) switches the run to an artificial clock and advanceClock(60) moves it forward by seconds, so a run is deterministic; a rolled-back atomic restores the clock too. Each run has its own clock. |
| State machines | machine Door { state closed { on open if ok => opened do count.update(\|n => n + 1\|) }, state opened { on close => closed } } declares a machine; Door() makes an instance in the first state; d.fire("open") takes the first transition from the current state for that event whose guard holds (no if means always) and runs its action, giving true (or false when none applies); d.state is the current state's name. A step is one transaction: a failing action leaves the state and every box as they were. The checker reports a transition to an unknown state or a state declared twice, and warns about a machine with no states and about a transition that can only be reached when the guards of an earlier one fail. |
| State machines, in depth | Nesting: a state may hold states (state on { state idle { … }, state playing { … } }); entering it enters its first substate, d.state names the innermost state, d.isIn("on") is true for it and every state around it, and an event the innermost state does not handle is looked up in the states around it. Entry and exit: entry e and exit e inside a state run when it is entered or left; a transition leaves the current state and every state above it up to the nearest state that contains both ends, runs its own action, then enters down to the target's first leaf (a self transition leaves and re-enters). The initial state's entry actions are not run when the instance is made. strict machine M { … } fails on an event that nothing in the current chain has a transition for (a guard that merely fails still gives false). d.timeInState is the whole seconds since the instance entered its current state, by the run's clock. |
| Temporal values | TT[date("2026-01-01") => 10, date("2026-03-01") => 12] is a value that changes over time: each value holds from its time until the next slice starts. t.at(when) gives the value holding at a date or datetime (none before the first slice), t.mapEach(\|p => p * 2\|) applies a function to every slice, a.combine(b, \|x, y => x * y\|) combines two temporal values slice by slice (one slice for every time either side changes, from when both have a value), t.reduce(0, \|acc, v => acc + v\|) folds the values in time order, t.times lists the slice times and t.size counts them. Slices are kept sorted and a repeated time keeps its last value. The arithmetic and comparison operators lift over temporal values: t * 2 keeps the slices and changes the values, t * u has a slice at every time either changes (from when both have a value), and t > 11 is a temporal boolean; use mapEach / combine for anything else. TT<int> is a written type (fun f(p: TT<int>) = p * 2). |
| Physical units | quantity<m/s^2>(9.8) is a number with a unit. Quantities of the same dimension add, subtract and compare whatever units they are written in (quantity<km>(3) + quantity<m>(500) is 3.5 km, the first operand's unit); * and / combine units (quantity<km>(36) / quantity<h>(1) is 36 km/h) and a result whose dimensions cancel is a plain number. convert<m/s>(q) expresses a quantity in another unit of the same dimension, and q.magnitude is its number. Conversion and comparison are exact (quantity<km/h>(36) == quantity<m/s>(10) is true); a conversion with no finite decimal expansion rounds at 64 digits. The type quantity<m/s> is the dimension, so km/h and m/s are the same type, and adding metres to seconds is an error. Units: m, km, cm, mm, kg, g, mg, t, s, ms, min, h, d, A, K, mol, cd, Hz, N, J, W, Pa, L; write products and quotients as kg*m/s^2, 1/s. Every other numeric operation (mod, sqrt, pow, abs, sum, min, round, …) rejects a quantity: take .magnitude first. quantity and convert are reserved words (temperature scales and your own unit declarations are covered under More about units). |
| Math notation | Switch a node to a textbook projection with Mod+Alt+V (or Alt+Enter, or right-click → Switch Notation); the file text never changes. a / b becomes a stacked fraction, x.pow(n) a superscript, x.sqrt a radical, x.abs \|x\|, x.floor / x.ceil ⌊x⌋ / ⌈x⌉, and a quantity such as quantity<m/s^2>(9.8) reads 9.8 m/s² with upright unit symbols and a real superscript. The math view is read-only for the unit text: switch back to edit it. Σ, ∫, limits, π, ± and bounds have no KernelF concept to project, so they are not offered. |
| Dataflow blocks | block Add { in a: int, in b: int, out total: int = a + b } declares a block with typed input ports (in) and typed output ports (out name: T = expression). A block can contain instances of other blocks, wired together: block Scale { in x: int, inst k = Add{a = x, b = x}, out y: int = k.total }. Add{a = 1, b = 2} feeds the inputs and gives a record of the outputs, so Add{a = 1, b = 2}.total is 3. A wire is just an expression: a = x feeds an input, k.total reads an output of instance k; an output may feed any number of inputs, and every input must be fed exactly once. Instances may be written in any order (forward wires are fine); they run in dependency order, and a cycle of wires is reported as an error. A block must be declared before it is instantiated, so a block cannot contain itself. The checker reports an unwired, unknown or doubly-fed input, a wire of the wrong type, an output whose expression does not match its declared type, duplicate port or instance names, and a use of an instance outside its block. A port named like a built-in member (sum, size, first, …) is read with backticks, as for record fields: k.`sum`. In the block's graph view (the ⊞ badge, or Mod+Alt+V) every port is a named square on its box — inputs on top, outputs below — and each wire runs from the port it reads to the port it feeds. Drag from an output port (an input port of the block, or an output of an instance) onto an input port to write that wire into the text; dropping on the box itself uses the first output and the first input not yet fed. An input that is already fed is replaced (undo restores it), and an out expression is only replaced when it is empty or itself a plain wire. |
| Declarations | record Point { x: int, y: int } with values #Point{x = 1, y = 2} and field access p.x; enum Color { red, green } with Color.red (an enum can carry values — enum Level { low = 1, high = 10 } — and a literal offers .index, .name and .value); p with {x = 3} copies a record with some fields replaced; type Pos = int where it > 0 — a named type, optionally narrowed by a condition on it. A parameter may use any of these as its type, and cast<Pos>(n) checks the condition when the program runs. A field named like a built-in member (size, where) is written with backticks: r.`size`. |
| Errors and contracts | error(x) is a value, not a stop: it flows through operators like none (error("e") + 1 is that error), and x.isError / x.errorValue inspect it; the type attempt<int> is "an int or an error". A function can state conditions: fun half(n: int) = n / 2 pre n > 0 post res < n — pre is checked on entry, post on the result (named res), and a violated condition stops the run with a failure that names it. |
| Handling errors, importing | try f(x) error e => 0 is the value of f(x), or — when that is an error — the handler, with the error's payload as e. check<int>(v) is v when it fits and an error saying why when it does not (cast gives none). import "other-model" brings another model's declarations into scope. Comparisons: <, >, <=, >=, ==, !=. |
| Unwrap, defaults, templates | x! is the value of an option and stops the run with a failure when it is none or an error. default<T> is the default value of a type (0, false, an empty string or collection, none, an enum's first literal). '''total = $(total)''' builds a string with values in $( ) holes (str(a, b) is the same without the template). |
| Other | alt \| c => v otherwise e, cast<T>(e) (the value, or none when it does not fit the type), fail("message") (stops the run with a failure; it can stand wherever a value is expected), str(a, b, …) (builds a string). |
Things to know:
- Running. Run a KernelF model as usual; the value of its last line is the result. A division by zero or
fail(…)is a deliberate failure and is reported as such. - Parameters of a lambda. A lambda written with no parameters binds
it. To give it explicit parameters, use the Name the parameter intention on the lambda. - Syntax errors. The text format has no error recovery: a file that does not parse fails to load with the position of the problem rather than loading partly.
- Not included yet. the rest of KernelF's extensions (see
docs/architecture/kernelf-plan.mdin the repository for the roadmap).
Testing KernelF programs¶
A KernelF model can carry its own tests: import the KernelF tests language next to KernelF and write suites after the code they test.
fun double(n) = n * 2
suite "arithmetic" {
test "doubling" {
assert double(21) equals 42
assert double(2) not equals 5
assert double(3) > 5
confail 1 / 0 with "Division"
}
}
Open the Tests pane and run all tests. Each assert reports pass or fail with a message such as expected 42, got 41 and how long it took.
assert a equals bandassert a not equals bcompare by value: decimals exactly, lists element by element.assert condneeds the condition to be exactlytrue.confail epasses when evaluatingefails on purpose (a division by zero,fail(…), a violatedpre/post); addwith "text"to also require the message to contain that text.- A
testcan declare values withval, visible to the assertions after it; each test has a scope of its own, and everything declared above the suites is visible to all of them. - More checks:
assert x is none,is some,is error,is empty,is not empty;assert xs contains x(a list, set, text or a map's keys);assert x between 1, 10;assert a equals b within 0.01(a tolerance). report eshows the value ofein the results without checking anything.- A table of cases:
vector double { 1 => 2, 2 => 4, tuple(1, 2) => 3 }calls the function once per row (atuple(…)input supplies several arguments) and lists each row as its own result. inval epasses whenehas no valid value —none, as analtwith no matching arm gives.assert as surprise that a equals bis the same assertion reported under the labelsurprise.- A sheet is a grid of cells:
sheet { price = 100, vat = price * 0.2, price + vat == 120 }evaluates its rows top to bottom and each row left to right; a named cell (price = …) can be used by every cell after it, and a boolean cell is a check (true passes, false fails; other cells just hold values). Switch it to its grid view with Mod+Alt+V. - A test model can
import "other-model"to use the declarations of another model of the project; the Tests pane resolves the import against the project. ignore test "…" { … }andignore suite "…" { … }keep a test in the model without running it.- Run this test (Alt+Enter on a suite, test or assertion) runs just that part against the open model.
- The run also measures coverage of the code under test (which nodes and branches the tests reached), and a mutation run changes each operator or literal of your code in turn and checks that some test notices — a surviving change points at a missing test.
- A declaration that itself fails (say
val bad = 1 / 0) is reported as a setup error and the suites still run.