molt/value
molt/value: TOML value manipulation
This module provides functions for working with TOML data values extracted from the document. All TOML types are supported and there are some convenience functions for manipulating the types.
molt/value Preserves Content, Not Representation
Value preserves the content of the TOML values, but may change the
representation. Extracting a value from the document with molt.get,
unwrapping it with one of the unwrap_* functions, and creating a new
value instance to use with molt.set is not guaranteed to produce the
same representation.
-
String content is preserved, but not string representation. A multiline string with line-ending backslashes reads as the joined result:
"abc\↵ xyz"becomes"abcxyz"when accessed withunwrap_string. -
Integers and Floats lose leading
+for positive values (+99becomes99) and any underscore formatting (123_456_789). -
Structural values (tables, arrays of tables, inline tables, and arrays) will lose comments, whitespace, and inline formatting.
In most circumstances, molt/value manipulation is unnecessary, because
the operations provided by molt/ops for use with molt.run all
preserve the document representation.
Function Categories
There are six categories of functions in the molt/value interface:
-
constructor: functions that create a Value for the TOML value types and variants described below, including constructor variants that parse or classify the provided value. Some constructors perform validation on the values provided and returnResult(Value, MoltError)to ensure that no invalid value is possible. -
coercion: functions that coerce the representation of types into alternate, compatible versions. These always returnResult(Value, MoltError)since an integer value cannot be represented as a string without explicit conversion (or the reverse). -
introspection: functions that help distinguish between TOML value types and styles, or check the validity of user-constructedValues. -
value: functions that convert most scalarValues to Gleam values. -
array: functions that manipulate an arrayValue. -
table: functions that manipulate a tableValue.
TOML Value Types
String Values
There are four ways to express strings: basic, multi-line basic, literal, and multi-line literal. All strings must contain only Unicode characters.
-
basicstrings allow any Unicode character may be used except characters that must be escaped (",\, and Unicode characters U+0000 to U+0008, U+000A to U+001F, and U+007F).In TOML basic strings are surrounded by single
"characters and must begin and end on a single line. -
multiline basicstrings allow the same characters asbasicstrings, except that newlines (CRLF or LF) are permitted and retained within the multiline basic string (except for a newline immediately following the opening delimiter). Trailing whitespace may be suppressed with the line-ending\.In TOML multiline basic strings are surrounded by triple
"""characters, so up to two unescaped quotation marks may be present. -
literalstrings allow any Unicode character except the literal string delimiter (') and control characters except for tab. Literal strings must begin and end on a single line. No escapes are performed on literal strings. -
multiline literalstrings are just likemultiline basicstrings withliteralstring rules applied. There are no escapes (including line continuation escapes) and the delimiter is triple''', allowing up to two single quote marks may be present.
Integer Values
Integers are whole numbers. Positive numbers may be prefixed with a plus
sign (+99). Negative numbers are prefixed with a minus sign (-99).
Large numbers may have underscores between digits to enhance readability
(123_456_789). Non-negative integer values may be encoded as hexadecimal
(0x7f, 0xdead_beef), octal (0o755, 0o0123_4567), or binary
(0b0110, 0b0110_1001).
molt/value will preserve hex, octal, and binary encoded integers.
Float Values
A float consists of an integer part (which follows the same rules as
decimal integer values) followed by a fractional part and/or an exponent
part. If both a fractional part and exponent part are present, the
fractional part must precede the exponent part. Fractional parts are
separated by a decimal point and must have a digit on either side. As with
integers, underscores can separate digits. There are special float values
(treated separately by molt/value) also permitted:
valid = [+1.0, 3.14_15, -0.01, 5e+22, 1e06, -2E-2, 7_326.626e-34]
invalid = [.7, 7., 3.e+20]
special = [inf, +inf, -inf, nan, +nan, -nan]
Boolean Values
These values are always true or false and correspond to True and
False Gleam values.
Date and Time Values
TOML supports four date and time value types, which are treated as opaque
strings by molt/value. TOML date and type value types are not wholly
compatible with gleam_time and are stored internally as the
RFC3339 strings they are parsed from.
- Offset Date-Time: represents a specific instant with
a timezone offset. Seconds may be omitted in TOML 1.1 (
1979-05-27T07:32Zmeans the same as1979-05-27T07:32:00Z). - Local Date-Time: represents a date time without relationship to a timezone. Seconds may be omitted in TOML 1.1.
- Local Date: represents a calendar day.
- Local Time: represents a time of day without any relation to a specific day or timezone. Seconds may be omitted in TOML 1.1.
Array Values
Arrays are inline ordered values surrounded by square brackets ([]) and
are heterogenous containing any Value. Newlines are allowed in the
document representation, but molt/value does not guarantee any
particular formatting.
Table Values
Tables (roughly equivalent to Dict(String, Value)) are collections of
key/value pairs defined by headers on their own line ([key]). Until the
next header or end of file are key = value pairs. molt/value handles
tables as the key/value pairs.
Inline Table Values
Inline tables provide a more compact syntax for expressing tables, most
useful for grouped nested data that can otherwise quickly become verbose.
They are proper values are defined within curly braces ({}) with commas
separating key/value pairs.
In TOML 1.1, tables may span multiple lines.
Array of Tables Values
An array of tables (roughly equivalent to List(Dict(String, Value))) is
expressed as [[key]] on its own line with a table body of key/value pairs
immediately following.
Types
The sign to be used for a special float Value (Infinity or NaN).
| Infinity | NaN | |
|---|---|---|
| Unsigned | inf | nan |
| Positive | +inf | +nan |
| Negative | -inf | -nan |
pub type Sign {
Unsigned
Positive
Negative
}
Constructors
-
Unsigned -
Positive -
Negative
Values
pub fn array_append(
value value: Value,
new new: Value,
) -> Result(Value, error.MoltError)
Append an element to the end of an array.
array
pub fn array_get_at(
value value: Value,
index index: Int,
) -> Result(Value, error.MoltError)
Get the element at index from an array or array of tables Value.
Negative indices count from the end of the array.
array
pub fn array_insert_at(
value value: Value,
index index: Int,
new new: Value,
) -> Result(Value, error.MoltError)
Insert an element before the given index. Negative indices count from end.
array
pub fn array_length(value: Value) -> option.Option(Int)
Returns the size of an array. Returns None if the value provided is not an
array.
array
pub fn array_remove_at(
value value: Value,
index index: Int,
) -> Result(Value, error.MoltError)
Remove the element at index from the array Value.
Negative indices count from the end of the array.
array
pub fn array_replace_at(
value value: Value,
index index: Int,
new new: Value,
) -> Result(Value, error.MoltError)
Replace the element at index in an array Value.
Negative indices count from the end of the array.
array
pub fn array_to_list(
value: Value,
) -> Result(List(Value), error.MoltError)
Extract the items list from an array value.
array
pub fn as_array(value: Value) -> Result(Value, error.MoltError)
Coerces an array-like value to an array.
Returns a TypeMismatch error if the value is not array-shaped.
When coercing an array of tables to an array, as_array will coerce the
items with as_inline_table, returning an InvalidOperation if any item
fails to convert.
coercion
pub fn as_array_of_tables(
value: Value,
) -> Result(Value, error.MoltError)
Coerces an array-like value containing table-like values to an array of tables.
Returns a TypeMismatch error if the value is not array-shaped. If any
value in the provided array is not table-like, an InvalidOperation error
will be returned.
coercion
pub fn as_basic_string(
value: Value,
) -> Result(Value, error.MoltError)
Coerces a string to a basic (double-quoted, ") string.
Returns a TypeMismatch error if the value is not a string.
coercion
pub fn as_binary_int(
value: Value,
) -> Result(Value, error.MoltError)
Coerces an integer variant to binary representation.
Returns a TypeMismatch error if the value is not an integer.
coercion
pub fn as_decimal_int(
value: Value,
) -> Result(Value, error.MoltError)
Coerces an integer variant to decimal representation.
Returns a TypeMismatch error if the value is not an integer.
coercion
pub fn as_hex_int(value: Value) -> Result(Value, error.MoltError)
Coerces an integer variant to hex representation.
Returns a TypeMismatch error if the value is not an integer.
coercion
pub fn as_inline_table(
value: Value,
) -> Result(Value, error.MoltError)
Coerces a table-like value to an inline table.
Returns a TypeMismatch error if the value is not table-shaped.
coercion
pub fn as_literal_string(
value: Value,
) -> Result(Value, error.MoltError)
Coerces a string to a literal (single-quoted, ') string.
Returns a TypeMismatch error if the value is not a string. Returns
a ValueParseError if the content contains characters that cannot appear in
a single-quoted literal string: ', newlines, or control characters other
than tab.
coercion
pub fn as_multiline_basic_string(
value: Value,
) -> Result(Value, error.MoltError)
Coerces a string to a multiline basic (triple-double-quoted, """) string.
Returns a TypeMismatch error if the value is not a string.
coercion
pub fn as_multiline_literal_string(
value: Value,
) -> Result(Value, error.MoltError)
Coerces a string to a multiline literal (triple-single-quoted, ''')
string.
Returns a TypeMismatch error if the value is not a string. Returns
a ValueParseError if the content contains ''' or control characters not
permitted in multiline literal strings (only tab, LF, and CR are allowed
alongside other Unicode).
coercion
pub fn as_octal_int(
value: Value,
) -> Result(Value, error.MoltError)
Coerces an integer variant to octal representation.
Returns a TypeMismatch error if the value is not an integer.
coercion
pub fn as_section_table(
value: Value,
) -> Result(Value, error.MoltError)
Coerces a table-like value to a table with a section header.
Returns a TypeMismatch error if the value is not table-shaped.
coercion
pub fn basic_string(value: String) -> Value
Creates a basic string Value. TOML basic strings process escape characters and bare newlines are not permitted.
constructor
pub fn binary_int(value: Int) -> Value
Create a integer Value encoded as binary (0b1001).
constructor
pub fn datetime(text: String) -> Result(Value, error.MoltError)
Creates a date-time, date, or time Value from an RFC3339-compatible text
value. See Date and Time Values.
Returns a ValueParseError if the text cannot be parsed.
constructor
pub fn hex_int(value: Int) -> Value
Create a integer Value encoded as hex (0xff).
constructor
pub fn inspect(value: Value) -> String
Returns a debug string representation of a Value.
introspection
pub fn int_style(value: Value) -> option.Option(String)
Returns the style of integer Value, or None if not an integer.
introspection
pub fn invalid_text(value: Value) -> String
Returns the raw text of a TomlInvalid value, or empty string otherwise.
introspection
pub fn is_valid(value: Value) -> Bool
Returns True if a Value’s text is syntactically valid TOML.
Values created using the constructor functions (including parse_value) are
guaranteed to be valid, but values retrieved from a TOML document with
molt/cst functions may be invalid.
introspection
pub fn literal_string(
value: String,
) -> Result(Value, error.MoltError)
Creates a literal string Value. TOML literal strings do not process escape characters and bare newlines are not permitted.
Returns a ValueParseError if value contains ', a newline, a carriage
return, or any control character other than tab.
constructor
pub fn local_date(text: String) -> Result(Value, error.MoltError)
Creates a local date Value.
Returns a ValueParseError if the text cannot be parsed as a local date
value.
constructor
pub fn local_datetime(
text: String,
) -> Result(Value, error.MoltError)
Creates a local date-time Value.
Returns a ValueParseError if the text cannot be parsed as a local
date-time value.
constructor
pub fn local_time(text: String) -> Result(Value, error.MoltError)
Creates a local time Value.
Returns a ValueParseError if the text cannot be parsed as a local time
value.
constructor
pub fn multiline_basic_string(value: String) -> Value
Creates a multiline basic string Value. TOML basic strings process escape characters. Bare newlines are permitted.
constructor
pub fn multiline_literal_string(
value: String,
) -> Result(Value, error.MoltError)
Creates a multiline literal string Value. TOML literal strings do not process escape characters. Bare newlines are permitted.
Returns a ValueParseError if value contains ''' or any control
character other than tab, LF, or CR.
constructor
pub fn octal_int(value: Int) -> Value
Create a integer Value encoded as octal (0o67).
constructor
pub fn offset_datetime(
text: String,
) -> Result(Value, error.MoltError)
Creates an offset date-time Value.
Returns a ValueParseError if the text cannot be parsed as an offset
date-time value.
constructor
pub fn parse_value(
text: String,
) -> Result(Value, error.MoltError)
Parse a value as a Value or return an error if the value cannot be resolved.
constructor
pub fn string(value: String) -> Value
Create a string Value. This will attempt to guess the correct type of TOML
string to use, falling back to a basic or multiline basic string.
constructor
pub fn string_style(value: Value) -> option.Option(String)
Returns the style of string Value, or None if not a string.
introspection
pub fn table(entries: List(#(String, Value))) -> Value
Create an inline table Value from the entries.
constructor
pub fn table_from_dict(
entries: dict.Dict(String, Value),
) -> Value
Create an inline table Value from a Dict.
The order of keys in the inline table is non-deterministic but fixed at time of creation.
constructor
pub fn table_get_key(
value value: Value,
key key: String,
) -> Result(Value, error.MoltError)
Get the value for a key in a table.
table
pub fn table_has_key(value value: Value, key key: String) -> Bool
Check if a key exists in a table.
table
pub fn table_keys(
value: Value,
) -> Result(List(String), error.MoltError)
Get the list of key names from a table.
table
pub fn table_remove_key(
value value: Value,
key key: String,
) -> Result(Value, error.MoltError)
Remove a key from a table.
table
pub fn table_rename_key(
value value: Value,
from from: String,
to to: String,
) -> Result(Value, error.MoltError)
Rename a key in a table. Errors if the key doesn’t exist.
table
pub fn table_set_key(
value value: Value,
key key: String,
new new: Value,
) -> Result(Value, error.MoltError)
Set or replace a key in a table. Appends if key doesn’t exist.
table
pub fn table_to_dict(
value: Value,
) -> Result(dict.Dict(String, Value), error.MoltError)
Extract a Dict from a table value. Key order is lost.
table
pub fn table_to_list(
value: Value,
) -> Result(List(#(String, Value)), error.MoltError)
Extract the entries list from a table value.
table
pub fn to_cst(value: Value) -> greenwood.Element(types.TomlKind)
Produce a syntax tree representation of the value suitable for use with
cst.set_kv_value.
pub fn type_of(value: Value) -> String
Returns the TOML type name for a Value.
Strings and integers have attached styles that can be retrieved with
string_style and int_style.
introspection
pub fn unwrap_bool(value: Value) -> Result(Bool, error.MoltError)
Unwraps the boolean Value or returns a TypeMismatch error.
value
pub fn unwrap_bool_or(
value value: Value,
default default: Bool,
) -> Bool
Unwraps the boolean Value or returns the default.
value
pub fn unwrap_datetime(
value: Value,
) -> Result(String, error.MoltError)
Unwraps the offset date-time, local date-time, local date, or local time
Value as the constructed RFC3339 string or returns a TypeMismatch error.
value
pub fn unwrap_float(
value: Value,
) -> Result(Float, error.MoltError)
Unwraps the float Value or returns a TypeMismatch error.
value
pub fn unwrap_float_or(
value value: Value,
default default: Float,
) -> Float
Unwraps the float Value or returns the default.
value
pub fn unwrap_int(value: Value) -> Result(Int, error.MoltError)
Unwraps the integer Value or returns a TypeMismatch error.
value
pub fn unwrap_int_or(
value value: Value,
default default: Int,
) -> Int
Unwraps the integer Value or returns the default.
value
pub fn unwrap_string(
value: Value,
) -> Result(String, error.MoltError)
Unwraps the string Value or returns a TypeMismatch error.
value
pub fn unwrap_string_or(
value value: Value,
default default: String,
) -> String
Unwraps the string Value or returns the default.
value