精炼类型
基于一个内置类型或另一个精炼类型的类型会在其上添加规则。它没有字段:它的值就是通过这些规则的基础类型的值。
<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会把基础值传给该函数。规则检查返回的值。 |
factory(value) => ... |
此类型的值会被转换成什么:一个由它派生的类型的值。factory: ... 将该值读取为 $value。请参阅工厂。 |
value: expression |
值在使用处表示什么,在所有规则通过后最后求出。$value是已检查的值,结果可以是其他类型。见值表示什么。 |
值先转换为基础类型,然后规范化,再按规则检查,最后如果有value规则,则由它求出该值表示什么。未通过的值会报告它违反的每一条规则。字段上的规则也是同样的工作方式:title: string(min: 1)。
调用类型会生成该类型的值,检查方式相同:Age(42)、Slug(' Hello-World ')。每个声明的类型都是这样工作的(Repo($data)、Size('small')),其名称总是直接书写,不带$。
读取模式捕获的内容
带有 pattern 的类型经常需要其自身文本的一部分:[/3] 中的数字、12 cm 中的单位。与其切割文本,不如在模式中用括号括起该部分,并在类型的方法中用 .group() 读取。组 1 是第一个开启的组,2 是下一个,0 是整个匹配:
<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命名组写作 (?<name>...),按名称读取。它仍然计入编号,因此下面的 .group('amount') 和 .group(1) 读取的是同一部分:
<type name="Measure" with="string" pattern="/^(?<amount>[0-9]+) *(?<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() 读取 normalize 运行之后的值,因为那是模式所检查的文本。添加 raw 可改为读取原始传入的文本。未参与匹配的组,或模式不匹配的 raw 文本,会得到 null:
<type name="Measure" with="string" pattern="/^(?<amount>[0-9]+) *(?<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() 可用于每个带有 pattern 和方法或 value 规则 的类型,可在它的 validate 和 value 规则中使用,也可从外部在它的值上使用($shelf->group(1))。由另一个类型构成的类型有自己的模式时读取自己的模式,否则读取它所基于的最近的模式,所以 factory 生成的每个类型都读取自己模式的分组。请求模式中没有的分组会产生 Value 错误,并列出已有的分组,编辑器会在你书写的位置报告它:
.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.在编辑器中,.group( 会提示模式中已有的编号和名称,拼错的名称有一个改为最接近名称的快速修复。
值表示什么
有时类型检查的文本并不是你想要处理的值。写作x11的微波炉按钮表示"乘以 11":类型应当检查文本,然后让脚本的其余部分使用这个数字。value规则说明该类型的值在使用处表示什么:
<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这些步骤总是按相同的顺序运行,每一步都有自己的职责:
- 值被转换为基础类型:这里是文本。
normalize对其进行整理,结果仍是基础类型:' X11 '变为'x11'。- 规则(
pattern、min、max、one_of、not和validate)检查整理后的文本。 value求出值表示什么:11。它只在所有规则通过后才运行,因此可以依赖这些规则。
在value规则中,$value是已检查的文本,.group()读取模式捕获的内容。结果可以是任何类型。也可以使用函数,它会收到已检查的文本:
<type name="Shouted" with="string" min="1">
<value value="fn(text) => "{$text->upper()}!"" />
</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'类型的方法看到的是值所表示的内容:在方法中,$value是value规则的结果。.group()仍然读取已检查的文本,因此方法可以同时使用两者:
<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=""times {.group(1)}"" />
</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值会保留它的类型,因此把它传给该类型的参数时,不会把数字当作文本来检查。参数也接受文本本身,并以同样的方式求出结果:
<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由带有value规则的类型构成的类型表示同样的结果,除非它有自己的value规则。它的规则仍然检查文本,因此也可以使用.group():
<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一个类型最多有一条value规则,而且只有由单个其他类型构成的类型才能有:带字段的类型本身就表示它的记录。这种类型的数据库列存储已检查的文本,并在读取该行时重新求出结果。
在编辑器中,对该类型的值使用->时,会同时提供结果的方法(这里是数字的方法)和类型自身的方法;对它调用文本方法会被报告,因为运行时会失败。
使用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。 |
kscript make native Multiplier --pattern '/^x(\d+)$/' --value '.group(1)->to_int()' | 像 x11 这样表示数字 11 的文本。 |
第一个会写成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.
}然后,在项目中的任何脚本里:
<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'"和--value,后者说明值表示什么(见值表示什么)。在类型体中用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])和退格键(<)。它们都是按钮,但每一个的读取方式不同,按下时所执行的操作也不同。
给父类型加上 factory。它说明该类型的值会被转换成什么,并通过 with [Parent] 返回一个由父类型派生的类型的值。每个派生类型都保留自己的规则。常见的工厂是 try each,它会依次尝试每个类型:
<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="['<']">
<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
}调用父类型会读取一个标签,并返回工厂由它生成的结果。每个值都保留自己的类型,其文本仍然是该标签:
<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) // truefactory(label) => ... 为值命名。factory: ... 是同一个工厂,只是把值作为 $value,与 validate: 和 normalize: 的读法相同:
<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为什么使用工厂
由于每个值都保留自己的类型,接收 MicrowaveButton 的代码无需询问它属于哪一类:调用方法时会运行该类型自己的版本,如果该类型没有声明,则运行父类型的版本。
<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="['<']">
<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] {
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类型化列表 MicrowaveButton[] 和 reduce 中的 button 会保留每一项的类型,因此在 calculate 中 [*3] 仍然是 MultiplierEntry,运行的也是它自己的 apply。
值是如何生成的
调用 MicrowaveButton($label) 时,KScript 会:
- 一次性检查父类型自身的规则(此处为:不含空格);
- 用该标签运行工厂,然后
- 返回工厂生成的结果,它必须是
MicrowaveButton或其派生类型的值。
使用 try each 时,书写顺序就是尝试顺序,因此应把更具体的类型放在前面:回复 ok 同时符合 ShortReply 和 AnyReply,而 ShortReply 因为排在前面而胜出。工厂生成的类型不会再次检查父类型的规则。类型的 validate 规则在其普通规则(pattern、min、max、one_of、not)通过后才运行,因此规则可以依赖模式已经匹配这一前提。
没有任何匹配时
不符合父类型自身规则的标签会得到相应的错误,工厂不会运行。不符合 try each 中任何类型的标签会产生一个 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]' 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.
}如果想用自己的话来表述,可以在 try each 末尾加一行会抛出错误的 _ =>:
<type name="Coin" with="string" factory="fn(side) => try each $side |>
Heads,
Tails,
_ => throw Validation "A coin lands on heads or tails, not {$side}"" />
<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规则失败只表示"不是这个类型",因此会尝试下一个。规则抛出的错误(例如 validate 中的除以零)不算不匹配:它会一直向上传给调用方。
直接创建类型
你也可以直接调用工厂生成的类型。MultiplierEntry('[*3]') 会检查父类型的规则,然后检查 MultiplierEntry 的规则,仅此而已:工厂不会运行,因此即使 12 是一个有效的 NumberEntry,MultiplierEntry('12') 也是 Shape 错误。
位于不同文件中的类型
每个类型都可以放在单独的文件中。把父类型及其派生类型放在项目的 natives/ 文件夹中:每个脚本无需导入就能看到它们,因此父类型放在它们之前或之后都可以。项目的 kscript check 和编辑器以同样的方式检查工厂:
try each中列出的每个类型都必须由父类型派生(with [MicrowaveButton]),- 工厂绝不调用父类型本身,否则会再次运行工厂,无限循环,
factory(label) => ...只接受一个值,并且- 工厂只能放在由另一个类型派生的类型上,而不能放在带字段的类型上。
在编辑器中,由另一个类型派生的类型里会提示 factory 行;|> 及其后的每个逗号处会提示工厂尚未尝试的、由父类型派生的类型,每个名称都可以跳转到对应的类型。factory 之前使用的 variants: [...] 列表会报错,并说明应改写成什么。
相邻值:列表中位于它旁边的值
从序列中读取的值有时需要知道它前面或后面是什么。退格键会撤销紧挨在它之前按下的按钮;右括号属于它前面的左括号。在类型自己的方法中,.behind 是列表中当前值之前的值,.ahead 是它之后的值:
<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="['<']">
<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 <'->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值在其所在列表被指定类型时得知自己的位置:如上面的 as Key[],或者 Key[] 变量、参数、字段或返回类型。每个值都保留它当时在该列表中的位置,因此即使把某个值从列表中过滤出来,或作为 Backspace 传递出去,它仍然知道旁边的键:
<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="['<']">
<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 <')" />
<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规则如下:
- 类型为顶层类型或 null。
.ahead和.behind的类型是带有?的with链顶端的类型(这里是Key?),因为第一个值前面没有值,最后一个值后面也没有值。每个相邻值都保留自己的类型,因此->is_a(Digit)可以告诉你它是哪一类。不使用?.或!= null检查就对其调用方法,会像对待任何可能为 null 的值一样在编辑器中产生警告。 - 相邻值也知道它们自己的相邻值。
.behind?.behind是往前数两个的值。 - 只能在类型自己的方法中使用。只有在那里,值才总是知道自己所在的列表。在类型外部使用
$keys[1].ahead、在for循环中使用.ahead,或在另一个类型的方法中使用$key.ahead,无论在编辑器中还是运行时都是错误:
.ahead is read inside Key's own methods, such as fn next(): Key? => .ahead, where a value knows the list it was read into.- 单独创建的值没有相邻值。
Backspace('<')->undoes()不属于任何列表,因此在其中读取.behind会产生Value错误。当编辑器能看出该值是单独创建的时,会在调用处报告:
->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.- 只为你读取的内容付出代价。只有当值所属类型的某个方法读取
.ahead或.behind时,列表才会保留值的位置。从不读取它们的类型和以前一样快,也不会带有任何额外开销。
在编辑器中,方法内的 . 会提示 ahead 和 behind(在 .behind?. 之后也会再次提示),并显示它们被读取为的类型,悬停时会说明它们是什么。在会导致错误的位置不会提示它们。
来自包的原生类型
包通过p.NativeType(new IsbnType())添加原生类型,其中IsbnType是NativeType(KScript.Core)的子类。基类使类型能说明语言对其值所做的一切,因此不能遗漏任何内容:它的名称、描述和示例,文本如何变为值(Parse),它不带引号时如何书写,==意味着什么(Equality),是否支持<和排序(Ordering),for循环能否遍历它(Iteration),它的运算符(DeclareOperators),它的字段和方法(DeclareMembers),由它组成的列表的过滤器和方法(DeclareListMembers),它保留的字符串方法,以及编辑器提供的值。对其中任何一项回答“无”都是可以的,写成空的正文或Ordering.None即可。DurationType是应当复制的那个。包导入后,该类型就像内置类型一样工作:值无需引号,编辑器会进行检查,并支持->type()和OpenAPI模式。原生类型名称为小写,已被占用的名称不能重复使用。