moonbit_codegen

    Reusable MoonBit code-generation library: naming, a backend-neutral source model, AST building, formatting and manifest emission.

    codegen
    moonbit
    ast
    formatter
    Download zip
    Author
    Version
    0.1.0
    License
    Apache-2.0
    Last updated
    8 hours ago
    Downloads
    9

    #moonbit_codegen

    Reusable MoonBit code-generation library: identifier naming, a backend-neutral source model, AST building over moonbitlang/parser, canonical rendering, and moon.mod / moon.pkg / moon.work manifest emission.

    Pure MoonBit — compiles and runs across native, js, wasm, and wasm-gc.

    #Install

    moon add vigoo/moonbit_codegen

    #Packages

    PackagePurpose
    nameWord splitting, case conversion (to_pascal/to_snake/…), keyword escaping, scoped unique-name allocation.
    docBackend-neutral model: SourceFile, Item, declarations, doc comments, attributes, TypeExpr.
    astdoc model → moonbitlang/parser syntax nodes (including raw-body parsing).
    fmtRendering: one canonical formatter pass; raw-text route; is_formatted.
    projectImportSet (alias-collision detection) and canonical manifest emission.

    The root package re-exports render_file, format_source and Namer.

    #Naming

    ///|
    test "naming" {
    inspect(@name.to_snake("Idempotency-Key"), content="idempotency_key")
    inspect(@name.to_pascal("OAuth2Provider"), content="OAuth2Provider")
    inspect(@name.ident_snake("type"), content="type_")
    inspect(
    @name.split_words("r#CreateParams").join(","),
    content="Create,Params",
    )
    let namer = @name.Namer::new()
    inspect(namer.unique("field"), content="field")
    inspect(namer.unique("field"), content="field2")
    }

    #Building and rendering source

    Describe code with the doc model, render through fmt:

    ///|
    test "render a struct" {
    let file = @doc.SourceFile::new()
    file.push(
    @doc.struct_item(@doc.DocComment::new(["A point in 2D space."]), {
    name: "Point",
    type_params: [],
    vis: @doc.PubAll,
    fields: [
    {
    name: "x",
    ty: @doc.Name("Int32"),
    mut_: false,
    vis: @doc.Private,
    doc: @doc.DocComment::empty(),
    attrs: [],
    },
    {
    name: "y",
    ty: @doc.Name("Int32"),
    mut_: false,
    vis: @doc.Private,
    doc: @doc.DocComment::empty(),
    attrs: [],
    },
    ],
    derives: ["Debug", "Eq"],
    }),
    )
    inspect(
    @fmt.render_file(file),
    content=(
    #|///|
    #|/// A point in 2D space.
    #|#derive(Debug, Eq)
    #|pub(all) struct Point {
    #| x : Int32
    #| y : Int32
    #|}
    #|
    ),
    )
    }

    Function bodies are raw MoonBit source — the renderer parses them into the AST so they format canonically:

    ///|
    test "function with a raw body" {
    let file = @doc.SourceFile::new()
    file.push(
    @doc.item(
    @doc.DocComment::empty(),
    @doc.Decl::Fn({
    self_type: None,
    name: "twice",
    type_params: [],
    params: [@doc.FnParam::positional("value", @doc.Name("Int32"))],
    return_type: Some(@doc.Name("Int32")),
    is_async: false,
    error: @doc.NoRaise,
    vis: @doc.Pub,
    body: "value * 2",
    }),
    ),
    )
    inspect(
    @fmt.render_file(file),
    content=(
    #|///|
    #|pub fn twice(value : Int32) -> Int32 {
    #| value * 2
    #|}
    #|
    ),
    )
    }

    #Manifests

    ///|
    test "emit a moon.mod" {
    let deps = @project.ImportSet::new()
    deps.add_dependency("moonbitlang/parser@0.4.9")
    let moon_mod : @project.MoonMod = {
    header: [],
    name: "vigoo/sample",
    version: "0.1.0",
    readme: None,
    repository: None,
    license: Some("Apache-2.0"),
    keywords: [],
    description: None,
    preferred_target: Some("native"),
    is_private: false,
    deps,
    }
    inspect(
    moon_mod.emit(),
    content=(
    #|name = "vigoo/sample"
    #|
    #|version = "0.1.0"
    #|
    #|license = "Apache-2.0"
    #|
    #|keywords = []
    #|
    #|preferred_target = "native"
    #|
    #|import {
    #| "moonbitlang/parser@0.4.9",
    #|}
    #|
    ),
    )
    }

    Emit package (moon.pkg) and workspace (moon.work) manifests with alias-collision detection:

    ///|
    test "emit moon.pkg and moon.work" {
    let pkg = @project.MoonPkg::new()
    pkg.imports.add("moonbitlang/core/json", as_="cjson")
    inspect(
    pkg.emit(),
    content=(
    #|import {
    #| "moonbitlang/core/json" @cjson,
    #|}
    #|
    ),
    )
    let work = @project.MoonWork::new(["./runtime", "./client"])
    inspect(
    work.emit(),
    content=(
    #|members = [
    #| "./runtime",
    #| "./client",
    #|]
    #|
    ),
    )
    }

    #Formatting contract

    fmt.render_file renders @doc.SourceFile through moonbitlang/parser/fmt and repairs the upstream single-parameter arrow trailing-comma bug using token spans from moonbitlang/lexer. fmt.format_source validates syntax via @ast.parse_source and formats via @moonfmt.format (preserving // comments). Because moonbitlang/parser/fmt has minor spacing differences from the standalone moonfmt binary on a few constructs (e.g. generic trait bounds), run moon fmt when strict binary-formatter parity is required. Byte stability and parse validity are enforced by goldentest/ plus scripts/golden_check.sh.

    #Development

    moon check --target native # this module is pure — any target works moon test --target native ./scripts/golden_check.sh # from repo root: golden + binary moonfmt gate

    Namer

    Re-exported scoped identifier allocator from vigoo/moonbit_codegen/name.

    format_source

    fn format_source(src : String) -> String raise
    CodegenError

    Format valid MoonBit source, preserving // comments via @moonfmt.format. Raises CodegenError if src does not parse cleanly.

    render_file

    Render a @doc.SourceFile to formatted MoonBit source text via the AST pipeline (@ast.file_to_impls + @moonfmt).

    Source Files