精炼类型
基于一个内置类型或另一个精炼类型的类型会在其上添加规则。它没有字段:它的值就是通过这些规则的基础类型的值。
<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
}每条规则单独占一行,或者用分号在同一行分隔多条规则。规则值后面的逗号(例如min: 8,)是语法错误。validate规则允许在测试与消息之间使用逗号。
| 规则 | 检查内容 |
|---|---|
min, max |
数字的值,或文本或列表的长度。 |
pattern |
文本必须匹配。它是一个正则字面量,例如/^[a-z]+$/i,或带引号的文本。 |
one_of |
值必须是其中之一。 |
not |
值不能是其中之一。 |
validate: test, 'message' |
任意表达式,其中值为$value。可以给出多个;每个失败的表达式都会添加其消息。 |
normalize: expression |
用$value中的基础值求值一个表达式。如果表达式提供了一个函数,KScript会把基础值传给该函数。规则检查返回的值。 |
variants: [A, B] |
由此类型派生出的类型,在制作该类型的值时按顺序尝试。参见 变体。 |
值会先转换为基础类型,然后规范化,再依据规则检查。失败时会报告它违反的每一条规则。字段上的规则工作方式相同:title: string(min: 1)。
调用类型会生成该类型的值,检查方式相同:Age(42)、Slug(' Hello-World ')。每个声明的类型都是这样工作的(Repo($data)、Size('small')),其名称总是直接书写,不带$。
使用as进行受检转换
当你需要在表达式中使用带类型的值时,用expression as Type。KScript会先对表达式求值一次,然后应用与带类型赋值相同的转换、规范化和验证。检查失败会在转换处抛出错误。
<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) // 13在正则字面量中,开头的斜杠位于^锚点之前。这里,规范化器会在模式运行前接收字符串。你也可以直接写normalize: $value->trim()。
as set和as list可在列表与集合之间转换。集合会让每一项只保留一次,因此['tea', 'milk', 'tea'] as set包含两项,而$set as list会按添加顺序把它们以列表形式返回:
<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[]辅助函数可以定义在类型本身上。规范化器可以用@trim_key($value)调用它,或把该函数作为normalize: @trim_key传入。两种形式都使用输入字符串。KScript能找到块中稍后声明的辅助函数、继承的方法,以及外层模块中声明的函数。类型上的方法优先于同名的模块函数。
<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_LoginPasskeySessionKey支持string的方法以及它自己的方法。在精炼方法内部,$value是底层值,$this是被精炼的接收者,因此$this->length()可以调用该类型上的另一个方法。精炼类型会从其基础类型继承方法,并可通过声明同名方法来替换它。使用$value调用底层内置方法。你也可以把键传给类型化函数,例如key_length。在记录方法中,$this.field读取记录的某个字段。
目标也可以是内置类型($text as int)、带局部规则的类型($name as string(min: 2)),或列表($rows as Repo[])。可选目标(例如PasskeySessionKey?)接受null,并验证每个非null值。对算术表达式加括号可转换其结果,如($a + $b) as int。
用as int转换一个数字、转换带类型的变量($n: int = 3.9)或int参数会舍去小数部分,得到3。对照类型检查的数据更严格:int字段、int[]项,或int的精炼类型会报告非整数的数字(needs a whole number, but got a number (12.9)),而不是将其截断。像'NaN'或'Infinity'这样的文本不是数字,而像'1.5'这样的普通数字也不是日期。
你自己的原生类型
kscript make native会把一个精炼类型写入natives/,使其像内置类型一样工作。项目中的每个脚本都可以无需导入使用它,方式与extensions/文件夹相同。该类型的值在类型读取文本的地方无需引号书写,在该类型被使用的任何地方(赋值、参数、类型调用和请求体)都会被检查,编辑器也会检查代码中写入的值:
| 命令 | 作用 |
|---|---|
kscript make native Sku --pattern '/^[A-Z]{3}-\d{4}$/' --normalize '$value->trim()->upper()' | 模式中的文本,已先整理。 |
kscript make native Percent --base int --min 0 --max 100 | 0到100之间的整数。 |
kscript make native Username --base handle --max 16 --not @admin,@root | 一个句柄,包含不允许的名称。 |
kscript make native CompanySite --base url --validate '$value.host->ends_with("example.com"), "Use a company site"' | 带有自身规则的URL。 |
第一个会写成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.
}然后,在项目中的任何脚本里:
<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选择基础类型,默认为string。它接受url、domain和country等原生类型,或另一个精炼类型。规则有--pattern、--min、--max、--one-of a,b、--not a,b、--normalize和--validate "test, 'message'"。在类型体中用fn声明方法,并用->调用它们。
该块只包含规则和fn方法,绝不包含语句。像echo或if这样的代码应放在方法内部,否则编辑器会在块中的其他位置将其报告为错误,并说明该块能包含什么:
<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
}每个声明块都遵循同样的规则:记录类型包含其字段、规则、construct和方法;模型包含其字段、validate:规则和方法;作业包含其字段及其handle、failed和middleware函数;错误包含其字段;extend块包含其方法;枚举包含其值。块中的补全只会建议它能容纳的内容。在XML项目中,该文件是natives/sku.ks.xml中的一个<type>元素。
natives/下每个文件(包括子文件夹)中的类型和枚举都是项目自己的原生类型。kscript.json中的"natives"指定其他文件夹或通配符,而kscript make native会写入它列出的第一个文件夹:
{ "natives": ["src/types", "shared/**/*.kscript"] }脚本自己声明的类型优先于同名的项目类型。
变体:一个类型,多种形式
有时某一种值会以多种形态出现,而每种形态都需要自己的规则和自己的行为。微波炉的键盘有数字按钮(7)、倍数按钮([*2])和退格键(<)。它们都是按钮,但每一个的读取方式不同,按下时所执行的操作也不同。
你可以使用 variants 在父类型上列出这些形态。每个变体都是用 with [Parent] 从父类型派生出的类型,并保留其自身的规则:
<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
}调用父类型会读取一个标签,并返回与之匹配的变体的值。每个值都保留其变体,而其文本仍为该标签:
<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) // true将父类型用作工厂
由于每个值都保留其变体,父类型可充当工厂。接受 MicrowaveButton 的代码无需询问它属于哪一种:调用方法时会运行该变体自己的版本;若变体未声明该方法,则运行父类型的版本。
<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 digit类型化列表 MicrowaveButton[] 以及 reduce 中的 button 会保留每个项的变体,因此 [*3] 在 calculate 中仍是 MultiplierEntry,并且运行的是它自己的 apply。
变体如何被选中
父类型决定顺序。当你调用 MicrowaveButton($label) 时,KScript 会:
- 一次性检查父类型自身的规则(此处为:不含空格);
- 按列表给出的顺序依次尝试每个变体;并且
- 返回第一个通过其规则的标签所对应变体的值。
当两个变体有重叠时,应把更具体的那个放在前面。ok 的回复同时符合这两者,但 ShortReply 因列在前面而胜出:
<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 ShortReply文件名和导入顺序都不影响结果:只有列表才会影响。变体的 validate 规则会在其普通规则(pattern、min、max、one_of、not)通过后运行,因此某条规则可以依赖于模式已匹配这一事实。
没有任何匹配时
未能通过父类型自身规则的标签会返回该错误,且不会尝试任何变体。通过了父类型规则但不符合任何变体的标签,会返回一个 Shape 错误,其中列出父类型、该标签以及所尝试的每个变体:
<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).
}一条规则失败仅表示“不是此变体”,因此会尝试下一个。规则抛出的错误(例如 validate 中的除以零)不是不匹配:它会继续向上传递给调用方。
直接制作变体
你也可以直接调用某个变体本身。MultiplierEntry('[*3]') 会检查父类型的规则以及 MultiplierEntry 的规则,而不会做其他任何事情。它从不会尝试其他变体,因此即使 12 是一个有效的 NumberEntry,MultiplierEntry('12') 仍会是 Shape 错误。
变体放在单独的文件中
每个变体都可以位于其自己的文件中。将父类型及其变体放在项目的 natives/ 文件夹中:每个脚本都无需导入即可看到它们,并且 KScript 会在所有原生类型文件加载完成后,找到列表中指定的变体,因此父类型可以位于其变体之前或之后。项目的 kscript check 和编辑器同样以相同方式检查该列表:
- 每个名称都必须是直接从父类型派生的类型(
with [MicrowaveButton]), - 每个名称只能列出一次,并且
- 该列表只能放在从另一个类型派生的类型上,而不能放在带有字段的类型上。
在编辑器中,variants: [ 会提供列表中尚未指定的、从父类型派生的类型;将鼠标悬停在父类型上会按顺序显示其变体;列表中的每个名称都会跳转到其对应的类型。
来自包的原生类型
包通过p.NativeType(new IsbnType())添加原生类型,其中IsbnType是NativeType(KScript.Core)的子类。基类使类型能说明语言对其值所做的一切,因此不能遗漏任何内容:它的名称、描述和示例,文本如何变为值(Parse),它不带引号时如何书写,==意味着什么(Equality),是否支持<和排序(Ordering),for循环能否遍历它(Iteration),它的运算符(DeclareOperators),它的字段和方法(DeclareMembers),由它组成的列表的过滤器和方法(DeclareListMembers),它保留的字符串方法,以及编辑器提供的值。对其中任何一项回答“无”都是可以的,写成空的正文或Ordering.None即可。DurationType是应当复制的那个。包导入后,该类型就像内置类型一样工作:值无需引号,编辑器会进行检查,并支持->type()和OpenAPI模式。原生类型名称为小写,已被占用的名称不能重复使用。