Designing a programming language's syntax and semantics (lessons from H)
language-designsyntaxsemanticspipelinesstatic-typingh-language
Designing a language is mostly a long series of small decisions, each of which looks harmless
alone and interacts with all the others. This article collects the reasoning behind the
decisions made for H, Justin's hobby language (imperative, braces, | pipelines, compiled to
native x86-64 by hc, repo ~/dev/h), and generalizes the ones that apply to any language. The
compiler side is in Writing a native compiler in C that emits x86-64 assembly.
Running the design process
- Keep a decision log with Decided and Open sections (H's
DESIGN.md). Each decided row records the answer, the date, and the alternatives considered and why they lost. Never re-ask a decided question; moving an answer into the table is part of making it. - Ask one or two questions at a time, each with a recommendation. Long numbered question lists stalled H for days; five runs of design Q&A without code drew "what's taking so long?". Bias toward building, and ask only when the code actually needs an answer.
- Build around open questions with a conservative default: make the uncertain construct a
compile error ("
breakinside aneachbody is not allowed yet"). Turning an error into a feature later breaks no program; changing a behavior does. - Prefer choices you can extend over ones you would have to retract. H requires every mutable
variable to state its type (no
var/auto): addingvarlater breaks nothing, removing it would. - Check practical fallout of cosmetic choices. The file extension
._was tested against shell globs and make pattern rules (%: %._) before it was adopted. - Write the decision as an example, not just a rule:
while (int i++ = 0; i < 5) { }prints 0 to 4, so the step runs before every check after the first.
Grammar: keep it unambiguous on purpose
- Make comparisons non-chaining (
a < b > cis a compile error). That freesname<expr>to mean something else without ambiguity: H uses angle brackets for options (each<" ">,echo<"">), and an option containing<or>needs parentheses. - Reject the classic
=/==slip. If assignment is an expression, a bare=at the top of anif/whilecondition is a compile error ("did you mean==?"); doubled parenthesesif ((x = next()))say it is intended. The same trick C compilers warn about, made an error. - Tokens are greedy (maximal munch). Once
++and--exist,--3lexes as a decrement of a literal, not double negation. Users write-(-3). Decide this explicitly and test it. - Optional parentheses need a rule for the cases they create. H's
if x > 0 {andif (x > 0) {both work, and the design records ahead of time that(...)followed by{inside a condition is grouping, never a function literal. - Name rules: letters, digits and
_, plus an optional trailing?for yes/no values (alive?, from Ruby). A name may not start with a digit, so2xis a clear error. - Semicolons: required, with two conveniences (none before
}, none after a statement that is anifor block). Fully optional semicolons need newline rules that cause their own bugs.
Things declined, and why
- Implicit multiplication (
2xmeaning2*x, as in Julia): declined. Multiplication is always*. - Bash-style string adjacency (
"error: "msg" - aborting."): declined for the same reason as implicit multiplication. A missing operator would still compile, and a stray quote silently flips which parts are code. H has+(string + string only) and interpolation"score: {n + 1}". - Implicit program execution: a bare word never runs an external program (unlike shell); an
explicit
exec(...)does, like PHP. - Two spellings for one thing:
xs.lengthonly;xs.length()is an error that shows the right form. Members without parentheses read facts, with parentheses they act. Two spellings split code by habit. - A
forloop andcontinue: H has onlywhile, with a header that declares loop variables and their step (while (int i++ = 0; i < 5)). An earlier proposal,when (int i++ < 5), was dropped once it was spotted that the body would see 1 to 5 (off by one), it had no start value, and Kotlin useswhenfor matching.
Semantics worth deciding early
- Evaluation order: strictly left to right, operands before operators (Java). Every expression
then has one result (
i++ + ++iis defined); C's unspecified order is a bug source with no benefit for a new language. - Integer division: floor division with the remainder taking the divisor's sign (Python), so
-7 / 2 == -4and-7 % 2 == 1. It also makes Python a ready-made test oracle (Writing a native compiler in C that emits x86-64 assembly). - Overflow is an error, reported with file:line:col, never a silent wrap; same for division by zero.
- Truthiness: only
falseand nil are falsy (Lua/Ruby);0and""are true.&&and||return the operand that decided, soname || "guest"works as a default. - Equality across types is just false (
1 == "1"), never an error; ordering needs numbers. - Conversions are the type name called as a function:
int("42"),string(42). A bad literal (int("abc"), or aconstholding one) is a compile error; text that only exists at run time is checked then. Invented names (number()) were rejected. - End of input: H's
readline()returns""at end of input (every time after), rather than nil, which would have forced every caller to handle a second type. - Shadowing: the C++ rule. An inner block may reuse an outer name; redeclaring in the same block
is an error. A declaration's initializer is checked before the name exists, so
int x = x + 1;in an inner block reads the outerx.
Variables without a value: no silent defaults
H first gave unassigned variables Java-style defaults (0, "", false, []). When the
designer noticed, it turned out he had never chosen that; it had ridden along in a proposal. The
replacement is definite assignment, checked at compile time when the answer is certain and at
run time when it isn't:
- int x; echo x; doesn't compile. int x; if c { x = 1; } echo x; compiles and fails with
"'x' is used before it has a value" only when c was false.
- The checker follows the program in order: both branches of an if must assign (a branch that
ends in return/break doesn't count), the right side of &&/|| may not run, a loop body may
run zero times (what it assigns is "maybe set" afterward), and a call may assign any global.
- Proven reads cost nothing; "maybe" reads compare against a hidden "no value" marker.
- x = e doesn't need a value; x += e and x++ do.
Java requires definite assignment everywhere and rejects the "maybe" case; C leaves it undefined. The hybrid keeps simple programs compiling while never inventing a value. Lesson for any language design: list every default explicitly and get each one approved; implicit ones slip through.
Closures: share, don't copy
A function literal (const f = (int x) int { x * 2 };) shares the variables around it, the
JavaScript/Python rule: count++ inside changes the real count, and later outside changes show
inside. C++-style copies made at creation were rejected because count++ would silently change
only the copy. This matches the choice to share lists. Until function types have a name, a literal
may only be the value of an untyped const and can't be passed, returned or stored, which also
means it can never outlive its frame (see Writing a native compiler in C that emits x86-64 assembly). No self-call through the
const's own name; use a named fn for recursion.
Mutable collections: sharing, freezing, identity
- Lists are shared on assignment and calls (Java, JS, Python). Copy-on-assign hides costs and surprises anyone coming from those languages.
constmeans deeply frozen (C++), but with sharing that has a consequence: a change through another alias (const snapshot = live;thenlive.push(1)) cannot be caught at compile time. H freezes the list object itself when it is bound to aconst, so the alias change is a runtime error. If you combine reference semantics with deepconst, you need a runtime freeze.- Contents vs identity:
==compares items deeply; identity gets a separate, clearly named member,xs.is(other)..equalswas considered and rejected because in Java.equalsmeans equal contents and==means identity, the reverse; borrowing a famous name with the opposite meaning invites bugs.isaccepts any value and answers false for a different type, like==. - Searching:
xs.has(v)returns a bool andxs.find(v)returns the first index or-1(a plain int rather than "int or nil", so callers need no nil check); both compare with==. Strings get the same pair for substrings.pop()andremove(i)remove and return items. - Printing a list shows strings quoted with the language's own escapes (
["a,b"]vs["a", "b"]), and the same text comes fromecho xs, interpolation andstring(xs).
Records first, methods second, inheritance when a program asks
A record is a class minus methods, constructors, private members and inheritance, so starting with records closes nothing off.
- Definition and value: type Room { string name; int visits = 0; } and Room { name: "Hall" }. Fields are named at the use site, in any order; a field without a default is required. Defaults must be plain values, and each record gets a fresh copy.
- Records follow the list rules: shared on assignment, deeply frozen in a const, == field by field, and printing shows the literal form.
- Methods arrived as a second step once records had been used: fn enter() { visits++; } inside the type, called as hall.enter().
- Explicit this. first, bare names later. Requiring this.name can be relaxed afterward without breaking code; the reverse cannot. It was relaxed within a day (too much typing), using Java's lookup order: local, then field, then top level.
- Adding methods exposed a rule that was too strict: a loop parameter was constant, so rooms | each (r) { r.visits++; } failed to compile. The rule was narrowed to "the parameter cannot be reassigned, but a record it holds can be changed".
- An error that lists what exists ("Room has no method 'x' (it has enter, describe)") costs one line and saves a lookup.
Modules
import "lib/text";loads a file relative to the importer, and its names are used with a prefix (text.trim(s));aspicks another prefix. Bare names, as with PHP'srequire, were rejected because names clash silently.- A module's top-level code runs once, before any importer's, in import order. "Definitions only" modules were rejected: a
constline is already top-level code. State that must survive between calls has to live somewhere, and the choice is the module or every caller. - Decisions that could wait did: there is no
exportor private marker yet, and everything at a module's top level is visible.
Error handling
try { ... } catch (e) { ... }is an expression, likeif:const n = try { int(line) } catch (e) { -1 };.- The caught value is a built-in type with members (
e.message,e.file,e.line), not a string, so it can gain kinds later without breaking code that printed it. The nameexceptionwas chosen overerror. - Every run-time error is catchable in the same way (division by zero, a missing file, a bad conversion), and uncaught it behaves exactly as before.
- One catch per try, catching everything; telling kinds apart waits for the type system to offer a way. No
finallyyet. - Rejected: returning nil on failure, a plain string, and "check before you try" functions as the only tool.
Pipelines as a core operator
H's | streams values left to right, lazily, one item at a time:
open("notes.txt") | each (line) { echo line[0]; };
- One job per stage. each is pass-through (like tee): its function's result is discarded and
the item flows on. Transforming is a separate map. Splitting (each<sep>) never joins;
join<sep> is its own stage.
- Layered splitting: every each cuts its input at its separator, so
file | each | each<" "> (w) { } walks every word of every line.
- When does a lazy pipeline run? A pipeline used as a statement drains; one bound to a name stays
a lazy stream until consumed. Streams are read once.
- break and return in each bodies act as in the while the pipeline stands for:
break stops the whole pipeline (items already passed on are still joined), return leaves the
enclosing function. There is no skip-one form, as there is no continue.
- Lists as sources are walked, not cut: each stage's input decides (text is split, a list is
iterated). each (x) takes the items' type, and an optional written type (each (int x)) is
checked. x | join<sep> and x | echo may follow the source directly (an implicit each).
- Streams get a type name (stream) so they can be variables, parameters and return values.
- Inline literal stages: when the stage function is a literal, the compiler can turn the whole
pipeline into nested loops, so pipelines work before closures exist.
Functions and globals
- Functions at the top level only until closures exist; callable before their definition, so mutual recursion just works.
- Trailing return type, Go style:
fn fact(int n) int { ... }. - Functions see top-level variables (lexical, hoisted). Using one before its declaration has run
(
show(); int lives = 3;) is a runtime error, never a silent default value.
See also
- Writing a native compiler in C that emits x86-64 assembly
- Garbage collection, exceptions, records and modules in a small native compiler
- umlol, a programming language whose source is a flowchart
- Parallel reductions and associativity (std::transform_reduce as the case study)
Linked from
- A calculator engine that gets 0.1 + 0.2 and sin(30) right
- Garbage collection, exceptions, records and modules in a small native compiler
- Generating narrated screencast tutorials from a script (PIL + Piper TTS + ffmpeg)
- umlol, a programming language whose source is a flowchart
- Writing a native compiler in C that emits x86-64 assembly