# Teaspoon v0 Language Specification

Status: v0 implementation contract, verified against the fixture corpus on
2026-06-03.

Teaspoon is a small text programming language for non-professional users. The
v0 language is intentionally narrow: one file, explicit `start()`, a small value
model, friendly structured errors, and a deterministic sandboxed runtime.

## 1. Scope

### 1.1 In Scope

- Source files are plain text files with the `.tsp` extension.
- A runtime program is one complete source file; separately maintained fragments
  may be concatenated before checking, deployment, or migration.
- Top-level definitions are order-independent.
- The entry point is exactly one `start() { ... }` function.
- Core value kinds are `number`, `text`, `list of number`, `list of text`, and
  `empty list`.
- Variables are created with `let` and are mutable.
- Lists and text values are immutable.
- The runtime is dynamically checked, with as many structural checks as
  practical before execution.
- The only required CLI command is `teaspoon run file.tsp`.

### 1.2 Out of Scope for v0

Teaspoon v0 does not support:

- imports, module loading, packages, or runtime loading of multiple source files
- constants
- boolean values
- objects, maps, structs, records, or user-defined kinds
- nested lists
- exceptions, `try`, or `catch` (explicit API error outcomes are described in
  [Server Design](server_design.md#8-return-model))
- early return from ordinary functions (API bodies permit it)
- `while` or fixed-count `repeat`
- formatter, REPL, playground, package manager, or language server
- random numbers
- time, timers, `wait`, async, or concurrency
- file system, network, system commands, environment variables, or clipboard
- command-line arguments for user programs
- syntax version declarations

## 2. Source Files

### Namespaces and Source Bundles

`namespace name { ... }` groups ordinary functions under qualified names such as
`markdown.render(source)`. Namespace names are simple identifiers. The same
namespace may be reopened in another block; duplicate complete function names
are errors, not overrides. Inside a namespace, an unqualified call resolves to a
function of that namespace first, then to an existing root function or builtin.
Cross-namespace calls use explicit qualified names. Definitions remain
order-independent, including across reopened blocks.

Namespaces contain ordinary functions and API declarations: no nested namespaces,
globals, or `start()`. The complete program still has one root `start()`.
An API named `auth.session` is exposed at `/api/auth/session` (schema at
`/apis/auth/session/schema`); dot-path aliases are not accepted over HTTP.
Ordinary helpers remain private to the program. Namespacing does not permit
local calls to APIs. External calls can use `await service.auth.session()`.
Namespaces are static name grouping, not objects or separately initialized
modules. Their names cannot collide with root declarations or builtins, including
case-only collisions. There is no import, export, private visibility, or file
search mechanism.

An application can concatenate newline-terminated `.tsp` fragments into one
bundle. Each fragment must contain complete declarations; strings and functions
must not span fragments. Keep a fixed explicit file order and deploy the complete
bundle, not references to mutable library files. Diagnostics refer to bundle
locations. Existing fingerprint, historical replay, and migration checks apply
to that complete program; adding namespaces does not bypass compatibility checks
or make identity independent of source locations.

### Transient HTTP Pages

Server programs may declare exact-path, read-only GET or POST handlers:

```text
transient GET "/book"(title: text, revision: number) {
  return http_response(200, "text/plain; charset=utf-8", title + " / " + as_text(revision))
}
```

The parameter list is optional when empty. GET query parameters follow the existing readonly API decoding rules. POST
requires an application/json object and rejects URL query parameters. Both
methods use the same typed parameter declarations and readonly state semantics. Every handler path must return a value;
early returns are permitted. `http_response(status, content_type, body)` creates
an HTTP-only value, not an API `ok/error` outcome. Status must be an integer from
200 through 599, content type a valid media type, and body text. Statuses 204,
205, and 304 require an empty body. The response value cannot be an API payload
or list element. HTTP-only helpers cannot be reached from `start()` or business
APIs. No transient globals or external transient calls are implemented.

Routes have canonical absolute paths, without query strings, fragments, encoded
paths, or wildcards. `/` may replace the default status page. Runtime routes
`/view`, `/health`, `/api`, `/apis`, `/state`, and `/revisions`, including their
subpaths, are reserved. Pages are not added to `/apis` or revision-prefixed routes.
Other methods return 405 with the declared methods in `Allow`; invalid
arguments return 400. GET and POST may share a path. Handlers may also return
`ok(value)` (HTTP 200 JSON) or `error(value)` (HTTP 422 JSON), using ordinary
typed outcome payloads. POST bodies are limited to 2 MiB.

Each request copies committed globals under the business mutex and renders with
a separate runtime after releasing that mutex. The entire reachable helper
graph is checked: pages may read that snapshot but cannot write globals, call
business APIs or `start()`, execute `await`, perform console I/O, or set
session cookies. `request_time()`, `current_user()` and `current_session()` read
the fixed request context; `request_id()` is empty because transient requests
have no durable UUID. Runtime readonly guards provide an additional boundary. Shared
pure helpers need no annotation. Transient GET and POST requests do not allocate request UUIDs,
write journal entries, record activity, or participate in replay. An
`Idempotency-Key` header has no effect. Closed, paused, or draining servers return
503 rather than render a new snapshot.

Rendering failure or cancellation during execution returns a generic 500;
cancellation while waiting for a snapshot returns 503, without exposing stack,
globals, or raw diagnostics and without pausing the business server. Query strings
are limited to 8192 bytes; larger queries receive 414. Execution has a budget of
one million statement/expression steps, checks caller cancellation, and retains
the ordinary recursion limit. Concatenated text and response bodies are limited
to 2 MiB, concatenated lists to 50000 items, and arithmetic operands to 4096-bit
numerators/denominators. These are rendering limits, not changes to durable API
arithmetic or replay. Responses use `nosniff`, `no-store`, and `no-referrer`.

### 2.1 Encoding and Newlines

- Source files must be UTF-8.
- A UTF-8 BOM is allowed and ignored.
- Non-UTF-8 source is an error.
- LF and CRLF newlines are accepted.
- Internally, source is normalized to LF.
- Line numbers and columns shown to users start at 1.
- User-facing columns count grapheme clusters, not bytes.

### 2.2 Shebang

If the first line begins with `#!`, it is treated as a comment.

```text
#!/usr/bin/env teaspoon

start() {
  say("hello")
}
```

`#!` has no special meaning outside the first line.

### 2.3 Whitespace

- Outside text literals, Unicode whitespace is accepted as whitespace.
- Newline whitespace separates lines.
- Non-newline whitespace is equivalent to a normal ASCII space.
- Inside text literals, whitespace is preserved as text content.
- The official formatting style uses two spaces for indentation.
- Indentation has no semantic meaning.

### 2.4 Comments

Comments start with `#` and continue to the end of the line.

```text
# This is a comment.
let score = 0 # This is also a comment.
let tag = "#hello" # The # inside text is not a comment.
```

Block comments are not supported.

Keywords, reserved words, and built-in names have no special meaning inside text
literals.

```text
let message = "if let return say count"
```

### 2.5 Line Structure

- Teaspoon uses one statement per line.
- Semicolons are not used.
- General expression continuation across lines is not supported.
- A statement must be complete on one line.
- Function calls, argument lists, list literals, index expressions, and slice
  expressions must be written on one line.
- Multiline text literals are the only exception.

Invalid:

```text
let x = 1 +
  2

say(
  "hello"
)

let xs = [
  1,
  2
]
```

### 2.6 Braces

Opening braces must be on the same line as the function or control statement
header. Closing braces must be alone on their own line.

Valid:

```text
start() {
  say("hello")
}
```

Invalid:

```text
start()
{
  say("hello")
}

if score is 0 { say("ok") }
```

Empty blocks are allowed.

```text
start() {
}
```

## 3. Names

### 3.1 Identifier Syntax

Names may contain only ASCII letters, ASCII digits, and underscores.
They may not begin with a digit.

Valid:

```text
score
player_name
add2
```

Invalid:

```text
2add
分数
```

Chinese punctuation and other non-ASCII punctuation are not syntax.
Implementations should produce clear errors and suggest the ASCII equivalent
when possible.

### 3.2 Case Rules

- Name use is case-sensitive.
- Name definition is ASCII case-insensitive for conflict detection.
- `score`, `Score`, and `SCORE` cannot be defined as separate names.
- This rule applies to all user-defined names and built-in names.

Example:

```text
let score = 1
say(score) # ok
say(Score) # error
```

```text
let score = 1
let Score = 2 # error
```

### 3.3 Shared Namespace and No Shadowing

Variables, parameters, user functions, and built-in functions share one
namespace for conflict detection.

- A local variable cannot reuse a top-level variable name.
- A parameter cannot reuse a top-level variable, function, or built-in name.
- A local variable cannot reuse a parameter, function, built-in, or any visible
  variable name.
- Inner blocks cannot shadow names from outer blocks.
- User code cannot redefine built-in functions.

Invalid:

```text
let score = 0

start() {
  let score = 1
}
```

Invalid:

```text
let score = 0

show(score) {
}
```

### 3.4 Keywords and Reserved Words

Keywords are lowercase:

```text
let
if
else
for
in
return
match
is
not
and
or
```

`isnot` is also reserved and cannot be used as a name. It is not valid syntax.
Users should write `is not` as two words.

`start` is not a keyword, but exactly one function named `start` is required.
Since function names are in the shared namespace, no variable or other function
may also be named `start`.

Built-in function names are lowercase and must be called with their exact
spelling. For example, `say("hi")` is valid and `Say("hi")` is an unknown name
error, ideally with a suggestion to use `say`.

Other names that contain keywords are allowed:

```text
iffy
inlet
notable
```

## 4. Program Structure

### 4.1 Top-Level Forms

At the top level, v0 supports only:

```text
let name = literal
function_name(parameter_list) {
  ...
}
```

Top-level executable statements are not supported.

Top-level definitions are order-independent.

```text
start() {
  say(add(1, 2))
}

add(a, b) {
  return a + b
}
```

### 4.2 Top-Level Variables

Top-level `let` variables are mutable globals.

```text
let score = 0

start() {
  score = score + 1
  say(score)
}
```

Top-level `let` initializers must be literals. More complex initialization
belongs in `start()`.

Allowed:

```text
let score = 0
let greeting = "hello"
let help = """
Type your name.
Then press enter.
"""
let names = ["Ada", "Grace"]
let empty = []
```

Invalid:

```text
let a = 1 + 2
let b = count(["Ada"])
let c = other
let d = make_name()
```

In top-level list literals, elements must also be literals. Nested lists are not
supported.

### 4.3 Entry Point

A program must define exactly one entry point:

```text
start() {
  ...
}
```

Rules:

- `start()` has no parameters.
- `start()` has no return value.
- `start()` may be empty.
- `start()` may appear anywhere in the file.
- `return` is not allowed inside `start()`.

## 5. Functions

### 5.1 Function Definitions

Function definitions do not write parameter kinds or return kinds.

```text
add(a, b) {
  return a + b
}

greet(name) {
  say("hello " + name)
}
```

Rules:

- Parameter names cannot repeat.
- Parameter names cannot differ only by case.
- Parameters are read-only.
- Function definitions are order-independent.
- Functions are not first-class values.
- Functions can only be called by name.
- A function call must always use parentheses, even when there are no arguments.

Invalid:

```text
let f = add
f(1, 2)
```

### 5.1.1 Deprecated APIs

Server API declarations may be prefixed with `deprecated`, independently of
readonly status:

```tsp
deprecated api add(amount: number) {
  total = total + amount
  return ok(total)
}

deprecated readonly api get_total() {
  return ok(total)
}
```

Here `total` is an existing top-level number. The modifier rejects new host
requests without changing the body semantics. Matching completed UUID retries
return their saved outcomes; admitted pending requests may finish, and retained
bodies remain executable during replay and compatibility checking. It cannot be
used on ordinary helpers or `start()`, and does not permit calls between APIs.
The supported order is `deprecated readonly api`, not `readonly deprecated api`.
See [Server Design](server_design.md#12-http-api) for HTTP admission details.

### 5.2 Function Calls

Function calls have fixed arity:

- No default parameters.
- No variadic parameters.
- No named arguments.
- The argument count must exactly match the function definition.

```text
add(1, 2)    # ok
add(1)       # error
add(1, 2, 3) # error
```

Arguments are evaluated from left to right.

### 5.3 Return Rules

Ordinary functions do not support early return. API bodies are an exception:
they explicitly return `ok(value)`, `ok()`, or `error(problem)` and may do so from
nested control-flow blocks. See [Server Design](server_design.md#8-return-model).
The following restrictions apply to ordinary functions, not APIs.

Rules:

- A function either has no return value or ends with `return expr`.
- A returned-value function must have `return expr` as the last top-level
  statement in the function body.
- A no-return function must not contain `return`.
- `return` is not allowed inside `if`, `else`, or `for` blocks.
- `return` must include an expression.
- `start()` must be a no-return function.

Valid:

```text
abs(x) {
  let result = 0

  if x >= 0 {
    result = x
  }
  else {
    result = -x
  }

  return result
}
```

Invalid:

```text
abs(x) {
  if x >= 0 {
    return x
  }
  else {
    return -x
  }
}
```

### 5.4 Return Value Use

Function call use is strict.

- A function with no return value can only be called as a statement.
- A function with a return value must be used as an expression.
- Discarding a returned value is an error.
- Using a no-return function as an expression is an error.

```text
say("hello")              # ok
let name = ask("Name: ")  # ok
ask("Name: ")             # error
let x = say("hello")      # error
```

User functions are classified structurally:

- A function whose last top-level statement is `return expr` has a return value.
- A function without `return` has no return value.

### 5.5 Recursion

Recursive and mutually recursive functions are allowed.

```text
fact(n) {
  let result = 1

  if n > 1 {
    result = n * fact(n - 1)
  }

  return result
}
```

The runtime may enforce a maximum call depth and should report a `LimitError`
when exceeded.

## 6. Blocks and Scope

### 6.1 Block Scope

- Function parameters are visible only inside the function.
- A `let` variable is visible only inside the block where it is defined and
  nested child blocks.
- Inner blocks can read outer variables.
- Inner blocks cannot define a name that conflicts with any visible name.
- Assignment updates an existing variable.
- Assigning to an unknown name is an error.
- Functions cannot read local variables from other functions.
- Top-level variables can be read and assigned inside functions.

Example:

```text
start() {
  let score = 0

  if score is 0 {
    let message = "start"
    score = 1
  }

  say(score)    # ok
  say(message)  # error
}
```

### 6.2 Assignments

Assignment targets must be variable names.

Valid:

```text
score = score + 1
```

Invalid:

```text
names[1] = "Alan"
message[1] = "H"
```

The following cannot be assigned:

- function parameters
- `for` loop variables
- function names
- built-in function names

## 7. Statements

### 7.1 Statement Forms

Inside function and block bodies, v0 supports:

```text
let name = expr
name = expr
function_call(args)
if condition {
}
else {
}
for name in expr {
}
return expr
```

Bare expression statements are not supported.

Invalid:

```text
1 + 2
name
names[1]
```

### 7.2 Variable Declarations

Variables are created with `let`.

```text
let score = 0
score = score + 1
```

`let` variables are mutable. Teaspoon v0 has no constants.

### 7.3 If and Else

`if` syntax:

```text
if condition {
  ...
}
```

`else` syntax:

```text
if score >= 10 {
  say("win")
}
else {
  say("keep going")
}
```

Rules:

- `else if` is not supported.
- `else` must be written on its own line.
- `} else {` is not supported.
- `else` must follow an `if` block.
- Empty lines and comments may appear between the `if` block and `else`.
- No other statement may appear between the `if` block and `else`.
- A standalone `else` is an error.

### 7.4 For Loops

The only loop form in v0 is:

```text
for item in source {
  ...
}
```

Rules:

- `source` may evaluate to a list or text.
- `for` over a list yields each element.
- `for` over text yields one grapheme cluster at a time as a text value.
- `for` over a number is an error.
- The loop variable is created automatically.
- The loop variable is scoped to the loop body.
- The loop variable is read-only.
- Index iteration is not supported.
- `while` is not supported.
- Fixed-count `repeat` is not supported.

The iteration source is evaluated once before the loop begins, producing a
snapshot. If the source expression is directly a variable name, that variable
cannot be assigned inside the loop body.

Invalid:

```text
for name in names {
  names = names + ["Linus"]
}
```

Valid:

```text
let more_names = names

for name in names {
  more_names = more_names + ["Linus"]
}
```

## 8. Values and Kinds

Teaspoon user-facing documentation and errors should prefer the word `kind`
over `type`.

Value kinds:

- `number`
- `text`
- `list of number`
- `list of text`
- `empty list`
- `outcome`, constructed by `ok(value)`, `ok()`, or `error(problem)`

Outcomes carry an ordinary value (or no payload for `ok()`). They are not
booleans, cannot nest, and cannot be list elements or comparison operands.
An outcome variable can change from success to error without changing its kind.
Inspect it with an exhaustive `match` statement:

```text
let result = error("Not enough stock")
match result {
  ok(value) {
    say(value)
  }
  error(problem) {
    say(problem)
  }
}
```

There is no `=>`. Each branch has a required brace-delimited block. Both
outcomes must appear exactly once; either order is allowed. Payload bindings
are read-only and scoped to their branch. An `ok()` branch ignores any success
payload, including payload-free success. An `ok(value)` branch requires a payload
at runtime. `match` produces no expression value and does not itself commit or
roll back state. It does not allow ordinary functions to return early.

Server APIs may also obtain an outcome from `await service.api(arguments)`.
The service alias is resolved from deployment configuration, not a local function
or object. Remote readonly calls use GET with text/decimal-number inputs;
transactional calls use POST with named JSON parameters supporting exact numbers
and flat lists. Both require a persistent server request journal. A readonly API,
including its helper calls, cannot invoke an external transactional API.
It cannot run in `start()` or global initialization. Transport uncertainty does
not produce an `error` outcome: execution is paused until recovery can determine
the original result. See [API server semantics](api_server_semantics.md#101-implemented-external-calls)
for configuration, HTTP encoding, retries and crash recovery.

There is no boolean kind. Conditions exist only in control-flow syntax.

### 8.1 Variable Kind Stability

Variables have a fixed kind after initialization.

```text
let x = 1
x = 2      # ok
x = "two"  # error
```

The rule is dynamic: it is enforced as the program runs.

Empty list variables have an unknown element kind until the first assignment to
a non-empty list.

```text
let xs = []
xs = [1]   # xs becomes list of number
xs = []    # ok
xs = ["a"] # error
```

Function parameters take their kind from each call. Different calls may pass
different kinds.

```text
same(x) {
  return x
}

half(x) {
  return x / 2
}

start() {
  say(same(1))
  say(same("hi"))
  say(half("hi")) # runtime error
}
```

Function return values are not declared. Assignment of returned values follows
normal variable kind stability.

## 9. Numbers

### 9.1 Number Model

`number` values are exact arbitrary-precision rational numbers.

- Integers and decimals are exact.
- Division is exact rational division.
- Floating point is not used.
- Implementations may represent numbers as arbitrary-precision numerator and
  denominator integers.
- Numbers should be normalized and reduced after operations.

Examples:

```text
0.5       # exact 1/2
1 / 3     # exact 1/3
0.1 + 0.2 # exact 0.3
```

The language does not define a fixed maximum number size. Runtimes may apply
resource limits.

### 9.2 Number Literals

Number literals support:

```text
0
12
345
3.14
0.5
-5
-3.14
```

The `-` is parsed as unary minus.

Not supported:

```text
1_000
.5
5.
0xff
1e6
```

Number literals use only ASCII digits `0` through `9` and ASCII `.`.
Unicode digit characters are not number literal syntax.

### 9.3 Arithmetic

Supported arithmetic operators:

```text
+ - * /
```

The actual operators are `+`, `-`, `*`, and `/`; `+` is also used for text and
list concatenation.

Arithmetic rules:

- `number + number -> number`
- `number - number -> number`
- `number * number -> number`
- `number / number -> number`
- Division by zero is a runtime error.
- Integer division is not supported.

Unary `-` is supported for numbers only.

Unary `+` is not supported.

Unary `not` is not supported. The word `not` is only used as part of `is not`
inside conditions.

### 9.4 Display

Default number display:

- finite decimals display as decimals
- non-terminating decimals display as reduced fractions
- negative fractions put the sign at the front

```text
say(1)         # 1
say(0.5)       # 0.5
say(1 / 2)     # 0.5
say(1 / 3)     # 1/3
say(2 / 6)     # 1/3
say(-1 / 3)    # -1/3
say(0.1 + 0.2) # 0.3
```

### 9.5 Irrational and Approximate Values

v0 does not include irrational-producing functions such as `sqrt`, `pi`, or
trigonometric functions.

Future approximate functions must require an explicit precision argument and
return an exact rational value at that requested precision. Teaspoon should not
introduce hidden floating-point approximation.

## 10. Text

### 10.1 Text Model

Text is Unicode text normalized to NFC.

- Text equality compares normalized content.
- Text indexing and counting are based on grapheme clusters, not bytes and not
  Unicode code points.
- Go `rune` is not sufficient for Teaspoon text indexing.
- Implementations should use Unicode grapheme segmentation, such as Unicode
  UAX #29.

Examples:

```text
let word = "é"
say(count(word)) # 1
say(word[1])     # é

let emoji = "👍🏽"
say(count(emoji)) # 1
say(emoji[1])     # 👍🏽
```

### 10.2 Single-Line Text Literals

Single-line text literals use double quotes.

```text
let name = "Ada"
let message = "Hello, Ada"
```

Supported escapes:

```text
\"  # double quote
\\  # backslash
```

`\n` is not a supported escape. Unknown escapes are parse errors.
Single-line text literals cannot contain actual newlines.
Single quotes are not text literal syntax.

### 10.3 Multiline Text Literals

Multiline text literals use triple quotes and are restricted.

Rules:

- A multiline text literal can only appear in `let name = """`.
- This is allowed at top level and inside blocks.
- The opening `"""` must be immediately followed by the line ending.
- The opening `"""` must be followed directly by a newline.
- No comment or other token may appear after the opening `"""`.
- The closing `"""` line must contain exactly `"""`.
- No whitespace, comment, or other token may appear before or after the closing
  `"""`.
- The content is everything between the opening line and closing line.
- The boundary newline immediately after the opening delimiter is not part of
  the content.
- The boundary newline immediately before the closing delimiter is not part of
  the content.
- Other whitespace, indentation, blank lines, and tabs inside the content are
  preserved exactly.
- `#` inside multiline text is text content, not a comment.
- A multiline text literal cannot directly contain `"""`.
- To include `"""`, build it with ordinary text and concatenation.

Valid:

```text
let help = """
Type your name.
Then press enter.
"""

start() {
  let message = """
line 1
line 2
"""

  say(message)
}
```

Invalid:

```text
say("""
hello
""")

let messages = ["""
hello
"""]
```

To include triple quotes:

```text
let quotes = "\"\"\""
let message = "before " + quotes + " after"
```

### 10.4 Text Operations

Text supports:

- concatenation with `+`
- `count(text)`
- single index
- inclusive slice
- iteration with `for`

```text
let name = "Ada"
say(name[1])     # A
say(name[1, 2])  # Ad
```

Text values can contain newline characters from multiline text. A newline
counts as one grapheme cluster for `count`, indexing, and slicing.

`say(text)` outputs the text content. If the text contains newlines, the output
contains those newlines, but it is still one `say` output event.

## 11. Lists

### 11.1 List Literals

List literals use square brackets.

```text
let numbers = [1, 2, 3]
let names = ["Ada", "Grace"]
let empty = []
```

Rules:

- Lists may contain numbers or text.
- Lists may not contain both numbers and text.
- Lists may not contain lists.
- Empty lists are allowed.
- In function and block expressions, list elements may be arbitrary
  expressions.
- At top level, list elements must be literals.

Valid inside a block:

```text
start() {
  let ys = [1 + 2, as_number("3")]
}
```

Invalid:

```text
let things = [1, "Ada"]
let grid = [[1, 2], [3, 4]]
```

### 11.2 List Immutability

Lists are immutable values. There is no element assignment and no in-place list
operation.

Invalid:

```text
names[1] = "Alan"
add(names, "Linus")
remove(names, 2)
```

Append by creating a new list:

```text
names = names + ["Ada"]
```

### 11.3 List Concatenation

`+` concatenates two lists.

```text
let a = [1, 2]
let b = [3, 4]
let c = a + b # [1, 2, 3, 4]
```

Rules:

- `list + list -> list`
- Non-empty lists must have the same element kind.
- `empty list` can concatenate with any list kind.
- `list + item` is an error.
- `item + list` is an error.

```text
[] + [1, 2]      # ok
[] + ["a", "b"]  # ok
[1] + ["a"]      # error
names + "Ada"    # error
names + ["Ada"]  # ok
```

### 11.4 List Display

`say(list)` is allowed. It displays lists using literal-style formatting:

```text
say([1, 2, 3])  # [1, 2, 3]
say(["a", "b"]) # ["a", "b"]
say([])         # []
```

Text elements are shown with double quotes and supported escaping.
`as_text(list)` is not supported, including `as_text([])`.

## 12. Indexing and Slicing

### 12.1 General Rules

Teaspoon indexes start at 1.

`1st`, `2nd`, and similar ordinal words are explanatory concepts, not syntax.

Valid:

```text
names[1]
names[2]
```

Invalid:

```text
names[1st]
names[2nd]
```

Indexing and slicing can be applied to any expression whose value is text or
list.

```text
say("Ada"[1])
say([1, 2, 3][2])
say(("A" + "da")[1, 2])
```

Chained indexing and slicing is allowed.

```text
say("hello"[1, 4][2])
say(["Ada", "Grace"][1][2])
```

### 12.2 Single Index

Syntax:

```text
value[index]
```

Rules:

- `index` must evaluate to an integer `number`.
- `1.0` is allowed because it is exactly integer 1.
- `1.5` is an error.
- The valid range is `1 <= index <= count(value)`.
- Out-of-range indexing is a runtime error.
- `list[index]` returns the list element.
- `text[index]` returns text containing one grapheme cluster.

```text
let names = ["Ada", "Grace"]
let first_name = names[1] # text

let word = "Ada"
let first_char = word[1] # text
```

### 12.3 Inclusive Slice

Syntax:

```text
value[left, right]
```

The result includes both endpoints.

```text
let names = ["Ada", "Grace", "Linus"]
let first_two = names[1, 2]     # ["Ada", "Grace"]
let without_first = names[2, 3] # ["Grace", "Linus"]
```

Rules:

- `left` and `right` must evaluate to integer numbers.
- If `left <= right`, the valid range is
  `1 <= left <= right <= count(value)`.
- If `left = right + 1`, the result is empty text or empty list.
- If `left > right + 1`, it is an error.
- Other out-of-range bounds are errors.
- `list[left, right]` returns a list.
- `text[left, right]` returns text.

This allows common list operations:

```text
let removed = names[1, i - 1] + names[i + 1, count(names)]
```

For empty text or list, only `value[1, 0]` is a valid slice.
Single indexing an empty value is always out of range.

## 13. Expressions

### 13.1 Expression Forms

Expressions include:

- number literals
- single-line text literals
- list literals
- variable references
- function calls with returned values
- arithmetic and concatenation
- unary minus
- parenthesized expressions
- index and slice postfixes

Multiline text literals are restricted to `let name = """` and are not general
expressions.

### 13.2 Commas

Commas are used in:

- function parameter lists
- function call argument lists
- list literals
- slices

Trailing commas are not supported.

Valid:

```text
add(a, b) {
  return a + b
}

let xs = [1, 2, 3]
say(xs[1, 2])
```

Invalid:

```text
add(a, b,) {
}

let xs = [1, 2, 3,]
```

### 13.3 Operators

Expression operators:

```text
+ - * /
```

The actual expression operators are `+`, `-`, `*`, and `/`.

`+` valid cases:

- `number + number -> number`
- `text + text -> text`
- `list + list -> list`

There is no automatic conversion.

Invalid:

```text
"score: " + 10
names + "Ada"
```

Use explicit conversion or a single-element list:

```text
"score: " + as_text(score)
names + ["Ada"]
```

Assignment update shorthand is not supported. Use ordinary assignment instead.

Invalid:

```text
score += 1
name += "!"
score++
```

Valid:

```text
score = score + 1
name = name + "!"
```

### 13.4 Parentheses

Ordinary expressions support parentheses.

```text
let x = (1 + 2) * 3
say((score + bonus) / 2)
```

Condition grouping with parentheses is not supported. See section 14.

### 13.5 Precedence and Associativity

From highest to lowest:

1. Function calls and index/slice postfixes.
2. Unary `-`.
3. `*` and `/`.
4. `+` and `-`.
5. Condition comparisons.
6. Condition combination with `and` or `or`.

Comparisons and condition combination are only valid in conditions.

Arithmetic binary operators are left-associative.

```text
10 - 3 - 2 # 5
8 / 4 / 2  # 1
-nums[1]   # means -(nums[1])
```

### 13.6 Evaluation Order

Evaluation is left to right:

- function arguments
- list literal elements
- binary operator operands
- condition terms

`and` and `or` do not short-circuit, but still evaluate left to right.

```text
show(ask("first: "), ask("second: "))
```

## 14. Conditions and Comparison

### 14.1 No Boolean Values

Teaspoon v0 has no boolean kind and no `true` or `false` literals.

Programs can use text such as `"yes"` or `"no"` as ordinary values, but `if`
does not accept a plain text value as a condition.

Invalid:

```text
if ready {
}

let ok = score > 10
```

Valid:

```text
if ready is "yes" {
  say("go")
}
```

### 14.2 Comparisons

Condition terms have one of these forms:

```text
expr is expr
expr is not expr
expr > expr
expr >= expr
expr < expr
expr <= expr
```

The expressions on both sides may be arbitrary single-line expressions.

```text
if count(names) + 1 is target {
}

if name[1] is "A" {
}

if as_number(age_text) >= 18 {
}
```

`=` is not comparison. It is only used in `let` and assignment statements.
`==` and `!=` are not supported.

### 14.3 Equality

`is` and `is not` support number, text, and list.

- Number equality compares exact numeric value.
- Text equality compares NFC-normalized text.
- List equality compares length and element values.
- Empty list equals empty list.
- Empty list compared with a non-empty list is valid and unequal.
- Number vs text is an error.
- List vs non-list is an error.
- Two non-empty lists with different element kinds are an error.

```text
if 1 is 1.0 {
}

if [] is [1] {
  # not equal
}

if [1] is ["1"] {
  # error
}
```

### 14.4 Ordering

Ordering comparisons are only valid for numbers:

```text
> < >= <=
```

Text and list ordering are not supported.

### 14.5 Condition Combination

Conditions may combine comparison terms with `and` or `or`.

```text
if age >= 10 and age <= 12 {
  say("middle")
}

if name is "Ada" or name is "Grace" or name is "Linus" {
  say("known")
}
```

Rules:

- `and` and `or` are valid only in conditions.
- A condition cannot mix `and` and `or`.
- Condition grouping parentheses are not supported.
- `and` and `or` do not short-circuit.
- Terms are evaluated left to right.

Invalid:

```text
if a is 1 or b is 2 and c is 3 {
}

if (name is "Ada" or name is "Grace") and age >= 10 {
}
```

## 15. Built-In Functions

Built-in function names are global names. User code cannot redefine them.

Built-ins in v0:

```text
say
ask
count
as_text
as_number
floor
ceil
round
ok
error
request_time
http_response
to_utf8_bytes
parse_utf8_bytes
```

Text splitting, joining and replacement belong in ordinary TSP application
libraries, using loops, indexes, slices and concatenation. There are no runtime
`text_split`, `text_lines`, `text_join` or `text_replace` functions, reserved names,
or compatibility aliases. Application helpers follow ordinary grapheme/NFC
semantics and transient execution limits, not implicit byte-level matching.
`http_response` is described under [Transient HTTP Pages](#transient-http-pages).

`ok(value)` and `error(problem)` construct outcomes; their payload must be a
number, text, or supported list. `ok()` constructs payload-free success.
Both success and error payloads must be finite, acyclic, JSON-serializable
ordinary values. Current lists are flat homogeneous scalar lists; references,
nested lists and nested outcomes are not allowed, so TSP source cannot create
a cyclic payload. Any future collection/reference feature must preserve this
boundary; serialization failure must not commit an API mutation.
`error()` is invalid. Constructors do not alter execution flow; an API commits
or rolls back when it explicitly returns the constructed outcome. Their ordinary
expression use is also available to helper functions and `start()`.

### 15.1 `say(value)`

`say` has no return value and must be used as a statement.

Rules:

- Emits one output event.
- CLI writes the event display text to stdout followed by a newline.
- `say("")` outputs an empty line.
- `say(text)` displays the text content directly.
- `say(number)` uses default number display.
- `say(list)` uses list display syntax.

### 15.2 `ask(prompt)`

`ask` returns text and must be used as an expression.

Rules:

- `prompt` must be text.
- Emits an input request event.
- CLI writes the prompt to stdout without automatically appending a newline.
- The prompt is displayed exactly as provided; `ask` does not append a question
  mark or any other text.
- The host reads one line of input.
- The trailing input newline is not part of the result.
- The returned text is trimmed at both ends using Unicode whitespace.
- Whitespace inside the returned text is preserved.
- The returned text is normalized to NFC.
- If input reaches EOF before a line is read, `ask` raises `InputError`.

Example:

```text
let name = ask("Name: ")
say("Hello " + name)
```

### 15.3 `count(value)`

`count` returns a number.

Rules:

- `count(list)` returns the number of elements.
- `count(text)` returns the number of grapheme clusters.
- `count(number)` is an error.
- The result is an exact integer number.
- `count(text)` does not trim whitespace.

### 15.4 `as_text(value)`

`as_text` returns text.

Rules:

- `as_text(text)` returns the same text.
- `as_text(number)` returns default number display text.
- `as_text(list)` is an error, including `as_text([])`.
- `as_text(text)` does not add quotes or escaping.

### 15.5 `as_number(value)`

`as_number` returns a number.

Rules:

- `as_number(number)` returns the same number.
- `as_number(text)` trims Unicode whitespace at both ends and parses a number.
- `as_number(list)` is an error.

Accepted decimal/integer formats match number literals, plus an optional leading
minus:

```text
"123"
"-123"
"3.14"
"-3.14"
"0.5"
" 12 "
```

Not accepted:

```text
".5"
"5."
"1_000"
"1e6"
```

Fraction strings are accepted:

```text
"1/3"
"-1/3"
```

Rules for fractions:

- Numerator and denominator must be integer digits.
- Denominator must not be zero.
- A minus sign is allowed only at the front.
- `1/-3` and `-1/-3` are errors.

This allows:

```text
as_number(as_text(1 / 3))
```

### 15.6 `floor(number)`, `ceil(number)`, `round(number)`

These functions require a number and return an integer number.

- `floor(x)` returns the greatest integer less than or equal to `x`.
- `ceil(x)` returns the least integer greater than or equal to `x`.
- `round(x)` returns the nearest integer.
- `round` uses half away from zero.

```text
round(1.5)  # 2
round(-1.5) # -2
```

### 15.7 `request_time()`

Returns the current request's runtime-assigned admission time as an exact integer
number of Unix nanoseconds (UTC epoch). It takes no arguments. It is not a
continuously advancing wall clock: every call within the request, including calls
inside ordinary helpers, returns the same value. Readonly and transactional APIs
can both read it. Clients cannot override it through request arguments or headers.

```tsp
start() {
}

readonly api admitted_at() {
  return ok(request_time())
}
```

It is unavailable during `start()` or `teaspoon run`, including through helpers;
these produce `RequestContextRequired`. Global initializers remain literals only.
Historical execution without admission metadata produces `RequestTimeUnavailable`
if it evaluates this builtin; neither completion timestamps nor today's clock
are substitutes. Upgrade checking reports such a history as unverifiable.

The server persists admission time before executing an API body. Matching UUID
retries return the original outcome without reading the clock. Recovery and
compatibility checking evaluate historical calls with their original time.
The stored representation is signed 64-bit Unix nanoseconds; clocks outside this
range are rejected before execution rather than wrapped. TSP numbers and the
HTTP value envelope preserve the integer exactly, without floating-point loss.

Nanosecond representation does not imply nanosecond clock accuracy, uniqueness,
monotonicity or a globally synchronized order. A backwards clock adjustment can
produce a smaller value for a later request; the request journal's `seq` remains
the execution order. Calls to other servers receive those servers' independently
assigned request times; A's time is not implicitly forwarded as B's time.

### 15.8 `current_user()`

`current_user()` takes no arguments and returns an identity, not an API outcome.
Match it exhaustively using `authenticated(user)` and `anonymous`, in either
order. The authenticated branch binds a read-only text user ID. The anonymous
branch has no payload and does not allocate a fictitious user ID.

```text
readonly api who_am_i() {
  match current_user() {
    authenticated(user) {
      return ok(user)
    }
    anonymous {
      return error("Login required.")
    }
  }
}
```

Identity values cannot be compared, placed in lists, or returned as API
payloads. Match them and use the bound user text instead. Calls outside an API
execution context, including `start()` and ordinary CLI execution, fail with
`RequestContextRequired`. Transient GET and POST handlers receive the same
identity context, without recording it in a journal.

The runtime records trusted user/session IDs alongside request admission time.
Recovery and compatibility checks use these recorded IDs, without using present
credentials or contacting an identity service. Missing historical metadata is
not equivalent to anonymous: an executed `current_user()` makes such history
unverifiable. Paths that do not need identity can still replay legacy history.

This primitive is an admission-context foundation, not an authentication
provider. The in-process `APICallOptions.Identity` is a trusted embedding input;
the bare HTTP handler supplies anonymous identity and does not trust caller
user headers or API arguments as user IDs. With an authentication provider,
Bearer/cookie credentials are verified before execution. `allow_anonymous`
retains a valid identity while permitting missing credentials;
`always_anonymous` skips identity resolution entirely. These declarations apply
to durable APIs and transient HTTP handlers, not ordinary helpers or globals.
See [authentication configuration](authentication.md).

### 15.9 `to_utf8_bytes(text)`, `parse_utf8_bytes(bytes)`

These pure functions use ordinary call syntax and existing values; there is no
blob type or new string escape syntax.

- `to_utf8_bytes(text)` returns a number list containing the text's UTF-8 bytes,
  each an exact integer from 0 through 255. Empty text returns `[]`. Valid TSP
  text always has a UTF-8 encoding, so this function does not return an outcome.
- `parse_utf8_bytes(bytes)` accepts a number list and returns `ok(text)` on
  success. `[]` returns `ok("")`, with a text payload rather than payload-free
  `ok()`.
- Fractional, negative and larger-than-255 elements return
  `error("invalid_byte_value")`, without rounding, truncation or wrapping.
- A byte sequence that is not valid UTF-8 returns `error("invalid_utf8")`:
  overlong encodings, surrogate code points, truncated sequences and values
  above U+10FFFF are not replaced or ignored. These two error payloads are text
  codes, not runtime diagnostics.
- Decoded text follows ordinary NFC normalization and grapheme indexing. Byte
  sequences are not guaranteed to survive decode/encode unchanged: for example,
  `[101, 204, 129]` decodes to the same text as `[195, 169]`, and re-encodes to
  `[195, 169]`. CR, LF, NUL and a leading BOM are preserved as text content.
- The functions perform no I/O and are available in startup, ordinary helpers,
  APIs and transient handlers. A parse error does not terminate execution or
  roll back state by itself: `match` can handle it and continue. An API that
  explicitly returns `error(reason)` from its error branch uses the existing
  business-error rollback contract. An API that handles it and returns `ok(...)`
  can commit its changes normally. API returns still require an explicit `ok`
  or `error` constructor; this does not enable `return parse_utf8_bytes(bytes)`
  at an API boundary.
- Wrong argument kinds still raise `KindError`; cancellation and execution
  limits remain runtime failures. None are converted into catchable parse
  outcomes. Both functions expect well-formed values from the host; an invalid
  internal text value is a runtime error, not an encoding result.
- In transient execution, input byte lists and encoded output lists are capped
  at 50000 items. Conversion loops consume the existing execution budget and
  check cancellation; these are not unbounded native shortcuts.

```tsp
start() {
  let bytes = to_utf8_bytes("ABC")  # [65, 66, 67]
  match parse_utf8_bytes(bytes) {
    ok(text) {
      say(text)
    }
    error(reason) {
      say("Cannot parse: " + reason)
    }
  }
}
```

`parse_utf8_bytes([13, 10])` returns `ok(text)` containing CRLF. Top-level
initializers remain literals only. These functions do not perform text
splitting, replacement or rendering. The earlier experimental names
`utf8_encode` and `utf8_decode` are no longer built-ins or compatibility aliases;
source using those names must be updated, including matching on parse outcomes.

## 16. Runtime Model

### 16.1 Execution

`teaspoon run file.tsp`:

1. Reads the source file.
2. Parses it.
3. Runs structural validation.
4. Initializes top-level literal variables.
5. Calls `start()`.
6. Emits structured runtime events.
7. Returns a structured success result or structured error.

### 16.2 Validation Before Execution

The implementation should report these before running user code:

- syntax errors
- unknown names when statically knowable
- duplicate names and case-insensitive name conflicts
- invalid use of keywords or reserved names
- wrong function argument count
- invalid `return` position
- returned-value/no-return function call misuse when statically knowable
- invalid top-level `let` initializer
- invalid assignment target
- invalid `else` placement
- invalid statement forms

### 16.3 Runtime Checks

The runtime checks:

- operation support by value kind
- variable kind stability on assignment
- list element kind consistency
- comparison kind compatibility
- index and slice bounds
- integer requirement for indexes and slice bounds
- division by zero
- `as_number(text)` parse failures
- `ask()` EOF
- resource limits

### 16.4 Resource Limits

The language permits runtimes to enforce resource limits, such as:

- maximum call depth
- maximum execution steps
- maximum output size
- maximum input requests
- maximum text length
- maximum list length
- maximum displayed or captured value size
- maximum memory use

Specific numeric limits are implementation configuration, not fixed language
semantics.

Limit violations should produce `LimitError`.

### 16.5 Determinism and Sandbox

Aside from `ask`, v0 programs are deterministic.

The v0 runtime has no file, network, environment, system command, time, random,
or clipboard access.

## 17. Events and Results

### 17.1 Event Stream

The runtime produces structured events.

Required event kinds:

- output event from `say`
- input request event from `ask`
- structured error result/event
- structured success result

CLI renders these events as normal terminal IO. A future UI can render the same
events differently.

### 17.2 Output Events

`say(value)` produces an output event containing:

- the structured value
- the default display text

Example shape:

```json
{
  "type": "output",
  "value": {
    "kind": "list of number",
    "items": [
      { "kind": "number", "display": "1" },
      { "kind": "number", "display": "2" }
    ]
  },
  "display": "[1, 2]"
}
```

The CLI writes `display` to stdout followed by a newline.

### 17.3 Input Request Events

`ask(prompt)` produces an input request event containing:

- a request id
- the structured prompt value
- the prompt display text

The prompt must be text. The host returns raw input text; the runtime trims and
normalizes it before returning from `ask`.

### 17.4 Success Result

Successful program completion returns a structured result containing:

- success status
- final globals snapshot
- optional stats, such as step count, maximum stack depth, and output count

The CLI does not display globals or stats by default.

## 18. Errors

### 18.1 Structured Errors

Errors should be structured first, then rendered for CLI or UI.
The detailed snapshots in this section describe local CLI debugging. Server API
failure records keep only code, location and a safe description; HTTP responses
omit debug details regardless of authentication configuration. Explicit business
error payloads are preserved. See [the output contract](output_contract.md#server-api-diagnostics).
Default rendered human-readable messages are English. Future runtimes may add
localization without changing the structured error shape.

Each error should include:

- error `code`
- human-readable `message`
- source file
- line and column
- source snippet
- optional suggestion
- structured call stack when available
- globals snapshot when available

Example rendered form:

```text
NameError at main.tsp:4:7
  say(Score)
      ^^^^^
Unknown name.
Suggestion: Did you mean `score`?
```

### 18.2 Call Stack

Runtime errors include a structured call stack.

Each stack frame includes:

- function name
- call site
- current source location
- parameters and their values
- local variables and their values

`start()` appears as a stack frame. Recursive calls appear as separate frames.

### 18.3 Side Effects in User Functions

User functions may have side effects. They may call `say`, call `ask`, and assign
top-level variables. Teaspoon v0 does not restrict returned-value functions to
be pure.

### 18.4 Globals Snapshot

Runtime errors include a globals snapshot separate from the stack frames.

This is needed because top-level variables are mutable and can be changed by
functions.

### 18.5 Value Capture and Truncation

Error values may be truncated to avoid huge error payloads.

Captured values should include:

- kind
- display text
- `truncated` marker
- for text: total grapheme length and captured prefix when truncated
- for list: total length and captured leading elements when truncated
- for number: display text, possibly truncated

Full values are not guaranteed to appear in an error object.

## 19. CLI

The only required v0 command is:

```bash
teaspoon run main.tsp
```

Rules:

- `run` reads one `.tsp` file.
- Extra program arguments are not supported and are CLI argument errors.
- There is no `teaspoon main.tsp` shorthand.
- `say` output goes to stdout.
- `ask` prompts go to stdout without automatic newline.
- `ask` reads stdin.
- Language errors and runtime errors are written to stderr after rendering from
  the structured error.

Exit codes:

- `0`: success
- `1`: syntax, validation, input, limit, or runtime error
- `2`: CLI argument error

The concrete Go API result, event, success result, and structured error shapes
are documented in `docs/output_contract.md`.

## 20. Official Formatting Style

Teaspoon v0 does not require a formatter, but the official style is:

- two spaces for indentation
- opening `{` on the same line as the header
- closing `}` alone on its own line
- spaces around operators
- one space after commas
- blank lines between top-level definitions
- top-level `let` definitions usually before functions, without semantic
  requirement
- outside text literals, future formatters should output ordinary ASCII spaces
  for spacing and indentation
- formatters must preserve the content of text literals, including multiline
  text indentation, spacing, tabs, and blank lines

Example:

```text
let greeting = "hello"

start() {
  say(greeting)
}

add(a, b) {
  return a + b
}
```

## 21. Go Implementation Plan

The first implementation will be written in Go.

Suggested package layout:

```text
cmd/teaspoon/main.go
internal/teaspoon/lexer.go
internal/teaspoon/parser.go
internal/teaspoon/ast.go
internal/teaspoon/checker.go
internal/teaspoon/runtime.go
internal/teaspoon/value.go
internal/teaspoon/error.go
```

Implementation notes:

- Use a hand-written lexer.
- Use a hand-written parser.
- Use a Pratt parser or equivalent precedence parser for expressions.
- AST nodes should carry source spans.
- Use `math/big.Rat` or equivalent for exact rational numbers.
- Use a Unicode grapheme segmentation library, such as `github.com/rivo/uniseg`,
  for text indexing and counting.
- Do not implement text indexing with Go `[]rune`.
