KScript docs
EN

Types and validation

Refinement types

A type built on one built-in type, or on another refinement type, adds rules to it. It has no fields: its values are the base type's values that pass the rules.

<type name="Age" with="int" min="0" max="150" />

<type name="Slug" with="string" pattern="/^[a-z0-9]+(-[a-z0-9]+)*$/">
  <normalize value="$value->trim()->lower()" />
</type>

<type name="Username" with="handle" max="16" not="[@admin, @root]" />

<let name="age" type="Age" value="42" />
<let name="slug" type="Slug" value="' Hello-World '" />
<echo>{ $age } { $slug }</echo>
<try>
  <let name="too_old" type="Age" value="200" />
  <catch as="err">
    <echo value="$err.message" />
  </catch>
</try>
type Age with [int] { min: 0; max: 150 }

type Slug with [string] {
  pattern: /^[a-z0-9]+(-[a-z0-9]+)*$/
  normalize: $value->trim()->lower()
}

type Username with [handle] {
  max: 16
  not: [@admin, @root]
}

$age: Age = 42
$slug: Slug = ' Hello-World '
echo "{ $age } { $slug }"
try {
  $too_old: Age = 200
} catch err {
  echo $err.message
}

Write each rule on its own line, or separate rules on one line with a semicolon. A comma after a rule value, such as min: 8,, is a syntax error. A validate rule accepts a comma between its test and its message.

Rule What it checks
min, max A number's value, or the length of text or a list.
pattern Text must match. It is a regex literal such as /^[a-z]+$/i, or quoted text.
one_of The value must be one of these.
not The value must not be one of these.
validate: test, 'message' Any expression, with the value as $value. Several can be given; each one that fails adds its message.
normalize: expression Evaluates an expression with the base value in $value. If the expression supplies a function, KScript passes the base value to that function. The rules check the returned value.
factory(value) => ... What a value of this type is made into: a value of a type made from it. factory: ... reads the value as $value. See Factories.
value: expression What a value reads as wherever it is used, worked out last, once every rule has passed. $value is the checked value, and the result can be of another type. See What a value reads as.

A value is converted to the base type first, then normalized, then checked against the rules, and last its value rule, if it has one, works out what it reads as. One that fails reports every rule it broke. Rules on a field work the same way: title: string(min: 1).

Calling a type makes a value of it, checked the same way: Age(42), Slug(' Hello-World '). Every declared type works like this (Repo($data), Size('small')), and its name is always written bare, without $.

Reading what the pattern captured

A type with a pattern often needs a part of its own text: the number in [/3], the unit in 12 cm. Rather than slicing the text, put the part in brackets in the pattern and read it with .group() inside the type's methods. Group 1 is the first group to open, 2 the next, and 0 is the whole match:

<type name="DivisionEntry" with="string" pattern="/^\[\/0*([1-9][0-9]*)\]$/">
  <fn name="apply_to" params="display: int" description="The display after pressing this button: divided by its number, rounded down." returns="int" value="($display / .group(1)->to_int())->floor()" />
</type>

<let name="button" value="DivisionEntry('[/05]')" />
<echo value="$button->apply_to(100)" /> <!-- 20, because group 1 is '5': the 0 before it is outside the brackets -->
type DivisionEntry with [string] {
  pattern: /^\[\/0*([1-9][0-9]*)\]$/

  /// The display after pressing this button: divided by its number, rounded down.
  fn apply_to(display: int): int => ($display / .group(1)->to_int())->floor()
}

$button = DivisionEntry('[/05]')
echo $button->apply_to(100)  // 20, because group 1 is '5': the 0 before it is outside the brackets

A named group, written (?<name>...), is read by its name. It still counts in the numbering, so .group('amount') and .group(1) below read the same part:

<type name="Measure" with="string" pattern="/^(?&lt;amount>[0-9]+) *(?&lt;unit>cm|mm|m)$/">
  <fn name="amount" returns="int" value=".group('amount')->to_int()" />
  <fn name="unit" returns="string" value=".group('unit')" />
</type>

<let name="shelf" value="Measure('120 cm')" />
<echo value="$shelf->amount() + 30" /> <!-- 150, because .group('amount') is the text '120', read as a number -->
<echo value="$shelf->unit()" /> <!-- cm -->
<echo value="$shelf->group(1)" /> <!-- 120: the same group as 'amount', by its number -->
type Measure with [string] {
  pattern: /^(?<amount>[0-9]+) *(?<unit>cm|mm|m)$/

  fn amount(): int => .group('amount')->to_int()
  fn unit(): string => .group('unit')
}

$shelf = Measure('120 cm')
echo $shelf->amount() + 30  // 150, because .group('amount') is the text '120', read as a number
echo $shelf->unit()          // cm
echo $shelf->group(1)        // 120: the same group as 'amount', by its number

.group() reads the value after normalize has run, as that is the text the pattern was checked against. Add raw to read the text as it was given instead. A group that took no part in the match, or raw text that the pattern doesn't match, gives null:

<type name="Measure" with="string" pattern="/^(?&lt;amount>[0-9]+) *(?&lt;unit>cm|mm|m)$/">
  <normalize value="$value->lower()" />

  <fn name="unit" returns="string" value=".group('unit')" />
  <fn name="unit_as_written" returns="string" value=".group('unit', raw)" />
</type>

<let name="shelf" value="Measure('120 CM')" />
<echo value="$shelf" /> <!-- 120 cm, because normalize lowered it -->
<echo value="$shelf->unit()" /> <!-- cm, read from the normalized text -->
<echo value="$shelf->unit_as_written()" /> <!-- CM, read from the text as it was given -->
type Measure with [string] {
  pattern: /^(?<amount>[0-9]+) *(?<unit>cm|mm|m)$/
  normalize: $value->lower()

  fn unit(): string => .group('unit')
  fn unit_as_written(): string => .group('unit', raw)
}

$shelf = Measure('120 CM')
echo $shelf               // 120 cm, because normalize lowered it
echo $shelf->unit()       // cm, read from the normalized text
echo $shelf->unit_as_written()  // CM, read from the text as it was given

.group() is there on every type that has a pattern and methods or a value rule, in its validate and value rules, and on its values from outside too ($shelf->group(1)). A type made from another one reads its own pattern when it has one, else the nearest one it is made from, so each type a factory makes reads the groups of its own pattern. Asking for a group the pattern hasn't got is a Value error that lists the groups it has, and the editor reports it where you write it:

Text
.group(3) is past the last group. Measure's pattern /^(?<amount>[0-9]+) *(?<unit>cm|mm|m)$/ has 2 groups: .group(0) is the whole match, .group(1) to .group(2) the groups, and .group('amount'), .group('unit') by name.

In the editor, .group( offers the numbers and names the pattern has, and a misspelt name has a quick fix to the closest one.

What a value reads as

Sometimes the text a type checks isn't the value you want to work with. A microwave button written x11 means "times 11": the type should check the text, then let the rest of the script use the number. A value rule says what a value of the type reads as wherever it is used:

<type name="MultiplierEntry" with="string" pattern="/^x(\d+)$/">
  <normalize value="$value->trim()->lower()" />
  <value value=".group(1)->to_int()" />
</type>

<let name="button" value="MultiplierEntry(' X11 ')" />
<echo value="$button" /> <!-- 11, because value: reads group 1 of 'x11' as a number -->
<echo value="$button + 1" /> <!-- 12, because $button is the number 11 wherever it is used -->
type MultiplierEntry with [string] {
  normalize: $value->trim()->lower()
  pattern: /^x(\d+)$/
  value: .group(1)->to_int()
}

$button = MultiplierEntry(' X11 ')
echo $button      // 11, because value: reads group 1 of 'x11' as a number
echo $button + 1  // 12, because $button is the number 11 wherever it is used

The steps always run in the same order, and each one has its own job:

  1. The value is converted to the base type: here, text.
  2. normalize cleans it up, and the result is still the base type: ' X11 ' becomes 'x11'.
  3. The rules (pattern, min, max, one_of, not and validate) check that cleaned-up text.
  4. value works out what the value reads as: 11. It runs only once every rule has passed, so it can rely on them.

Inside the value rule, $value is the checked text, and .group() reads what the pattern captured. The result can be any type. A function works too, given the checked text:

<type name="Shouted" with="string" min="1">
  <value value="fn(text) => &quot;{$text->upper()}!&quot;" />
</type>

<echo value="Shouted('hello')" /> <!-- HELLO!, because the fn is given the checked text 'hello' -->
type Shouted with [string] {
  min: 1
  value: fn(text) => "{$text->upper()}!"
}

echo Shouted('hello')  // HELLO!, because the fn is given the checked text 'hello'

The type's methods see the value as it reads: in a method, $value is the result of the value rule. .group() still reads the checked text, so a method can use both:

<type name="MultiplierEntry" with="string" pattern="/^x(\d+)$/">
  <value value=".group(1)->to_int()" />

  <fn name="apply_to" params="display: int" returns="int" value="$display * $value" />
  <fn name="label" returns="string" value="&quot;times {.group(1)}&quot;" />
</type>

<let name="button" value="MultiplierEntry('x3')" />
<echo value="$button->apply_to(20)" /> <!-- 60, because $value is the number 3 -->
<echo value="$button->label()" /> <!-- times 3, read from the checked text 'x3' -->
<echo value="$button->is_odd()" /> <!-- true: $button reads as 3, so it has a number's methods -->
type MultiplierEntry with [string] {
  pattern: /^x(\d+)$/
  value: .group(1)->to_int()

  fn apply_to(display: int): int => $display * $value
  fn label(): string => "times {.group(1)}"
}

$button = MultiplierEntry('x3')
echo $button->apply_to(20)  // 60, because $value is the number 3
echo $button->label()       // times 3, read from the checked text 'x3'
echo $button->is_odd()      // true: $button reads as 3, so it has a number's methods

A value keeps its type, so passing it to a parameter of the type doesn't check the number as if it were text. A parameter also takes the text itself, and works it out the same way:

<type name="MultiplierEntry" with="string" pattern="/^x(\d+)$/">
  <value value=".group(1)->to_int()" />
</type>

<fn name="add_ten" params="entry: MultiplierEntry" returns="int" value="$entry + 10" />

<echo value="@add_ten(MultiplierEntry('x5'))" /> <!-- 15, because the value already has the type -->
<echo value="@add_ten('x6')" /> <!-- 16, because 'x6' is checked, then read as 6 -->
type MultiplierEntry with [string] {
  pattern: /^x(\d+)$/
  value: .group(1)->to_int()
}

fn add_ten(entry: MultiplierEntry): int => $entry + 10

echo @add_ten(MultiplierEntry('x5'))  // 15, because the value already has the type
echo @add_ten('x6')                    // 16, because 'x6' is checked, then read as 6

A type made from one with a value rule reads as the same result, unless it has a value rule of its own. Its rules still check the text, so they can use .group() too:

<type name="MultiplierEntry" with="string" pattern="/^x(\d+)$/">
  <value value=".group(1)->to_int()" />
</type>

<type name="BigMultiplier" with="MultiplierEntry">
  <validate test=".group(1)->to_int() > 10" message="must be over 10" />
</type>

<echo value="BigMultiplier('x12') * 2" /> <!-- 24, because BigMultiplier reads as MultiplierEntry's number -->
type MultiplierEntry with [string] {
  pattern: /^x(\d+)$/
  value: .group(1)->to_int()
}

type BigMultiplier with [MultiplierEntry] {
  validate: .group(1)->to_int() > 10, 'must be over 10'
}

echo BigMultiplier('x12') * 2  // 24, because BigMultiplier reads as MultiplierEntry's number

A type has at most one value rule, and only a type made from one other type has one: a type with fields already reads as its record. A database column of such a type stores the checked text and works the result out again when the row is read.

In the editor, -> on a value of the type offers the result's methods (a number's, here) along with the type's own, and a text method on it is reported, as it would fail when run.

Checked conversions with as

Use expression as Type when you need a typed value inside an expression. KScript evaluates the expression once, then applies the same conversion, normalization and validation as a typed assignment. A failed check raises an error at the cast.

<type name="PasskeySessionKey" with="string" min="8" pattern="/^passkey_[a-zA-Z]+$/">
  <normalize value="fn(c) => $c->trim()" />
  <fn name="length">
    <return value="$value->count()" />
  </fn>
</type>

<fn name="key_length" params="key: PasskeySessionKey" value="$key->count()" />

<let name="kind" value="'login'" />
<let name="session_key" value="&quot;passkey_{$kind}&quot; as PasskeySessionKey" />
<echo value="$session_key" /> <!-- passkey_login -->
<echo value="$session_key->count()" /> <!-- 13 -->
<echo value="$session_key->length()" /> <!-- 13 -->
<echo value="@key_length($session_key)" /> <!-- 13 -->
type PasskeySessionKey with [string] {
  min: 8
  normalize: fn(c) => $c->trim()
  pattern: /^passkey_[a-zA-Z]+$/
  fn length() {
    return $value->count()
  }
}

fn key_length(key: PasskeySessionKey) => $key->count()

$kind = 'login'
$session_key = "passkey_{$kind}" as PasskeySessionKey
echo $session_key  // passkey_login
echo $session_key->count()  // 13
echo $session_key->length()  // 13
echo @key_length($session_key)  // 13

The opening slash comes before the ^ anchor in a regex literal. Here the normalizer receives the string before the pattern runs. You can also write normalize: $value->trim() directly.

as set and as list move between a list and a set. A set keeps each item once, so ['tea', 'milk', 'tea'] as set holds two items, and $set as list gives them back as a list in the order they were added:

<let name="drinks" value="['tea', 'milk', 'tea'] as set" />
<echo value="$drinks->count()" /> <!-- 2 -->
<echo value="($drinks as list)->type()" /> <!-- string[] -->
$drinks = ['tea', 'milk', 'tea'] as set
echo $drinks->count()          // 2
echo ($drinks as list)->type() // string[]

A helper can live on the type itself. The normalizer can call it with @trim_key($value) or pass the function as normalize: @trim_key. Both forms use the input string. KScript finds helpers declared later in the block, inherited methods, and functions declared in the surrounding module. A method on the type takes precedence over a module function of the same name.

<type name="KeyText" with="string">
  <normalize value="@trim_key($value)" />
  <fn name="trim_key" params="key: string" value="$key->trim()" />
</type>
<echo value="KeyText('  passkey_Login  ')" /> <!-- passkey_Login -->
type KeyText with [string] {
  normalize: @trim_key($value)
  fn trim_key(key: string) => $key->trim()
}
echo KeyText('  passkey_Login  ')  // passkey_Login

A PasskeySessionKey supports the methods of string and its own methods. Inside a refinement method, $value is the underlying value and $this is the refined receiver, so $this->length() can call another method on the type. A refinement inherits methods from its base and can replace one by declaring the same name. Use $value to call the underlying built-in method. You can also pass the key to a typed function such as key_length. In a record method, $this.field reads a field of the record.

The target can also be a built-in type ($text as int), a type with local rules ($name as string(min: 2)), or a list ($rows as Repo[]). An optional target such as PasskeySessionKey? accepts null and validates every non-null value. Parenthesize an arithmetic expression to convert its result, as in ($a + $b) as int.

Converting one number with as int, a typed variable ($n: int = 3.9) or an int parameter drops the fraction and gives 3. Data checked against a type is stricter: an int field, an int[] item or a refinement of int reports a number that isn't whole (needs a whole number, but got a number (12.9)) instead of cutting it down. Text such as 'NaN' or 'Infinity' is not a number, and a plain number such as '1.5' is not a date.

Your own native types

kscript make native writes a refinement type to natives/ that works like a built-in one. Every script in the project can use it without an import, the same way the extensions/ folder works. Values of it are written without quotes where the type reads text, they are checked wherever the type is used (assignments, arguments, a call of the type and request bodies), and the editor checks the values written in code:

CommandWhat it does
kscript make native Sku --pattern '/^[A-Z]{3}-\d{4}$/' --normalize '$value->trim()->upper()'Text in a pattern, tidied first.
kscript make native Percent --base int --min 0 --max 100A whole number from 0 to 100.
kscript make native Username --base handle --max 16 --not @admin,@rootA handle, with names that aren't allowed.
kscript make native CompanySite --base url --validate '$value.host->ends_with("example.com"), "Use a company site"'A URL with a rule of its own.
kscript make native Multiplier --pattern '/^x(\d+)$/' --value '.group(1)->to_int()'Text such as x11 that reads as the number 11.

The first one writes natives/sku.kscript:

<type name="Sku" with="string" description="Sku: a native type built on string. A value that breaks a rule fails where it is made, and the editor checks the values written in code." pattern="/^[A-Z]{3}-\d{4}$/">
  <normalize value="$value->trim()->upper()" />
  <!-- Rules: normalize, pattern, min, max, one_of, not, validate and value. Add methods with fn. -->
</type>
/// Sku: a native type built on string. A value that breaks a rule fails where it is made, and the editor checks the values written in code.
type Sku with [string] {
  normalize: $value->trim()->upper()
  pattern: /^[A-Z]{3}-\d{4}$/
  // Rules: normalize, pattern, min, max, one_of, not, validate and value. Add methods with fn.
}

Then, in any script in the project:

<let name="sku" type="Sku" value="abc-1234" /> <!-- ABC-1234 -->
<fn name="price" params="of: Sku" value="10" />
$sku: Sku = abc-1234   // ABC-1234
fn price(of: Sku) => 10

--base selects the base type, which defaults to string. It accepts native types such as url, domain and country, or another refinement. The rules are --pattern, --min, --max, --one-of a,b, --not a,b, --normalize, --validate "test, 'message'" and --value, which says what a value reads as (see What a value reads as). Declare methods with fn in the type body and call them with ->.

The block holds only the rules and the fn methods, never statements. Code such as echo or if goes inside a method, and the editor reports it as an error anywhere else in the block, saying what the block holds:

<type name="Percent" with="int" min="0" max="100">
  <!-- A method: code goes in here. echo or if on its own line in the block is an error. -->
  <fn name="is_full" value="$value == 100" />
</type>
type Percent with [int] {
  min: 0
  max: 100

  // A method: code goes in here. echo or if on its own line in the block is an error.
  fn is_full() => $value == 100
}

The same goes for every declaration's block: a record type holds its fields, rules, construct and methods; a model its fields, validate: rules and methods; a job its fields and its handle, failed and middleware functions; an error its fields; an extend block its methods; and an enum its values. Completion in a block suggests only what it can hold. In an XML project, the file is a <type> element in natives/sku.ks.xml.

The types and enums in every file under natives/ (subfolders too) are the project's own native types. "natives" in kscript.json names other folders or globs, and kscript make native writes to the first folder it lists:

JSON
{ "natives": ["src/types", "shared/**/*.kscript"] }

A type a script declares itself wins over a project type of the same name.

Factories: one type, several kinds

Sometimes one kind of value comes in several shapes, and each shape needs its own rule and its own behaviour. A microwave's keypad has digit buttons (7), multiplier buttons ([*2]) and a backspace (<). They are all buttons, but each one is read differently and does something different when pressed.

Give the parent type a factory. It says what a value of the type is made into, and it gives back a value of a type made from the parent with with [Parent]. Each of those types keeps its own rule. The usual factory is a try each, which tries each type in turn:

<type name="MicrowaveButton" with="string" factory="fn(label) => try each $label |> NumberEntry, MultiplierEntry, BackspaceEntry">
  <validate test="not $value->contains(' ')" message="a label has no spaces" />

  <fn name="apply" params="total: int" returns="int" value="$total" />
</type>

<type name="NumberEntry" with="MicrowaveButton" pattern="/^[0-9]+$/">
  <fn name="apply" params="total: int" returns="int" value="$total * 10 ** $value->count() + $value->to_int()" />
</type>

<type name="MultiplierEntry" with="MicrowaveButton" pattern="/^\[\*([0-9]+)\]$/">
  <fn name="apply" params="total: int" returns="int" value="$total * .group(1)->to_int()" />
</type>

<type name="BackspaceEntry" with="MicrowaveButton" one_of="['&lt;']">
  <fn name="apply" params="total: int" returns="int" value="$total ~/ 10" />
</type>
type MicrowaveButton with [string] {
  validate: not $value->contains(' '), 'a label has no spaces'
  factory(label) => try each $label |> NumberEntry, MultiplierEntry, BackspaceEntry

  fn apply(total: int): int => $total
}

type NumberEntry with [MicrowaveButton] {
  pattern: /^[0-9]+$/
  fn apply(total: int): int => $total * 10 ** $value->count() + $value->to_int()
}

type MultiplierEntry with [MicrowaveButton] {
  pattern: /^\[\*([0-9]+)\]$/
  fn apply(total: int): int => $total * .group(1)->to_int()
}

type BackspaceEntry with [MicrowaveButton] {
  one_of: ['<']
  fn apply(total: int): int => $total ~/ 10
}

Calling the parent reads a label and gives back what the factory made of it. Each value keeps its own type, and its text is still the label:

<let name="button" value="MicrowaveButton('[*11]')" />
<echo value="$button" /> <!-- [*11] -->
<echo value="$button->is_a(MultiplierEntry)" /> <!-- true, because [*11] matches MultiplierEntry's pattern -->
<echo value="$button->is_a(MicrowaveButton)" /> <!-- true, because a MultiplierEntry is still a MicrowaveButton -->
<echo value="MicrowaveButton('7')->is_a(NumberEntry)" /> <!-- true -->
$button = MicrowaveButton('[*11]')
echo $button                           // [*11]
echo $button->is_a(MultiplierEntry)    // true, because [*11] matches MultiplierEntry's pattern
echo $button->is_a(MicrowaveButton)    // true, because a MultiplierEntry is still a MicrowaveButton
echo MicrowaveButton('7')->is_a(NumberEntry)  // true

factory(label) => ... names the value. factory: ... is the same factory with the value as $value, as validate: and normalize: read it:

<type name="Reply" with="string" factory="try each $value |> ShortReply, AnyReply" />

<type name="ShortReply" with="Reply" max="3" />

<type name="AnyReply" with="Reply" min="1" />

<echo value="Reply('ok')->is_a(ShortReply)" /> <!-- true, because ShortReply is tried first -->
<echo value="Reply('hello')->is_a(AnyReply)" /> <!-- true, because hello is too long for ShortReply -->
type Reply with [string] {
  factory: try each $value |> ShortReply, AnyReply
}

type ShortReply with [Reply] {
  max: 3
}

type AnyReply with [Reply] {
  min: 1
}

echo Reply('ok')->is_a(ShortReply)     // true, because ShortReply is tried first
echo Reply('hello')->is_a(AnyReply)    // true, because hello is too long for ShortReply

Why a factory

Because each value keeps its own type, code that takes a MicrowaveButton never needs to ask which kind it has: calling a method runs the type's own version, or the parent's when the type doesn't declare one.

<type name="MicrowaveButton" with="string" factory="fn(label) => try each $label |> NumberEntry, MultiplierEntry, BackspaceEntry">
  <fn name="apply" params="total: int" returns="int" value="$total" />
</type>

<type name="NumberEntry" with="MicrowaveButton" pattern="/^[0-9]+$/">
  <fn name="apply" params="total: int" returns="int" value="$total * 10 ** $value->count() + $value->to_int()" />
</type>

<type name="MultiplierEntry" with="MicrowaveButton" pattern="/^\[\*([0-9]+)\]$/">
  <fn name="apply" params="total: int" returns="int" value="$total * .group(1)->to_int()" />
</type>

<type name="BackspaceEntry" with="MicrowaveButton" one_of="['&lt;']">
  <fn name="apply" params="total: int" returns="int" value="$total ~/ 10" />
</type>

<fn name="parse_buttons" params="input: string" returns="MicrowaveButton[]" value="
  $input->split(' ')->map(fn(label) => MicrowaveButton($label))" />

<fn name="calculate" params="buttons: MicrowaveButton[]" returns="int" value="
  $buttons->reduce(fn(total, button) => $button->apply($total), 0)" />

<let name="buttons" value="@parse_buttons('1 2 [*3] &lt;')" />
<echo value="@calculate($buttons)" /> <!-- 3: 1, then 12, then 36, then the backspace drops the 6 -->
<echo value="MicrowaveButton('[*3]')->apply(12)" /> <!-- 36, because MultiplierEntry's apply multiplies -->
<echo value="MicrowaveButton('&lt;')->apply(36)" /> <!-- 3, because BackspaceEntry's apply drops the last digit -->
type MicrowaveButton with [string] {
  factory(label) => try each $label |> NumberEntry, MultiplierEntry, BackspaceEntry
  fn apply(total: int): int => $total
}

type NumberEntry with [MicrowaveButton] {
  pattern: /^[0-9]+$/
  fn apply(total: int): int => $total * 10 ** $value->count() + $value->to_int()
}

type MultiplierEntry with [MicrowaveButton] {
  pattern: /^\[\*([0-9]+)\]$/
  fn apply(total: int): int => $total * .group(1)->to_int()
}

type BackspaceEntry with [MicrowaveButton] {
  one_of: ['<']
  fn apply(total: int): int => $total ~/ 10
}

fn parse_buttons(input: string): MicrowaveButton[] =>
  $input->split(' ')->map(fn(label) => MicrowaveButton($label))

fn calculate(buttons: MicrowaveButton[]): int =>
  $buttons->reduce(fn(total, button) => $button->apply($total), 0)

$buttons = @parse_buttons('1 2 [*3] <')
echo @calculate($buttons)  // 3: 1, then 12, then 36, then the backspace drops the 6
echo MicrowaveButton('[*3]')->apply(12)  // 36, because MultiplierEntry's apply multiplies
echo MicrowaveButton('<')->apply(36)     // 3, because BackspaceEntry's apply drops the last digit

The typed list MicrowaveButton[] and the button in reduce keep each item's type, so [*3] is still a MultiplierEntry inside calculate, and its own apply is the one that runs.

How a value is made

When you call MicrowaveButton($label), KScript:

  1. checks the parent's own rules once (here, no spaces),
  2. runs the factory with the label, and
  3. gives back what the factory made, which must be a value of MicrowaveButton or of a type made from it.

With try each, the order written is the order tried, so put the more specific type first: a reply of ok fits both ShortReply and AnyReply, and ShortReply wins because it comes first. The types the factory makes don't check the parent's rules a second time. A type's validate rules run once its plain rules (pattern, min, max, one_of, not) pass, so a rule may rely on the pattern having matched.

When nothing fits

A label that fails the parent's own rules gets that error, and the factory doesn't run. A label no type in the try each fits gets one Shape error naming the parent, the label and every type tried:

<try>
  <let name="button" value="MicrowaveButton('[x]')" />
  <catch type="Shape" as="err">
    <echo value="$err.message" />
    <!-- The value doesn't fit MicrowaveButton: the string '[x]' fits none of NumberEntry, MultiplierEntry, BackspaceEntry. -->
  </catch>
</try>
try {
  $button = MicrowaveButton('[x]')
} catch Shape as err {
  echo $err.message
  // The value doesn't fit MicrowaveButton: the string '[x]' fits none of NumberEntry, MultiplierEntry, BackspaceEntry.
}

To say it in your own words, end the try each with a _ => line that throws:

<type name="Coin" with="string" factory="fn(side) => try each $side |>
    Heads,
    Tails,
    _ => throw Validation &quot;A coin lands on heads or tails, not {$side}&quot;" />

<type name="Heads" with="Coin" one_of="[heads]" />

<type name="Tails" with="Coin" one_of="[tails]" />

<echo value="Coin('heads')->is_a(Heads)" /> <!-- true -->
type Coin with [string] {
  factory(side) => try each $side |>
    Heads,
    Tails,
    _ => throw Validation "A coin lands on heads or tails, not {$side}"
}

type Heads with [Coin] {
  one_of: [heads]
}

type Tails with [Coin] {
  one_of: [tails]
}

echo Coin('heads')->is_a(Heads)  // true

A rule that fails only means "not this type", so the next one is tried. An error a rule throws, such as a division by zero inside validate, is not a mismatch: it goes on up to the caller.

Making a type directly

You may also call a type the factory makes. MultiplierEntry('[*3]') checks the parent's rules and then MultiplierEntry's, and nothing else: the factory doesn't run, so MultiplierEntry('12') is a Shape error even though 12 is a fine NumberEntry.

Types in separate files

Each type may live in its own file. Put the parent and the types made from it in the project's natives/ folder: every script sees them without an import, so the parent may come before or after them. The project's kscript check and the editor check the factory the same way:

  • each type the try each names must be made from the parent (with [MicrowaveButton]),
  • the factory never calls the parent itself, which would run the factory again, forever,
  • factory(label) => ... takes the one value, and
  • the factory goes on a type made from one other type, not on a type with fields.

In the editor, the factory line is offered in a type made from one other type, the |> and each comma after it offer the types made from the parent that the factory doesn't try yet, and each name goes to its type. The variants: [...] list that came before factory is an error that says what to write instead.

Neighbours: the values beside it in a list

A value read from a sequence sometimes needs to know what came before or after it. A backspace takes back the button pressed just before it; a closing bracket belongs to the opening one ahead of it. Inside a type's own methods, .behind is the value before this one in its list and .ahead is the value after it:

<type name="Key" with="string" factory="fn(label) => try each $label |> Digit, Backspace">
  <fn name="label" description="What the key shows on its label." returns="string" value="$value" />
</type>

<type name="Digit" with="Key" pattern="/^[0-9]$/">
  <fn name="undone" description="True when the next key is a backspace, which takes this digit back." returns="bool" value=".ahead != null and .ahead->is_a(Backspace)" />
</type>

<type name="Backspace" with="Key" one_of="['&lt;']">
  <fn name="undoes" description="The key this backspace takes back: the one pressed just before it." returns="Key?" value=".behind" />
</type>

<let name="keys" value="'4 2 &lt;'->split(' ') as Key[]" />
<let name="back" value="$keys[2] as Backspace" />
<echo value="$back->undoes()" /> <!-- 2, because .behind is the key pressed before the backspace -->
<echo value="($keys[1] as Digit)->undone()" /> <!-- true, because the key after the 2 is a backspace -->
<echo value="($keys[0] as Digit)->undone()" /> <!-- false, because the key after the 4 is a 2 -->
type Key with [string] {
  factory(label) => try each $label |> Digit, Backspace

  /// What the key shows on its label.
  fn label(): string => $value
}

type Digit with [Key] {
  pattern: /^[0-9]$/

  /// True when the next key is a backspace, which takes this digit back.
  fn undone(): bool => .ahead != null and .ahead->is_a(Backspace)
}

type Backspace with [Key] {
  one_of: ['<']

  /// The key this backspace takes back: the one pressed just before it.
  fn undoes(): Key? => .behind
}

$keys = '4 2 <'->split(' ') as Key[]
$back = $keys[2] as Backspace
echo $back->undoes()                  // 2, because .behind is the key pressed before the backspace
echo ($keys[1] as Digit)->undone()    // true, because the key after the 2 is a backspace
echo ($keys[0] as Digit)->undone()    // false, because the key after the 4 is a 2

A value learns its place when its list is typed: as Key[] as above, a Key[] variable, parameter, field or return type. Each value keeps the place it had in that list then, so a value you filter out of the list, or pass on as a Backspace, still knows the keys that were beside it:

<type name="Key" with="string" factory="fn(label) => try each $label |> Digit, Backspace">
  <fn name="label" returns="string" value="$value" />
</type>

<type name="Digit" with="Key" pattern="/^[0-9]$/" />

<type name="Backspace" with="Key" one_of="['&lt;']">
  <fn name="undoes" returns="Key?" value=".behind" />
</type>

<fn name="parse_keys" params="input: string" returns="Key[]" value="
  $input->split(' ')->map(fn(label) => Key($label))" />

<let name="keys" value="@parse_keys('7 3 &lt;')" />
<let name="backspaces" value="$keys->filter(fn(key) => $key->is_a(Backspace))" />
<echo value="($backspaces[0] as Backspace)->undoes()" /> <!-- 3, its neighbour in the list parse_keys returned -->
type Key with [string] {
  factory(label) => try each $label |> Digit, Backspace
  fn label(): string => $value
}

type Digit with [Key] {
  pattern: /^[0-9]$/
}

type Backspace with [Key] {
  one_of: ['<']
  fn undoes(): Key? => .behind
}

fn parse_keys(input: string): Key[] =>
  $input->split(' ')->map(fn(label) => Key($label))

$keys = @parse_keys('7 3 <')
$backspaces = $keys->filter(fn(key) => $key->is_a(Backspace))
echo ($backspaces[0] as Backspace)->undoes()  // 3, its neighbour in the list parse_keys returned

The rules:

  • Typed as the top type, or null. .ahead and .behind are typed as the type at the top of the with chain with ? (here Key?), because the first value has nothing behind it and the last has nothing ahead. Each neighbour keeps its own type, so ->is_a(Digit) tells you which kind it is. Calling a method on one without ?. or a != null check is a warning in the editor, as for any value that may be null.
  • Neighbours know their neighbours. .behind?.behind is two values back.
  • Only inside the type's own methods. That is where a value always knows its list. $keys[1].ahead outside the type, .ahead in a for loop, or $key.ahead in another type's method is an error, in the editor and in the run:
Text
.ahead is read inside Key's own methods, such as fn next(): Key? => .ahead, where a value knows the list it was read into.
  • A value made on its own has no neighbours. Backspace('<')->undoes() has no list, so reading .behind in it is a Value error. The editor reports it on the call when it can see the value was made on its own:
Text
->undoes() reads .behind, but this Backspace was made on its own, not read into a typed list, so it has no neighbours. A value knows its neighbours when its list is typed, such as $labels as Key[], or a Key[] parameter, field or variable.
  • You only pay for what you read. A list keeps its values' places only when one of their types' methods reads .ahead or .behind. A type that never reads them is as fast as before and carries nothing extra.

In the editor, . inside a method offers ahead and behind (and again after .behind?.), with the type they read as, and hovering them says what they are. They are never offered where they would be an error.

Native types from packages

A package adds a native type with p.NativeType(new IsbnType()), where IsbnType is a subclass of NativeType (KScript.Core). The base class makes a type say everything the language does with its values, so none can be left out: its name, description and example, how text becomes a value (Parse), how it is written without quotes, what == means (Equality), whether < and sorting work (Ordering), whether a for loop can walk it (Iteration), its operators (DeclareOperators), its fields and methods (DeclareMembers), the filters and methods of a list of it (DeclareListMembers), the string methods it keeps and the values the editor offers. "None" is a fine answer to any of them, written as an empty body or Ordering.None. DurationType is the one to copy. Once the package is imported, the type works like a built-in one: values without quotes, checks in the editor, ->type() and OpenAPI schemas. Native type names are lowercase, and a name that is taken can't be reused.