# umlol language specification — v0.2 (draft)

umlol programs are flowcharts drawn in plain text. The source is parsed into a
graph of shapes joined by arrows; the graph is what runs. Two drawings with the
same shapes, text, and connections are the same program, however they are laid
out.

This document is the source of truth. `tests/programs/` is the executable
form of it: an implementation conforms when `tests/run-tests.js` passes against
it (`UMLOL_CMD="<your umlol>" node tests/run-tests.js`).

## 1. Source and the grid

- Source is UTF-8. Line endings `\n`, `\r\n`, or `\r`.
- Tab characters are an error anywhere in the file.
- The source is read as a grid of **display cells**. A character's width is
  its width in a monospace terminal: East Asian Wide/Fullwidth characters and
  most emoji take 2 cells; combining marks, variation selectors, and other
  format characters take 0 cells and join the preceding character.
- Positions are reported as `row:col`, 1-based, where `col` counts cells.
- Cells past the end of a line are spaces.

## 2. Shapes

Every shape encloses text. A shape with no text is an error, and shapes may
not overlap.

### 2.1 Boxes

A box is a closed rectangle at least 3 × 3 cells.

| Kind | Unicode corners | ASCII corners |
|---|---|---|
| process | `┌ ┐ └ ┘` | `+ + + +` |
| terminal | `╭ ╮ ╰ ╯` | `. . ' '` |

Top and bottom borders are made of `─ ━ ═ -`; sides of `│ ┃ ║ |`. Borders may
also contain ports (§2.3).

```
┌───────────┐   +-----------+   ╭───────╮   .-------.
│ read n    │   | read n    |   │ start │   | start |
└─────┬─────┘   +-----+-----+   ╰───┬───╯   '---+---'
```

A terminal's text is one of (keywords case-insensitive):

| Text | Kind | |
|---|---|---|
| `start` or `begin` | start | where the program begins |
| `end` `stop` `halt` `exit` `done` | end | the main diagram halts; a subroutine returns no value |
| `return` or `return EXPR` | return | a subroutine returns, with EXPR's value if given (one line) |
| `NAME(PARAM, …)` | sub | the entry of subroutine NAME (§5.1; one line) |

### 2.2 Decisions

A decision is a hexagon exactly three rows tall:

```
 ╱─────────╲          /---------\
▶   n > 1   ├        <   n > 1   +
 ╲────┬────╱          \----+----/
```

- Top row: `╱` or `/`, a border run, then `╲` or `\`.
- Bottom row, in the same columns: `╲` or `\`, a border run, then `╱` or `/`.
- Middle row: the condition. The cell just left of the top-left glyph and the
  cell just right of the top-right glyph are the **vertices**. A left vertex
  is a space, `<`, a port `┤`/`+`, or the head of an arrow pointing in
  (`▶ ► ▷ → >`). A right vertex is a space, `>`, a port `├`/`+`, or an arrow
  pointing in (`◀ ◄ ◁ ← <`).

### 2.3 Ports

Edges leave a shape only through ports drawn on its border:

| Border | Unicode | ASCII | Edge leaves heading |
|---|---|---|---|
| top | `┴` | `+` | up |
| bottom | `┬` | `+` | down |
| left side / left vertex | `┤` | `+` | left |
| right side / right vertex | `├` | `+` | right |

Corners are never ports. A port whose next cell outward is an arrowhead
pointing at the shape is decoration for an incoming edge, not an exit.

## 3. Edges

An edge starts at a port and follows line characters to an arrowhead. The
shape the arrowhead points at (the cell one step past the head, in the head's
direction) is the edge's target. It may land on a border or a decision vertex.

### 3.1 Line characters

| Glyphs | Connects |
|---|---|
| `─ ━ ═ -` | left, right |
| `│ ┃ ║ \|` | up, down |
| `┌ ╭` `┐ ╮` `└ ╰` `┘ ╯` | corners |
| `├ ┤ ┬ ┴` | junctions (three ways) |
| `┼` | crossing: two edges pass straight through each other |
| `+` | ASCII: a crossing if the line continues straight, otherwise a corner or junction |

### 3.2 Arrowheads

| Points | Unicode | ASCII |
|---|---|---|
| right | `▶ ► ▷ →` | `>` |
| left | `◀ ◄ ◁ ←` | `<` |
| down | `▼ ▽ ↓` | `v` |
| up | `▲ △ ↑` | `^` |

A Unicode arrowhead may point straight ahead or turn the edge 90°. An ASCII
arrowhead counts only when it points the way the edge is already moving, so
`v` and `<` stay ordinary characters elsewhere. An arrowhead pointing back
along the edge is an error.

### 3.3 Merges

At a junction the edge may continue down more than one branch. Exactly one
branch must reach an arrowhead; the others lead back to other shapes' ports
(edges from several shapes joining one line). If more than one branch reaches
an arrowhead, it is an error: an edge cannot split.

```
      ├──────────────┐      the loop from below joins the line
      ▼              │      into the decision
```

### 3.4 Errors

These are all errors: an edge that ends without an arrowhead; an arrowhead
that points at no shape; an edge that runs into a shape without an arrowhead;
an edge that loops back on itself; a box-drawing character (U+2500–U+257F)
that belongs to no shape or edge.

## 4. Labels and comments

- **Inline label:** text written into a horizontal edge, `──no──▶` or
  `── no ──▶`. Single spaces may appear inside; two spaces in a row break the
  edge.
- **Side label:** loose text that starts or ends one or two cells from a cell
  of an edge on the same row, or sits directly above or below one. It belongs
  to the nearest such edge; a tie between two edges is an error.
- An edge has at most one label.
- **Comments:** any other text outside shapes. It has no effect.

## 5. Program structure

- Exactly one start terminal, with exactly one exit. Each subroutine entry
  also has exactly one exit.
- No arrow may point into a start terminal or a subroutine entry.
- End terminals have no exits. A program may have any number of them.
- A process box has exactly one exit.
- A decision has exactly two exits, labeled yes and no (case-insensitive):
  yes is `yes y true t ✓ ✔`, no is `no n false f ✗ ✘`.
- Labels on edges that leave anything but a decision are documentation only.

### 5.1 Diagrams and subroutines

A file holds one or more **diagrams**. The main diagram is everything reachable
from the start terminal; each subroutine is everything reachable from its
entry terminal, `NAME(PARAM, …)`. The diagrams may sit anywhere in the file.

- No shape may be reachable from two entries: diagrams do not share shapes.
- A `return` terminal must not be reachable from start.
- Subroutine names are unique, may not be a built-in's name (§6.5), and live
  apart from variables: `len` can be a variable and `f(…)` still a call. A
  subroutine's parameters are distinct names.
- Every call names a subroutine or built-in and passes exactly as many values
  as it takes. Both are compile errors, checked anywhere in the file.
- Shapes reachable from no entry are checked like the rest and never run.

```
 ╭────────╮
 │ fib(n) │
 ╰───┬────╯
     ▼
╱─────────╲         ╭──────────╮
   n < 2   ├──yes──▶│ return n │
╲────┬────╱         ╰──────────╯
     │ no
     ▼
╭────────────────────────────────╮
│ return fib(n − 1) + fib(n − 2) │
╰────────────────────────────────╯
```

## 6. Text inside shapes

### 6.1 Values

Integers of unlimited size, strings, the booleans `true` and `false`, and
lists.

- A **list** holds any values, including other lists. Lists are shared, not
  copied: after `ys ← xs`, changing `ys[0]` or pushing onto `ys` changes `xs`
  too, and a subroutine given a list can change the caller's list.
- Strings cannot be changed in place. Their length and indexes count Unicode
  code points.
- `print` shows a list as `[1, "a", [true]]`: items separated by `, `, strings
  inside a list quoted with JSON escapes. A list that contains itself shows
  the inner occurrence as `[…]`.

### 6.2 Statements (process boxes)

Each line of a process box is one or more statements separated by `;`, run
top to bottom.

| Statement | Meaning |
|---|---|
| `x ← e` (also `x <- e`, `x := e`) | assign |
| `xs[i] ← e`, `m[i][j] ← e` | set a list element; `e` is evaluated first, then the list, then the index |
| `f(e, …)` | call a subroutine or built-in for its effect; any value is dropped |
| `print e, …` | print the values separated by single spaces, then a newline |
| `write e, …` | the same without the newline |
| `read x, …` | read the next whitespace-separated input token; an optional sign plus digits is read as an integer, anything else as a string. Reading past the end of input is a runtime error |

`x = e` as a statement is an error (`=` compares).

### 6.3 Expressions

From loosest to tightest binding:

| Level | Operators |
|---|---|
| or | `or` `∨` |
| and | `and` `∧` |
| not | `not` `¬` (prefix) |
| comparison (not chainable) | `=` `==` `≠` `!=` `<` `≤` `<=` `>` `≥` `>=` |
| sum | `+` `-` `−` |
| product | `*` `×` `·` `/` `÷` `%` `mod` |
| negation | `-` `−` (prefix) |
| power (right-associative) | `^` `**` |
| postfix | `x[i]` index |

Primaries are numbers, strings, `true`, `false`, variables, `( … )`, list
literals `[e, …]` (a new list each time), and calls `f(e, …)`. Arguments and
list items are evaluated left to right.

- `+` concatenates when either side is a string, and joins two lists into a
  new list.
- `x[i]` is element `i` of a list or the `i`th code point of a string, as a
  one-character string. Indexes start at 0; one outside `0 … len(x) − 1` is a
  runtime error.
- `/` and `%` truncate toward zero; dividing by zero is a runtime error.
  Negative exponents are a runtime error.
- `=` and `≠` compare any two values (different types are unequal; lists are
  equal when they have equal items in order). Ordering compares two integers
  or two strings.
- `and`, `or`, and `not` take booleans; `and` and `or` short-circuit.
- Strings are written `"…"` (escapes `\n`, `\t`, `\"`, `\\`) or `“…”`.
- Identifiers are a letter or `_` followed by letters, digits, or `_`, in any
  script. Keywords (`and or not mod true false print write read return`)
  cannot be names. Using a variable before it is assigned is a runtime error.
- The tokens `<-` and `<` `-` differ: write `x < -1` with a space.

### 6.4 Conditions (decisions)

A decision's text is one expression, optionally ending in `?`. It must
evaluate to a boolean.

### 6.5 Built-in functions

| Call | Gives |
|---|---|
| `len(x)` | length of a list or string |
| `push(xs, v)` | appends `v` to `xs`; no value |
| `pop(xs)` | removes and gives the last item; an empty list is a runtime error |
| `slice(x, i, j)` | items `i` up to (not including) `j` of a list (a new list) or string; needs `0 ≤ i ≤ j ≤ len(x)` |
| `list(n, v)` | a new list of `n` items, each `v` |
| `num(s)` | a string of optional spaces, sign, digits, spaces as an integer (an integer is given back as is) |
| `str(v)` | `v` as `print` would show it |
| `chr(n)` / `ord(c)` | code point to one-character string, and back |

Using the missing value of `push`, or of a subroutine that ended without one,
in an expression is a runtime error.

## 7. Execution

Execution begins at the start terminal and follows its exit. A process box
runs its statements and follows its exit. A decision follows its yes or no
exit. Reaching an end terminal of the main diagram halts the program with
exit status 0.

A subroutine call evaluates its arguments, then runs the subroutine from its
entry with fresh variables holding only its parameters; there are no global
variables. A `return` terminal ends the call with its value; an end terminal
ends it with no value. Recursion is allowed. Implementations must support
calls nested at least 10,000 deep; deeper may be a runtime error, never a
crash.

## 8. Implementation interface

The conformance tests drive an implementation only through its command line.

- `umlol FILE` runs the program; stdin is the program's input, stdout its
  output; exit status 0 on halt.
- On a compile error, exit non-zero; the first line of stderr is
  `error at ROW:COL: MESSAGE`. On a runtime error it is
  `runtime error at ROW:COL: MESSAGE`. Message wording is checked by the
  tests in v0.1; later versions may check only the position.
- `umlol --graph FILE` prints the graph as JSON:
  `{"nodes":[{"id","kind","text","at":[row,col]}], "edges":[{"from","to","label"?}]}`.
  `kind` is `start`, `end`, `process`, `decision`, `sub`, or `return`. Nodes are numbered `n1`,
  `n2`, … in reading order (top to bottom, then left to right) of each
  shape's top-left glyph (for a decision, its top-left `╱`), which is also
  `at`. `text` is the shape's trimmed text lines joined with `\n`. Edges are
  listed by source node, then in reading order of their ports.

## 9. Reserved for later versions

Double and heavy box lines (`╔ ┏`), parallelogram I/O shapes, UML class
boxes, sequence diagrams, state machines, data-flow diagrams, maps or
records, and diagrams split across files.
