# Errors

MUL has no exceptions and no error values yet. An error either stops
compilation or stops the whole program; nothing in the program can catch it.

## Compile-time errors

- The parser stops at the first syntax error (`MUL-S*`).
- Semantic analysis reports every error it finds, in source order (`MUL-T*`).
- A program with a compile-time error never runs.

Format: `file:line:column: error[CODE]: message [byte N]`, then the source
line and a `^` marker under the offending range. Line and column count from 1
in the file as written; the byte offset counts from 0 and locates the error in
a file written in the compact layout, which is one long line
(RFC-011). A line longer than 100
characters is shown as 40 characters on each side of the range, with `...`
where it is cut.

```text
examples/broken.mul:2:39: error[MUL-T003]: literal 3000000000 does not fit in `i32` [byte 134]
  | module demo pub fn main()->i64{return 3000000000*2}
  |                                       ^^^^^^^^^^
```

```mul
// expect-error: MUL-T011
module demo

pub fn main() -> i32 {
    let count = 1
    count = count + 1
    return count
}
```

```mul
// expect-error: MUL-T004
module demo

fn abs(n: i32) -> i32 {
    if n < 0 {
        return -n
    }
}

pub fn main() -> i32 {
    return abs(-3)
}
```

```mul
// expect-error: MUL-T009
module demo

fn add(a: i32, b: i32) -> i32 {
    return a + b
}

pub fn main() -> i32 {
    return add(1)
}
```

## Run-time errors (traps)

A trap ends the whole program at once with the same error in every backend
(interpreter, Cranelift JIT, native executable). Callers do not observe it and
`main` returns no result; what the program printed before the trap stays
printed. When several operations could trap, the first one in evaluation
order is reported ([types.md](types.md#evaluation-order)). `mul run` reports
the trap in the format of the compile-time errors above, at the operation that
trapped: `file:line:column: error[CODE]: message [byte N]`, the source line and
a `^` marker under the operation (the whole `a / b` or `a + b`, the call that
exceeded the depth), in both backends and also in a file written on one line,
where the byte offset is the address. A trap inside a called function points
into that function. A native executable from `mul build` prints the same
diagnostic: it stores the rendered position of every operation that can trap
when it is built (ADR-018), so editing the source afterwards does not change
what it prints. `mul build --strip-positions` leaves the positions out: the
executable then contains neither the file path nor the source text and prints
`error[CODE]: message` only.

```mul
// expect-error: MUL-R003
module demo

fn ratio(a: i32, b: i32) -> i32 {
    return a / b
}

pub fn main() -> i32 {
    return ratio(10, 0)
}
```

## Exit codes

| Code | Meaning |
|---|---|
| 0 | success |
| 1 | program error: unreadable file, compile-time error, trap, linking failure |
| 2 | invalid command-line usage |
| 3 | internal compiler error (a bug in MUL, please report it); a verifier or code generation error names the source position of the IR node it is about on a second line, `  at file:line:column [byte N]` |

`mul run` (without `--print-result`) and a built executable exit with the
value `main` returns, cut to its low 8 bits (`-1` is 255, `300` is 44), as
every process does. That value can collide with the codes above; read stderr
to tell a trap from a program that returned 1, or run with `--print-result`,
which prints the value and exits with 0.

## Codes

| Code | Phase | Meaning | Typical fix |
|---|---|---|---|
| MUL-S001 | lexer | unexpected character | remove it; identifiers are ASCII |
| MUL-S002 | parser | a different token was expected | the message names the expected token |
| MUL-S003 | parser | expression over 256 operators, calls and parentheses | split it with `let` or helper functions |
| MUL-S004 | parser | blocks nested deeper than 64 levels (these two limits, S003 and S004, keep every later phase at a bounded depth; corrupted or hostile input ends in a diagnostic, never a stack overflow: ADR-015) | flatten the blocks or move code into a function |
| MUL-S005 | parser | comparisons chained, as in `a < b < c` | `a < b && b < c`, or parentheses |
| MUL-S006 | lexer | invalid string literal: no closing quote on the line, unknown escape, raw control character | close the quote; use `\n`, `\t`, `\\` or `\"` |
| MUL-T001 | sema | function is already defined (`print` is built in) | rename one of the functions |
| MUL-T002 | sema | unknown type | use `i32`, `bool` or `string` |
| MUL-T003 | sema | literal does not fit in `i32` | stay within `0..=2147483647` (or `-2147483648`) |
| MUL-T004 | sema | some path does not end with `return` (a `while` never ends a path) | add an `else` that returns, or a `return` after the `if` or the loop |
| MUL-T005 | sema | code after `return` (or after an `if` whose every arm returns) is unreachable | delete it, or move the `return` to the end |
| MUL-T006 | sema | parameter is already defined | rename the parameter |
| MUL-T007 | sema | unknown name | declare it first; a variable ends with its block |
| MUL-T008 | sema | unknown function | define it in the module or fix the name |
| MUL-T009 | sema | wrong number of arguments | pass one argument per parameter |
| MUL-T010 | sema | name already defined (no shadowing) | pick a new name, or assign to a `var` |
| MUL-T011 | sema | assignment to a `let` or a parameter | declare it with `var`, or use a new `let` |
| MUL-T012 | sema | type mismatch | compare to get a `bool` (`n != 0`), use `if` to get an `i32` |
| MUL-T013 | sema | a `pure` function (or one with no effect written) calls an `io` function or `print` | mark the caller `io`, or make the callee `pure` |
| MUL-T014 | sema | `print` used as a value | call `print(text)` as a statement of its own |
| MUL-T015 | sema | `==` or `!=` on `string` values | not supported yet; compare the values the strings came from |
| MUL-R001 | runtime | missing entry function | define `pub fn main() -> i32` |
| MUL-R002 | runtime | `i32` overflow | keep intermediate values in range |
| MUL-R003 | runtime | division or remainder by zero | ensure the divisor is not 0 |
| MUL-R005 | runtime | call depth limit (10 000) exceeded | stop the recursion with an `if` that returns |
| MUL-R006 | runtime | entry function is not `fn() -> i32` | `main` takes no parameters and returns `i32` |

Internal codes signal a compiler bug, never a mistake in the program; report
them with the source file:

| Code | Phase | Meaning |
|---|---|---|
| MUL-V001 | verifier | IR value defined more than once |
| MUL-V002 | verifier | IR value used before its definition, or in a block its definition does not dominate |
| MUL-V003 | verifier | duplicate function in IR |
| MUL-V004 | verifier | call of an unknown function in IR |
| MUL-V005 | verifier | wrong number of arguments in an IR call |
| MUL-V006 | verifier | jump to an unknown IR block |
| MUL-V007 | verifier | wrong number of IR block arguments |
| MUL-V008 | verifier | missing IR entry block, or entry block with parameters |
| MUL-V009 | verifier | IR block unreachable from the entry |
| MUL-V010 | verifier | IR type mismatch (operand, result, condition, block or call argument, returned value, `print` of a non-string) |
| MUL-V011 | verifier | a `pure` IR function calls an `io` one or prints |
| MUL-R004 | runtime | undefined value: the IR did not pass the verifier |

## `.mulb` files

`mul check|ir|run|build|inspect` on a `.mulb` file report a rejected file as
`<file>: error[MUL-B0xx]: ...` and exit with 1; so does
`mul inspect --file <file>.mulb`. The rules are in
RFC-012.

A file written by `mul build --emit mulb` keeps the source map and the Code
Graph. A run-time error in such a file points into the MUL Source it was built
from, in the same format as for the source, when that file is still at the
recorded path with the recorded SHA-256. When the source is missing or has
changed, the error names the source path and the byte offset only:
`<source>: error[CODE]: message [byte N]`. A file written without these sections
cannot be used with `mul ir --source-map` or `mul inspect`: `mul` says which
section is missing and exits with 1; write the file again.

| Code | Meaning | Typical fix |
|---|---|---|
| MUL-B001 | the file is truncated | write the file again; the copy was cut short |
| MUL-B002 | bad magic: not a `.mulb` file | pass a file written by `mul build --emit mulb` |
| MUL-B003 | schema version this `mul` does not read | rebuild the file with this version, or use the `mul` that wrote it |
| MUL-B004 | the header requires a feature this `mul` does not know | use a newer `mul` |
| MUL-B005 | a size or count is above a format limit | split the module |
| MUL-B006 | content hash mismatch: the file is corrupted | write the file again |
| MUL-B007 | a required section this `mul` does not know | use a newer `mul` |
| MUL-B008 | structure the format does not allow | the file was not written by `mul` |
| MUL-B009 | the IR in the file does not pass the verifier | the file was not written by `mul` |

## Patch plans

`mul apply` refuses a plan, with nothing written, as
`mul: error[MUL-P0xx]: <file>: ...` and exit code 1. The checks are in
RFC-014 (`spec/rfc-014-patch.md`). A code keeps its meaning in later
versions; the message text can change.

| Code | Meaning | Typical fix |
|---|---|---|
| MUL-P001 | the plan file cannot be read, is not JSON, is not schema `mul-plan-v0`, or lacks a field | write the plan again with `mul plan` |
| MUL-P002 | the plan has no edits | write the plan again |
| MUL-P003 | a path is not a plain relative path, or leads out of `--dir` through `..`, an absolute path or a linked directory | run `mul apply` with the `--dir` the plan was made for |
| MUL-P004 | a path is missing, unreadable, a directory or a link | check `--dir`; a link is never followed |
| MUL-P005 | the file's SHA-256 is not the edit's `baseHash`: the file changed after the plan was made (also `mul plan --at <file>:<line>:<column>`: the file no longer matches the facts the position refers to) | ingest the project again and write a new plan |
| MUL-P006 | a range is empty or outside the file | write the plan again |
| MUL-P007 | two edits of one file overlap | split the plan |
| MUL-P008 | the bytes of a range are not the edit's `old` | write the plan again from the current file |
| MUL-P009 | a new value is not a well-formed literal of its kind (a number with a sign included unless the plan was made with `--signed`: a minus is an operator, not part of the literal token), or the kind has no rule and the edit is not marked `validatedBy: adapter` | give a literal of the kind of the old one, without a sign |
| MUL-P010 | a file changed between the check and the write | run `mul apply` again; nothing was written |
| MUL-P011 | the system failed while writing (permissions, disk, a temporary file in the way); files already written were restored | fix the cause and run `mul apply` again |
| MUL-P012 | `mul apply --verify` wrote the change, the verification refused it, and putting the old bytes back failed for the named file (it changed meanwhile, or the system failed); that file is not overwritten | restore the file by hand (the diff printed by `mul apply` has the old lines) or from version control |
| MUL-P013 | `mul plan` refused to plan an edit in a file the adapter marked as generated (for Go the header `// Code generated ... DO NOT EDIT.`): the edit is lost the next time the file is generated | change the generator and generate again, or plan the edit anyway with `--allow-generated` |
| MUL-P014 | `mul apply` refused a plan whose written sign (`mul plan --signed`) would join the operator before it in the file (a `-` right after a `-`, a `+` right after a `+`: `a-` and `-5` read as `a--5`) | plan again after a space is put in front of the number, or write the other sign |

## Verification

`mul verify` and `mul apply --verify` run the commands an adapter declares for
a language (`spec/rfc-013-adapter.md`, ADR-024).
A step that runs and fails is part of the report
(`  build   fail   0.61 s  error[MUL-E005]: exit status 1`) and `mul verify`
exits with 1; `mul apply --verify` then restores the old bytes and prints
`mul: error[MUL-E008]: ...`. A verification that cannot start is printed as
`mul: error[MUL-E0xx]: <message>`, exit code 1, and `mul apply --verify` has
written nothing. A code keeps its meaning in later versions.

| Code | Meaning | Typical fix |
|---|---|---|
| MUL-E001 | the system cannot run a step in isolation (not Linux, `unshare` or `prlimit` missing or without `--kill-child`, unprivileged user namespaces forbidden); nothing was run | enable user namespaces, or run the language's own commands by hand; there is no way to run the steps unisolated |
| MUL-E002 | the adapter declares no `verify` block, or no command for a requested step | add the step to the adapter's `capabilities.json`, or ask for other steps |
| MUL-E003 | `--steps` or `--verify` is empty or names something that is not `format`, `build` or `test` | list steps from `format,build,test` |
| MUL-E004 | a step could not be started, or its log or log directory could not be written | check `--log-dir` and the tool's presence in `PATH` |
| MUL-E005 | a step ended with a non-zero exit status, or a signal (a memory or file size limit, a crash) | read the first lines in the report and the log |
| MUL-E006 | a step did not finish within the wall-clock limit (`--timeout`, default 120 s) and was killed with all its processes | find the test that hangs; raise `--timeout` if the step is only slow |
| MUL-E007 | the change left files unformatted that were not before (the format step lists them) | run the language's formatter on the named files |
| MUL-E008 | `mul apply --verify` restored the old bytes because a step failed | read the step's report; plan the change again |
