# moonmo

[![CI](https://github.com/LP-XXX/moonmo/actions/workflows/ci.yml/badge.svg)](https://github.com/LP-XXX/moonmo/actions/workflows/ci.yml)
[![license](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)

[中文版](README.md)

`moonmo` is a GNU gettext `.mo` **runtime** written in pure MoonBit: load a compiled MO catalog and look up ordinary, contextual, and plural messages. It is runtime-only — no PO parsing or compilation toolchain. This is an independent implementation, written against the public GNU gettext format specification and observable behavior. `YanFangNie/moongettext` in the same ecosystem is a full toolkit including the PO toolchain; the two projects differ in scope, and the interoperability and performance figures below were measured directly against it.

Published as `LP-XXX/moonmo 0.1.0` on [mooncakes](https://mooncakes.io/docs/LP-XXX/moonmo), verified by consuming it with `moon add` from an empty directory.

## Features

- Reads MO revision 0.0, little- or big-endian; the core takes only `Bytes`, no file-system dependency;
- `gettext`, `pgettext`, `ngettext`, and `npgettext` lookups, plus a `try_*` family that distinguishes "missing" from an explicitly empty translation;
- A self-contained `Plural-Forms` lexer, parser, and evaluator — nothing is delegated to the host language;
- Strict load-time validation (offsets, ordering, charset, plural slots, …) with specific error types instead of silent acceptance;
- Accepts UTF-8 catalogs, or pure 7-bit ASCII when no charset is declared;
- Zero-dependency core; separate packages provide file loading (`fs`) and a moonpug template-engine adapter;
- The same test suite passes on native, wasm, wasm-gc, and js.

## Installation

```bash
moon add LP-XXX/moonmo
```

Add this to the `moon.pkg` of the consuming package:

```moonbit
import {
  "LP-XXX/moonmo",
}
```

## Minimal example

This function takes caller-provided French MO bytes and returns a contextual translation. Passing `fixtures/mo/fr_le.mo` yields `Ouvrir la carte`:

```moonbit
fn menu_label(bytes : Bytes) -> String raise @moonmo.GettextError {
  let cat = @moonmo.Catalog::from_bytes(bytes)
  cat.pgettext("menu", "Open")
}
```

When the runtime can read files, `load_catalog_from_file(path)` from `LP-XXX/moonmo/fs` does the same job. For a quick look, run `moon run --target wasm-gc examples/demo`.

## Example programs

The repository ships three trilingual apps and a lookup tool. All translations come from real GNU MO files; regenerate a catalog with `msgfmt` after editing its PO source:

```sh
moon run --target wasm-gc examples/todo        # to-do list in English, Chinese, French
moon run --target wasm-gc examples/scoreboard  # football scoreboard in English, French, Czech
moon run --target wasm-gc examples/duration    # duration formatting, plural forms follow the count
moon run --target native examples/lookup -- fixtures/mo/fr_le.mo Open --context menu
```

## API at a glance

| Entry point | Convention |
| --- | --- |
| `Catalog::from_bytes` / `Catalog::empty` | Build a read-only catalog from MO bytes, or an empty catalog for source-text fallback |
| `gettext` / `pgettext` | Look up by message ID, or by context + message ID; missing entries return the source text |
| `ngettext` / `npgettext` | Pass singular source, plural source, and a `UInt64` count; the contextual form takes a context too |
| `try_gettext` / `try_pgettext` | Return `String?` directly, distinguishing missing from explicitly empty |
| `try_ngettext_checked` / `try_npgettext_checked` | Need only the singular key and count, context optional; evaluation failures raise specific errors |
| `metadata()` / `plural_rule()` / `len()` | Inspect the structured header, the compiled plural rule, or the entry count (which includes the stored metadata header) |
| `mo.parse_mo` / `plural.parse_expr` / `PluralRule::parse` | Inspect an MO layout, parse an expression, or parse a full plural declaration on their own |
| `make_translator` / `make_switchable_translator` | Connect a fixed or switchable catalog reference to moonpug's `translate` callback |

See the [tutorial](docs/tutorial.md) and the [API reference](docs/api.md) for more.

## Architecture

The file adapter and the template adapter both call the root package. The root package uses `mo` to validate and read catalogs and `plural` to build and evaluate plural rules; the two lower-level packages are independent of each other.

```mermaid
flowchart LR
    fs["fs · file → Bytes"] --> catalog
    pug["adapters/moonpug · translate callback"] --> catalog
    catalog["Catalog · lookup and fallback"] --> mo["mo · binary validation and metadata"]
    catalog --> plural["plural · lexing, parsing, evaluation"]
```

## Verification

```bash
moon test --target native
moon test --target wasm
moon test --target wasm-gc
moon test --target js
moon check --deny-warn
moon fmt --check
```

Results (2026-12-03, commit `2079f86`):

- 109/109 tests pass on each of the four targets; the five public JS packages pass 78/78 under Node 24;
- Interoperability matrix: with GNU msgfmt and `YanFangNie/moongettext` 0.1.1 as the two producers, six parties cross-check 190/190 entries identically; 7 real MO catalogs from Sphinx, Spyder, and Django match Python on all 76 queries;
- Live differential testing: 17,646 lines of output checked per target, zero differences against the Python baseline;
- Mutation testing: a fixed seed generated 3,000 random catalogs and 382,720 mutants; three targets agree throughout, with zero panics.

Details: [differential method and summary](docs/oracle-diff.md), [interoperability record](interop/README.md), [evidence index](docs/evidence-index.md).

## Performance

Paired timing against `YanFangNie/moongettext` 0.1.1 on the same machine and workload (10 pairs per cell):

- Plural queries: this library is stably faster on both native and wasm-gc (10/0/0);
- Plain queries: after one targeted optimization round, native shows no stable winner (6/0/4) and wasm-gc is stably faster here (9/0/1); before the optimization, the other library was stably faster on both backends;
- Whole-page rendering: no stable difference resolved (7/0/3). The page is a self-built adapter page — the moonpug 0.2.1 release ships no example page, so it was assembled from its five adapter test blocks; both sides share the same template and render entry, and outputs are byte-identical.

Raw data and reproduction steps: [performance record](docs/perf.md) and the [opt1 re-measurement report](docs/perf-opt1-2026-12-03.md).

## GNU and Python semantics

When GNU msgfmt compiles an original PO file, empty untranslated entries disappear from the MO. If an MO does keep a zero-length translation, `try_gettext` returns `Some("")` and the convenience API returns the empty string; fallback happens only for missing entries, or when a convenience plural lookup hits an evaluation error, and source plurals select the singular form by `n == 1`. A plain lookup that hits a plural entry follows Python and takes the `plural(1)` slot (GNU libintl takes slot 0), falling back to slot 0 when that index is invalid or the slot is missing. The full contract is in the [frozen spec](SPEC.md).

To check your own catalog, run `python scripts/verify_external_mo.py --mo /path/to/catalog.mo` (use `--po` for a PO file); the script verifies entry by entry in a temporary directory and your translation assets stay on your machine.

## Contest and judging

This project is an entry in the December 2026 season of the MoonBit Hackathon. A one-page judging summary, the verification script, and all evidence (commit SHAs, CI runs, raw benchmark data, outreach records) are collected in the [evidence index](docs/evidence-index.md). One command runs the six-step verification:

```powershell
.\scripts\verify_all.ps1   # Windows
```

```bash
bash scripts/verify_all.sh # Linux / macOS / Git Bash
```

On success the last line starts with `SUMMARY: 6/6 steps PASS`. Minimal migration invitations were sent to three real projects — MoPress, HexEditor, and tokencalc-mbt (see the evidence index) — and the interoperability matrix was shared in [YanFangNie/moongettext #2](https://github.com/YanFangNie/moongettext/issues/2#issuecomment-7376408526).

## Documentation

[Tutorial](docs/tutorial.md) · [API reference](docs/api.md) · [Judging record](docs/submission-check.md) · [Evidence index](docs/evidence-index.md) · [Contributing](CONTRIBUTING.md) · [Frozen spec](SPEC.md)

## Sources

The format, plural expressions, and reference lookup behavior follow the GNU gettext manual and the Python standard library; no code was copied from GNU gettext or any other existing implementation. [GNU MO files](https://www.gnu.org/software/gettext/manual/html_node/MO-Files.html) · [GNU plural forms](https://www.gnu.org/software/gettext/manual/html_node/Plural-forms.html) · [Python gettext](https://docs.python.org/3/library/gettext.html)

## License

Project code and the checked-in PO/MO test assets are under [Apache-2.0](LICENSE). Upstream versions, file paths, and audit decisions are recorded in the [third-party notices](THIRD_PARTY_NOTICES.md).
