Oussama Essamadi

Publications

Writing an interpreter in our group's slang

How Langkama works, from a lexer that handles multi-word keywords to a recursive-descent parser and a tree-walking evaluator, and what building it taught me about language design.

Publié

Temps de lecture

16 minutes

Article

Every group of friends ends up with its own vocabulary, and ours in the Nakama Realm got big enough that a newcomer needs a while to follow a conversation, so at some point the obvious question came up, if we already talk in our own language, why not code in it too?

That’s how Langkama was born, a small dynamically typed language with a tree-walking interpreter written in TypeScript (around 1,700 lines for the lexer, parser and evaluator), and yes, it’s on npm as @nakamaorg/langkama. The keywords are jokes, the interpreter isn’t, so after the first example this is mostly about how it works under the hood, and about the stuff I’d do differently if I started over.

What it looks like

Here’s a factorial:

let me cook factorial(n) {
  hear me out val is 0.

  big if true (n = 0) {
    val is 1.
  } sike {
    val is n * factorial(n - 1).
  }

  reda val.
}

loncina(factorial(5)). bs Outputs: 120

and here’s pretty much the whole language in one table:

Langkama Meaning
hear me out x is 1. declare a variable
a sa7 hear me out x is 1. declare a constant
x is 2. assign
let me cook f(a, b) { } declare a function
reda x. return
big if true (c) { } if
jk (c) { } else if
sike { } else
cook until (c) { } loop until c becomes true
bs ... line comment
W, L, bruh true, false, null
loncina(...) print
bait(x) convert to a string
length, push, pop array built-ins

A couple of things worth noticing past the words, statements end with a dot instead of a semicolon (like an actual sentence), and = is comparison, not assignment, assignment is the keyword is, so x = 1 is a boolean, and you can’t mix the two up even if you tried.

How it runs

Langkama is your classic three-stage interpreter:

source code  ->  Lexer      ->  tokens
tokens       ->  Parser     ->  abstract syntax tree (AST)
AST          ->  Evaluator  ->  a runtime value

No bytecode, no compilation step, the evaluator just walks the tree node by node. It’s the simplest design that works, and the easiest to debug too, at every stage you can just print what you have and read it.

The API exposes those stages as events, so whatever is hosting it can follow along:

const interpreter = new LangKama();

interpreter
  .on(LangKamaEvent.Lexer, () => console.info('Tokenizing...'))
  .on(LangKamaEvent.Parser, tokens => console.info(`Parsing ${tokens.length} tokens...`))
  .on(LangKamaEvent.Interpreter, () => console.info('Interpreting...'))
  .on(LangKamaEvent.Stdout, text => console.log(text))
  .on(LangKamaEvent.Error, error => console.error(error.toString()))
  .on(LangKamaEvent.Success, result => console.log(result.value))
  .interpret('(1 + 2) * 3');

Notice the Stdout event there, the interpreter never writes to the console itself, loncina just calls a callback and the host decides where the text goes, and that’s exactly why I could run the same package in a terminal and in a browser later on without changing a thing.

The lexer

One cursor for both

The lexer walks over characters, the parser walks over tokens, but they both need the same three things, look at the current item, consume it, and consume it only if it’s what you expected, so both of them extend one small generic class:

export class Consumer<T> {
  protected content!: Array<T>;
  protected index!: number;

  protected at(): T {
    return this.content[this.index];
  }

  protected eat(): TNullable<T> {
    return this.content[this.index++] ?? null;
  }

  protected expect<U = any>(target: U, error: LangKamaError): T {
    const current = this.eat();

    if (!this.compareFn<U>(target, current as T)) {
      this.errorManager.raise(error);
    }

    return current as T;
  }
}

Consumer<string> is the lexer, Consumer<TToken> is the parser, and each one passes its own compare function, the parser for example compares an expected TokenType with a token’s type. The class also keeps track of the line and column, so every token gets a location, which comes in handy later for the error messages.

Tokens

A token is a type, a value and a location:

type TToken = {
  type: TokenType;
  value: TNullable<string>;
  location: { row: number; col: number };
};

Most of the lexer is one big switch on the current character, punctuation gets its own token, + - * / % = < > & | become BinaryOp tokens, ! becomes a LoneOp, a " starts a string that has to close on the same line, digits start a number, letters start an identifier, whitespace gets skipped (except newlines, those bump the line counter), and anything else is an UnrecognizedTokenError, and the lexer just keeps going.

Funny side effect of ending statements with a dot, number literals can only be integers, the lexer reads digits and stops, because a dot always means the end of a statement. You still get decimals at runtime from division, you just can’t type one.

Keywords with spaces in them

Now this was the most interesting problem of the whole thing. Most languages have single-word keywords, the lexer reads a word, looks it up in a table, done. Langkama’s keywords are full phrases though, big if true, cook until, a sa7 hear me out, here’s the table:

export const keywords: Record<string, TokenType> = {
  'is': TokenType.Equals,
  'jk': TokenType.ElseIf,
  'sike': TokenType.Else,
  'bs': TokenType.Comment,
  'reda': TokenType.Return,
  'big if true': TokenType.If,
  'hear me out': TokenType.Let,
  'cook until': TokenType.While,
  'let me cook': TokenType.Function,
  'a sa7 hear me out': TokenType.Const
};

So the lexer reads a word first, then keeps extending it across spaces for as long as some keyword still starts with what it has so far, if the phrase completes, it’s a keyword, and if at any point nothing matches anymore, it rewinds back to where the word ended and treats it as a plain identifier:

const baseIndex = this.index;
const baseIdentifier = identifier;

while (this.at() && (!CharHelper.isSkippable(this.at()) || this.at() === Char.Space)) {
  key = keys.find(e => e.startsWith(identifier));

  if (identifier === key) {
    break;          // the whole phrase matched
  }

  if (!key) {
    this.index = baseIndex;   // nothing fits, rewind
    identifier = baseIdentifier;
    break;
  }

  identifier += this.eat();
}

That’s why something like a sa7 hear me out a is 10. works fine, even though a is both a variable and the start of a keyword, after a, the lexer tries a then a i, finds no keyword starting with a i, rewinds, and spits out the identifier a. It’s a little backtracking lexer, more than most languages need, but that’s what lets the keywords read like actual sentences. Comments (bs) are handled in the same spot, once the lexer sees one, it swallows everything until the end of the line.

The parser

The tree

The parser takes the tokens and builds an AST out of them, every node has a kind plus a start and end location, and the node types map pretty much one to one onto the language:

interface IBinaryExpression extends IExpressionNode {
  kind: NodeType.BinaryExpression;
  operator: string;
  left: IExpressionNode;
  right: IExpressionNode;
}

interface IFunctionDeclarationNode extends IStatementNode {
  kind: NodeType.FunctionDeclaration;
  name: string;
  parameters: Array<string>;
  body: Array<IStatementNode>;
}

interface IConditionBlockNode extends IStatementNode {
  kind: NodeType.Condition;
  conditions: Array<{ condition?: IExpressionNode; body: Array<IStatementNode> }>;
}

An if with its jk and sike branches is one Condition node holding a list of condition/body pairs, the final sike being the one without a condition, so evaluating it is just “run the first body whose condition is true”.

Recursive descent

The parser is hand-written recursive descent, one method per grammar rule, each one calling the next tighter one. At the top, parseStatement looks at the current token and dispatches, reda goes to a return, big if true to a condition, cook until to a loop, hear me out to a declaration, let me cook to a function, and anything else to an expression, and expressions go down this ladder:

parseExpression
  -> parseAssignmentExpression      x is ...
  -> parseAdditiveExpression        + -  and  = < > & |
  -> parseMultiplicativeExpression  * / %
  -> parseCallPrimaryExpression     f(...)  and  arr[...]
  -> parsePrimaryExpression         literals, names, ( ), [ ], !

Each level parses the one below it, then keeps looping as long as it sees one of its own operators, folding everything to the left, and that loop is what makes 1 - 2 - 3 mean (1 - 2) - 3:

private parseMultiplicativeExpression(): IExpressionNode {
  let left = this.parseCallPrimaryExpression();

  while ([Char.Star, Char.Slash, Char.Percentage].includes(this.at().value as Char)) {
    const operator = this.eat().value;
    const right = this.parseCallPrimaryExpression();

    left = { kind: NodeType.BinaryExpression, operator, left, right, /* locations */ };
  }

  return left;
}

Assignment is the odd one out, it calls itself for its right-hand side instead of looping, which makes it right-associative, so a is b is 5 assigns 5 to b, then to a.

Small trick in the function parser, parameters get parsed with the exact same code as call arguments, then checked to be plain identifiers, so let me cook f(a, b) and f(a, b) share their parsing, and something like f(1) in a declaration gets you an ExpectedIdentifierError.

My precedence mistake

If you looked at that ladder closely you probably caught it already, comparisons and logic operators sit on the same level as + and -. It worked for every example I wrote, because they all compared one side against something simple, but it means that this:

big if true (x = y + 1) { }

parses as (x = y) + 1, a boolean plus a number, which the evaluator rejects with a type error. The fix is the standard ladder, a level each for |, &, equality, comparison, then + -, then * / %, then unary !, and it’s the first thing I’d fix if I went back to it, lesson learned the hard way.

It doesn’t stop at the first error

When the parser expects something and doesn’t find it (a closing brace, a dot, a function name), it doesn’t throw, expect reports the error and moves on, and anything it can’t make sense of becomes a Skip node that the evaluator just ignores, so one run can report every problem in a script instead of stopping at the first one.

The evaluator

Walking the tree

The evaluator is one big switch on node.kind, with a method per node type, each one takes the node and the current scope and returns a runtime value:

public evaluate(node: IStatementNode, env: Environment): IRuntimeVal {
  switch (node.kind) {
    case NodeType.Number:              return RuntimeHelper.createNumber(node.value);
    case NodeType.BinaryExpression:    return this.evaluateBinaryExpression(node, env);
    case NodeType.Call:                return this.evaluateFunction(node, env);
    case NodeType.Condition:           return this.evaluateConditionBlock(node, env);
    // ... one case per node type
  }
}

Runtime values are just tagged objects, { type: Type.Number, value: 3 }, { type: Type.String, value: "hi" }, plus booleans, null, arrays, user functions and native functions. Statements that don’t produce anything return a Skip value, and a program’s result is simply the last value that isn’t a skip, that’s how something like (1 + 2) * 3 or reda length(arr) hands a result back.

Strict types

Binary operators refuse to mix types, adding or comparing a number and a string raises UnmatchingTypesError instead of guessing (looking at you, JavaScript), and + on strings concatenates, but any other operator on a string is an InvalidOperationError, that’s why numbers go through bait before getting glued to a string:

loncina("result: " + bait(z)).

This one I’d keep, implicit conversions are where scripting languages hide their worst surprises, and avoiding them costs you one function call.

Scopes

Scopes are a chain of Environment objects, each one with a map of variables and a pointer to its parent, and looking a name up just walks up the chain until it finds it:

public resolve(name: string): Environment {
  if (this.variables.has(name)) {
    return this;
  }

  if (!this.parent) {
    this.errorManager?.raise(new VariableNotDefinedError(name));
    return this;
  }

  return this.parent.resolve(name);
}

Every variable remembers whether it’s a constant, so reassigning an a sa7 hear me out raises ConstantReassignmentError, and declaring the same name twice in one scope raises VariableDefinedError. The global scope is where the language’s own vocabulary lives, bruh, W and L are constants, and loncina, bait, length, push and pop are native functions written in TypeScript, declared just like any other variable.

Functions and closures

Declaring a function stores its parameters, its body and the environment it was declared in, as a constant under its name. Calling it creates a fresh scope whose parent is that stored environment (not the caller’s), binds the arguments, and runs the body:

const scope = new Environment(func.env);

for (let i = 0; i < func.parameters.length; ++i) {
  scope.declareVariable(func.parameters[i], args[i]);
}

That’s lexical scoping and closures in a handful of lines, and it’s also why recursion just works, by the time factorial calls itself, its name is already declared in the scope it closed over.

Loops, and the reda problem

cook until runs its body until the condition becomes true, so it’s basically the opposite of a while, and it reads exactly like the phrase:

while (!(this.evaluate(loop.condition, env) as IBooleanVal).value) {
  loop.body.forEach(statement => this.evaluate(statement, env));
}

Now the weak spot, reda. A function call runs the statements of its body in order and stops when one of them is a return, but a reda inside a big if true block isn’t a statement of the function, it’s a statement of the block, and the block has no way of telling the function to stop. That’s why the factorial at the top assigns to val in both branches and only returns at the very end (you thought that was a style choice, didn’t you).

The usual fixes are either throwing a special return signal from the return statement and catching it in the function call, or having every evaluation return a completion record (normal, return, break) that blocks pass up, and either one would’ve given me break for free too.

Arrays by value

Arrays are stored as plain values, assigning to an index builds a new array and reassigns the variable, and since a function argument is a copy, push and pop can’t receive the array itself, so they take its name as a string and look it up:

hear me out arr[].
push("arr", 4).

It works, but it’s one of those decisions that are cheap on day one and expensive to change later, so next time, value or reference semantics gets decided before I write a single line of the evaluator.

Errors

A language is only as nice as its error messages, so a good chunk of the code is errors, 34 error classes, each with its own number, built on a base LangKamaError. Nothing in the lexer, parser or evaluator throws them, they go to an ErrorManager that collects them and calls the host’s error callback, which is how one run can report several problems at once.

An error that knows where it happened prints the line and points at the spot, take a declaration that forgot its dot:

hear me out x is 5

which gives you:

  [MissingDotError] - statements should end with a dot.
  1:19 - hear me out x is 5
         ~~~~~~~~~~~~~~~~~~^

The error numbers aren’t just there for the tests either, the CLI exits with the error’s number as its exit code, so whatever runs a script can tell what went wrong from the exit code alone. Not every error knows its location yet though, the runtime ones about variables, like VariableNotDefinedError, only name the variable, that one’s on the list.

Tests and tooling

Tests

Every feature has its own Jest suite (variables, constants, strings, booleans, null, math, arrays, conditions, loops, functions and comments), and each one runs scripts through the built package and checks either the result or the error number:

test('Loop statement', done => {
  const code = `
    hear me out index is 0.
    hear me out sum is 0.

    cook until (index = 10) {
      sum is sum + index.
      index is index + 1.
    }

    reda sum.
  `;

  compiler
    .on(LangKamaEvent.Success, result => {
      expect(result.value).toBe(45);
      done();
    })
    .interpret(code);
});

Testing through the public API instead of the internals means the tests stay valid no matter how much the lexer, parser or evaluator change underneath.

CLI and REPL

The CLI runs a .nkm file, printing each stage with a timer, or opens a REPL if you don’t give it a file. The REPL keeps one Environment across inputs, so a variable you declare on one line is still there on the next, and honestly that’s the whole trick to a REPL, same evaluator, scope that sticks around.

The browser

Vite builds the TypeScript into ES module and UMD bundles, and since the interpreter never touches any Node API (remember the Stdout callback?), the online editor (opens in a new tab) is just a Vue app importing the same package. The editor itself is Monaco, with Langkama registered as a language and a small Monarch tokenizer for the highlighting:

monaco.languages.register({ id: 'nkm', extensions: ['.nkm'], aliases: ['LangKama'] });

monaco.languages.setMonarchTokensProvider('nkm', {
  tokenizer: {
    root: [
      [/bs.*/, 'comment'],
      [/".*?"/, 'string'],
      [/\b\d+(\.\d+)?\b/, 'number'],
      [/\b(W|L)\b/, 'constant.language.boolean'],
      [/\b(is|sike|bruh|jk|big if true|let me cook|reda|cook until|hear me out|a sa7 hear me out)\b/, 'keyword'],
    ]
  }
});

There’s a VS Code extension (opens in a new tab) too that highlights the keywords the same way. Asking friends to install a command-line tool is a hard sell, a link they can open on their phone though, not so much.

If I did it again

  • A proper precedence ladder, so x = y + 1 means what it says.
  • Proper control flow, a return signal or completion records, so reda works anywhere, with break for free.
  • Block scopes, big if true and cook until bodies run in the enclosing scope right now, so a variable declared in a loop leaks out of it.
  • Reference semantics for arrays, so push can take the array itself.
  • Locations on every error, not just the parse ones.
  • Decimal literals, which means giving the statement-ending dot a rule that doesn’t clash with 1.5.

None of these needed a smarter idea, just the boring parts of language design (grammar, scoping, control flow, value semantics) settled earlier than I settled them, and building something small enough to actually finish is the cheapest way I know to find out where those bite.

If you’re part of the Realm, you already know what half of these keywords mean, and if you’re not, the online editor (opens in a new tab) is the fastest way in, and the source (opens in a new tab) is small enough to read in an evening.

Suivant

ouLes 21 publicationsouAu hasardouAccueil

ProjetsPublications

Chargement de la liste…

Chargement de la liste…

Raccourcis clavier

Recherche et commandes
Ctrl K⌘K
Passer du clair au sombre
T
Tous les projets
P
Toutes les publications
W
Chercher dans la liste ouverte
S
Accueil
H
M’écrire
C
Afficher ces raccourcis
?
Fermer ce qui est ouvert
esc

Les raccourcis sont activés.