Tutorial: build a small todo language¶
Audience: language and plugin authors. Time: about 45 minutes. Prerequisites:
Setup and workflow (a clone with npm install done) and the
Language authoring guide skimmed once.
You will build todotutorial, a four-concept language for task lists, as a built-in plugin:
todoList("weekend",
todoTask("Buy flour", False, todoHours(0.5)),
todoTask("Bake bread", False, todoHours(3)),
todoTask("Eat bread", True, todoHours(1)))
Along the way you add an editor projection, a check, a type rule, an interpreter, a code generator, a sample, tests and a package. This page is a walkthrough; the pages it links to are the reference.
How this tutorial was verified
Every file below was created exactly as shown, in a plugin folder in this repository, and then run with the
commands in each step: the headless CLI (npm run strukts) for check, generate and package, and vitest for
evaluation and rendering. The snippets are copied from those files. What was not exercised is clicking
through the result in the running IDE.
The finished plugin is small enough to keep in your head: one folder, five files.
plugins/lang-todo-tutorial/
project.json
languages/index.ts the language definition
languages/concepts.tsx the four concepts
models/todo-demo/ the sample
model.json
todo-demo.model.py
tests/todo-tutorial.test.mjs
Step 1: the language shell (5 min)¶
Create plugins/lang-todo-tutorial/languages/index.ts. Every file in a plugin's languages/ that exports a language
object is discovered automatically by src/lang-library.ts; there is nothing to register.
import { conceptsFromModule } from "../../../src/base-concept.ts";
import "../../lang-python/grammar/ts-parser.ts"; // the model files are Python-syntax text
import * as concepts from "./concepts.tsx";
export default {
name: "todotutorial",
namespace: "todotutorial",
displayName: "Todo (tutorial)",
description: "A tiny todo-list language built in the Developer Guide tutorial.",
concepts: conceptsFromModule(concepts),
};
The Python grammar import is needed because the model files are Python-syntax text and this language does not import Core, which would otherwise bring the grammar in. See Plugins and devkits.
Add the plugin's own project description, project.json:
{
"name": "Todo tutorial",
"description": "The tiny todo-list language from the Developer Guide tutorial."
}
Step 2: concepts (10 min)¶
A concept is a class declared with Concept(...), which names the interfaces it implements. Create
languages/concepts.tsx with the imports and the root concept.
import { h, Fragment, Br, Indent, Child, Children, Text } from "../../../src/editor-jsx.ts";
import { ChildSlot, Prop } from "../../../src/base-concept.ts";
import { Concept, IBlock, IExpression, IStatement } from "../../../src/concept-interfaces.ts";
import type { EvalContext } from "../../../src/evaluator.ts";
import type { GenerateContext } from "../../../src/generator.ts";
import type { CheckContext } from "../../../src/checker.ts";
import type { TypeCheckContext, TypeInferContext } from "../../../src/hook-contexts.ts";
import { isCon } from "../../../src/typesystem.ts";
const isNumber = (t: any) => isCon(t, "number");
/** `TodoList` is the model's own root: a name plus the tasks under it. */
export class TodoList extends Concept(IBlock) {
head = "todoList";
isFileRoot = true;
description = "A named list of tasks.";
name = Prop({ type: "name", default: "" });
tasks = ChildSlot({ type: IStatement, cardinality: "0..n" });
editor = this.template((self) => (
<>
<Text class="kw">todo </Text><Child link={self.name} />
<Br />
<Indent><Children link={self.tasks} vertical emptyText="(no tasks yet)" /></Indent>
</>
));
async eval({ evaluate, output }: EvalContext) {
output(`# ${this.name}`);
for (const task of this.tasks) await evaluate(task);
return null;
}
generate({ emit, indent }: GenerateContext) {
const lines = [`${indent}print(${JSON.stringify("# " + this.name)})`];
for (const task of this.tasks) lines.push(emit(task));
return lines.join("\n");
}
}
/** `TodoTask` is one line of the list: a title, a done flag and an estimate in hours. */
export class TodoTask extends Concept(IStatement) {
head = "todoTask";
description = "A task: title, done flag and an hour estimate.";
shortDescription = "Add a task";
title = Prop({ type: "string" });
done = Prop({ type: "boolean", default: false });
estimate = ChildSlot({ type: IExpression });
editor = this.template((self) => (
<>
<Text class="kw">task </Text><Child link={self.title} />
<Text> done: </Text><Child link={self.done} />
<Text> estimate: </Text><Child link={self.estimate} />
</>
));
async eval({ evaluate, output }: EvalContext) {
const hours = await evaluate(this.estimate);
output(`[${this.done ? "x" : " "}] ${this.title} (${hours}h)`);
return null;
}
generate({ inline, indent }: GenerateContext) {
const mark = this.done ? "x" : " ";
return `${indent}print(${JSON.stringify(`[${mark}] ${this.title} (`)} + str(${inline(this.estimate)}) + "h)")`;
}
checks() {
return [
{
name: "task-needs-a-title",
severity: "error",
check({ node }: CheckContext) {
if (typeof node.title !== "string" || node.title.trim() === "") return { message: "A task needs a title" };
return null;
},
},
];
}
typesystem() {
return {
infer() { return "void"; },
check({ node, whenConcrete }: TypeCheckContext) {
let issue: { severity: string; message: string } | null = null;
whenConcrete(node.estimate, (t: any) => {
if (!isNumber(t)) issue = { severity: "error", message: "An estimate must be a number of hours" };
});
return issue;
},
};
}
}
/** `TodoHours` is a number of hours, the one expression a task estimate normally holds. */
export class TodoHours extends Concept(IExpression) {
head = "todoHours";
description = "A number of hours.";
shortDescription = "Hours";
value = Prop({ type: "number" });
editor = this.template((self) => <><Child link={self.value} /><Text class="kw">h</Text></>);
eval() {
return this.value;
}
generate() {
return String(this.value);
}
typesystem() {
return { infer() { return "number"; } };
}
}
/** `TodoNote` is free text. It is an expression too, so it can be put in an estimate by mistake. */
export class TodoNote extends Concept(IExpression) {
head = "todoNote";
description = "A free-text note.";
shortDescription = "Note";
text = Prop({ type: "string" });
editor = this.template((self) => <><Text class="kw">note </Text><Child link={self.text} /></>);
eval() {
return this.text;
}
generate() {
return JSON.stringify(this.text);
}
typesystem() {
return { infer() { return "string"; } };
}
}
Read it once; the following steps explain each part. What matters now:
headis the concept's persisted name. Choose distinctive heads: two concepts sharing aheadshadow each other silently. See Concepts.isFileRoot = truemarksTodoListas the model's root, andConcept(IBlock)marks it as a statement-list container. The engine asks the language for these, never for names.- Slots are fields.
Propis a persisted scalar (name,title,done,value,text);ChildSlotis a nested node. A variadic slot (cardinality: "0..n") must be the last slot, which is whytaskscomes aftername. Concept(IStatement)andConcept(IExpression)say where a concept may be placed:tasksaccepts statements,estimateaccepts expressions. A slot names the same interface as itstype.- The editor is
this.template((self) => …):self.titleis the slot's handle (a typo in it fails to compile), whilethis.titleinevalandgenerateis the value.
A note on the slot order: todoTask("Bake bread", False, todoHours(3)) is the persisted form, and the arguments are
positional by slot order. Inserting a slot before an existing one later would silently reassign already-saved
files (the lint in npm run lint:concepts exists for that bug class).
Step 3: a sample and the first check (5 min)¶
A model needs a folder with a model.json that names its language, and the source file.
{
"imports": [{ "qualifiedName": "todotutorial" }],
"label": "Weekend list",
"description": "A three-task todo list.",
"roots": { "todo-demo.model.py": "Weekend list" }
}
todoList("weekend",
todoTask("Buy flour", False, todoHours(0.5)),
todoTask("Bake bread", False, todoHours(3)),
todoTask("Eat bread", True, todoHours(1)))
Because the folder sits under plugins/<name>/models/, it is a bundled sample. Ask the CLI whether it sees it:
npm run strukts -- list # a project with "id": "todo-demo" and "imports": ["todotutorial"]
npm run strukts -- check --project todo-demo
The second command prints a JSON report ending in "status": "ok" and exits 0. If list does not show the project,
the language failed to load: run npm run strukts -- info and read its error output.
Root names come from model.json
The root's name slot is not read from the file. The loader blanks it and writes the display name from
model.json's roots map ("Weekend list" here). The file's "weekend" is used only when you parse text
directly, as the tests in step 8 do.
Step 4: the editor projection (5 min)¶
The editor template is JSX that describes the cells. You already wrote them in step 2; this is TodoTask's:
editor = this.template((self) => (
<>
<Text class="kw">task </Text><Child link={self.title} />
<Text> done: </Text><Child link={self.done} />
<Text> estimate: </Text><Child link={self.estimate} />
</>
));
Text is decoration (class="kw" styles a keyword), Child renders a slot's value in place (a text cell for a
Prop, a nested editor for a ChildSlot), and Children renders a variadic slot, here vertical with an
emptyText. Br and Indent lay out the root. The full token
vocabulary is in Editors and projections.
The tests render the projection with the real projectAST. Create tests/projection.test.mjs; the first line is a
vitest docblock that opts this one file into a DOM, because plugin tests run DOM-less by default.
// @vitest-environment jsdom
import { assert, Language, parseSurface, test } from "../../../tests/test-utils.mjs";
import { projectAST } from "../../../src/projection.ts";
import todoDef from "../languages/index.ts";
test("todo: the editor shows a task as task, title, done flag and estimate", () => {
const lang = new Language(todoDef);
const root = parseSurface('todoList("w", todoTask("Bake", False, todoHours(3)))', { lang });
const dom = projectAST(root, lang, { onLiteralEdit() {}, onCellFocus() {} });
const text = dom.textContent.replace(/\s+/g, " ");
assert(text.startsWith("todo w"), text);
assert(text.includes('task "Bake" done: false estimate: 3h'), text);
});
npx vitest run plugins/lang-todo-tutorial/tests/projection.test.mjs
Seeing the real result in the IDE needs the plugin staged into the webview's glob roots (npm run stage:active-roots,
which the predev, prebuild:webview and pretest hooks run for you) and then the fast loop from
Setup and workflow. Then Load Sample... lists "Todo tutorial".
Step 5: a check (5 min)¶
checks() returns rules. A rule returns null for no problem or { message }; severity is on the rule.
checks() {
return [
{
name: "task-needs-a-title",
severity: "error",
check(node: any) {
if (typeof node.title !== "string" || node.title.trim() === "") return { message: "A task needs a title" };
return null;
},
},
];
}
Make a deliberately bad model in a scratch folder, outside the repo. A project folder needs project.json,
model.json and the source file:
todoList("weekend",
todoTask("", False, todoHours(1)),
todoTask("Bake bread", False, todoNote("some time")))
npm run strukts -- check --project-dir /path/to/scratch
The empty title is reported as STRUKT-CHK-task-needs-a-title, "A task needs a title", at line 2, column 5, and the
command exits 3 ("check found errors"). Exit codes are documented in Command-line tool.
The second task is flagged too, by the type rule in the next step. See
Checks, constraints and types for constraints and intentions.
Step 6: a type rule (5 min)¶
Types are inferred per concept. TodoHours produces a number and TodoNote a string:
typesystem() {
return { infer() { return "number"; } };
}
(That is TodoHours; TodoNote is the same with "string".) TodoTask then checks its estimate slot:
typesystem() {
return {
infer() { return "void"; },
check(node: any, env: any, infer: any, whenConcrete: any) {
let issue: { severity: string; message: string } | null = null;
whenConcrete(node.estimate, (t: any) => {
if (!isNumber(t)) issue = { severity: "error", message: "An estimate must be a number of hours" };
});
return issue;
},
};
}
Two details worth knowing. whenConcrete(child, fn) calls fn only when the child's type is known, so an unfilled
slot or an any never produces a mismatch. And a hook receives type terms, not strings, so compare with
isCon(t, "number") from src/typesystem.ts, as the file's one helper does:
const isNumber = (t: any) => isCon(t, "number");
Run the same CLI check on the scratch model. The report now also contains
"An estimate must be a number of hours" at line 3, column 5 (code STRUKT-CHK-GENERIC): the CLI runs the checker
and the type pass together, like the IDE. The full hook contract is in
Checks, constraints and types and Type terms.
Step 7: eval and generate (5 min)¶
eval runs when the program executes. It takes one context object: evaluate(child) evaluates a child and output(text)
prints. Everything is async. Here are both runtime hooks of TodoTask:
async eval({ evaluate, output }: EvalContext) {
const hours = await evaluate(this.estimate);
output(`[${this.done ? "x" : " "}] ${this.title} (${hours}h)`);
return null;
}
generate({ inline, indent }: GenerateContext) {
const mark = this.done ? "x" : " ";
return `${indent}print(${JSON.stringify(`[${mark}] ${this.title} (`)} + str(${inline(this.estimate)}) + "h)")`;
}
generate returns text; emit(child) generates a child at this node's indentation and inline(child) with none (used
here, because the estimate sits in the middle of a line). This language generates Python,
because the generated-file extension follows the language's persistence grammar. Run it:
npm run strukts -- generate --project todo-demo --output /tmp/todo-out
It reports one artifact, todo-demo/todo-demo.py, and the file contains:
print("# Weekend list")
print("[ ] Buy flour (" + str(0.5) + "h)")
print("[ ] Bake bread (" + str(3) + "h)")
print("[x] Eat bread (" + str(1) + "h)")
and running it with python3 prints the checklist ([ ] Buy flour (0.5h) and so on). The CLI has no run verb:
evaluation is tested in step 8, and in the IDE it is Run > Execute. More in
Evaluation and generation.
Step 8: tests (5 min)¶
Tests live in plugins/<name>/tests/*.test.mjs, which vitest.config.js picks up with no edit. Build the language
from its definition and call the engine directly:
import { assert, assertEqual, Evaluator, Language, parseSurface, runChecks, runGenerator, test } from "../../../tests/test-utils.mjs";
import todoDef from "../languages/index.ts";
const lang = new Language(todoDef);
const clean = `todoList("weekend",
todoTask("Buy flour", False, todoHours(0.5)),
todoTask("Eat bread", True, todoHours(1)))`;
const issuesOf = (root) => [...runChecks(root, lang).values()].flat().map((i) => i.message);
test("todo: a clean list has no issues", () => {
assertEqual(issuesOf(parseSurface(clean, { lang })).length, 0);
});
test("todo: an empty title is an error", () => {
const root = parseSurface('todoList("w", todoTask("", False, todoHours(1)))', { lang });
assert(issuesOf(root).includes("A task needs a title"));
});
test("todo: a note in an estimate is a type error", () => {
const root = parseSurface('todoList("w", todoTask("x", False, todoNote("later")))', { lang });
assert(issuesOf(root).includes("An estimate must be a number of hours"));
});
test("todo: eval prints the checklist", async () => {
const out = [];
const ev = new Evaluator(lang, { output: (s) => out.push(s) });
await ev.evaluate(parseSurface(clean, { lang }));
assertEqual(out.join("\n"), "# weekend\n[ ] Buy flour (0.5h)\n[x] Eat bread (1h)");
});
test("todo: the generator emits runnable Python", () => {
const text = runGenerator(parseSurface(clean, { lang }), lang);
assert(text.includes('print("[x] Eat bread (" + str(1) + "h)")'));
});
npx vitest run plugins/lang-todo-tutorial/tests
Six tests pass (five here, one in projection.test.mjs). Note the expected output # weekend: parseSurface keeps the
name from the text, unlike the file loader of step 3. For model-level tests that run inside the IDE's Tests pane see
Testing.
Step 9: package it (2 min)¶
npm run strukts -- package --project todo-demo --output /tmp/todo-pkg
This gates on check (exit 3 if the model has errors), generates, and writes manifest.json next to the output: the
SHA-256 of the source and every generated file, plus the check summary. The directory is the package. It is the same
command a CI job or a Gradle/Bazel build calls (see Command-line tool).
Going further¶
- Devkit. A devkit bundles sibling languages into one installable language
(
plugins/<name>/<name>.devkit.json; today onlycoreuses it). It is optional here, because one language needs no bundle. See Plugins and devkits. - Scope and references. Make a task refer to another by name with
Refandscope(): Scope and dataflow. - Another file format. Persistence grammars.
- Iterate without rebuilding, or write the language as a single hot-reloaded file: Plugins and devkits.
Checklist before you send it¶
npm run strukts -- check --project <your-demo>exits 0.- Your own tests pass with
npx vitest run plugins/<name>/tests. npm run lint:concepts -- <your-plugin-folder>: lints only your plugin, so findings in other plugins don't show.npm testbefore a pull request; the sample smoke tests load, project and evaluate every bundled sample, including yours. See Contributing.
Gaps found while writing this tutorial¶
- Whole-repo
npm run lint:conceptscan exit 1 on findings in other plugins; pass your plugin folder name to gate on it alone.