exampleloom

    Bounded example-guided string program synthesis, disagreement selection and portable recipes in MoonBit.

    program-synthesis
    programming-by-example
    data-transformation
    Download zip
    Version
    0.1.0
    License
    MIT
    Last updated
    11 hours ago
    Downloads
    7

    No dependencies

    #ExampleLoom

    给出几个样例,生成可检查、可重用的数据转换程序。

    ExampleLoom 是使用 MoonBit 实现的程序合成引擎、独立浏览器工作台和 CLI。它面向反复整理编号、名单、文件目录的人:导入 CSV/JSONL,标注输入输出样例,比较候选程序的不同解释,明确选择后保存配方并用于下一批数据。不依赖 Excel、云模型、PROSE 或维护者的其他项目。

    工作台运行截图

    #快速体验

    要求 MoonBit(验证版本 moonc 0.10.17+093cb8f9c、moon 0.1.20261021),工作台/CLI 另需 Node.js ≥20。没有 npm 运行时依赖。

    moon check --deny-warn moon test --deny-warn moon run cmd/demo node scripts/build.mjs node scripts/serve.mjs

    打开 http://127.0.0.1:4173,点击“供应商编码”“活动名单”或“素材目录”。两个样例已填好;点击生成候选,检查分歧,选用规则,再预览整批结果。切换示例输出字段可继续添加另一条规则。

    点击“看看歧义”可重现:订单-0012 → 0012、订单-0081 → 0081 同时支持“末尾四位”和“最后一个连字符后的完整编号”。订单-123456 能区分它们。补充该行正确输出再搜索。此交互是已有 PBE 技术的应用,不是算法首创声明。

    #已实现功能

    • MoonBit 原生有限表达式解释器、输出引导的程序搜索、稳定候选排名。
    • 多输入列、多个独立输出字段;字段、常量、分隔词、ASCII 连续段、Unicode 字符区间、trim、ASCII 大小写、拼接、五种显式公历日期格式。
    • 实际输入行上的候选分歧(包含失败预测),提示补充有区分力的样例。
    • 版本化 JSON 配方;按列名绑定新数据,列顺序变化不影响已保存规则。
    • 严格 CSV/JSONL 导入;保留前导零;批处理按行报告错误;失败时停止 CSV 导出。
    • 独立中文工作台:文件导入、样例编辑、多字段配方、预览、下载、Worker 取消、手机布局。运行期间无外部数据请求。
    • CLI 和公开 Mooncakes 库接口。实际验证与限制见 VALIDATION.md。

    #三个完整使用场景

    使用者与问题输入与操作输出与验证
    小商家/运营整理供应商复合编码examples/products/input.csv;提供两个型号/颜色样例,分别选择规则型号 0012、123456 等保留前导零,颜色转大写;另外两行不参与训练,逐值检查
    活动组织者生成名单标签examples/labels/input.csv;用姓名、班级示范 A1 / 陈雨,另外复制编号字段新行生成 C20 / 赵晨,编号不变;测试重排列后重用配方仍一致
    内容创作者整理音视频文件examples/media/input.csv;标注两个日期和 take 编号未见的 20240229 正确变为 2024-02-29;invalid.csv 中 20260229 报错并停止 CSV 导出

    这些是构造的演示数据,并非已获客户采用的证明。可复现实验:

    node scripts/integration.mjs

    它验证三个场景与额外歧义演示、留出行、配方往返、列名重绑定、CLI 全流程、150 组 CSV 往返,以及 10000 行批处理,并写入 artifacts/integration-results.json。

    #CLI

    node bin/exampleloom.mjs learn --data examples/products/input.csv --examples examples/products/model-labels.json --out candidates.json node bin/exampleloom.mjs recipe --report candidates.json --choose 0 --name model --out product.recipe.json node bin/exampleloom.mjs apply --data examples/products/input.csv --recipe product.recipe.json --out product.result.csv

    候选编号从 0 开始,选择需要显式 --choose。检查报告中的其他候选与分歧后再选择;排名不表示正确率。标签文件为 [{"row":0,"output":"0012"}, ...],行号不计表头。JSONL 可加 --format jsonl。run request.json 支持完整 JSON 协议。

    #MoonBit 库

    安装发布模块后在 moon.pkg 中导入 "zhangbowen2006/exampleloom" @loom。完整可运行调用见 cmd/demo/main.mbt。

    let report = @loom.synthesize([
    { input: ["订单-0012"], output: "0012" },
    { input: ["订单-123456"], output: "123456" },
    ])
    // 先检查 report.truncated、候选表达式和 disagreements,再选择。
    let output = @loom.evaluate(report.candidates[0].expression, ["订单-00987"])

    API 通过 LoomError 报告普通输入错误;调用者需要处理异常和空候选数组。attempt 返回值形式的错误。pkg.generated.mbti 是生成的公开接口。

    #边界与可靠性

    **这是有界的字符串程序合成器。**不支持任意自然语言任务、表格连接/重排、条件分支、循环、完整正则上下文或所有 Unicode 大小写规则。训练样例一致不保证未见数据正确;truncated=true 表示候选不完整。观察到的搜索语法依赖首个样例。

    默认最多 32 个样例、16 输入列、每个样例字段 128 字符、64 候选、6 个拼接片段。整表最多 20000 行、64 列;歧义检查最多前 5000 行。ASCII 词类与大小写有明确限制;日期必须指定格式,不能猜月日。全部预算、状态含义及算法见 ARCHITECTURE.md。

    #工程验证

    moon fmt --check moon check --deny-warn --target all moon test --deny-warn --target wasm-gc moon test --deny-warn --target js moon test --deny-warn --target wasm moon info

    原生后端另需 C 编译器;Windows 需要 MSVC C++ 工具与 SDK。CI 在 Linux 同时测试 native。可选浏览器回归:安装 Playwright 1.62.1 和 Chromium,启动本地服务后运行 node scripts/browser-test.mjs;它生成桌面/手机截图和 JSON 证据。也支持通过 PLAYWRIGHT_MODULE / BROWSER_EXECUTABLE 指定已安装环境。

    #来源与维护

    MIT 开源。仅依赖工具链 moonbitlang/core(Apache-2.0);浏览器回归使用 Playwright(Apache-2.0,开发期依赖)。交付的静态 JS 包含编译的 core 代码,分发其许可证与版权声明。

    该项目由维护者在 AI 辅助下从新目录实现,没有复制旧项目业务代码。算法思想参考既有 PBE 研究;明确对比 Flash Fill、PROSE、Foofah、MoonFrame 和 moon-databridge,见 调研与来源。不声称全球唯一,也不保证通过竞赛审核或获奖。

    后续优先扩大独立验证数据与真实使用反馈、减少搜索截断、提升候选多样性。欢迎附上最小输入/输出样例、期望结果、工具链版本和复现步骤提交 issue;请移除私人数据。

    LoomError

    pub(all) suberror LoomError {
    LoomError(String)
    } derive(Eq,
    Debug
    )

    LoomError::equal

    fn LoomError::equal(LoomError, LoomError) -> Bool

    LoomError::not_equal

    fn LoomError::not_equal(x : LoomError, y : LoomError) -> Bool

    BatchResult

    pub(all) struct BatchResult {
    rows : Array[Result[Array[String], String]]
    failures : Int
    }

    Candidate

    pub(all) struct Candidate {
    expression : Expr
    cost : Int
    }

    Disagreement

    pub(all) struct Disagreement {
    row_index : Int
    groups : Array[PredictionGroup]
    score : Int
    }

    Example

    pub(all) struct Example {
    input : Array[String]
    output : String
    } derive(Eq,
    Debug
    )

    Example::equal

    fn Example::equal(Example, Example) -> Bool

    Example::not_equal

    fn Example::not_equal(x : Example, y : Example) -> Bool

    Example::to_repr

    Expr

    pub(all) enum Expr {
    Field(Int)
    Literal(String)
    Slice(Expr, Position, Position)
    Token(Expr, String, Int)
    Run(Expr, RunKind, Int)
    Trim(Expr)
    Lower(Expr)
    Upper(Expr)
    Concat(Array[Expr])
    DateText(Expr, String, String)
    } derive(Eq,
    Debug
    )

    Pure, finite-data expressions. No eval, I/O, regex execution or host calls.

    Expr::equal

    fn Expr::equal(Expr, Expr) -> Bool

    Expr::not_equal

    fn Expr::not_equal(x : Expr, y : Expr) -> Bool

    Expr::to_repr

    OutputField

    pub(all) struct OutputField {
    name : String
    expression : Expr
    }

    Position

    pub(all) enum Position {
    Start(Int)
    End(Int)
    } derive(Eq,
    Debug
    )

    A position counts Unicode scalar values, not UTF-16 units or graphemes.

    Position::equal

    fn Position::equal(Position, Position) -> Bool

    Position::not_equal

    fn Position::not_equal(x : Position, y : Position) -> Bool

    Position::to_repr

    PredictionGroup

    pub(all) struct PredictionGroup {
    prediction : Result[String, String]
    candidates : Array[Int]
    }

    Recipe

    pub(all) struct Recipe {
    columns : Array[String]
    outputs : Array[OutputField]
    }

    RunKind

    pub(all) enum RunKind {
    Digits
    Letters
    } derive(Eq,
    Debug
    )

    ASCII run classes are deliberate; non-ASCII letters are not folded.

    RunKind::equal

    fn RunKind::equal(RunKind, RunKind) -> Bool

    RunKind::not_equal

    fn RunKind::not_equal(x : RunKind, y : RunKind) -> Bool

    RunKind::to_repr

    SearchOptions

    pub(all) struct SearchOptions {
    max_candidates : Int
    max_parts : Int
    max_atom_evaluations : Int
    max_steps : Int
    max_frontier : Int
    }

    All limits are deterministic. Hitting a resource limit is reported, never interpreted as proof that the retained program is unique.

    SearchReport

    pub(all) struct SearchReport {
    candidates : Array[Candidate]
    status : String
    truncated : Bool
    atom_evaluations : Int
    atoms : Int
    steps : Int
    }

    Table

    pub(all) struct Table {
    columns : Array[String]
    rows : Array[Array[String]]
    } derive(Eq,
    Debug
    )

    Table::equal

    fn Table::equal(Table, Table) -> Bool

    Table::not_equal

    fn Table::not_equal(x : Table, y : Table) -> Bool

    Table::to_repr

    apply_recipe

    fn apply_recipe(recipe : Recipe, table : Table) -> BatchResult raise LoomError

    Bind saved input column names to each new table. Column reordering is safe; missing required names fail the batch, and individual row failures persist.

    attempt

    fn attempt(expr : Expr, row : Array[String]) -> Result[String, String]

    Convert a typed evaluation failure to a value for batch processing.

    convert_date

    fn convert_date(text : String, source : String, target : String) -> String raise LoomError

    Calendar validation is Gregorian and rejects impossible or ambiguous formats.

    date_formats

    fn date_formats() -> Array[String]

    Accepted date formats have an explicit day/month order and four-digit years.

    default_options

    fn default_options() -> SearchOptions

    disagreements

    fn disagreements(candidates : Array[Candidate], rows : Array[Array[String]], limit? : Int) -> Array[Disagreement] raise LoomError

    Find actual rows on which retained candidates disagree. Consensus means agreement among this finite set, never correctness outside the examples.

    evaluate

    fn evaluate(expr : Expr, row : Array[String]) -> String raise LoomError

    Evaluate one row. A malformed selector fails instead of silently padding.

    explain

    fn explain(expr : Expr) -> String

    A stable readable description; it is not executable host code.

    expression_from_json

    fn expression_from_json(value : Json) -> Expr raise LoomError

    Stable version-1 AST data. This parser never evaluates host code.

    expression_to_json

    fn expression_to_json(e : Expr) -> Json raise LoomError

    handle

    fn handle(request : String) -> String

    Single JSON boundary shared by the Node CLI and browser worker. All data parsing, search, recipe validation and transformation execute in MoonBit.

    parse_csv

    fn parse_csv(source : String) -> Table raise LoomError

    Strict comma CSV with headers, doubled quotes, quoted newlines and optional BOM.

    parse_jsonl

    fn parse_jsonl(source : String) -> Table raise LoomError

    JSONL accepts string/null-valued objects. Numbers are rejected to avoid rounding identifiers and losing leading zeros. Null is explicitly empty.

    recipe_from_json

    fn recipe_from_json(value : Json) -> Recipe raise LoomError

    recipe_to_json

    fn recipe_to_json(recipe : Recipe) -> Json raise LoomError

    render_csv

    fn render_csv(table : Table, spreadsheet_safe? : Bool) -> String raise LoomError

    Spreadsheet-safe output prefixes formula-like cells with an apostrophe. Disable only when exact machine-readable round trips are intended.

    synthesize

    fn synthesize(examples : Array[Example], options? : SearchOptions) -> SearchReport raise LoomError

    Enumerate a ranked subset of programs consistent with every example. Ranking is a simplicity preference, never a statistical confidence score.

    validate_table

    fn validate_table(table : Table) -> Unit raise LoomError

    Reject ragged rows rather than shifting or guessing column alignment.

    Powered by MoonBit

    Site sourceReport issueModulesSkillsBuild queueStatistics

    © 2026 mooncakes.io