MoonFrame

    A lightweight DataFrame and tabular-data library for MoonBit

    dataframe
    data-analysis
    csv
    tabular
    Download zip
    Author
    Version
    0.9.0
    License
    Apache-2.0
    Last updated
    16 days ago
    Downloads
    370

    #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 — the "Quick start" below runs this same
    // pipeline as a doc test)
    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 / Parquet 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 of the package that uses it:

    ///|
    import {
    "ihb2032/MoonFrame" @moonframe,
    }

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

    MoonBit v0.10.4 deprecates the legacy JSON package manifest. New and migrated projects should use moon.mod / moon.pkg, as this repository does.

    #Compatibility

    The facade package — what import "ihb2032/MoonFrame" @moonframe re-exports — is the supported surface; the public sub-packages (@types, @series, @expr, @frame, @io, @chart) stay directly importable for a slice of it. Two families are deliberately off the facade: the fluent-chain intermediates (WhenThen / GroupedDataFrame / … — chain through them without naming them), and the string-level serialisers, reached through @io by name.

    Pre-1.0, additions and fixes ride a patch version and a change to that surface rides the minor one. One case reads as additive but is not: adding a variant to a pub(all) enum (DataType, Scalar, DataError, …) is source-breaking under MoonBit's exhaustive match — only a caller whose match carries a wildcard arm stays compatible. The two error-detail enums (TypeMismatchDetail, ParseErrorDetail) are the exception: they are #non_exhaustive, so a match over them ends in a .. arm and a new diagnostic shape is a recompile, not a break. The upgrade steps for each release are in docs/migration.md.

    #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. The block below is a doc test: moon test compiles and runs it, so the example cannot drift from the API. It stages sales.csv itself through the public write_csv (the test suites stage fixtures the same way), uses the names the facade re-exports, and expects the rendered table inline — in your own module you write the same pipeline with the @moonframe. prefix from the import above:

    ///|
    test "readme: keep the widget rows, sort by quantity" {
    let path = "_build/readme_sales.csv"
    write_csv(
    path,
    DataFrame::DataFrame([
    Series::from_strings("region", [
    "west", "east", "west", "east", "north", "north", "west", "east",
    ]),
    Series::from_strings("product", [
    "widget", "gadget", "gadget", "widget", "widget", "gadget", "gizmo", "gizmo",
    ]),
    Series::from_ints("revenue", [100, 50, 70, 30, 40, 60, 90, 20]),
    Series::from_ints("quantity", [10, 5, 7, 3, 4, 6, 9, 2]),
    ]),
    )
    fn widgets(p : String) -> String raise DataError {
    read_csv(p)
    .filter(col("product").eq(lit_str("widget")))
    .select(cols(["region", "revenue", "quantity"]))
    // each key is (key, descending, nulls_last)
    .sort([(col("quantity"), true, true)])
    .to_markdown()
    }
    inspect(
    widgets(path),
    content=(
    #|| 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, which runs the same way.

    #What you can do

    • Read & write CSV, JSON, and NDJSON — read_csv / read_json / read_ndjson and their write_* counterparts, with tunable type inference, opt-in strict CSV quote validation, formula neutralisation for spreadsheet-facing exports, and transparent gzip (.gz sources decompress on read; write_* compresses a .gz path).
    • Reshape — filter, select, drop, rename, with_columns, multi-key sort, row dedup (unique), seeded row draws (sample, shuffle), and null handling (drop_nulls, fill_null). Brackets read Polars-style: df["qty"] a column, df[1:3] / df[:-1] a row window, s[0] a cell.
    • 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 — df.to_lazy() (or LazyFrame::LazyFrame(df)), or scan_csv / scan_ndjson for a lazy file source (deferred execution with projection and predicate pushdown into the reader, not streaming — the file still tokenizes at collect()), builds a query plan you can explain(); collect() runs it through the optimizer, producing an equal frame for the cells it reads. What a push-down does not read, it does not parse — so a parse error confined to a pruned column, or to a row the pushed-down predicate drops (in a column that predicate does not itself read), never surfaces. LazyFrame::collect's docstring states the contract in full.
    • Join — the full inner / left / right / outer / cross matrix on expression keys, e.g. orders.join(customers, JoinOptions::on([col("customer_id")])) — or, for differently-named or derived keys, JoinOptions::left_on([col("customer_id")], right_on=[col("id")]).
    • Summarize — describe() for a per-column summary, or single statistics (sum / mean / min / max / …).
    • Export — to_markdown() / to_html(), and charts: plot(df) chains to a finished chart over plain column names (plot(df).bar(x="region", y="revenue").write_html("out.html")), backed by format_vega_lite (a full typed mirror of Vega-Lite v6: seventeen marks, thirty-eight encoding channels, the nineteen transforms with the filter-predicate union, layer / concat / facet / repeat compositions, interactive parameters and conditional encodings, and the theme tree — every emission held to the vendored schema of the mirrored Vega-Lite release by a CI-walked golden corpus), and — through the io package — the string-level format_csv / format_json / format_ndjson.

    For example, summarise the same data by region (another doc test, in-memory this time — group_by starts from any frame):

    ///|
    test "readme: summarise by region" {
    let sales = DataFrame::DataFrame([
    Series::from_strings("region", [
    "west", "east", "west", "east", "north", "north", "west", "east",
    ]),
    Series::from_ints("revenue", [100, 50, 70, 30, 40, 60, 90, 20]),
    Series::from_ints("quantity", [10, 5, 7, 3, 4, 6, 9, 2]),
    ])
    let summary = sales
    .group_by([col("region")])
    .agg([
    col("revenue").sum().with_alias("revenue"),
    col("quantity").sum().with_alias("quantity"),
    ])
    inspect(
    summary.to_markdown(),
    content=(
    #|| 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(options=HtmlOptions::HtmlOptions(caption="Summary")), or as a Vega-Lite chart via plot(summary).bar(x="region", y="revenue").to_json() — a v6 spec ready to paste into the Vega editor, or written as a self-contained page with .write_html("out.html").

    #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:

    ///|
    test "readme: bridging a raise back to a Result" {
    let df = DataFrame::DataFrame([Series::from_ints("a", [1, 2])])
    let result : Result[DataFrame, DataError] = Ok(df.select([col("missing")])) catch {
    e => Err(e)
    }
    assert_true(result is Err(ColumnNotFound(_)))
    }

    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.

    #Documentation

    • The generated API reference — built from the docstrings, deployed to GitHub Pages on every merge to main, and published on mooncakes.io; one source, two hosts. Per-symbol contracts live in the docstrings, and that reference is where they are read.
    • quickstart.mbt.md — a runnable tour; every snippet and its expected output is executed by moon test, and by CI across all four backends, so a code block cannot drift from the API. The prose around them is reviewed, not executed
    • docs/comparison.md — how MoonFrame aligns with, and deliberately differs from, Polars / pandas
    • docs/performance.md — columnar layout, the Numeric fast path, and per-operation complexity
    • docs/type-inference.md — how CSV / JSON / NDJSON columns get their dtypes
    • docs/migration.md — upgrading across breaking releases
    • The release notes — what each release changed, written when it is cut

    Four runnable end-to-end programs live in examples/ (a fifth directory, readme_install, is not one of them — it is the README install snippet's compile probe):

    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

    #Design notes

    MoonFrame's API and column semantics are modeled on Polars — see docs/comparison.md for the full alignment and the deliberate differences, 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.
    • to_x never fails; as_x raises. Scalar::to_string renders any cell for display (a null cell gives ""); Scalar::as_string is a typed read that raises TypeMismatch on a wrong dtype. The wrong one does not fail — it silently stringifies — so reach for as_* when a wrong dtype is a bug you want reported, and to_* only for display text whatever the cell holds.
    • null and NaN are different. null is missing and propagates; NaN is a value (sum / mean / median propagate it, min / max skip it), and sort orders it by the IEEE total order — larger than every other value, so it trails an ascending sort and leads a descending one.
    • 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 and a pkg.generated.mbti interface snapshot. Which kind of test a thing gets follows from what is under test rather than from which directory it sits in: a contract a caller can reach is tested from outside, through *_test.mbt, and a representation is tested from within, through *_wbtest.mbt, so that asserting it does not require making it public. Public packages are therefore mostly blackbox and internal/ ones mostly whitebox — an internal package with a contract of its own (a parser, a renderer, a comparison) has blackbox tests too, and one whose whole surface is driven from a single caller has none of its own (internal/kernel is covered through frame's expression evaluator, which is what exercises every kernel a caller can reach):

    types/ value types, errors (DataError), schemas internal/buffer/ the raw buffer primitives — the Arrow validity bitmap and the UTF-8 (bytes + offsets) string buffer every columnar layout flattens from internal/scan/ the scan-driver seam — what one readable source (CSV, NDJSON, Parquet) implements so the lazy engine executes, narrows, and renders it format-agnostically internal/column/ Arrow-style storage — validity bitmap + Builtin/Numeric backends; wrapped by Series and read by internal/kernel (which packages may name it is enforced by check_layering.sh) internal/kernel/ the vectorized expression kernels — Series broadcasting, arithmetic / logic / comparison / string ops, ternary, map, and the dtype inference behind a computed column; called by frame's evaluator internal/text/ shared text primitives — lexicographic compare, debug escaping, decimal literal parsing internal/numeric/ shared numeric primitives — exact Int64/Double comparison and the extremum fold, used from types up through the kernels internal/order/ shared position primitives — the stable index sort behind every sort, and the row-count clamp behind every head / tail / limit internal/ir/ module-internal expression AST — ExprNode + the operator tags, walked by the engine internal/parquet/ the native parquet codec — thrift compact metadata, RLE definition levels, PLAIN and dictionary values, snappy / gzip page bodies; wrapped by io's read / write / scan_parquet series/ Series + column-level stats + the shared reduction / rebuild / key-cell kernels expr/ opaque Expr handle — constructors, operators, when/then/otherwise builders, to_string rendering frame/ DataFrame + the operators (usually one per file) + group_by + join + the expression evaluator (with_columns / select / filter / agg) + to_markdown / to_html + the deferred query plan (LazyFrame builders, collect / explain, predicate + projection pushdown) io/ CSV (NyaCSV-backed), JSON, NDJSON read / write + their options types + the lazy scan sources (scan_csv / scan_ndjson / scan_json / scan_parquet) chart/ Vega-Lite v6 typed mirror — the plot(df) fluent chain over plain column names, ChartSpec mark-named builders over VegaChannel (field / constant / datum), the Chart composition layer, the guide trees (scale / axis / legend / header / projection / title), transforms, parameters, and the VegaConfig theme, format_vega_lite / write_vega_lite, a golden corpus schema-walked in CI (shares io's JSON cell conventions) moonframe.mbt the root package — facade over the public API (fluent-chain intermediates stay in their sub-packages)

    The internal/ packages are MoonBit internal packages: importable inside this module only, so they carry no compatibility promise. Where a new piece of engine work belongs follows from what each layer owns:

    internal/column how a column is laid out: data buffers + validity bitmap series what a column is: dtype, validity, backend convergence internal/kernel how a column is computed: one vectorized pass per operator frame and above what a verb means: row sets, scheduling, schema, errors

    Two different relations are stacked there, and it helps to keep them apart: internal/kernel depends on series (it takes columns and hands columns back), while being its peer in storage access — both may name the physical column, because a vectorized pass needs the representation to keep the numeric fast paths. So a new vectorized operator goes in internal/kernel — where naming the physical column is the point — a new column-level primitive goes in series, and frame reads a column only through Series. frame's production build does not import internal/column at all; its test build does, to assert which backend an operator's output lands on.

    The dependency graph is a DAG, not a chain — expr and internal/ir sit off to one side of it. Which package may import which is not restated here on purpose: .github/scripts/check_layering.sh holds that rule and enforces it against the manifests, so there is one copy of it and it cannot quietly stop being true.

    The data model is an Apache Arrow-style column layout — a data buffer beside a byte-packed validity bitmap (1 = valid), except on the Numeric fast path, where an all-valid Int / Float column carries no bitmap at all — with an O(1) name→index cache; DataFrame::check_invariants() is a formal structural spec (INV1–INV5), and the operator test suites assert it over representative outputs. 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 every source file fully covered (moon coverage analyze) and a warning-free moon check; CI also runs the moon bench suite, so keep it green too.

    #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.

    CellParseLocation

    Identifies how a typed cell's 1-based source position is reported. Row is used by CSV, Record by JSON arrays, and Line by NDJSON.

    Chart

    A chart: a single view (a ChartSpec, wrapped through Chart::of) or a composition over child charts — Layer (children in one coordinate system), VConcat / HConcat / Concat (a vertical, horizontal, or wrapped grid), Facet (small multiples by a row / column channel), and Repeat (the same view over a field list). Compositions nest: a concat's child may itself be a layer or a facet. pub(all) so callers build the variants; Chart::of wraps a single view, and the operator constructors (VegaLayer::VegaLayer, …) build the compositions.

    ChartKind

    The mark type of a chart, mapped to a Vega-Lite top-level mark: Bar → "bar", Line → "line", Point → "point", Area → "area", Tick → "tick", Rect → "rect", Rule → "rule", Circle → "circle", Square → "square", Trail → "trail", Text → "text", Arc → "arc", Image → "image", Geoshape → "geoshape", and the composites Boxplot → "boxplot", Errorbar → "errorbar", Errorband → "errorband". pub(all) so callers can name the variants when building a ChartSpec (though the ChartSpec constructors set the kind for you).

    ChartSpec

    A chart specification: the mark kind, its encoding channels (each a VegaChannel, built with field / VegaChannel::repeat / constant / datum), and the optional top-level chrome (title, width / height as a VegaExtent, name, description, autosize, padding, background). Fields are read-only outside the package — build a spec through one of the mark-named constructors (ChartSpec::bar(x,y) / line / point / area / tick / rect / rule / circle / square / trail / boxplot, the polar ChartSpec::arc(theta), ChartSpec::text(x, y, text), ChartSpec::image(x, y, url), ChartSpec::geoshape(shape), and the error composites ChartSpec::errorbar / errorband), each naming the channels that mark commonly consumes — or through ChartSpec::of, the general form that carries every channel and every chrome property there is:

    ChartSpec::bar(field("region"), field("revenue"), title="Revenue")

    Every field channel's column resolves against the frame at format_vega_lite time in a fixed order — x, y, x2, y2, xError, xError2, yError, yError2, xOffset, yOffset, longitude, longitude2, latitude, latitude2, theta, theta2, radius, radius2, color, fill, stroke, opacity, fillOpacity, strokeOpacity, strokeWidth, strokeDash, size, shape, angle, time, text, tooltip, href, url, description (the ARIA channel, description_channel here because the top-level prose description takes the plain name), key, detail, order — and the first name absent from the frame raises ColumnNotFound (a count channel reads no column). Each channel's dtype decides its Vega-Lite field type (the dtype→type rule format_vega_lite's doc states) unless the channel's type_override replaces it; the declared modifiers pass through to the Vega-Lite runtime, which computes them at render time.

    ClosedInterval

    Which endpoints an is_between range includes. Both (the default) is lo <= x <= hi; Left / Right open the other end; None excludes both (lo < x < hi).

    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, 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. A cell a ragged short row never held is null regardless of this list — the mapping decides what a read value means, and no value was read. Read it back through the null_values() accessor: the field itself is private, and both it and the constructor copy, so the token list a reader uses cannot be changed after the options are built.
    • 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 the reader's long-standing default).
    • 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 with ParseError(Cell(...)); Null downgrades the offending cell to a null cell and keeps the column's inferred dtype.
    • dtypes — per-column dtype overrides that pin a column's type instead of inferring it, as a name → DataType map. Only the seven dtypes a reader can parse — the four inference picks (Int / Float / Bool / String) plus the three rider dtypes a pin carries (Date / Timestamp / Decimal, read back through the writers' exact text forms) — can be pinned; anything else is refused with InvalidOperation at read time, as is a name the input does not carry (a pin is an assertion about the input; a misspelt one fails rather than silently does nothing). Columns not named keep their inferred dtype. A pinned column skips inference entirely, so it locks in even when its cells would have inferred differently — and a cell that does not parse under the pin is handled per on_parse_error, exactly as a post-window mismatch is. The map is copied, so mutating it afterwards cannot alter the options; read it back through the dtypes() accessor.
    • allow_nonfinite_floats — when true (default), the float probe accepts every non-finite result: the nan / inf / infinity literals, and a finite literal that overflows Double to a signed Infinity (1e999), 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).
    • strict_quotes — when true, the input is pre-scanned and an unterminated quoted field, text after a closing quote, or a bare quote inside an unquoted field raise ParseError instead of being repaired by the lenient tokeniser. Defaults to false.

    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.
    • sanitize_formulas — when true, a String cell beginning with =, +, -, @, a tab, or a carriage return is prefixed with a single quote so a spreadsheet reads it as text. Deliberately lossy: such a cell reads back with the leading quote. Defaults to false.
    • line_terminator — the string written after every row. The default "\n" (LF) matches every mainstream writer; RFC 4180's letter calls for "\r\n" (CRLF), and the reader accepts LF, CRLF, and CR alike, so either choice round-trips. Must not be empty — an empty terminator would fuse the rows into one.

    DataError

    Unified error type for all MoonFrame operations.

    The diagnostic shapes it carries — ParseErrorDetail, TypeMismatchDetail — are #non_exhaustive: a new shape is not a breaking change, and a caller matching those details carries a .. arm for the shapes it does not know. DataError itself stays exhaustive: #non_exhaustive is not supported on a suberror (MoonBit v0.10.14), so a new error kind remains a deliberate, breaking change under the enum-surface lock.

    DataFrame

    The lazy layer's deferred query plan lives in the frame package — the engine that executes its verbs — re-exported beside the eager face it defers.

    DataType

    Logical data type for a column.

    Null is the dtype of a missing value, not of a column: it is what Scalar::Null.dtype() reports, and so what a TypeMismatch's "expected T, got Null" names when a null cell reaches a typed read. A hand-built Schema may also carry it, but nothing materialises a column on it — DataFrame::empty raises Unsupported for such a field, cast refuses it as a target, and no reader infers it: an all-null probe window falls back to String. Concrete columns always carry one of the other variants.

    A logical dtype is more than its variant: its display name, the physical buffer its columns ride, and its numericity are registered in the dtype registry, whose per-dtype rows are the compile-forced registration point for a dtype added here.

    Dec128

    An IEEE 754 decimal128 value. The fields are the representation, not the API: build values with the constructors (of_int64, parse_opt, …) and read them with the predicates and conversions — neg is the sign bit (true = negative; on NaN it carries nothing), kind names the exceptional shapes (0 finite, 1 infinity, 2 NaN), limbs is the little-endian base-10^9 coefficient, and exp the quantum exponent (the value is ±(Σ limbs[i]·BASE^i)·10^exp).

    Expr

    A composable column expression — the reified upgrade over the closure-based surfaces (the original row-predicate closure) and pre-materialised Series columns. An Expr is built through the constructor functions (col / lit / lit_* / when), the operator impls, and the methods, so every tree is well-formed by construction; the when chain stages through the WhenThen / WhenThenElse types below, completing as a Ternary. Building one is total — unknown columns and dtype mismatches surface at evaluation time (in frame), never here.

    The type is opaque: it wraps an ExprNode AST and exposes no variants. Outside this package an expression is a value you build and pass on, or render with to_string — there is no matching on its shape. The AST itself is module-internal, in a package a downstream module cannot import at all, so no caller can name a node, match one, or hold one: adding a node for a new operator breaks nobody.

    The shape is not observable either: there is no == on an expression. One existed, comparing the two trees, and it made how an operator lowers a promise to callers — normalising a tree or merging two node kinds would have changed what compared equal without changing what any expression means. to_string() is what a caller inspects with instead; it renders what it prints, so two literal series differing only in their cells render alike.

    The engine reads the shape through three accessors beside the type — node() hands over the wrapped AST, and referenced_columns() / output_name() answer its introspection questions. frame and lazy are in-module and match ExprNode directly.

    The wrapped AST carries ExprNode children, not Expr, so a constructor unwraps its child Exprs with .node — the only bridge the package needs, every consumer of a child matching ExprNode itself. The nodes, in construction-route order:
    • Col / Lit / LitSeries — leaves (col, lit / lit_*, lit_series); a LitSeries embeds a pre-materialised Series;
    • Binary — arithmetic + - * /, comparisons, Kleene & / |;
    • Unary — -e, .not(), the null / NaN / finiteness probes, the dt_* calendar quartet, .abs() / .floor() / .ceil() / .sign() / .round(), and the always-Float math family .sin() … .sqrt() (.atan2() / .hypot() ride Binary);
    • Agg — .sum() / .mean() / … reductions;
    • Str — the .str_* namespace;
    • Positional — the history-dependent transforms (.shift(n) / .diff(n), the .cum_* running aggregates, .rank(how~), .arg_sort(), the .rolling_* windowed statistics, .forward_fill() / .backward_fill(), .unique_counts(), .is_first_distinct() / .is_last_distinct()), whose cell reads its neighbours or the column's occurrence structure;
    • Cast — .cast(dtype); Alias — .with_alias(name);
    • Ternary — when(c).then(a).otherwise(b);
    • FillNull / FillNan — .fill_null(v) / .fill_nan(v), dedicated nodes (not lowered to a Ternary) so the operand appears once and a chained coalesce stays linear;
    • Diff / Clip — .diff(n) / .clip(lower?, upper?), likewise dedicated (not lowered to - shift(n) / a nested when) so the operand appears once and a chained difference or clamp stays linear;
    • IsIn / IsBetween — the membership / range predicates, likewise dedicated so the operand is evaluated once;
    • Map / MapBatches — the row-wise / batched closure escape hatches (.map_elements() / map_many() / .map_batches()), the function opaque so each is identified by its (label, inputs) (MapBatches also by its returns_scalar flag);
    • Over — .over(keys), the window wrapper: its inner expression is evaluated once per key group and stitched back to the frame's rows (an aggregation broadcasts over its group, a group-length transform lands cell-for-cell), so the output is frame-tall like any other expression but its cells read their group's rows.

    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 never inferred from a column's contents: the constructor's nullable default — and so DataFrame::DataFrame and the IO readers — always sets nullable = true, so a nullable = false field only ever originates from an explicit Field::Field(..., nullable=false) in a caller-supplied schema.

    Once declared, it travels with the cells it describes. Every operation that moves a column carries its field rather than re-deriving one: Field::rename (and so DataFrame::rename / rename_with, which change nothing but the name), Schema::select / Schema::rename, the row-only frame transforms that reuse their input's schema verbatim (head / tail / slice / filter / sort / unique / fill_null / …), and the projections: a select or with_columns entry that is a bare col("x") (or an aliased one, which carries the field renamed), every column drop or select leaves in place, and the counter-prepending with_row_index. A column replaced through with_columns takes the field of whichever column now supplies its cells.

    An operation that computes cells derives a fresh field instead, with the constructor default: arithmetic, aggregations, cast, fill_null as an expression, group_by(...).agg(...), join (an outer one introduces nulls), and the summary frames (describe / null_count / sum / …). The declaration was made about the input's cells, not about these.

    That split is what keeps the flag honest without ever inspecting a column: it is validated once, by from_rows, and thereafter only accompanies cells it was validated against — the operations that carry it drop, reorder or rename, and never introduce a value.

    The fields are priv, so the struct is opaque outside this package: build one through Field::Field(...) and read it through name() / dtype() / nullable(). That is what actually keeps a future field additive — a readable field is also matchable, and MoonBit requires a struct pattern to name every field or carry .., so a public field's arrival would break a caller's pattern exactly as a new pub(all) enum variant breaks a match.

    HtmlOptions

    The lazy layer's deferred query plan lives in the frame package — the engine that executes its verbs — re-exported beside the eager face it defers.

    JoinOptions

    The lazy layer's deferred query plan lives in the frame package — the engine that executes its verbs — re-exported beside the eager face it defers.

    JoinType

    The lazy layer's deferred query plan lives in the frame package — the engine that executes its verbs — re-exported beside the eager face it defers.

    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. 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 with ParseError(Cell(...)); Null downgrades the offending cell to a null and continues.
    • reject_duplicate_keys — whether an object repeating a key is an error. The default false keeps the common JSON reading: a repeated key survives only as its last value, the earlier ones silently dropped. true rejects the read instead — ParseError(Message(...)) naming the key and the line / column it repeated at — so a payload that would silently lose cells fails loudly. The check rides the parser itself (which reports whichever trouble it meets first: a repeat ahead of a syntax error surfaces as the repeat, and vice versa).
    • allow_nonfinite_floats — when true (default), a number whose magnitude overflows Double (e.g. 1e999) infers the column as Float holding ±Infinity. When false, such a number is not Float evidence — the column stays String, the CSV reader's allow_nonfinite_floats rule, so a silent retype to Float(∞) cannot happen either way a file is read.
    • dtypes — per-column dtype overrides that pin a column's type instead of inferring it, as a name → DataType map. Only the seven dtypes a reader can parse — the four inference picks (Int / Float / Bool / String) plus the three rider dtypes a pin carries (Date / Timestamp / Decimal, read back through the writers' exact text forms, so the cell must be a JSON String) — can be pinned; anything else is refused with InvalidOperation at read time, as is a name the input does not carry (a pin is an assertion about the input; a misspelt one fails rather than silently does nothing). Columns not named keep their inferred dtype. A pinned column skips inference entirely, and a cell that does not parse under the pin — a JSON String in a column pinned Int, say, since JSON has strong types and no "1" → 1 coercion — is handled per on_parse_error. The map is copied, so mutating it afterwards cannot alter the options; read it back through the dtypes() accessor.

    The NDJSON reader shares this type: the two formats differ in framing, not in what there is to configure.

    KeepStrategy

    The lazy layer's deferred query plan lives in the frame package — the engine that executes its verbs — re-exported beside the eager face it defers.

    LazyFrame

    The lazy layer's deferred query plan lives in the frame package — the engine that executes its verbs — re-exported beside the eager face it defers.

    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 ParseError(Cell(...)), 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. The column keeps its inferred dtype; only the unparseable cells become null.

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

    Optimizations

    The lazy layer's deferred query plan lives in the frame package — the engine that executes its verbs — re-exported beside the eager face it defers.

    ParquetCodec

    The compression a written parquet file carries (the reader takes every codec it can decode; this names the writer's).

    ParseErrorDetail

    Structured details carried by DataError::ParseError. #non_exhaustive: a new diagnostic shape here is not a breaking change — a caller matching these details carries a .. arm for the shapes it does not know (the contract the DataError variants naming them inherit).

    PivotAgg

    The lazy layer's deferred query plan lives in the frame package — the engine that executes its verbs — re-exported beside the eager face it defers.

    QuantileInterpolation

    Series has its own package (extracted 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 for Series is unchanged for callers. QuantileInterpolation is named by callers to pick a non-default interpolation — the only enum-argument vocabulary on the reduction family.

    RankMethod

    How rank numbers a tie. Over the m sorted non-null cells, a tie group spanning sorted positions [a, b]:

    • Average (the default) — every member gets the mean of a+1 … b+1, a Float rank ([3, 6, 1, 1, 6] ranks 3.0, 4.5, 1.5, 1.5, 4.5);
    • Min — every member gets a+1, competition ranking (gaps follow ties);
    • Max — every member gets b+1;
    • Dense — like Min but the next tie group starts one past the previous group's rank, no gaps;
    • Ordinal — no tie sharing: cells rank 1 … m in input order among equals.

    Null cells stay null under every method (only non-null cells rank). No seeded-random tie-break method exists: its output would be seeded randomness, out of place in a library whose every other verb is deterministic.

    Scalar

    A single cell value in a DataFrame.

    Null represents a missing value. The as_* conversions raiseTypeMismatch(Expected(expected, got, "")) on a wrong dtype (got = Null for a nullcell). Comparisons between cells are column-level — an expression'seq / lt / gt` verbs — and their dtype matrix lives on the comparison kernel, not here.

    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. The Date variant carries whole days since the Unix epoch (1970-01-01 = day 0), rendering as an ISO YYYY-MM-DD string.

    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.

    The fields array is priv: build a schema with Schema::Schema and read a copy via fields() / field_names(). External code cannot reach or mutate the backing array, so a validated schema stays valid.

    index is the name→position map behind index_of, and through it field / select / rename. It is derived from fields and built in lock-step with it, never separately: the constructors are the only writers, and each one builds both. Uniqueness is what makes it total — every name maps to exactly the position that carries it — so it is the same validation pass that establishes both. A schema is immutable, so one scan at construction replaces a scan per lookup: resolving c names against a c-column schema was O(c²) while every resolution walked the array, which is the shape a wide select or rename hits.

    Series

    Series has its own package (extracted 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 for Series is unchanged for callers. QuantileInterpolation is named by callers to pick a non-default interpolation — the only enum-argument vocabulary on the reduction family.

    TypeMismatchDetail

    Structured details carried by DataError::TypeMismatch. #non_exhaustive: a new diagnostic shape here is not a breaking change — a caller matching these details carries a .. arm for the shapes it does not know (the contract the DataError variants naming them inherit).

    VegaAggregate

    A Vega-Lite channel aggregate, declared for the Vega-Lite runtime to compute at render time (MoonFrame emits it, it does not evaluate it): one variant per operation the schema's AggregateOp lists. Count tallies the rows of each group and needs no column — a count channel is exempt from column resolution and its field type is "quantitative"; ArgMax / ArgMin may also carry a field in the schema's object form, which the string form emitted here does not (a bare field under the same aggregate serves the common case). pub(all) so callers can name the variants in a channel's aggregate.

    VegaAutoSize

    A top-level autosize: Pad → "pad" (the default; the view grows to fit axes and legends), Fit → "fit", FitX → "fit-x", FitY →"fit-y" (each dimension shrinks the chart into the given total size), and None → "none" (no automatic fitting). pub(all) so callers can name the variants.

    VegaBin

    A Vega-Lite channel bin: On ("bin": true, the runtime picks the bins), Params (an explicit VegaBinParams), and Binned (the "binned" marker: the data is already binned — the start maps to x and the end to x2, so a binned histogram pairs Binned on x with the pre-binned end in x2). pub(all) so callers can name the variants.

    VegaBinParams

    Explicit binning parameters, the schema's BinParams: the maximum bin count the binning method aims for (maxbins), an anchor to force as a bin boundary (anchor), a number base and allowable subdivision factors (base, divide), a required step size or the list to choose from (step, steps), a minimum allowed step (minstep), nice round boundaries (nice), already-binned data (binned), and an explicit value range (extent, a min / max pair). Fields are read-only outside the package — build one through the same-named constructor, which copies the array parameters it takes, and read divide / steps back through their accessors, which copy again.

    VegaChannel

    One encoding-channel definition: a column field plus optional pass-through modifiers, or — instead of a field — a reference to a repeat variable (repeat_ref, the placeholder a child spec inside a Repeat composition resolves per panel) or a constant value or a constant datum (the schema's value / datum definitions; a channel is exactly one of the four, and the builders keep it that way — a field and a repeat_ref on one channel raise InvalidOperation at emission, since the schema's field slot holds one or the other). aggregate declares an aggregation over the column (a Count aggregate ignores the field — no column is read, and the channel's type is "quantitative"); bin declares binning; time_unit truncates a temporal column to calendar units; sort orders the channel's scale; type_override replaces the dtype-inferred field type on this one channel; title names the axis / legend entry and format formats its ticks (a number / time format pattern); stack overrides position stacking; band_position places a mark within its band (0 start, 0.5 middle, 1 end). The modifiers are declared, not computed — the Vega-Lite runtime evaluates them at render time. Build one with field / VegaChannel::repeat / constant / datum; fields are read-only outside the package.

    VegaChannelSort

    A Vega-Lite channel sort, the complete schema union: Ascending / Descending (the bare orders), ByChannel (sort by another channel's values, the descending flag spelling the schema's -x forms), ByField (sort by a data field, optionally in a given order), Values (sort by an explicit list of the channel's values, in that order), and Off (null, which turns sorting off). pub(all) so callers can name the variants; build the Values form through VegaChannelSort::values, which copies the caller's array.

    VegaExtent

    A top-level width / height: Px (a fixed number of pixels), Container ("container", responsive sizing — not combinable with row / column facet channels), and Step ({"step": n}, the size of one discrete step, so a discrete axis sizes itself by its category count). pub(all) so callers can name the variants in a constructor's width / height.

    VegaPadding

    A top-level padding: Px (the same number on all four sides) or Sides (per-side values, the sides unset left to the runtime's default). pub(all) so callers can name the variants.

    VegaRepeatRef

    A reference to a repeat variable — the placeholder a child spec inside a Repeat composition names where a plain field reference would name a column: Row → {"repeat": "row"}, Column → {"repeat": "column"}. The schema's RepeatRef enum also lists "repeat" and "layer", which belong to hosts this mirror does not build (a wrapped repeat-of-concats and a layer-level field spec), so the two variants here are the reachable set. pub(all) so callers can name the variants; a channel carrying one is built with VegaChannel::repeat.

    VegaSort

    A sort order: Ascending → "ascending", Descending → "descending". The order half of a VegaChannelSort's by-field form; a bare order is also a complete sort on its own. pub(all) so callers can name the variants.

    VegaSortChannel

    A channel another channel's sort may be keyed on — the schema's SortByChannel list ("x" … "-text"): X → "x", Color → "color", FillOpacity → "fillOpacity", Text → "text", and so on through the twelve. pub(all) so callers can name the variant inside a VegaChannelSort.

    VegaStack

    A Vega-Lite position-channel stack for stacked bar / area: Zero → "zero" (baseline stacking, the default when a mark stacks), Center → "center", Normalize → "normalize" (each stack rescaled to full height), and Off (null, which turns stacking off — the layered form). pub(all) so callers can name the variants.

    VegaTimeUnit

    A Vega-Lite timeUnit, the complete schema closure: the eleven calendar units (Year … Milliseconds), their Utc counterparts, and every consecutive-unit concatenation the schema enumerates (YearQuarter, MonthDateHours, UtcSecondsMilliseconds, …). Each variant emits its schema string verbatim (Dayofyear → "dayofyear", UtcWeekdayHours → "utcweekdayhours"). pub(all) so callers can name the variants in a channel's time_unit.

    VegaType

    A Vega-Lite field type, used to override the dtype-based inference of any channel. pub(all) so callers can name the variants in a channel's type_override. Quantitative is a continuous measure (a color gradient), Nominal an unordered category (distinct colors per value), Ordinal an ordered category, Temporal a time field, and Geojson a GeoJSON feature collection carried in a String column (a geoshape channel; the dtype rule never infers it — a String column is nominal unless a caller says otherwise).

    col

    fn col(name : String) ->
    Expr

    Reference a column by name, for the operator call shape col("a") + col("b"). The name resolves at evaluation time — ColumnNotFound then if the frame has no such column; building the reference itself is total. A free function, like the lit* family — the facade re-exports it.

    Example

    test "col: renders as a reference" {
    inspect(col("qty").to_string(), content="col(qty)")
    }

    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.

    Example

    test "cols: shorthand for the reference list" {
    debug_inspect(
    cols(["a", "b"]).map(e => e.to_string()),
    content="[\"col(a)\", \"col(b)\"]",
    )
    }

    constant

    A constant-value encoding channel: the channel shows the given JSON value for every row (the schema's value definition — a fixed color, a fixed size) instead of reading a column. Its type inference has no column to read, so the emitted definition carries only the value (and any title / format set on the channel through a builder is unreachable — use field when a column is wanted).

    datum

    A constant-datum encoding channel: like constant, but the value passes through the channel's scale (a scale type must fit — a number under a linear scale) rather than being shown verbatim. The schema's datum definition.

    field

    The field-reference encoding channel for column name, with any of the VegaChannel modifiers named — e.g. field("revenue",aggregate=Sum), field("price", bin=On), field("ts",time_unit=Month), field("region", sort=Descending), field("g",type_override=Nominal). The col idiom of the chart export: a free function, so the facade re-exports it and the common call stays two words short.

    format_vega_html

    Render df and chart as a standalone HTML document that displays the chart: the specification format_vega_lite emits, embedded as a JavaScript expression, plus the three pinned runtime scripts (vega@6.4.0, vega-lite@6.5.0 — the mirrored schema's own version — and vega-embed@7.3.0, loaded from a public CDN). Opening the file in a browser renders the interactive chart; vega-embed's default action links offer SVG / PNG export, the spec source, and the online editor. The spec and its inlined data travel inside the document, so the file is self-contained apart from the CDN scripts — viewing needs network access.

    Each field channel names a column of df, resolved in the fixed order the ChartSpec doc states, and the first name absent from the frame raises ColumnNotFound(name). This is not total, for the same full set of reasons format_vega_lite's doc enumerates — the ColumnNotFound family (a channel column, a facet channel's column, a repeat field-list name) and the InvalidOperation family (a constant a position or offset channel's value definition refuses, a channel carrying both a field and a repeat reference, a facet sort keyed on another channel, a composition child of an illegal shape for its host, and a composition with nothing to compose); the spec emission underneath is the shared one. Before embedding, every literal < in the emitted JSON is rewritten to its \u003c JSON escape, and the U+2028 / U+2029 line separators likewise, so chart data cannot close the host <script> element early; the embedded text is the same JSON value, readable by any standards-compliant JSON reader.

    format_vega_lite

    Render df and spec as a complete Vega-Lite v6 specification JSON string: $schema (pinned to the Vega-Lite v6 schema URL) + the optional chrome (name, description, title, autosize, background, padding, width, height) + mark (from spec.kind) + encoding (the spec's channels, each {field, type} or a value / datum definition, plus its declared modifiers) + data.values (the frame inlined as JSON records, sharing format_json's cell mapping — null and non-finite-float cells become JSON null). A frame with the encoded columns but zero rows yields "data":{"values":[]}.

    Each field channel's type follows its column's dtype — the single statement of the dtype→type rule: a numeric column (Int / Float / Decimal) is "quantitative", a Date / Timestamp column is "temporal" (its ISO cells — data.values' date units, via the JSON records' ISO mapping — sort chronologically, and a temporal axis orders by time rather than by first appearance), a Duration column is "quantitative" (its data.values cells leave as microsecond counts, chart_data_values's one departure from the shared JSON records walk — Vega's temporal has no ISO-duration parser, so a temporal type would hand the runtime strings it cannot read), and every other dtype is "nominal" — unless the channel carries an explicit type_override. A count channel reads no column and is "quantitative".

    The spec's channels are resolved in the fixed order the ChartSpec doc states (x first through order last), and the first name absent from df raises ColumnNotFound(name). The function is not total, and this is the full set of reasons it raises:

    • ColumnNotFound — a channel column, a facet channel's column, or a repeat field-list name absent from df (the composition halves are resolved ahead of their children, in the order they are written).
    • InvalidOperation — a constant a position channel's value definition refuses (not a number or "width" / "height"), a constant on an offset channel that is not a number, a channel carrying both a field and a repeat reference, a facet sort keyed on another channel (the bare-channel form), and a composition shape the schema rejects: a layer member or a facet's spec that is not a single view or a layer, or a layer / concat / facet / repeat with nothing to compose (see chart_emit).

    The declared modifiers are not computed here — the Vega-Lite runtime evaluates them at render time. 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.

    lit

    Embed a literal Scalar. At evaluation it becomes a length-1 column broadcast against its siblings. Prefer the typed shorthands (lit_int / lit_float / lit_str / lit_bool), which avoid spelling the Scalar variant at call sites.

    Example

    test "lit: embeds any Scalar" {
    inspect(lit(@types.Scalar::Int(3L)).to_string(), content="3")
    }

    lit_bool

    fn lit_bool(value : Bool) ->
    Expr

    Bool literal.

    Example

    test "lit_bool: renders bare" {
    inspect(lit_bool(true).to_string(), content="true")
    }

    lit_float

    fn lit_float(value : Double) ->
    Expr

    Float literal.

    Example

    test "lit_float: whole values keep their point" {
    inspect(lit_float(2.0).to_string(), content="2.0")
    }

    lit_int

    fn lit_int(value : Int64) ->
    Expr

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

    Example

    test "lit_int: renders bare" {
    inspect(lit_int(5L).to_string(), content="5")
    }

    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.

    Example

    test "lit_series: names its column after the series" {
    let s = @series.Series::from_ints("score", [1, 2])
    inspect(lit_series(s).output_name(), content="score")
    }

    lit_str

    fn lit_str(value : String) ->
    Expr

    String literal.

    Example

    test "lit_str: renders quoted" {
    inspect(lit_str("ab").to_string(), content="\"ab\"")
    }

    map_many

    Apply a host closure across several input columns, row by row — the multi-input escape hatch, and the reified replacement for the original closure filter predicate: f is handed one Scalar per input in inputs order (null cells as Scalar::Null) and is called for every row, so a row predicate is a 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 — with the dtype fallback reading the leftmost input, whatever it is, so only an empty inputs leaves an all-null result with no witness and raises Unsupported. The inputs array is copied, so mutating it after construction cannot alter the built expression.

    Example

    test "map_many: drops to a host closure" {
    let total = map_many(label="total", [col("a"), col("b")], cells => {
    @types.Scalar::Int(cells[0].as_int() + cells[1].as_int())
    })
    inspect(total.to_string(), content="map(\"total\", [col(a), col(b)])")
    }

    parse_parquet

    fn parse_parquet(bytes : Bytes, projection? : Array[String]) ->
    DataFrame
    raise
    DataError

    Parse parquet bytes into a frame — the string-level entry's binary counterpart (what read_parquet hands the codec, exposed for in-memory bytes). The same contract as read_parquet's.

    plot

    Bind df as the data of a chart and pick its mark: the returned FramePlot carries a mark method per ChartSpec constructor, each taking plain column names where the mirror takes a VegaChannel. The frame is held for the terminals, so it appears once, here, rather than at every render call:

    plot(df).bar(x="region", y="revenue").write_html("out.html")

    read_csv

    Read a CSV file. options defaults to CsvReadOptions::CsvReadOptions(), so read_csv(path) is the default-options read. IOError from the file system surfaces as raise IoError(message). CsvReadOptions::CsvReadOptions(strict_quotes=true) rejects malformed quoting before NyaCSV tokenisation, exactly as parse_csv_str does.

    read_json

    Read a JSON records file. options defaults to JsonReadOptions::JsonReadOptions(), so read_json(path) is the default-options read. Filesystem errors surface as raise IoError(message).

    read_ndjson

    Read an NDJSON file. options defaults to JsonReadOptions::JsonReadOptions(), so read_ndjson(path) is the default-options read. Filesystem errors surface as raise IoError(message).

    read_parquet

    fn read_parquet(path : String, projection? : Array[String]) ->
    DataFrame
    raise
    DataError

    Read a parquet file into a frame: the footer's schema names the dtypes, each column chunk decodes its pages, and the projection (every column when projection? is omitted) rides into the chunk walk — unprojected columns are never parsed. The projection is lenient like the text readers': a name the file does not carry builds no column (a projection matching no column yields the file's rows over zero columns), and whichever expression references the missing name raises ColumnNotFound, the same error a full read plus a select would. Also raises Unsupported for a dtype or encoding the mapping does not carry (a FLOAT column would narrow; a nested or dictionary-only page shape decodes or names itself) and ParseError for a malformed file.

    scan_csv

    The lazy CSV source: scan_csv(path) builds a LazyFrame whose leaf is a deferred read of path — the push-down-aware 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). It is not a streaming read — the reader still tokenises the whole file, and streaming it is tracked as future work.

    The payoff over @frame.LazyFrame::LazyFrame(read_csv(path)) is that this leaf absorbs both push-downs, so the work it skips is work the eager pipeline does:
    • projection — 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;
    • predicate — a filter sitting on the leaf moves into the read: the reader builds the predicate's columns, asks which rows survive, then parses the remaining columns for the survivors alone. Only the first such filter is absorbed; a second stays a node above the scan.

    Both prune cells an eager read-then-filter would have parsed, which is the one way a narrowed scan diverges from a full eager read: a ParseError confined to a dropped column, or to a row the predicate drops in a column the predicate does not read, does not surface. Dtype inference still walks the whole file, so dtypes and the surviving cells match the eager read exactly. The pin that fences this back is the temporal family (Date / Timestamp): temporal + / - refuse on instants leaving the microsecond range, so above a scan whose pin carries one, the value-fence holds any predicate or stage expression with such an operation in place — a sunk one would prune away the very rows the refusal lives on, and a plan that fails to collect must still fail optimized. A Decimal pin needs no fence: the decimal operations carry NaN and ±∞ as values and never raise, so a sunk predicate cannot change which rows collect.

    options (delimiter, header, null strings, inference window, parse-error policy, strict quotes, dtype pins, …) defaults to CsvReadOptions::CsvReadOptions(), mirroring eager read_csv. It is 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_json

    The lazy JSON source: scan_json(path) builds a LazyFrame whose leaf is a deferred read of path — the push-down-aware counterpart of eager read_json, for the single top-level array of records ([{...}, {...}]). Like every LazyFrame constructor it is total: nothing is read or parsed until collect, so a missing file, malformed JSON, or a non-object record only surfaces then (as the eager reader's IoError / ParseError).

    The one-way shape of the format sets what the push-downs can prune: the top-level array must be parsed whole to find its records, so the pruning both push-downs bring is at the assembly — projection leaves the dropped columns uninferred and unbuilt, and the first predicate sitting on the leaf builds only the surviving rows' cells past the predicate's own columns. The parse itself is never skipped, which is also why this is not a streaming read. A ParseError confined to a dropped column or to a dropped row therefore does not surface, and the surviving cells and dtypes match an eager read exactly — the contract the other two scan sources honour, at the granularity this format allows.

    options defaults to JsonReadOptions::JsonReadOptions(), mirroring eager read_json, and is captured into the plan and applied at collect time; projection push-down narrows which columns those options parse, never which options apply. A Date / Timestamp pin fences the temporal value half of the push-downs exactly as it does for scan_csv, read off the same options field; a Decimal pin carries no value fence.

    scan_ndjson

    The lazy NDJSON source: scan_ndjson(path) builds a LazyFrame whose leaf is a deferred read of path — the push-down-aware 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). It is not a streaming read — the reader still parses every line — and it absorbs the same two push-downs scan_csv documents: projection (only the consumed columns are built) and the first predicate sitting on the leaf (the surviving rows' cells are the only ones built past the predicate's own columns). So a parse error confined to a dropped column, or to a dropped row, does not surface; the surviving cells and the inferred dtypes match an eager read exactly. (The single-array shape has its own source, scan_json.)

    options (inference window, parse-error policy, dtype pins, …) defaults to JsonReadOptions::JsonReadOptions(), mirroring eager read_ndjson. It is 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. A Date / Timestamp pin fences the temporal value half of the push-downs exactly as it does for scan_csv, read off the same options field; a Decimal pin carries no value fence (its operations are total).

    scan_parquet

    fn scan_parquet(path : String) ->
    LazyFrame

    The lazy parquet source: scan_parquet(path) builds a LazyFrame whose leaf is a deferred read of path — the push-down-aware counterpart of eager read_parquet, and the columnar twin of the text scans. Nothing is read until collect (the builder is total). The projection push-down is where a columnar source pays: the optimizer narrows the leaf to the columns the pipeline consumes, and only those chunks decode — a select of two columns of a wide file never touches the other chunks' bytes at all. The predicate push-down moves the filter into the read as a post-decode filter over the projected frame (the row pruning a columnar file without row-group statistics can offer); a ParseError in an unprojected column does not surface, exactly like the text scans' dropped columns. The dtypes come from the footer's schema, so a narrowed scan matches the eager read exactly — and the footer can name temporal columns no plan-time fact can rule out (reading it at build would break the builder's totality), so this source takes the temporal value-fence's conservative arm: a predicate or stage expression carrying a temporal-checked operation stays above the scan, trading that push-down for a failing plan still failing. A decimal column needs no fence — its operations are total over values.

    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.

    Example

    test "when: the chain is the only construction route" {
    let tagged = when(col("qty").gt(lit_int(5)))
    .then(lit_str("big"))
    .otherwise(lit_str("small"))
    inspect(
    tagged.to_string(),
    content="when((col(qty) > 5)).then(\"big\").otherwise(\"small\")",
    )
    }

    write_csv

    Write a DataFrame to a CSV file. options defaults to CsvWriteOptions::CsvWriteOptions(), so write_csv(path, df) is the default-options write. 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. CsvWriteOptions::CsvWriteOptions(sanitize_formulas=true) applies the same spreadsheet-safety transformation as format_csv before writing. Rendering runs through format_csv first, so its refusals come first too — an unrepresentable delimiter and the N×0 shape (rows but no columns) both raise InvalidOperation before the file is opened, leaving nothing written.

    write_json

    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_parquet

    Write a frame as one parquet file. Raises Unsupported for a column whose dtype the mapping does not carry (a Null column) and InvalidOperation for a Date day count outside the INT32 the parquet DATE annotation rides, for a Decimal cell whose NaN / ±∞ shape has no fixed-point spelling, and for a decimal column past the 38-digit payload window.

    write_vega_html

    Write the HTML document format_vega_html produces to path. A ColumnNotFound from the spec emission (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.

    write_vega_lite

    Write a Vega-Lite v6 spec for df / chart to path. Mirrors write_json: 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