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. |
variants: [A, B] |
The types made from this one to try, in order, when a value of it is made. See Variants. |
A value is converted to the base type first, then normalized, then checked against the rules. 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 $.
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=""passkey_{$kind}" 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) // 13The 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_LoginA 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:
| Command | What 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 100 | A whole number from 0 to 100. |
kscript make native Username --base handle --max 16 --not @admin,@root | A 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. |
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 and validate. 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 and validate. 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 and --validate "test, 'message'". 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:
{ "natives": ["src/types", "shared/**/*.kscript"] }A type a script declares itself wins over a project type of the same name.
Variants: 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.
You may list those shapes on the parent type with variants. Each variant is a type made from the parent with with [Parent], and it keeps its own rule:
<type name="MicrowaveButton" with="string" variants="[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 * $value->trim('[*]')->to_int()" />
</type>
<type name="BackspaceEntry" with="MicrowaveButton" one_of="['<']">
<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'
variants: [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 * $value->trim('[*]')->to_int()
}
type BackspaceEntry with [MicrowaveButton] {
one_of: ['<']
fn apply(total: int): int => $total ~/ 10
}Calling the parent reads a label and gives back a value of the variant it fits. Each value keeps its variant, 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 variant 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 variant is still a MicrowaveButton
echo MicrowaveButton('7')->is_a(NumberEntry) // trueUsing the parent as a factory
Because each value keeps its variant, the parent works as a factory. Code that takes a MicrowaveButton never needs to ask which kind it has: calling a method runs the variant's own version, or the parent's when the variant doesn't declare one.
<type name="MicrowaveButton" with="string" variants="[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 * $value->trim('[*]')->to_int()" />
</type>
<type name="BackspaceEntry" with="MicrowaveButton" one_of="['<']">
<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] <')" />
<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('<')->apply(36)" /> <!-- 3, because BackspaceEntry's apply drops the last digit -->type MicrowaveButton with [string] {
variants: [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 * $value->trim('[*]')->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 digitThe typed list MicrowaveButton[] and the button in reduce keep each item's variant, so [*3] is still a MultiplierEntry inside calculate, and its own apply is the one that runs.
How a variant is chosen
The parent owns the order. When you call MicrowaveButton($label), KScript:
- checks the parent's own rules once (here, no spaces),
- tries each variant in the order the list gives, and
- gives back a value of the first variant whose rules the label passes.
When two variants overlap, put the more specific one first. A reply of ok fits both of these, and ShortReply wins because it is listed first:
<type name="Reply" with="string" variants="[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] {
variants: [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 ShortReplyFile names and the order of imports make no difference: only the list does. A variant'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 no variant is tried. A label that passes them but fits no variant gets one Shape error naming the parent, the label and every variant 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]' matches none of its variants (tried 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]' matches none of its variants (tried NumberEntry, MultiplierEntry, BackspaceEntry).
}A rule that fails only means "not this variant", 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 variant directly
You may also call a variant itself. MultiplierEntry('[*3]') checks the parent's rules and then MultiplierEntry's, and nothing else. It never tries the other variants, so MultiplierEntry('12') is a Shape error even though 12 is a fine NumberEntry.
Variants in separate files
Each variant may live in its own file. Put the parent and its variants in the project's natives/ folder: every script sees them without an import, and KScript finds a variant named in the list once every native type file has loaded, so the parent may come before or after its variants. The project's kscript check and the editor check the list the same way:
- each name must be a type made directly from the parent (
with [MicrowaveButton]), - each name is listed once, and
- the list goes on a type made from one other type, not on a type with fields.
In the editor, variants: [ offers the types made from the parent that the list doesn't name yet, hovering the parent shows its variants in order, and each name in the list goes to its type.
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.