moonmo

    Download zip
    Author
    Version
    0.1.1
    License
    Apache-2.0
    Last updated
    43 minutes ago
    Downloads
    7

    No dependencies

    #moonmo

    CI license

    moonmo 是一个用纯 MoonBit 编写的 GNU gettext .mo 运行时:加载编译好的 MO 目录,查询普通、上下文和复数译文。它只做运行时,不做 PO 解析和编译工具链。本项目为独立实现,依据 GNU gettext 的公开格式规范与可观察行为编写;同生态的 YanFangNie/moongettext 是包含 PO 工具链的完整工具包,两者定位不同,下文的互操作与性能数据均与它实测对照得出。

    已发布:LP-XXX/moonmo 0.1.0(mooncakes),空目录 moon add 消费验证通过。

    #主要功能

    • 读取 MO revision 0.0,大端、小端均可;核心只接受 Bytes,不依赖文件系统;
    • gettext、pgettext、ngettext、npgettext 四类查询,另有 try_* 系列区分「未收录」与「显式空译文」;
    • 独立实现的 Plural-Forms 词法、语法与求值,不外包给宿主语言;
    • 加载期严格校验(偏移、排序、字符集、复数槽位等),出错给出具体错误类型,不静默吞掉;
    • 只接受 UTF-8,或未声明编码的纯 7-bit ASCII 目录;
    • 核心包零依赖;另提供文件加载包 fs 与模板引擎 moonpug 的适配包;
    • native、wasm、wasm-gc、js 四个后端均通过同一套测试。

    #安装

    moon add LP-XXX/moonmo

    在使用该包的 moon.pkg 中加入:

    import {
    "LP-XXX/moonmo",
    }

    #最小示例

    以下函数接受调用方提供的法语 MO 字节,返回带上下文的译文。传入 fixtures/mo/fr_le.mo 会得到 Ouvrir la carte:

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

    运行环境能读文件时,也可用 LP-XXX/moonmo/fs 的 load_catalog_from_file(path)。只看演示可运行 moon run --target wasm-gc examples/demo。

    #示例程序

    仓库带三个三语小应用和一个查词工具,译文都来自真实 GNU MO,改译文后可用 msgfmt 重新生成目录:

    moon run --target wasm-gc examples/todo # 待办清单,依次显示英、中、法 moon run --target wasm-gc examples/scoreboard # 足球计分牌,英、法、捷克语 moon run --target wasm-gc examples/duration # 时长换算,复数形式随数量变化 moon run --target native examples/lookup -- fixtures/mo/fr_le.mo Open --context menu

    #API 速览

    入口调用约定
    Catalog::from_bytes / Catalog::empty从 MO 构造只读目录,或创建用于源文回退的空目录
    gettext / pgettext按消息 ID,或按上下文与消息 ID 查询,缺失时返回源文
    ngettext / npgettext传入单数源文、复数源文和 UInt64 数量,上下文版本另传上下文
    try_gettext / try_pgettext直接返回 String?,可区分未收录和空译文
    try_ngettext_checked / try_npgettext_checked只需单数键和数量,可加上下文;求值失败或索引不可用时抛出具体错误
    metadata() / plural_rule() / len()查看结构化头、编译后的复数规则或目录条目数。条目数包含已存储的元数据头
    mo.parse_mo / plural.parse_expr / PluralRule::parse单独检查 MO 布局、解析表达式或解析整条复数声明
    make_translator / make_switchable_translator将固定目录或可切换的目录引用接到 moonpug 的 translate 回调

    更完整的说明见入门教程与 API 参考。

    #架构

    文件适配器和模板适配器都调用根包。根包用 mo 校验并读取目录,用 plural 构建和求值复数规则,两个底层包彼此独立。

    flowchart LR fs["fs · 文件 → Bytes"] --> catalog pug["adapters/moonpug · 翻译回调"] --> catalog catalog["Catalog · 查找与回退"] --> mo["mo · 二进制校验与元数据"] catalog --> plural["plural · 词法、语法与求值"]

    #验证

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

    结果(2026-12-03,提交 2079f86):

    • 四个目标各 109/109 项通过;JS 五个公共包在 Node 24 下 78/78;
    • 互操作矩阵:以 GNU msgfmt 与 YanFangNie/moongettext 0.1.1 为两个生产者,六方互验 190/190 一致;另取 Sphinx、Spyder、Django 的 7 份真实 MO 目录,76 条查询与 Python 零差异;
    • 实时差分:每个目标核对 17,646 行输出,与 Python 基准零差异;
    • 变异测试:固定种子生成 3,000 个随机目录与 382,720 个变异体,三目标结果一致、零 panic。

    #性能

    与 YanFangNie/moongettext 0.1.1 在同一台机器、同一负载下配对计时(每格 10 对):

    • 复数查询:native 与 wasm-gc 均为本库稳定领先(10/0/0);
    • 普通查询:经一轮定向优化后,native 未分出稳定胜负(6/0/4),wasm-gc 本库稳定较快(9/0/1);优化前两后端均为对方稳定领先;
    • 整页渲染:未分辨出稳定方向差异(7/0/3)。页面为自建适配页——moonpug 0.2.1 发布包未附示例页面,故用其五个适配测试块拼装,两侧共用同一模板与渲染入口,输出逐字节一致。

    原始数据与复现方法见性能记录与 opt1 复测报告。

    #GNU 与 Python 语义

    GNU msgfmt 编译原创 PO 时,空的未翻译项会从 MO 中消失。若 MO 保留了长度为零的译文,try_gettext 返回 Some(""),便捷 API 也返回空串;只有缺失、或便捷复数查询遇到求值错误时才回退,源文复数按 n == 1 选单数。普通查询命中复数条目时,本库按 Python 取 plural(1) 的槽位(GNU libintl 取槽 0),该索引无效或缺槽时尝试槽 0。完整约定见冻结规格。

    要核验自己的目录,可运行 python scripts/verify_external_mo.py --mo /path/to/catalog.mo(PO 用 --po),脚本在临时目录逐项核对,外部翻译资产留在本机。

    #参赛与评审

    本项目是 MoonBit 黑客松 2026 年 12 月赛季参赛项目。一页评审摘要、验收脚本与全部证据(提交 SHA、CI、基准原始数据、外部邀约记录)汇总在证据索引;一条命令跑完六步验收:

    .\scripts\verify_all.ps1 # Windows

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

    成功时最后一行以 SUMMARY: 6/6 steps PASS 开头。已向 MoPress、HexEditor、tokencalc-mbt 三个真实项目发出最小迁移邀约(见证据索引),并在 YanFangNie/moongettext #2 分享了互操作矩阵。

    #文档

    #来源说明

    格式、复数表达式与参考查询行为分别依据 GNU gettext 手册与 Python 标准库;本项目未复制 GNU gettext 或其他现有实现的代码。GNU MO 格式 · GNU 复数形式 · Python gettext

    #许可证

    项目代码和入库的 PO/MO 测试资产采用 Apache-2.0。上游版本、文件路径与核查决定见第三方来源核查。

    GettextError

    pub suberror GettextError {
    Mo(
    MoError
    )
    Plural(
    PluralError
    )
    PluralFormOutOfRange(msgid~ : String, index~ : Int, available_forms~ : Int, nplurals~ : Int)
    } derive(Eq,
    Debug
    )

    Catalog failure wrapping a binary or plural error, or identifying an unavailable translation slot. Example: cat.try_ngettext_checked("lamp", 2) catch { _ => None }.

    Catalog

    pub struct Catalog {
    // private fields
    }

    Immutable directory of validated UTF-8 messages, searched by MO key order. Example: Catalog::empty().len().

    Catalog::empty

    fn Catalog::empty() -> Catalog

    Create a zero-entry catalog with the default two-form rule. Queries fall back to source text. Example: Catalog::empty().gettext("Open").

    Catalog::from_bytes

    fn Catalog::from_bytes(bytes : Bytes) -> Catalog raise GettextError

    Validate revision, layout, ordering, encoding and plural syntax at load time. Raises Mo or Plural on invalid input. Example: Catalog::from_bytes(bytes).

    Catalog::gettext

    fn Catalog::gettext(self : Catalog, msgid : String) -> String

    Return a translation, including an explicit empty string, or the original ID on a miss. Example: cat.gettext("Ready").

    Catalog::len

    fn Catalog::len(self : Catalog) -> Int

    Count original-table entries, including the metadata row when stored. Example: cat.len().

    Catalog::metadata

    fn Catalog::metadata(self : Catalog) -> CatalogMetadata

    Return decoded metadata with a fresh header map that the caller may edit. Example: cat.metadata().headers.get("language").

    Catalog::ngettext

    fn Catalog::ngettext(self : Catalog, msgid : String, msgid_plural : String, n : UInt64) -> String

    Select a translated slot. On a miss or plural error, return the singular source for n=1 and the plural source otherwise. Example: cat.ngettext("lamp", "lamps", 2).

    Catalog::npgettext

    fn Catalog::npgettext(self : Catalog, msgctxt : String, msgid : String, msgid_plural : String, n : UInt64) -> String

    Select a translated slot within a context. Misses and plural errors fall back to the supplied source forms using n=1. Example: cat.npgettext("inventory", "lamp", "lamps", 2).

    Catalog::pgettext

    fn Catalog::pgettext(self : Catalog, msgctxt : String, msgid : String) -> String

    Return the contextual translation or the original ID on a miss. Example: cat.pgettext("menu", "Open").

    Catalog::plural_rule

    Return the compiled rule, including the default when the header omitted Plural-Forms. Example: cat.plural_rule().eval_index(2).

    Catalog::try_gettext

    fn Catalog::try_gettext(self : Catalog, msgid : String) -> String?

    Return None for a miss and Some("") for an empty hit. Ordinary plural hits select plural(1), with slot zero as fallback. Example: cat.try_gettext("Ready").

    Catalog::try_ngettext_checked

    fn Catalog::try_ngettext_checked(self : Catalog, msgid : String, n : UInt64) -> String? raise GettextError

    Return the selected plural slot, or None for absent or singular entries. Raises Plural for rule errors and PluralFormOutOfRange for missing slots. Example: cat.try_ngettext_checked("lamp", 2).

    Catalog::try_npgettext_checked

    fn Catalog::try_npgettext_checked(self : Catalog, msgctxt : String, msgid : String, n : UInt64) -> String? raise GettextError

    Look up a plural in one context. Absent or singular entries yield None. Rule errors raise Plural and missing slots raise PluralFormOutOfRange. Example: cat.try_npgettext_checked("inventory", "lamp", 2).

    Catalog::try_pgettext

    fn Catalog::try_pgettext(self : Catalog, msgctxt : String, msgid : String) -> String?

    Look up the exact context and ID. Returns None on a miss and preserves empty hits. Example: cat.try_pgettext("menu", "Open").

    CatalogMetadata

    pub struct CatalogMetadata {
    language : String?
    charset : String?
    nplurals : Int
    plural_forms_raw : String?
    raw_header : String?
    headers : Map[String, String]
    } derive(Eq,
    Debug
    )

    Catalog header snapshot with optional declared fields and an effective plural count. Example: cat.metadata().nplurals.