MoonFrame

    A lightweight DataFrame and tabular-data library for MoonBit

    dataframe
    data-analysis
    csv
    tabular
    Download zip
    Author
    Version
    0.5.3
    License
    Apache-2.0
    Last updated
    4 months ago
    Downloads
    305

    #MoonFrame

    A small, friendly DataFrame library for MoonBit. Read a CSV, reshape it with a few chained methods, and print or export the result. If you have used pandas or polars, the shape of the API will feel familiar:

    // API shape (illustrative; see "Quick start" below for a runnable,
    // `@moonframe`-prefixed version)
    read_csv("sales.csv")
    .filter(col("product").eq(lit_str("widget")))
    .group_by([col("region")])
    .agg([col("revenue").sum()])
    .to_markdown()

    It covers CSV / JSON / NDJSON I/O, filtering, sorting, null handling, group-by, joins, summary statistics, a composable expression engine, and a lazy query layer, and exports to Markdown, HTML, JSON, NDJSON, and Vega-Lite charts — a focused foundation for everyday tabular work, not a full pandas clone.

    #Install

    MoonFrame is published on mooncakes.io. Add it to your module's dependencies:

    moon add ihb2032/MoonFrame

    Then import it (with the @moonframe alias) in the moon.pkg.json of the package that uses it:

    { "import": [ { "path": "ihb2032/MoonFrame", "alias": "moonframe" } ] }

    Now @moonframe.read_csv, the DataFrame / Series types, and every operator method are available in that package.

    The moon.pkg.json snippet above uses the JSON manifest form. MoonBit also accepts the newer moon.mod / moon.pkg files (which is what this repository itself uses); the two forms are equivalent.

    #Quick start

    Suppose you have a sales.csv:

    region,product,revenue,quantity west,widget,100,10 east,gadget,50,5 west,gadget,70,7 east,widget,30,3 north,widget,40,4 north,gadget,60,6 west,gizmo,90,9 east,gizmo,20,2

    Keep the widget rows, pick a few columns, and sort by quantity:

    fn widgets(path : String) -> String raise @moonframe.DataError {
    @moonframe.read_csv(path)
    .filter(@moonframe.col("product").eq(@moonframe.lit_str("widget")))
    .select(@moonframe.cols(["region", "revenue", "quantity"]))
    .sort([
    (
    @moonframe.col("quantity"),
    @moonframe.SortOrder::Desc,
    @moonframe.NullOrder::NullsLast,
    ),
    ])
    .to_markdown()
    }

    widgets("sales.csv") returns a ready-to-print table:

    | region | revenue | quantity | | ------ | ------- | -------- | | west | 100 | 10 | | north | 40 | 4 | | east | 30 | 3 |

    Every transformation is a method on DataFrame, so pipelines read top-to-bottom; anything that can fail raises DataError rather than crashing (see Error handling). For a fuller tour — group-by, joins, round-trips — see quickstart.mbt.md, whose snippets all run as doc tests on every backend.

    #What you can do

    • Read & write CSV, JSON, and NDJSON — read_csv / read_json / read_ndjson and their write_* counterparts, with tunable type inference.
    • Reshape — filter, select, drop, rename, with_columns, multi-key sort, row dedup (unique), and null handling (drop_nulls, fill_null).
    • Group & aggregate — group_by(keys).agg([...]) with sum / mean / min / max / count / std / variance / median / n_unique / first / last.
    • Express — composable column expressions (col("revenue") - col("cost"), & / | logic, when / then / otherwise, a str_* string namespace) feed with_columns / filter / agg, including compound reductions like (col("revenue") - col("cost")).sum(); map_elements / map_many drop to a host closure for anything past the built-in algebra.
    • Defer & optimize — lazy_frame(df), or scan_csv / scan_ndjson for a lazy file source, builds a query plan you can explain(); collect() runs it through a predicate- and projection-pushdown optimizer, bitwise-equal to the eager pipeline (and a file scan only parses the columns the plan reads).
    • Join — the full inner / left / right / outer / cross matrix on expression keys, e.g. orders.join(customers, JoinOptions::on([col("customer_id")])) (or left_on / right_on for differently-named or derived keys).
    • Summarize — describe() for a per-column summary, or single statistics (sum / mean / min / max / …).
    • Export — to_markdown(), to_html(), format_json_records, format_ndjson, and format_vega_lite (a Vega-Lite v5 chart spec).

    For example, summarise the same data by region:

    let summary = @moonframe.read_csv("sales.csv")
    .group_by([@moonframe.col("region")])
    .agg([
    @moonframe.col("revenue").sum().with_alias("revenue"),
    @moonframe.col("quantity").sum().with_alias("quantity"),
    ])

    summary.to_markdown() renders a pipe table:

    | region | revenue | quantity | | ------ | ------- | -------- | | west | 260 | 26 | | east | 100 | 10 | | north | 100 | 10 |

    The same frame also exports as a styled HTML <table> via summary.to_html_with_options(...), or as a Vega-Lite v5 chart spec via format_vega_lite(summary, ChartSpec::bar("region", "revenue")) — ready to paste into the Vega editor.

    #Error handling

    Anything that can fail on bad input or I/O raises DataError; the library never aborts your program on a recoverable error. Call such functions inside a raise context (as the examples above do), or bridge back to a Result with a catch that re-wraps the error:

    let result : Result[String, @moonframe.DataError] = Ok(widgets("sales.csv")) catch {
    e => Err(e)
    }

    Operations that are provably total (head, to_markdown, …) just return their value. DataError is a pub(all) suberror, so you can match its variants (ColumnNotFound, ParseError, …) on the Err. The full model is in docs/api.md.

    #Documentation

    Four runnable end-to-end programs live in examples/:

    moon run examples/sales_analysis # filter → select → sort → describe → markdown moon run examples/data_cleaning # drop_nulls → fill_null → CSV round-trip moon run examples/reporting # group_by → to_html + Vega-Lite spec moon run examples/expressions # with_columns → filter → agg → lazy + explain

    #Status

    v0.5 — shipped: the eager and lazy surfaces converge onto a single, Polars-shaped expression engine. The four verbs (select / filter / agg / with_columns) and the sort / group_by / join / drop keys all take Exprs; the per-type *_join methods collapse into one join; the rich RowView gives way to df.row(i) / rows(); Series moves into its own package; and the vocabulary widens — std / variance / median / n_unique / first / last aggregations, a str_* string namespace, fill_null on the expression layer, lazy scan_csv / scan_ndjson sources, and df.unique(). This is the last breaking release — from v0.6 on the surface only grows. Next (v0.6, additive): more expression families (arithmetic like pow / floor_div, more string ops), predicate pushdown and streaming for lazy file scans, and unique subset / keep options. See the changelog for the full version history and docs/migration.md for upgrade steps.

    #Design notes

    MoonFrame's API and column semantics are modeled on Polars — see docs/comparison.md for the full alignment and the one deliberate difference, and docs/performance.md for the columnar layout and per-operation complexity. A few things that surprise newcomers:

    • / is always Float (integer operands promote); dividing by zero gives IEEE ±inf / NaN, never a trap.
    • null and NaN are different. null is missing and propagates; NaN is a value (sum / mean propagate it, min / max skip it) — except in sort, which orders NaN as missing.
    • Comparisons are methods (col("a").gt(lit_int(0))), not >, and & / | are Kleene-logical, not bitwise — both are MoonBit constraints.

    #Contributing

    The codebase is a small, layered stack of packages; each has its own sources, blackbox *_test.mbt tests, and a pkg.generated.mbti interface snapshot:

    types/ value types, errors (DataError), schemas column/ Arrow-style storage — validity Bitmap, BuiltinColumn, Numeric fast path, ColumnStorage seam series/ Series + column-level stats + the shared reduction / rebuild / key-cell kernels expr/ composable column expressions — Expr AST, operators / methods, when/then/otherwise, explain frame/ DataFrame + every operator (one per file) + group_by + join + the expression evaluator (with_columns / select / filter / agg) + to_markdown / to_html io/ CSV (NyaCSV-backed), JSON, NDJSON read / write + Vega-Lite export lazy/ deferred query plan — LazyFrame builders, collect / explain, predicate + projection pushdown moonframe/ facade — re-exports the whole public API

    The data model is an Apache Arrow-style column layout (a byte-packed validity bitmap, 1 = valid) with an O(1) name→index cache; DataFrame::check_invariants() is a formal structural spec (INV1–INV7) asserted by every operator test. The usual loop:

    moon check # type-check the workspace moon test # run all tests (add --target all for every backend) moon fmt # format sources moon info # regenerate .mbti interface snapshots

    Contributions keep 100% line coverage and a warning-free moon check.

    #Dependencies

    #Acknowledgements

    MoonFrame is an original MoonBit implementation whose API and semantics are modeled on Polars (MIT) — the primary reference — with a few I/O conventions from pandas (BSD-3-Clause). No Polars or pandas source was translated; see docs/comparison.md for what is aligned, what deliberately differs, and what is out of scope.

    #License

    Apache-2.0 — see LICENSE.

    Bitmap

    The low-level Arrow-storage types are surfaced too, for callers that reach the storage seam (Series::storage / hand-built columns): Bitmap / BuiltinColumn / NumericColumn / ColumnData / NumericData / ColumnStorage / StorageKind.

    BuiltinColumn

    The low-level Arrow-storage types are surfaced too, for callers that reach the storage seam (Series::storage / hand-built columns): Bitmap / BuiltinColumn / NumericColumn / ColumnData / NumericData / ColumnStorage / StorageKind.

    ChartKind

    The mark type of a chart, mapped to a Vega-Lite top-level mark: Bar → "bar", Line → "line", Point → "point", Area → "area". pub(all) so callers can name the variants when building a ChartSpec (though the ChartSpec::bar / line / point / area constructors set the kind for you).

    ChartSpec

    A chart specification: the mark kind, the x / y encoding columns, an optional color grouping column, and an optional title. Fields are read-only outside the package — build a spec through one of the mark-named constructors (ChartSpec::bar(x, y) / line / point / area) and chain with_color(column) / with_title(text):

    ChartSpec::bar("region", "revenue").with_title("Revenue by region")

    x / y / color are column names resolved against the frame at format_vega_lite time (a missing name raises ColumnNotFound); each column's dtype decides its Vega-Lite field type (numeric → quantitative, otherwise → nominal), unless color_type overrides the color channel — e.g. a numeric grouping column (a cluster id) rendered as Nominal distinct colors rather than a continuous gradient.

    ColumnData

    The low-level Arrow-storage types are surfaced too, for callers that reach the storage seam (Series::storage / hand-built columns): Bitmap / BuiltinColumn / NumericColumn / ColumnData / NumericData / ColumnStorage / StorageKind.

    ColumnStorage

    The low-level Arrow-storage types are surfaced too, for callers that reach the storage seam (Series::storage / hand-built columns): Bitmap / BuiltinColumn / NumericColumn / ColumnData / NumericData / ColumnStorage / StorageKind.

    CsvReadOptions

    Options that control how a CSV input is parsed into a DataFrame.

    • has_header — when true, the first row supplies column names. When false, every row is treated as data and column names are synthesised as "column1", "column2", … in declaration order; the first data row fixes the column count, so a later wider row's trailing cells are dropped under the lenient default (set strict_column_count = true to reject a ragged row instead).
    • delimiter — field separator passed through to NyaCSV.
    • infer_schema_rows — number of leading rows scanned when guessing each column's dtype. 0 (or any value <= 0) lifts the cap and scans every row (Polars' infer_schema_length=None), trading a slower inference pass for never mis-guessing a column from a prefix. Cells past a finite window are still parsed under the chosen dtype; one that doesn't fit is handled per on_parse_error.
    • null_values — raw strings that should be treated as null cells (both for type inference, which skips them, and for the final typed column, where they become None). The default [""] matches the empty string only, which is how an absent CSV cell is typically represented.
    • strict_column_count — when true, every data row must have exactly as many cells as the header declares; a ragged row (too few or too many cells) raise ParseError instead of being silently null-padded (short row) or truncated (long row). Defaults to false, preserving the lenient behaviour that tolerates ragged rows (a permissive CSV idiom, and what the v0.1 reader did).
    • on_parse_error — what to do when a non-null cell past the inference window fails to parse under its column's locked-in dtype. Raise (default) fails the whole read with ParseError; Null downgrades the offending cell to a null cell and keeps the column's inferred dtype (Polars' ignore_errors=True). See OnParseError.
    • allow_nonfinite_floats — when true (default), the float probe accepts the nan / inf / infinity literals @string.parse_double recognises, so a column of those tokens infers as Float. When false, the probe rejects them, so such a column falls back to String instead of being silently retyped to Float (a non-finite token past the window is then a parse failure handled per on_parse_error).

    CsvWriteOptions

    Options that control how a DataFrame is rendered as CSV text.

    • header — when true, the first emitted row is the column names; when false, only data rows are written.
    • delimiter — field separator written between cells.
    • null_value — the literal string written in place of a null cell. The default empty string round-trips with the reader's default null_values.

    DataError

    Unified error type for all MoonFrame operations.

    DataFrame

    A column-oriented, schema-aware table. DataFrame owns an ordered list of equally-tall Series, a derived Schema, and a private name_to_index cache so column lookup by name is O(1).

    The struct is pub (fields read-only outside the package — no reassignment), so frames are only ever built through the constructors below, which rebuild the cache and the schema in lock-step with the column vector. The containers read from the fields (columns, name_to_index) are the live objects, though: treat them as read-only — interior mutation bypasses the constructors and corrupts the frame (prefer the columns() / column_series() / schema() accessors, which return copies). The preserved invariants:
    • schema.field_names() == columns.map(.name)
    • columns.all(c => c.len() == nrows)
    • name_to_index[name] == i ⇔ columns[i].name == name

    DataType

    Logical data type for a column.

    Null represents a column that carries no inferred type (e.g. an all-null CSV column where inference could not promote it to anything more specific). Concrete columns always carry one of the other variants.

    Expr

    A composable, introspectable column expression tree — the reified upgrade over the closure-based surfaces (the v0.1 row-predicate closure) and pre-materialised Series columns. An Expr is data: the evaluator in frame pattern-matches it, and the v0.4 lazy layer will print and rewrite it — none of which a closure can offer.

    The enum is pub (read-only): other packages — including frame, whose evaluator matches the tree cross-package — can inspect it but cannot construct variants ([4036]). The only way to build an Expr is the constructor functions (col / lit / lit_* / when), the operator impls and the methods in expr_ops.mbt, so every tree is well-formed by construction. Building an expression is total — unknown columns and dtype mismatches surface at evaluation time (in frame), never here.

    Variant tour (construction route in parentheses):
    • Col / Lit / LitSeries — leaves (col, lit / lit_*, lit_series). LitSeries embeds a whole pre-materialised @series.Series as a literal column: at evaluation it is used as-is, broadcasting when length 1 and otherwise matching the frame height (LengthMismatch on any other length). It is named after the series it carries, so its output column keeps the series' name unless an alias overrides it;
    • Binary — arithmetic + - * /, comparisons eq/ne/lt/le/gt/ge, Kleene logic &/| (also .land()/.lor() — and/or are reserved words);
    • Unary — -e, .not(), .is_null(), .is_not_null(), .is_nan(), .is_not_nan();
    • Agg — .sum()/.mean()/.min()/.max()/.count(), reducing its operand to a single value per evaluation scope;
    • Str — the string namespace (.str_to_uppercase() / .str_contains(p) / …), mapping each cell of its String operand through a StrOp transform;
    • Cast — .cast(dtype);
    • Alias — .with_alias(name) (alias is a reserved word), naming the result column;
    • Ternary — when(cond).then(a).otherwise(b);
    • FillNull / FillNan — .fill_null(value) / .fill_nan(value), carrying (operand, value). Semantically these are the guarded ternaries when(operand.is_not_null()).then(operand).otherwise(value) (resp. is_not_nan), but as dedicated nodes the operand appears — and is evaluated, rendered, and compared — once: the ternary lowering embedded self twice, so a chained coalesce (e.fill_null(a).fill_null(b)…) built an exponentially-sized tree;
    • Map — the closure escape hatch (.map_elements() / map_many()), applying an opaque host function row by row over its input columns. It carries a label (for Show / explain), the input expressions, and the function (Array[Scalar]) -> Scalar raise. The closure makes the variant un-derive-able, so Expr hand-writes Eq (below), @debug.Debug and Show (in explain.mbt), each treating the function as opaque — a Map is identified by its (label, inputs).

    Field

    Column metadata: a name, the column's logical DataType, and a declared nullable flag.

    nullable = false is a declared constraint that DataFrame::from_rows enforces: row data placing a Scalar::Null in such a column raises NullInNonNullable(name). (DataFrame::empty builds 0-row columns, so it can never violate the constraint.) The flag is otherwise advisory — it is neither inferred from a column's contents nor propagated across operations: Field::new (and so DataFrame::new, the IO readers, and the ops that rebuild through them) always sets nullable = true, so a nullable = false field only ever originates from an explicit Field::with_nullable(..., false) in a caller-supplied schema.

    GroupedDataFrame

    A DataFrame partitioned into groups by one or more key expressions, produced by DataFrame::group_by and consumed by agg. Fields are read-only outside the package (no reassignment); the only way to build one is group_by, which guarantees every stored row index is in [0, source.nrows()) and every group is non-empty. Note that the Array values read from the fields are the live objects — treat them as read-only; a handle whose groups were mutated out of those invariants is rejected by agg with InvalidOperation rather than honoured.

    • source — the frame being grouped (its columns back every aggregation).
    • key_columns — the materialised key columns, one per key expression in the order passed to group_by, each already named by the expression's output name (alias, else leftmost column reference, else "literal") and carrying its evaluated dtype and backend. They head the agg output in this order; agg gathers one representative cell per group from them.
    • groups — one entry per distinct key tuple, in first-appearance order, each holding that group's row indices in ascending row order.

    HtmlOptions

    Options for DataFrame::to_html_with_options. Fields are read-only outside the package — build them through HtmlOptions::default() and chain the with_* setters:

    • max_rows — cap the number of data rows. None (the default) renders every row; Some(n) shows the first n and appends a <tfoot> banner (... (K more rows)) for the remainder. A negative n clamps to 0 (header + banner, no data rows), matching to_markdown_with_limit.
    • table_class — value of the <table class="..."> attribute. None (the default) omits the attribute.
    • caption — text of a leading <caption> element. None (the default) omits it.
    • escape — when true (the default) every emitted string — caption, header names, cell values, and the class attribute — has & / < / > / " / ' rewritten to their HTML entities, so untrusted data can't inject markup. Set false (via with_escape) to pass strings through verbatim for trusted input that intentionally carries HTML.

    JoinOptions

    The knobs for DataFrame::join: which columns to match on, the join how, the suffix disambiguating a right column whose name collides with a left one, and whether to coalesce the key columns. Fields are read-only outside the package — build options through JoinOptions::on / JoinOptions::left_on / JoinOptions::cross and (optionally) chain with_right_on / with_how / with_suffix / with_coalesce.

    • on — the key expressions, evaluated over both frames (Polars' IntoExpr). A bare col("id") matches on an existing column; a derived key such as col("ts") / lit_int(86400) matches on the computed value. ["region", "product"]-style multi-key joins become [col("region"), col("product")], matched on the tuple. An empty list is a documented cross join (see DataFrame::join).
    • left_on / right_on — paired key expressions evaluated on the left and right frame respectively, for joining on differently-named or differently-derived keys (left_on([col("a")]) against right_on([col("b")])). Mutually exclusive with on, and the two lists must name the same number of keys; key i on the left is matched against key i on the right.
    • how — Inner (the on / left_on default), Left, Right, Outer, or Cross.
    • suffix — appended to a right column whose name also occurs in the left frame (default "_right"); the left column keeps its name.
    • coalesce — whether each key column is merged into a single output column. None (the default) auto-selects by how, matching Polars: an inner / left / right join coalesces (the key appears once), while Outer does not (the right key is kept as <key><suffix>, null wherever its row had no match, so matched and unmatched rows are distinguishable). Some(true) always coalesces; Some(false) never does. Coalescing only applies when keying by on whose every key is a bare col(...) (the precondition for the key to name a single column on both sides); left_on / right_on and any derived key turn it off, keeping both key columns (Polars' "join on a non-column expression turns off coalescing"). When coalesced the single key takes its value from whichever side is present on that row (the two are equal on a matched pair) — the left on Inner / Left, the right on Right, and the present side per row on Outer.

    JoinType

    How an equi-join combines rows that share (or fail to share) a key.

    pub(all) so callers can name the variants directly (e.g. JoinOptions::on(keys).with_how(Left)), matching SortOrder / NullOrder:
    • Inner — keep only rows whose key matches on both sides.
    • Left — keep every left row; where it has no right match, the right-hand columns are filled with nulls.
    • Right — the mirror of Left: keep every right row; where it has no left match, the left-hand columns are filled with nulls. The output still leads with the left columns (only the row set changes to "all right rows").
    • Outer — the full outer join: keep matched pairs plus every unmatched row from both sides (the missing side's columns null). Left rows (matched and unmatched) come first in left order, then the unmatched right rows in right order.
    • Cross — the Cartesian product (every left row paired with every right row); takes no key columns.

    JsonReadOptions

    Options that control how a JSON records payload is parsed into a DataFrame.

    • infer_schema_rows — number of leading records inspected when guessing each column's dtype. 0 (or any value <= 0) lifts the cap and scans every record (Polars' infer_schema_length=None). Records past a finite window are still parsed under the chosen dtype; one that doesn't fit is handled per on_parse_error.
    • on_parse_error — what to do when a non-null cell past the inference window fails to parse under its column's locked-in dtype: Raise (default) fails the whole read with ParseError; Null downgrades the offending cell to a null and continues (Polars' ignore_errors=True). See OnParseError.

    LazyFrame

    The public face of the lazy layer: LazyFrame wraps a LogicalPlan and grows it through builder methods that mirror the eager DataFrame verbs name-for-name. Building is total — every builder just wraps the plan in one more node, so a LazyFrame can always be constructed, chained, and explained, even when collecting it would fail. All computation (and all failure) happens in collect, which interprets the plan through the public eager operators: with no optimizer in front, lazy_frame(df).f(…).g(…).collect() is bitwise-equal to df.f(…).g(…) — the faithful-deferred-executor contract every test in lazy_test.mbt pins.

    Every builder that takes an array copies it, so a plan can never observe later mutation of a caller's argument — the immutability the paragraph above promises holds for the arguments too, not just the captured frames.

    The entry point is the static constructor LazyFrame::from(df) with the free-function alias lazy_frame(df) (the read_csv feel) — not a DataFrame method, which would have to live in frame and close a frame ↔ lazy import cycle, and not lazy(df), since lazy is a MoonBit reserved word.

    LazyGroupBy

    A deferred group_by awaiting its aggregations — the lazy mirror of the eager GroupedDataFrame stage in group_by(keys).agg(…), except it holds no groups: just the input plan and the key expressions, which agg completes into a single Aggregate node. Both fields stay private — a LazyGroupBy is only ever the step between LazyFrame::group_by and LazyGroupBy::agg, and sharing one across several agg calls just forks the plan, like every other builder.

    NdjsonReadOptions

    Options that control how an NDJSON payload is parsed into a DataFrame.

    • infer_schema_rows — number of leading records inspected when guessing each column's dtype. 0 (or any value <= 0) lifts the cap and scans every record (Polars' infer_schema_length=None). Records past a finite window are still parsed under the chosen dtype; one that doesn't fit is handled per on_parse_error.
    • on_parse_error — what to do when a non-null cell past the inference window fails to parse under its column's locked-in dtype: Raise (default) fails the whole read with ParseError; Null downgrades the offending cell to a null and continues (Polars' ignore_errors=True). See OnParseError.

    (Same meanings and defaults as JsonReadOptions / the CSV reader — NDJSON keeps its own options type so the two formats can diverge later.)

    NullOrder

    Where missing cells go relative to non-missing ones. Missing means either a Null slot (validity bit 0) or — for Float columns — NaN. The plan specifies that NaN is treated identically to Null for ordering, so callers don't need a separate knob.

    NumericColumn

    The low-level Arrow-storage types are surfaced too, for callers that reach the storage seam (Series::storage / hand-built columns): Bitmap / BuiltinColumn / NumericColumn / ColumnData / NumericData / ColumnStorage / StorageKind.

    NumericData

    The low-level Arrow-storage types are surfaced too, for callers that reach the storage seam (Series::storage / hand-built columns): Bitmap / BuiltinColumn / NumericColumn / ColumnData / NumericData / ColumnStorage / StorageKind.

    OnParseError

    What a reader does when a non-null cell fails to parse under the dtype that inference locked in for its column — in practice a value past the inference window that doesn't fit (e.g. a String in a column inferred Int from its first rows).

    • Raise (every reader's default) — surface the cell's ParseError, failing the whole read. The strict, lossless behaviour: a malformed cell is never silently dropped.
    • Null — downgrade the offending cell to a null cell and keep going, the resilient behaviour Polars exposes as ignore_errors=True (pandas tolerates the same). The column keeps its inferred dtype; only the unparseable cells become null.

    Shared by CsvReadOptions / JsonReadOptions / NdjsonReadOptions and consumed in build_typed_column's parse-failure branch, so the three readers agree on the policy.

    Scalar

    A single cell value in a DataFrame.

    Null represents a missing value. All as_* conversions and comparisons involving Null raise TypeMismatch(...) — callers must check is_null() first or handle the error.

    The Float variant carries a 64-bit Double; the Int variant carries a 64-bit Int64. Use as_float for explicit access; Int is also accepted via numeric promotion to Double.

    Schema

    Ordered list of Fields describing a DataFrame's columns.

    Construction always validates uniqueness of names; once built, a Schema is guaranteed to have no duplicate column names.

    Series

    Series lives in its own @series package (extracted in v0.5 so the expression layer can build on the per-column unit); re-exporting the type carries its constructors (from_ints / …) and methods along, so the facade name @moonframe.Series is unchanged for callers.

    SortOrder

    Direction of a sort key. Asc sorts smaller values first, Desc sorts larger values first. The convention applies to every dtype: Int / Float use numeric ordering, Bool uses false < true, String uses lexicographic comparison.

    StorageKind

    The low-level Arrow-storage types are surfaced too, for callers that reach the storage seam (Series::storage / hand-built columns): Bitmap / BuiltinColumn / NumericColumn / ColumnData / NumericData / ColumnStorage / StorageKind.

    VegaType

    A Vega-Lite field type, used to override the dtype-based inference for the color channel. pub(all) so callers can name the variants when calling with_color_type. Quantitative is a continuous measure (a color gradient), Nominal an unordered category (distinct colors per value), Ordinal an ordered category, and Temporal a time field.

    WhenThen

    First step of the conditional chain when(cond).then(a).otherwise(b) — holds the Bool condition until then supplies the matching branch. Constructible only through when (a pub fn cannot return a priv type, so the builder is pub like the Expr variants it carries); its field is read-only outside the package.

    WhenThenElse

    Second step of the conditional chain — condition plus then branch, waiting for otherwise to complete the expression. Same read-only rationale as WhenThen.

    col

    fn col(name : String) ->
    Expr

    Free-function alias of Expr::col, for the Polars-style call shape col("a") + col("b") (the same static-method + free-alias double export the facade uses for read_csv).

    cols

    fn cols(names : Array[String]) -> Array[
    Expr
    ]

    Build a column-reference list from names: cols(["a", "b"]) is exactly [col("a"), col("b")]. The ergonomic shorthand for the common case of projecting (or dropping) several existing columns by name through the expression verbs — df.select(cols(["a", "b"])) reads almost like the names-only projection it replaces. Each name resolves at evaluation time, exactly like col; building the list is total.

    compare_string_lex

    fn compare_string_lex(a : String, b : String) -> Int

    Lexicographic string comparison by UTF-16 code unit, returning the usual -1 / 0 / 1. MoonBit's built-in < / Compare on String is shortlex (length first, then code unit) — e.g. "fig" < "apple" is true because "fig" is shorter, which surprises users expecting dictionary order. Every user-facing ordering in MoonFrame (Scalar::lt, Series::min / max, DataFrame::sort) routes through this helper instead of the built-in operator so they all agree.

    Ordering is by UTF-16 code unit, so it matches pandas / SQL dictionary order across the Basic Multilingual Plane (the common case). It can diverge for supplementary-plane characters, whose surrogate code units (0xD800–0xDBFF) sort below high-BMP code points rather than above them — a code-point-accurate comparison is deferred to a later release.

    format_csv

    Render a DataFrame as a CSV string.

    • Header (when options.header == true): column names joined by options.delimiter, each quoted only when it would otherwise be ambiguous.
    • Each row: cells joined by options.delimiter, terminated by \n (LF). Null cells are written as options.null_value; other cells render via Scalar::to_string.
    • Quoting: a cell containing the delimiter, a double quote, \r, or \n is wrapped in double quotes; interior double quotes are doubled (" → ""). Cells that need no quoting are written verbatim so the output matches the simple "no quotes" CSV idiom whenever possible. The lone exception: in a single-column frame an empty cell (or an empty column name) is written as "" rather than a bare blank, so the row is not a blank line the reader would skip.
    • Round-trip caveat: cells render via Scalar::to_string, so a Float whose value is a whole number is written without a fractional part (2.0 → 2) and is re-inferred as Int on read — the same dtype narrowing the JSON writer documents. Negative zero is one such whole value: -0.0 writes as 0, so its sign (observable under division) does not survive the round-trip. A String cell with significant leading / trailing whitespace is written bare (only the delimiter, a quote, \r, or \n force quoting), so this reader round-trips it (trim_spaces off), but an RFC-4180 consumer that trims surrounding whitespace may drop it. A String cell whose text equals a reader null token — the default null_value is the empty string "", so this includes empty strings, plus any custom null_values entry — is read back as null and cannot be distinguished from a true null. A String cell whose text parses as another dtype is likewise re-inferred on read: inference is content-based with no header type hints, so a column of numeric-looking strings ("01", "2") returns as Int / Float — dropping any leading zeros — and "true" / "false" as Bool, the dtype-from-content narrowing inherent to typeless CSV (matching Polars' read_csv). Quote / escape handling is otherwise round-trip safe.
    • Raises InvalidOperation if options.delimiter is a double quote or a line terminator (\n / \r): those collide with the hard-coded quote character and the row terminator, so no escaping could make the output frame fields unambiguously (see validate_csv_delimiter).

    format_json_records

    fn format_json_records(df :
    DataFrame
    ) -> String

    Render a DataFrame as a JSON records string [ {...}, ... ].

    Per cell:
    • Null → JSON null
    • Int → JSON number (no fractional part)
    • Float→ JSON number for finite values. NaN / ±Infinity have no JSON literal, so they are emitted as null (matching pandas' to_json) to keep the output valid JSON — a round-trip reads a non-finite cell back as a null.
    • Bool → JSON true / false
    • String → JSON string (escaping ", \, control chars via the builtin stringifier — we deliberately do not roll our own escape so any future Unicode spec tweaks land transparently)

    Keys appear in the column declaration order, preserved by the builtin Map (linked-hash-map) used for each record object.

    format_ndjson

    fn format_ndjson(df :
    DataFrame
    ) -> String

    Render a DataFrame as an NDJSON string: one flat JSON object per row, each terminated by \n (including the last, matching the CSV writer's per-row LF and Polars' write_ndjson). A 0-row frame renders the empty string.

    Per-cell conventions are shared with format_json_records via scalar_to_json: Null → null; Int → JSON number (no fractional part; exact across the full Int64 range via the preserved repr); finite Float → JSON number, non-finite (NaN / ±Infinity) → null so each line stays valid JSON; Bool → true / false; String → escaped JSON string. Keys appear in df.columns() order, preserved by the linked-hash-map Map backing each record object.

    format_vega_lite

    Render df and spec as a complete Vega-Lite v5 specification JSON string: $schema (pinned to the Vega-Lite v5 schema URL) + optional title + mark (from spec.kind) + encoding (x / y and, when set, color, each {field, type} with the type inferred from the column dtype: numeric → "quantitative", otherwise → "nominal") + data.values (the frame inlined as JSON records, sharing format_json_records' cell mapping — null and non-finite-float cells become JSON null). A frame with the encoded columns but zero rows yields "data":{"values":[]}.

    The spec's x / y / color columns are resolved left-to-right; the first name absent from df raises ColumnNotFound(name) — this is the one reason the function is not total (it accepts column names, and a name can be wrong). The emitted text is always valid JSON (it is built through @json and stringified), so it round-trips through any standards-compliant JSON / Vega-Lite reader.

    is_decimal_int_literal

    fn is_decimal_int_literal(s : String) -> Bool

    true when s is an optional + / - sign followed by one or more ASCII decimal digits and nothing else. Empty / sign-only strings, 0x / 0o / 0b base prefixes, and 1_000 underscore grouping all return false.

    Numeric recognition lives here, in types, so every layer agrees on what counts as an integer literal: the CSV / JSON readers' type inference and the @column String→Int cast all route through this one predicate before handing the text to @string.parse_int64. That parser defaults to base = 0 and would otherwise silently accept hex / octal / binary prefixes (0xFF → 255) and underscores (1_000 → 1000) — forms pandas / polars keep as strings. Sharing the screen (the way every ordering routes through compare_string_lex) keeps an explicit cast consistent with what the reader inferred for the same text.

    lazy_frame

    Free-function alias of LazyFrame::from, for the read_csv(path) hand-feel: lazy_frame(df).filter(…).collect(). (lazy(df) would be the obvious shorter name, but lazy is reserved.)

    lit

    Free-function alias of Expr::lit.

    lit_bool

    fn lit_bool(value : Bool) ->
    Expr

    Bool literal.

    lit_float

    fn lit_float(value : Double) ->
    Expr

    Float literal.

    lit_int

    fn lit_int(value : Int64) ->
    Expr

    Int literal (64-bit, like every MoonFrame integer cell).

    lit_series

    Embed a pre-materialised Series as a literal column, so a ready-made column joins a pipeline beside the declarative col(...) ... expressions (df.with_columns([lit_series(s), (col("a") + col("b")).with_alias("c")])). At evaluation the series is used as-is: a length-1 series broadcasts over the evaluation height (like a scalar lit), a series whose length matches the frame supplies one cell per row, and any other length raises LengthMismatch. The result column keeps the series' own name unless with_alias overrides it — so with_columns([lit_series(s)]) adds, or in-place replaces, a column named s.name(). A free function (the argument is a Series, not an Expr), like the lit_* family and map_many. Building the node is total; the length check happens at evaluation, in frame.

    lit_str

    fn lit_str(value : String) ->
    Expr

    String literal.

    map_many

    Apply a host closure across several input columns, row by row — the multi-input escape hatch, and the reified replacement for the v0.1 closure filter predicate: f is handed one @types.Scalar per input in inputs order (null cells as Scalar::Null) and is called for every row, so a row predicate is map_many(..., f). returning a Bool. A free function rather than a method (there is no single self); inputs may mix columns, literals, and aggregations, the length-1 results broadcasting over the row count. Same opacity, totality, dtype inference, naming (after the leftmost input), and value-barrier rules as map_elements. The inputs array is copied, so mutating it after construction cannot alter the built expression.

    parse_csv_str

    Parse a CSV-encoded string into a DataFrame. The pipeline is:
    1. NyaCSV tokenises the text into headers + rows. NyaCSV always treats the first row as a header, so the has_header = false case re-folds that row into the data section and synthesises column1, column2, … names.
    2. Per-column type inference walks the first infer_schema_rows rows in order Int → Float → Bool → String (a null cell within them is skipped but still counts toward the window). The first option that accepts every probed cell wins; a column with no non-null probes lands on String (no information to disambiguate).
    3. Null mapping replaces any raw cell whose verbatim string sits in null_values with None. The mapping runs after tokenisation, so quoted empty cells ("") and bare empty cells are both honoured.
    4. Each column is assembled into a typed Series and the result is wrapped through DataFrame::new.

    Raises:
    • DuplicateColumn(name) — two headers share a name.
    • ParseError(...) — a non-null cell does not parse under the inferred dtype for its column (typically because a sample row outside the inference window is malformed for the inferred type), unless options.on_parse_error is Null, which downgrades that cell to a null instead of failing the read; or — when options.strict_column_count is true — a data row's cell count differs from the header's (reported as row N: expected C columns,got G, 1-based over the data rows).
    • Whatever DataFrame::new propagates — for v0.1 this is limited to DuplicateColumn / LengthMismatch, neither of which can actually fire here (uniqueness is checked above; every column is built off the same rows.length()).

    Limitation: tokenisation is delegated to NyaCSV, whose quote handling is lenient and never raises a ParseError for a malformed quote. An unterminated quoted field at end-of-input is read as a complete field (1,"unclosed → last cell unclosed); text after a closing quote is folded into the same field ("ab"cd → abcd); and a lone quote inside an unquoted field is kept literally (ab"cd → ab"cd). A strict RFC-4180 reader rejects all three; MoonFrame accepts them, and no quote-balance pre-scan is performed.

    parse_json_records_str

    Parse a JSON records string ([ {...}, ... ]) into a DataFrame.

    @json.parse produces the Json AST; a top-level value that is not an array surfaces as ParseError. The array's elements are then handed to frame_from_json_records, which validates each is an object, collects headers in first-seen order across all records, infers one dtype per column, and materialises the frame (see that helper for the per-column rules). An empty array — like empty or whitespace-only input — yields a 0×0 frame.

    Raises:
    • ParseError(...) — malformed JSON, a top-level value that is not an array, a record that is not an object, or a non-null cell that does not fit the column's inferred dtype (the last unless options.on_parse_error is Null, which downgrades that cell to a null instead of failing the read).
    • Whatever DataFrame::new propagates (duplicate-header is pre-empted upstream; length-mismatch cannot fire because every column is built off records.length()).

    parse_ndjson_str

    Parse an NDJSON string (one JSON object per line) into a DataFrame.

    Pipeline:
    1. Split content on \n. Each non-blank line is parsed with @json.parse; a malformed line surfaces as ParseError("line N: ...") (1-based). Blank / whitespace-only lines are skipped, so the writer's trailing newline — and any incidental blank lines — never produce phantom records.
    2. The parsed values are handed to frame_from_json_records, which validates each is an object, collects headers in first-seen order across all records (sparse records → null cells), infers one dtype per column, and materialises the frame (see that helper, shared with parse_json_records_str, for the per-column rules).

    Empty input — or input that is entirely blank lines — yields a 0×0 frame, matching parse_json_records_str's empty-array behaviour.

    Raises:
    • ParseError(...) — a malformed line, a line whose value is not a JSON object, or a non-null cell that does not fit its column's inferred dtype (the last unless options.on_parse_error is Null, which downgrades that cell to a null instead).
    • Whatever DataFrame::new propagates.

    read_csv

    Read a CSV file using the default options.

    read_csv_with_options

    Read a CSV file with custom options. IOError from the file system surfaces as raise IoError(message).

    read_json

    Read a JSON records file using the default options.

    read_json_with_options

    Read a JSON records file with custom options. Filesystem errors surface as raise IoError(message).

    read_ndjson

    Read an NDJSON file using the default options.

    read_ndjson_with_options

    Read an NDJSON file with custom options. Filesystem errors surface as raise IoError(message).

    scan_csv

    fn scan_csv(path : String) ->
    LazyFrame

    The lazy CSV source: scan_csv(path) builds a LazyFrame whose leaf is a deferred read of path — the streaming-friendly counterpart of eager read_csv. Nothing is read or parsed until collect: the builder is total, like every other LazyFrame constructor, so a missing file or a malformed CSV only surfaces then (as the eager reader's IoError / ParseError / DuplicateColumn). The payoff over lazy_frame(read_csv(path)) is projection push-down — the optimizer narrows the leaf to the columns the pipeline provably consumes, and only those are parsed, so scan_csv("sales.csv").select([col("region"), col("revenue")]).collect() never builds the columns it drops. (Because a dropped column is never parsed, a parse error confined to one — a malformed cell no consumer reads — does not surface, exactly as in Polars' projection push-down; this is the one place a narrowed scan diverges from a full eager read.)

    scan_csv_with_options

    scan_csv with explicit CsvReadOptions (delimiter, header, null strings, inference window, parse-error policy, …), mirroring the eager read_csv / read_csv_with_options pair. The options are captured into the plan and applied by the reader at collect time; projection push-down narrows which columns those options parse, never which options apply. The projection starts None (read every column) — only the optimizer fills it.

    scan_ndjson

    fn scan_ndjson(path : String) ->
    LazyFrame

    The lazy NDJSON source: scan_ndjson(path) builds a LazyFrame whose leaf is a deferred read of path — the streaming-friendly counterpart of eager read_ndjson, and the line-oriented sibling of scan_csv. Like every LazyFrame constructor it is total: nothing is read or parsed until collect, so a missing file or a malformed line only surfaces then (as the eager reader's IoError / ParseError). Projection push-down narrows the leaf to the columns the pipeline consumes, and only those are built — so a dropped column is never materialised. (Because a dropped column is never built, a parse error confined to one does not surface, exactly as in scan_csv. There is no scan_json for the single-array shape [{...}], which must be parsed whole to find its records — so nothing can be pruned at read time, the same reason Polars has scan_ndjson but no scan_json.)

    scan_ndjson_with_options

    scan_ndjson with explicit NdjsonReadOptions (inference window, parse-error policy), mirroring the eager read_ndjson / read_ndjson_with_options pair. The options are captured into the plan and applied by the reader at collect time; projection push-down narrows which columns those options parse, never which options apply. The projection starts None (read every column) — only the optimizer fills it.

    when

    Open a conditional expression: when(cond).then(a).otherwise(b) evaluates to a where cond is true, b where it is false, and null where cond is null. The chain is the only construction route, so a conditional is complete by the time it becomes an Expr.

    write_csv

    Write a DataFrame to a CSV file using the default options.

    write_csv_with_options

    Write a DataFrame to a CSV file with custom options. IOError from the file system surfaces as raise IoError(message). A string cell (or column name) holding an unpaired UTF-16 surrogate is refused with raise InvalidOperation — the UTF-8 file encoding would swallow the following delimiter and silently shift every later cell boundary.

    write_json_records

    fn write_json_records(path : String, df :
    DataFrame
    ) -> Unit raise
    DataError

    Write a DataFrame to a JSON records file. Filesystem errors surface as raise IoError(message). A string cell (or column name) holding an unpaired UTF-16 surrogate is refused with raiseInvalidOperation — the UTF-8 file encoding would swallow the following code unit and corrupt the JSON framing.

    write_ndjson

    Write a DataFrame to an NDJSON file. Filesystem errors surface as raise IoError(message). A string cell (or column name) holding an unpaired UTF-16 surrogate is refused with raise InvalidOperation — the UTF-8 file encoding would swallow the following code unit and corrupt the line framing.

    write_vega_lite

    Write a Vega-Lite v5 spec for df / spec to path. Mirrors write_json_records: a ColumnNotFound from format_vega_lite (a spec column absent from df) propagates unchanged, a filesystem failure surfaces as raise IoError(message), and content holding an unpaired UTF-16 surrogate is refused with raise InvalidOperation.

    Source Files