CSV

:= { records : List(Record) }

RFC 4180-style CSV parsing and typed record decoding.

The dialect is RFC 4180 with the common relaxations of Python's csv module (strict mode) and Rust's csv crate:

  • Fields are separated by , and records by CRLF, LF or a lone CR. The line break after the last record is optional, and empty input has no records.
  • A field is any run of bytes other than ,, CR and LF, so fields may hold arbitrary UTF-8, tabs, spaces (kept verbatim) and control characters.
  • A field that starts with " is quoted: it may contain ,, CR and LF, a doubled "" stands for one ", and the closing quote must be followed by ,, a line break or the end of input. An unterminated quoted field is an error.
  • A " anywhere else in an unquoted field is an ordinary character.
  • A blank line is a record with one empty field, as RFC 4180's grammar says (Python's csv.reader returns an empty list for it instead).
  • Rows may have different numbers of fields. A byte order mark is not removed; it is part of the first field.

Read a file as typed rows, text fields, or raw bytes:

  • CSV.decode_str decodes rows into records whose field names match the header row, with the row type chosen by type inference;
  • CSV.rows_parser runs a hand-built record parser (record, field and Parser.keep) over every row, matching columns by position;
  • CSV.parse_string_records returns every field as a Str;
  • CSV.parse_str returns the raw fields.
Person : { name : Str, age : U64 }

people : Try(List(Person), [InvalidCsv(CSV.Error)])
people = CSV.decode_str("name,age\nAda,36\nAlan,41\n", {})

expect people == Ok([{ name: "Ada", age: 36 }, { name: "Alan", age: 41 }])
is_eq : _

Compare CSV documents by their raw records.

to_hash : _

Hash a CSV document by its raw records.

from_quote : Str -> Try(CSV, [BadQuotedBytes(Str)])

Check quoted CSV during compilation. Access raw records with .records. The first record is data unless configured validation selects a header.

validate : ValidationProps -> Try(List(Record), [InvalidCsv(Error)])

Validate raw CSV records, rejecting selected header checks as well as malformed CSV. Header checks compare normalized names in Normalized mode; Absent does not interpret any record as column names.

validate_as : DecodeValidationProps -> Try(List(row), [InvalidCsv(Error), ..errs]) where [row.Parseable([InvalidCsv(Error), ..errs])]

Validate and decode rows into the inferred Roc type. Exact and Normalized use a header; Absent decodes headerless tuples.

parse_string_records : Str, Props -> Try(List(List(Str)), [InvalidCsv(Error)])

Parse every field as text, including the header as an ordinary record.

Fields are kept verbatim, with CSV quoting removed and doubled quotes decoded. Empty input has no records; a blank line has one empty field. Uses the same grammar and syntax diagnostics as CSV.parse_str.

expect CSV.parse_string_records("name,note\nAda,\"said \"\"hello\"\"\"\n", {}) == Ok([["name", "note"], ["Ada", "said \"hello\""]])
parser : Props -> Parser(Bytes, CSV, [InvalidCsv(Error)])

A parser for a whole CSV file, for use inside larger parsers.

It reads records until its input ends, so it consumes all of it or fails with the offset of the malformed field. It accepts any bytes.

split_header : CSV -> { header : List(Str), rows : List(Record) }

Split off the first record as column names.

Names are decoded lossily and kept verbatim. Empty input gives no names and no rows.

expect {
    records = CSV.parse_str("name,age\nAda,36\n", {}).map_ok(|document| document.records)?
    CSV.{records:records}.split_header() == { header: ["name", "age"], rows: [["Ada".to_utf8(), "36".to_utf8()]] }
}
record : a -> Parser(Record, a, p)

Start a record parser with a curried constructor for the desired value.

Add one .keep(CSV.field(...)) per column, in column order:

Name : { first : Str, last : Str }

name : Parser(CSV.Record, Name, _)
name = CSV.record(|first| |last| { first, last }).keep(CSV.field(CSV.string({}))).keep(CSV.field(CSV.string({})))

expect CSV.rows_parser({row:name}).parse_str("Ada,Lovelace") == Ok([{ first: "Ada", last: "Lovelace" }])
field : Parser(Bytes, a, p) -> Parser(Record, a, [MissingField, UnconsumedField(U64), FieldProblem(Diagnostic(Problem(p)))])

Consume the next field of a CSV.Record using a parser for its bytes.

The field parser must consume the whole field. Fails when the record has no fields left.

string : {} -> Parser(Bytes, Str, Problem(p))

Parse one field as a valid UTF-8 string, kept verbatim (no trimming).

u64 : {} -> Parser(Bytes, U64, Problem(p))

Parse one field as an unsigned 64-bit integer.

The field must be ASCII decimal digits with an optional leading +, and fit in a U64 (the grammar of Rust's u64::from_str). Whitespace, underscores, signs other than + and 0x-style prefixes are rejected.

f64 : {} -> Parser(Bytes, F64, Problem(p))

Parse one field as a 64-bit floating-point number.

The field is an optional sign followed by inf, infinity or nan in any case, or by a decimal number with an optional fraction and exponent (12, 1.5, .5, 5., 1e-3, 2.5E+10); this is the grammar of Rust's f64::from_str. Magnitudes too large for an F64 become infinity and too small ones become zero. Whitespace, underscores and hexadecimal forms are rejected.

parse_bytes : List(U8), Props -> Try(CSV, [InvalidCsv(Error)])

Parse raw CSV bytes without imposing an encoding on field payloads.

decode_str : Str, DecodeProps -> Try(List(row), [InvalidCsv(Error), ..errs]) where [row.Parseable([InvalidCsv(Error), ..errs])]

Decode typed rows directly from source using the existing whole-input scanner.

decode : CSV, DecodeProps -> Try(List(row), [InvalidCsv(Error), ..errs]) where [row.Parseable([InvalidCsv(Error), ..errs])]

Decode an already parsed document without inventing physical coordinates.

decode_rows : CSV, RowsProps(row, problem) -> Try(List(row), [InvalidCsv(Error), InvalidRow(RowError(problem))])

Decode this document with a positional row grammar.

rows_parser : RowsProps(row, problem) -> Parser(Bytes, List(row), [InvalidCsv(Error), InvalidRow(RowError(problem))])
decoder : ReaderProps -> Decoder(State, Record, [InvalidCsv(Error)])

Decode raw byte records with the shared streaming API.

positional_decoder : PositionalProps(row, p) -> Decoder(State, row, [InvalidCsv(Error), InvalidRow(RowError(p))])
typed_decoder : TypedProps -> Decoder(TypedState, row, [InvalidCsv(Error), ..errs]) where [row.Parseable([InvalidCsv(Error), ..errs])]
encode_record : Record, WriteProps -> Try(List(U8), [InvalidCsv(Error)])

Validate and encode one byte record using necessary quoting and CRLF.

encoder : WriteProps -> Encoder(U64, Record, [InvalidCsv(Error)])

Encode validated records through the shared streaming writer.

encode : CSV, WriteProps -> Try(List(U8), [InvalidCsv(Error), InvalidChunkSize(Diagnostic(ChunkSizeProblem))])

Encode this document with the configured writer and completion checks.

Record : List(List(U8))

One CSV record: its fields as raw bytes, in column order.

Fields parsed from a Str are valid UTF-8; records built by hand may hold any bytes.

Problem : [Syntax(Problem), ExpectedValue({ expected : ValueType, source : Excerpt }), MissingField, WidthMismatch({ found : U64, expected : U64 }), EmptyHeader, DuplicateHeader(Str), MissingRequiredField(Str), EmptyRecord, LimitExceeded({ resource : Resource, max : U64, observed : Observed }), UnsupportedCell([Record, Tuple, TagPayload]), InvalidValue, UnknownTag(Excerpt), ..p]

Native CSV failures. Payload bytes are bounded excerpts of source data.

ValueType : [Text, Boolean, Empty, U8, I8, U16, I16, U32, I32, U64, I64, U128, I128, Dec, F32, F64]

The scalar type expected by a cell decoder.

Error : Diagnostic(Problem([]))

A CSV syntax or type-directed decoding failure.

RowError : Diagnostic([ParserFailure(Problem(problem)), UnreadFields({ found : U64, read : U64 })])

A custom positional parser failure, preserving its own tagged problem.

HeaderMode : [Absent, Exact, Normalized]

Whether the first record is a header, and how its names are matched. Raw validation keeps every record unchanged in all modes.

Lints

:= { duplicate_headers : Bool ?? True, empty_headers : Bool ?? True }

Header checks. They only apply when a header mode is selected.

ValidationProps

:= { source : Str, name : Str ?? "<literal>", header : HeaderMode ?? Absent, lints : Lints ?? {} }

Checked raw parsing; headers are absent unless explicitly selected.

DecodeValidationProps

:= { source : Str, name : Str ?? "<literal>", header : HeaderMode ?? Exact, lints : Lints ?? {} }

Checked decoding; header names match exactly unless overridden.

Decoded

:= { value : List(row) }

A quotation of typed CSV rows. Access the rows with .value.

from_quote : Str -> Try(Decoded(row), [BadQuotedBytes(Str)]) where [row.Parseable([InvalidCsv(Error), ..errs])]

Decode quoted CSV using exact header names and enabled header checks.

Parseable : row
    where [
        row.parser_for : Format(errs) -> (State -> Try({ value : row, rest : State }, errs)),
    ]

Names the requirement that a row type can be decoded from CSV, so a signature can say "CSV-parseable" without naming the internal format and state types.

DecodeProps

:= { header : HeaderMode ?? Exact }

Typed rows use exact headers unless another mode is explicitly selected.

Props

:= { header : HeaderMode ?? Absent, validation : [SyntaxOnly, Checked(Lints)] ?? SyntaxOnly }

Parse a complete CSV document and retain its raw records.

RowsProps

:= { row : Parser(Record, row, problem) }

A configured whole-document parser for hand-built positional row grammars.

Format

CSV.Format(errors) :: # (opaque)

The format protocol for custom parser_for implementations. Its parameter is the complete error row shared by all parsing operations.

parse_str : Format([InvalidCsv(Error), ..errors]), State -> Try({ value : Str, rest : State }, [InvalidCsv(Error), ..errors])

Read the cell as UTF-8 text, verbatim.

parse_bool : Format([InvalidCsv(Error), ..errors]), State -> Try({ value : Bool, rest : State }, [InvalidCsv(Error), ..errors])

Read true or false in any letter case.

parse_u8 : Format([InvalidCsv(Error), ..errors]), State -> Try({ value : U8, rest : State }, [InvalidCsv(Error), ..errors])

Read ASCII digits with an optional + as a U8.

parse_i8 : Format([InvalidCsv(Error), ..errors]), State -> Try({ value : I8, rest : State }, [InvalidCsv(Error), ..errors])

Read ASCII digits with an optional sign as a I8.

parse_u16 : Format([InvalidCsv(Error), ..errors]), State -> Try({ value : U16, rest : State }, [InvalidCsv(Error), ..errors])

Read ASCII digits with an optional + as a U16.

parse_i16 : Format([InvalidCsv(Error), ..errors]), State -> Try({ value : I16, rest : State }, [InvalidCsv(Error), ..errors])

Read ASCII digits with an optional sign as a I16.

parse_u32 : Format([InvalidCsv(Error), ..errors]), State -> Try({ value : U32, rest : State }, [InvalidCsv(Error), ..errors])

Read ASCII digits with an optional + as a U32.

parse_i32 : Format([InvalidCsv(Error), ..errors]), State -> Try({ value : I32, rest : State }, [InvalidCsv(Error), ..errors])

Read ASCII digits with an optional sign as a I32.

parse_u64 : Format([InvalidCsv(Error), ..errors]), State -> Try({ value : U64, rest : State }, [InvalidCsv(Error), ..errors])

Read ASCII digits with an optional + as a U64.

parse_i64 : Format([InvalidCsv(Error), ..errors]), State -> Try({ value : I64, rest : State }, [InvalidCsv(Error), ..errors])

Read ASCII digits with an optional sign as a I64.

parse_u128 : Format([InvalidCsv(Error), ..errors]), State -> Try({ value : U128, rest : State }, [InvalidCsv(Error), ..errors])

Read ASCII digits with an optional + as a U128.

parse_i128 : Format([InvalidCsv(Error), ..errors]), State -> Try({ value : I128, rest : State }, [InvalidCsv(Error), ..errors])

Read ASCII digits with an optional sign as a I128.

parse_dec : Format([InvalidCsv(Error), ..errors]), State -> Try({ value : Dec, rest : State }, [InvalidCsv(Error), ..errors])

Read an optional sign, digits and an optional fraction.

parse_f32 : Format([InvalidCsv(Error), ..errors]), State -> Try({ value : F32, rest : State }, [InvalidCsv(Error), ..errors])

Read a float with the grammar of CSV.f64.

parse_f64 : Format([InvalidCsv(Error), ..errors]), State -> Try({ value : F64, rest : State }, [InvalidCsv(Error), ..errors])

Read a float with the grammar of CSV.f64.

parse_null : Format([InvalidCsv(Error), ..errors]), State -> Try(State, [InvalidCsv(Error), ..errors])

An empty cell is null, so a Try(a, [Null]) field is Err(Null).

parse_record_start : Format([InvalidCsv(Error), ..errors]), State -> Try([Counted({ len : U64, rest : State }), Uncounted(State)], [InvalidCsv(Error), ..errors])

A row is one record; a record inside a row is rejected.

parse_record_field : Format([InvalidCsv(Error), ..errors]), FieldNames(_shape), State -> Try(
    [
        Field({ field : FieldName(_shape), rest : State }),
        TryField({ name : Str, rest : State }),
        TryFieldCaseless({ name : Str, rest : State }),
        Continue(State),
        Done(State),
    ],
    [InvalidCsv(Error), ..errors],
)

Offer the next header name as the field to fill.

parse_record_after_field : Format([InvalidCsv(Error), ..errors]), State -> Try([Continue(State), Done(State)], [InvalidCsv(Error), ..errors])

The record ends after the last header column.

skip_record_field : Format([InvalidCsv(Error), ..errors]), State -> Try(State, [InvalidCsv(Error), ..errors])

The cell to skip is chosen by the column, so nothing is consumed.

parse_tuple_start : Format([InvalidCsv(Error), ..errors]), State, U64 -> Try(State, [InvalidCsv(Error), ..errors])

A headerless row is a tuple with one element per field.

parse_tuple_next : Format([InvalidCsv(Error), ..errors]), State, U64, U64 -> Try(State, [InvalidCsv(Error), ..errors])

Move to the cell of the next tuple element.

invalid_value : Format([InvalidCsv(Error), ..errors]), State -> [InvalidCsv(Error), ..errors]

The error for a cell that holds no valid value.

parse_tuple_end : Format([InvalidCsv(Error), ..errors]), State, U64 -> Try(State, [InvalidCsv(Error), ..errors])

Finish a tuple row.

missing_field : Format([InvalidCsv(Error), ..errors]), Str -> [InvalidCsv(Error), ..errors]

Report a required field absent from the input.

parse_tag_union : Format([InvalidCsv(Error), ..errors]), ParseTagUnionSpec(a, Format([InvalidCsv(Error), ..errors]), State, [InvalidCsv(Error), ..errors]), State -> Try({ value : a, rest : State }, [InvalidCsv(Error), ..errors])

A tag without a payload is read from its name.

Resource : Resource

Limits for one unfinished record; completed rows leave the decoder.

ReaderLimits

:= { max_field_bytes : U64 ?? default_field_bytes, max_record_bytes : U64 ?? default_record_bytes, max_fields : U64 ?? default_fields }

ReaderProps

:= { max_field_bytes : U64 ?? CSVReader.default_field_bytes, max_record_bytes : U64 ?? CSVReader.default_record_bytes, max_fields : U64 ?? CSVReader.default_fields, errors : RecoveryProps ?? {} }

PositionalProps

:= { row : Parser(Record, row, p), reader : ReaderLimits ?? {}, errors : RecoveryProps ?? {} }

Decode safely framed rows with a custom positional parser.

TypedProps

:= { header : HeaderMode ?? Exact, reader : ReaderLimits ?? {}, errors : RecoveryProps ?? {} }

Decode rows into the inferred type using the chosen header mode.

LineEnding : [CrLf, Lf, Cr]

Writer options. Each emitted chunk is bounded; records are validated first.

Quoting : [Necessary, Always]

Whether to quote only special fields or every field.

WriteProps

:= { line_ending : LineEnding ?? CrLf, quoting : Quoting ?? Necessary, max_field_bytes : U64 ?? 16_777_216, max_record_bytes : U64 ?? 67_108_864, max_fields : U64 ?? 65_536, chunk_bytes : U64 ?? 65_536 }

Writer byte limits and output dialect.

State

CSV.State :: # (opaque)

The cursor for type-directed decoding: one record, the header names, and indices into them. Used through CSV.decode_str; you do not need to name it.