类型与验证
简介
KScript 为具有特定含义的文本提供内置类型,称为原生类型:email、url、ip、country、duration、color 以及另外二十多种。这些类型的值在创建时会被检查并整理,并且仍然作为文本使用。你也可以基于它们创建自己的类型。细化类型为某个类型添加规则,例如 type Age with [int] { min: 0; max: 150 }。联合类型将其他类型组合在一起,例如 type Admin with [User, Auditable]。通过某个类型规则检查的值,可以用于任何需要该类型的地方。
<type name="Username" with="handle" max="16" not="[@admin, @root]">
<validate test="not $value.name->starts_with('_')" message="A username cannot start with _" />
</type>
<fn name="greet" params="user: Username" value="'Hi ' + $user.name" />
<echo value="@greet(@Joan)" />
<try>
<echo value="@greet(@admin)" />
<catch as="err">
<echo value="$err.message" />
</catch>
</try>type Username with [handle] {
max: 16
not: [@admin, @root]
validate: not $value.name->starts_with('_'), 'A username cannot start with _'
}
fn greet(user: Username) => 'Hi ' + $user.name
echo @greet(@Joan)
try {
echo @greet(@admin)
} catch err {
echo $err.message
}本页其余部分介绍每种原生类型、它们支持的运算符、无需引号书写的值,以及如何基于这些类型构建自定义类型。
具有独立含义的文本
| 类型 | 它包含的内容 | 已整理 | 方法 |
|---|---|---|---|
email |
一个地址,例如 joan@example.com。 |
空格会被去除,域名会转换为小写。 | .local, .domain |
handle |
@后跟字母、数字、_、.或-,最多30个。 |
转为小写。 | .name(不含 @) |
uuid |
UUID,支持版本 1 到 8,以及 nil UUID 和 max UUID。 | 已转为小写形式:8-4-4-4-12。urn:uuid:、大括号和 32 位十六进制数字同样会被读取。 |
.version, .timestamp |
regex |
带有标志 i、m、s 和 x 的正则表达式。 |
->test(), ->match(), ->match_all(), ->replace(), ->split(), .pattern, .flags |
|
password |
一个秘密。它从不打印。 | ->hash(), ->verify(), ->needs_rehash(), ->strength(), ->is_strong(), ->reveal() |
原生值仍然是文本,整理之后与同样的文本比较时视为相等。电子邮件比较时会将域名转为小写。它保留了适用于它的字符串方法,编辑器也只提示这些方法:
| 类型 | 它保留的字符串方法 |
|---|---|
email |
contains, starts_with, ends_with, index_of, count, lower, upper, slice, split, replace, matches, truncate, pad, escape, url_encode, markdown_escape |
handle |
contains, starts_with, ends_with, count, upper, slice, matches, truncate, pad, escape, url_encode, markdown_escape |
uuid |
contains, starts_with, ends_with, upper, slice, split, pad, escape, url_encode, markdown_escape |
regex |
contains, starts_with, ends_with, count, escape, markdown_escape |
url |
contains, starts_with, ends_with, index_of, count, split, replace, slice, matches, truncate, pad, escape, url_encode, markdown_escape |
domain |
contains, starts_with, ends_with, index_of, count, split, upper, slice, matches, truncate, pad, escape, url_encode, markdown_escape |
ip |
contains, starts_with, ends_with, index_of, count, split, slice, matches, truncate, pad, escape, url_encode, markdown_escape |
cidr |
contains, starts_with, ends_with, index_of, count, split, slice, matches, truncate, pad, escape, url_encode, markdown_escape |
mac |
contains, starts_with, ends_with, index_of, count, split, upper, slice, matches, truncate, pad, escape, url_encode, markdown_escape |
slug |
contains, starts_with, ends_with, index_of, count, split, upper, replace, slice, matches, truncate, pad, escape, url_encode, markdown_escape |
file_path |
contains, starts_with, ends_with, index_of, count, split, lower, upper, replace, slice, matches, truncate, pad, escape, url_encode, markdown_escape |
slash_path |
contains, starts_with, ends_with, index_of, count, split, lower, upper, replace, slice, matches, truncate, pad, escape, url_encode, markdown_escape |
semver |
contains, starts_with, ends_with, index_of, count, split, slice, matches, truncate, pad, escape, url_encode, markdown_escape |
mime |
contains, starts_with, ends_with, index_of, count, split, slice, matches, truncate, pad, escape, url_encode, markdown_escape |
hex |
contains, starts_with, ends_with, index_of, count, upper, slice, matches, truncate, pad, escape, url_encode, markdown_escape |
base64 |
contains, starts_with, ends_with, index_of, count, slice, matches, truncate, pad, escape, url_encode, markdown_escape |
jwt |
contains, starts_with, ends_with, index_of, count, slice, matches, truncate, pad, escape, url_encode, markdown_escape |
json |
contains, starts_with, ends_with, index_of, count, slice, matches, truncate, pad, escape, url_encode, markdown_escape |
csv |
contains, starts_with, ends_with, index_of, count, slice, matches, truncate, pad, escape, url_encode, markdown_escape |
phone |
contains, starts_with, ends_with, index_of, count, slice, matches, truncate, pad, escape, url_encode, markdown_escape |
country |
contains, starts_with, ends_with, index_of, count, slice, matches, truncate, pad, escape, url_encode, markdown_escape |
currency |
contains, starts_with, ends_with, index_of, count, slice, matches, truncate, pad, escape, url_encode, markdown_escape |
locale |
contains, starts_with, ends_with, index_of, count, split, slice, matches, truncate, pad, escape, url_encode, markdown_escape |
timezone |
contains, starts_with, ends_with, index_of, count, split, slice, matches, truncate, pad, escape, url_encode, markdown_escape |
duration |
contains, starts_with, ends_with, index_of, count, slice, matches, truncate, pad, escape, url_encode, markdown_escape |
date_format |
contains, starts_with, ends_with, index_of, count, slice, matches, truncate, pad, escape, url_encode, markdown_escape |
cron |
contains, starts_with, ends_with, index_of, count, slice, matches, truncate, pad, escape, url_encode, markdown_escape |
color |
contains, starts_with, ends_with, index_of, count, upper, slice, matches, truncate, pad, escape, url_encode, markdown_escape |
iban |
contains, starts_with, ends_with, index_of, count, slice, matches, truncate, pad, escape, url_encode, markdown_escape |
port、card或password不保留任何内容。其余的,例如uuid上的->to_date(),会在编辑器中报告,并在脚本运行时失败。如果仍要对文本使用它,请先调用->to_string():$id->to_string()->to_date()。
<let name="email" type="email" value="' Joan.Smith@Example.COM '" />
<echo>{ $email } { $email.local } at { $email.domain }</echo>
<echo>{ $email == 'Joan.Smith@EXAMPLE.com' }</echo>
<let name="who" type="handle" value="@Joan_S" />
<echo>{ $who } { $who.name }</echo>
<let name="id" value="@uuid()" />
<let name="key" value="@uuid(v: 8, name: 'joan@example.com')" />
<echo>{ $id.version } { $key.version } { $key == @uuid(v: 8, name: 'joan@example.com') }</echo>$email: email = ' Joan.Smith@Example.COM '
echo "{ $email } { $email.local } at { $email.domain }"
echo "{ $email == 'Joan.Smith@EXAMPLE.com' }"
$who: handle = @Joan_S
echo "{ $who } { $who.name }"
$id = @uuid()
$key = @uuid(v: 8, name: 'joan@example.com')
echo "{ $id.version } { $key.version } { $key == @uuid(v: 8, name: 'joan@example.com') }"要检查文本是否为 UUID,请使用 $text->is_a(uuid)。使用 $text as uuid 进行转换,并将无效文本报告为错误。
@uuid() 生成一个随机的第 4 版 UUID。@uuid(v: 7) 生成一个按时间排序的第 7 版 UUID,通常用作数据库主键,因为新生成的 UUID 排在旧的之后;其 .timestamp 即为生成时的时间。@uuid(v: 8) 生成一个同样按时间排序的第 8 版 UUID。使用 name: 时,同一个名称每次都会得到相同的 UUID,namespace: 则用于区分来自不同位置的名称。
值的形式错误时,会在产生该值的位置直接失败,并给出一条 Shape 错误,说明原因:
$email doesn't fit email: 'joan@' isn't an email: there's nothing after the @.编辑器会在你输入时于该值处报告相同的问题(KS5012)。
更多原生类型
这些类型的工作方式与 email 和 uuid 相同:值在创建时即被检查和整理,编辑器会检查以代码形式写入的值(KS5012),并且每种类型都有其自己的方法。这些类型名称仅使用小写,因此脚本自定义的 Color 或 Duration 类型永远不会与它们混淆。
<let name="site" type="url" value="https://example.com:8443/docs?page=2" />
<echo>{ $site.host } { $site.port } { $site.query.page }</echo>
<echo value="$site->with(query: { page: 3 })" />
<echo value="$site->without(query, fragment)" />
<let name="home" type="ip" value="192.168.0.12" />
<echo>{ $home.is_private } { $home in '192.168.0.0/16' }</echo>
<let name="v" type="semver" value="1.4.2" />
<echo>{ $v->satisfies('^1.2.0') } { $v->bump('minor') }</echo>
<let name="uk" type="country" value="'United Kingdom'" />
<echo>{ $uk } { $uk.name } { $uk.currency->format(1234.5) } { $uk.flag }</echo>
<let name="wait" type="duration" value="1h30m" />
<echo>{ $wait.minutes } { $wait + 45m }</echo>
<let name="brand" type="color" value="'#ff8800'" />
<echo>{ $brand->lighten(0.5) } { $brand->contrast_ratio(white) }</echo>
<let name="pay" type="card" value="'4242 4242 4242 4242'" />
<echo>{ $pay } { $pay.brand }</echo>$site: url = https://example.com:8443/docs?page=2
echo "{ $site.host } { $site.port } { $site.query.page }"
echo $site->with(query: { page: 3 })
echo $site->without(query, fragment)
$home: ip = 192.168.0.12
echo "{ $home.is_private } { $home in '192.168.0.0/16' }"
$v: semver = 1.4.2
echo "{ $v->satisfies('^1.2.0') } { $v->bump('minor') }"
$uk: country = 'United Kingdom'
echo "{ $uk } { $uk.name } { $uk.currency->format(1234.5) } { $uk.flag }"
$wait: duration = 1h30m
echo "{ $wait.minutes } { $wait + 45m }"
$brand: color = '#ff8800'
echo "{ $brand->lighten(0.5) } { $brand->contrast_ratio(white) }"
$pay: card = '4242 4242 4242 4242'
echo "{ $pay } { $pay.brand }"Web 与网络
| 类型 | 它包含的内容 | 已整理 | 方法 |
|---|---|---|---|
url |
一个绝对 http、https、ftp、ws 或 wss URL。 |
协议和主机名均会转换为小写。 | .scheme, .host, .port, .path, .query, .fragment, .origin, ->with(path, query, fragment), ->without(query, fragment), ->join(path) |
domain |
域名例如 api.example.co.uk。支持国际化域名。 |
小写,不带结尾的点。 | .tld, .labels, ->is_subdomain_of(domain), ->ascii() |
ip |
一个 IPv4 或 IPv6 地址。 | 以标准方式编写:2001:db8::1。 |
.version, ->in(cidr), .is_private, .is_loopback |
cidr |
一段地址,例如 10.0.0.0/8。 |
主机位已清零:10.1.2.3/8 为 10.0.0.0/8。 |
->contains(ip), .network, .prefix, .size |
mac |
网卡的 MAC 地址。 | 由六组小写键值对组成,用 : 分隔。 |
|
port |
端口号,范围 1 至 65535。它是数字,不是文本。 |
标识符与格式
| 类型 | 它包含的内容 | 已整理 | 方法 |
|---|---|---|---|
slug |
由小写单词组成、用于 URL 的文本,用 - 连接。@slugify(text) 会生成一个。 |
.words |
|
file_path |
文件或文件夹的位置:./data/input.txt 指脚本所在文件夹中的路径,../shared/rates.json 指上一级文件夹,~/notes.md 指主文件夹。每个读写文件的命令都需要其中之一。参见文件路径。 |
按原样保留。 | .name, .stem, .extension, .folder, .segments, + 'name' |
slash_path |
由 / 连接的名称:页面、菜单或分类路径,例如 /docs/getting-started 或 /My Apps/Notes。它不是文件:文件是 file_path。参见斜杠路径。 |
它总是以 / 开头(home 即 /home)。每个名称两侧的空格、空部分(//)、. 以及末尾的 / 都会被去掉;.. 表示上移一级。保留大小写。 |
.segments, .name, .parent, .depth, .is_root, ->join(more), ->is_within(other) |
semver |
语义化版本号,例如 1.4.2 或 2.0.0-beta.1。 |
开头的 v 会被去掉。 |
.major, .minor, .patch, .prerelease, ->compare(other), ->satisfies(range), ->bump(part) |
mime |
媒体类型,例如 application/json; charset=utf-8。 |
类型部分会转为小写。 | .main_type, .subtype, .essence, .params, ->is('text/*') |
hex |
十六进制数字,例如哈希值。 | 转为小写;0x 会被去掉。 |
.bytes, ->to_number() |
base64 |
Base64 文本,标准或 URL 安全格式均可。$text->to_base64() 会生成一个。 |
->decode(), .bytes |
|
jwt |
JSON Web Token。不检查其签名,因此不要依据其中的声明进行登录验证。 | .header, .claims, .expires, .is_expired |
|
json |
包含有效 JSON 的文本。 | ->convert(from: json) |
|
csv |
包含有效 CSV 的文本,例如 ```csv 块。它不是文件。参见CSV。 |
.headers、->cells() 搭配 row: 或 rows、column: 或 columns、header?、as?、->save(path) |
人员与地点
| 类型 | 它包含的内容 | 已整理 | 方法 |
|---|---|---|---|
phone |
E.164 格式的电话号码:以 + 开头,后接国家代码和号码。 |
空格、点号、短横线、括号和 (0) 都会被去掉:+44 (0)7700 900123 即 +447700900123。 |
.country_code, .national, ->tel() |
country |
ISO 3166 国家代码。可识别两位和三位代码以及英文名称。 | 两个首都:GB。 |
.name, .alpha3, .currency, .flag |
currency |
ISO 4217 货币代码。 | 首都:GBP。 |
.name, .symbol, .digits, ->format(amount) |
locale |
语言标签,例如 en-GB 或 pt-BR。 |
通常的大小写形式:en_gb 即 en-GB。 |
.language, .region, .name, .native_name, ->format(value) |
timezone |
IANA 时区,例如 Europe/London,或 UTC。 |
通常的大小写形式。 | ->offset(at?), ->now(), ->convert(time), ->is_dst(at?) |
时间
| 类型 | 它包含的内容 | 已整理 | 方法 |
|---|---|---|---|
duration |
时长:1h30m、90s、2d,年和月如 5y10mo,ISO 8601 格式如 PT1H30M 或 P1Y2M,或以秒为单位的数字。 |
简写形式:90m 即 1h30m。 |
.seconds, .minutes, .hours, .days, .ms, ->iso(), ->after(time?), ->before(time?), ->add(other), ->subtract(other) |
date_format |
日期的书写格式:dd-MM-yyyy、d MMMM yyyy 或 HH:mm。每个字母都必须有意义,因此 YYYY-DD 会失败并给出提示。参见日期格式。 |
.tokens, .has_date, .has_time, .example, ->format(date), ->parse(text) |
|
cron |
由五个字段组成的 cron 计划表达式,或 @daily、@hourly 之类的表达式。 |
转为小写。 | ->next(after?), ->next_times(count, after?) |
color |
#rgb、#rrggbb、#rrggbbaa、rgb(...) 或 CSS 颜色名称。 |
#rrggbb,或带透明度的 #rrggbbaa。 |
->rgb(), ->hex(), ->css(), ->mix(other, amount?), ->lighten(amount?), ->darken(amount?), .luminance, ->contrast_ratio(other) |
金额
| 类型 | 它包含的内容 | 已整理 | 方法 |
|---|---|---|---|
iban |
银行账号,按 mod-97 校验位进行检查。 | 大写且不含空格。 | .country, ->formatted(), .bban |
card |
支付卡号,按 Luhn 校验位进行检查。与密码一样,它在输出时会被遮蔽:•••• 4242,日志和 JSON 中同样如此。 |
空格和短横线会被去掉。 | .last4, .brand, ->reveal() |
money |
某种货币的金额:GBP 9.50、9.50 GBP、£9.50、$12(美元)、€3.50、¥1200(日元)。小数点始终为 .。 |
代码、一个空格加上该货币的小数位数:£9.5 即 GBP 9.50。 |
.amount, .currency, ->format(locale?), ->add(other, rate?), ->subtract(other, rate?), ->split(parts), ->allocate(ratios) |
紧凑形式的金额,例如 GBP1.0,是货币字面量。使用大写的 ISO 货币代码,后面紧跟金额。它可用于赋值、列表和函数参数。对于负金额,写作 -GBP1.0。显式声明类型的变量也接受 $price: money = 'GBP 1.00' 这样的文本。
加法返回左侧金额的货币。要把欧元加到英镑上,需提供每欧元对应的英镑数。你可以为当前运行的主机设置一次汇率。
<do>@set_exchange_rate(from: 'EUR', to: 'GBP', rate: 0.80)</do>
<let name="price" value="GBP1.00" />
<let name="extra" value="EUR0.75" />
<echo value="$price + $extra" /> <!-- GBP 1.60 -->
<echo value="$price->add($extra, rate: 0.92)" /> <!-- GBP 1.69 -->@set_exchange_rate(from: 'EUR', to: 'GBP', rate: 0.80)
$price = GBP1.00
$extra = EUR0.75
echo $price + $extra // GBP 1.60
echo $price->add($extra, rate: 0.92) // GBP 1.69要在多次运行之间共享汇率,请把它们放在 kscript.json 的 config 部分下的 money.exchange_rates 中。外层键表示传入货币,内层键表示接收货币。
{
"config": {
"money": { "exchange_rates": { "EUR": { "GBP": 0.80 } } }
}
}你也可以用 $price: money(rates: { EUR: 0.85 }) = GBP1.00 为某个特定余额附加报价。每次相加时,KScript 按以下顺序使用第一个可用汇率。
- 在
->add()中显式指定的rate:,仅用于本次调用。 - 接收值的
money(rates: ...)表。 - 通过
@set_exchange_rate()为本次运行注册的汇率。 - 项目的
$config.money.exchange_rates设置。
+、+=、->add()、->subtract() 和 money[]->total() 遵循相同规则。列表以其第一个金额的货币进行累加。每个传入金额在相加前会按四舍五入到接收货币的最小单位,舍入时遇到中间值则远离零取整。缺少某个方向的汇率时会抛出 Type,即使存在反向或间接汇率对也是如此。两个金额之间的减法、比较和除法仍要求货币相同。
新类型的参数
| 类型 | 参数 |
|---|---|
url |
schemes(允许的协议,例如 ['https']),hosts(允许的主机) |
ip |
version(4 或 6) |
hex |
bytes(它必须容纳的字节数) |
phone |
countries(允许的国际区号,例如 ['+44', '+353']) |
money |
rates(从传入 ISO 货币代码到正数数值汇率的映射,用于传入金额的相加) |
<let name="api" type="url(schemes: ['https'], hosts: ['api.example.com'])" value="https://api.example.com/v1" />
<let name="office" type="ip(version: 4)" value="10.0.0.1" />
<echo>{ $api } { $office }</echo>$api: url(schemes: ['https'], hosts: ['api.example.com']) = https://api.example.com/v1
$office: ip(version: 4) = 10.0.0.1
echo "{ $api } { $office }"原生类型上的运算符
原生类型会声明哪些运算符可用于其值,并且只有这些运算符能用。duration支持加、减、缩放和比较。semver按版本比较。email不支持任何运算符,因此$email + 1会停止并显示相应的提示信息。编辑器读取同一份列表,因此它知道1h + 30m会得到什么结果,并在脚本运行前对$version * 2发出警告。
<let name="wait" type="duration" value="1h30m" />
<echo value="$wait + 15m" /> <!-- 1h45m -->
<echo value="$wait * 2" /> <!-- 3h -->
<echo value="$wait / 30m // 3" />
<echo value="90s < 2m" /> <!-- true -->
<echo value="@now() + $wait > @now()" /> <!-- true -->
<let name="v" type="semver" value="1.4.2" />
<echo value="$v < '1.10.0'" /> <!-- true: versions compare by number, not as text -->
<let name="price" type="money" value="'GBP 9.50'" />
<echo value="$price * 3" /> <!-- GBP 28.50 -->
<echo value="$price + 'GBP 0.50'" /> <!-- GBP 10.00 -->
<let name="home" type="ip" value="10.0.0.1" />
<echo value="$home + 5" /> <!-- 10.0.0.6 -->
<echo value="$home in '10.0.0.0/8'" /> <!-- true -->$wait: duration = 1h30m
echo $wait + 15m // 1h45m
echo $wait * 2 // 3h
echo $wait / 30m // 3
echo 90s < 2m // true
echo @now() + $wait > @now() // true
$v: semver = 1.4.2
echo $v < '1.10.0' // true: versions compare by number, not as text
$price: money = 'GBP 9.50'
echo $price * 3 // GBP 28.50
echo $price + 'GBP 0.50' // GBP 10.00
$home: ip = 10.0.0.1
echo $home + 5 // 10.0.0.6
echo $home in '10.0.0.0/8' // true紧邻原生值的文本会被按该类型读取,因此 $wait + '15m' 和 $v < '1.10.0' 可以正常工作。使用 + 连接文本时,结果仍然是文本:'Wait ' + $wait。
| 类型 | 运算符 | < > 和排序 |
for |
当……为假时 |
|---|---|---|---|---|
duration |
duration + duration、duration - duration、duration * number、number * duration、duration / number(时长)、duration / duration(数字)、duration % duration、date + duration、duration + date、date - duration、-duration、date..date step duration(step 1mo给出每个月) |
按长度(1mo 和 30d 没有顺序) |
0s |
|
money |
money + money(混合货币需要定向汇率)、money - money(单一货币)、money * number、number * money、money / number(按该货币的最小单位取整)、money / money(一个数字)、-money |
按金额计算,使用同一种货币 | 数量为 0 | |
ip |
ip + number、ip - number、ip - ip(一个数字)、ip..ip step number |
按地址排序,IPv4 优先 | ||
cidr |
ip in cidr, cidr in cidr |
按网络,然后按前缀 | 其地址(最多 65,536 个) | |
semver |
按版本:1.0.0-rc.1 < 1.0.0 < 1.10.0。== 会忽略构建元数据。 |
|||
port |
数字运算符(端口是一个数字) | 按数字 | ||
email, handle, uuid, url, domain, mac, slug, mime, hex, country, currency, locale, timezone |
按字母顺序 | |||
password |
不要用 ==,也不要用它。请使用 ->verify() |
|||
regex, base64, jwt, json, phone, cron, color, iban, card |
无 |
没有顺序的类型会以一条消息停止 < 和 ->sort()。请改为按键排序:$colors->sort(by: .luminance)。少数类型按含义而非拼写进行比较:json 忽略空格和键的顺序,base64 忽略填充,cron 比较它们运行的时间(@daily == '0 0 * * *'),color 比较颜色(orange == '#ffa500')。
日期范围按时长递增,默认为一天:
<let name="start" value="'2026-11-23'->to_date()" />
<for each="day" in="$start..$start + 5d">
<echo value="$day->format('ddd')" /> <!-- Mon to Fri -->
</for>$start = '2026-11-23'->to_date()
for day in $start..$start + 5d {
echo $day->format('ddd') // Mon to Fri
}单一原生类型的列表
所有元素为同一原生类型的列表,既拥有该类型的列表方法,也拥有所有列表都具有的方法。->only() 和 ->without() 接受该类型声明的过滤器,或类型名称,类型名称无需加引号:
<let name="versions" type="semver[]" value="[1.0.0, 1.1.0-rc.1, 1.1.0-beta.2, 1.0.10]" />
<echo value="$versions->only(releases)" /> <!-- 1.0.0, 1.0.10 -->
<echo value="$versions->without(release_candidates)" /> <!-- 1.0.0, 1.1.0-beta.2, 1.0.10 -->
<echo value="$versions->latest()" /> <!-- 1.0.10, the highest release -->
<echo value="$versions->max()" /> <!-- 1.1.0-rc.1, prereleases included -->
<let name="fees" type="money[]" value="['GBP 9.50', 'GBP 0.50']" />
<echo value="$fees->total()" /> <!-- GBP 10.00 -->
<let name="a" type="semver" value="2.0.0" />
<let name="mixed" value="[$a, 'hello', 3]" />
<echo value="$mixed->only(semver)->only(releases)" /> <!-- 2.0.0 -->
<echo value="$mixed->without(string)" /> <!-- 2.0.0, 3 -->
<echo value="'hello'->is_a(string)" /> <!-- true -->$versions: semver[] = [1.0.0, 1.1.0-rc.1, 1.1.0-beta.2, 1.0.10]
echo $versions->only(releases) // 1.0.0, 1.0.10
echo $versions->without(release_candidates) // 1.0.0, 1.1.0-beta.2, 1.0.10
echo $versions->latest() // 1.0.10, the highest release
echo $versions->max() // 1.1.0-rc.1, prereleases included
$fees: money[] = ['GBP 9.50', 'GBP 0.50']
echo $fees->total() // GBP 10.00
$a: semver = 2.0.0
$mixed = [$a, 'hello', 3]
echo $mixed->only(semver)->only(releases) // 2.0.0
echo $mixed->without(string) // 2.0.0, 3
echo 'hello'->is_a(string) // true| 类型 | 过滤器 | 列表方法 |
|---|---|---|
semver |
releases, prereleases, release_candidates, betas, alphas |
->latest() |
money |
->total() |
显式类型化的空列表会保留其元素类型。当所有项都被过滤掉时,过滤操作同样会保留类型。例如,$mixed->only(semver)->only(releases)在没有版本匹配时返回[]。对于空的semver[],->latest()返回null。对于空的money[],->total()返回null,因为没有可求和的货币。
原生类型的列表也可以不加引号书写,如上:[1.0.0, 1.1.0-rc.1]。
无引号的值
有些值不需要引号,就像 JavaScript 中的正则表达式不需要引号一样。
- 时长可以在任何地方直接作为字面量使用:
30s、500ms、1h30m。参见时间长度。 - 电子邮件、URL、UUID 和正则表达式在任何位置都是字面量:
joan@example.com、https://example.com/docs、3f2a8c1e-9b7d-4c2a-8e1f-0a9b8c7d6e5f、/^[a-z]+$/i。编辑器会在你输入时对其进行检查。URL 以http://、https://、ftp://、ws://或wss://开头,因此其中的//永远不会被视为注释,并且 URL 以空格、逗号、括号或->结束。 - 斜杠路径在每个名称仅由字母、数字、
_、-、.、~或%组成时,可在任何位置作为字面量使用:/docs/getting-started、/v1/users/12。同时也是正则表达式的斜杠路径(例如/blog/或/a/i),在未声明类型时为正则表达式,在声明了类型时为斜杠路径。名称中含有空格的路径(例如/My Apps/Notes)需要加引号,但作为已声明的slash_path($menu: slash_path = /My Apps/Notes)的整个值时除外。其中的$name和{ expression }会被替换填入。 - 文件路径在任何位置只要以
./、../或~/开头,就会被视为字面量:./data/input.txt、../shared/rates.json、~/notes.md。其名称遵循斜杠路径的规则,其中的$name和{ expression }会被替换:./days/day{ $n }.txt。绝对路径或包含空格的路径需要加引号:'/var/log/app.log'。 - 句柄仅在需要句柄的位置写作
@joan:即handle变量或参数、句柄类型上的not:或one_of:列表,或==中紧邻句柄的位置。在其他任何地方,@joan仍然表示函数joan。 - 词语在类型可从文本读取的情况下无需加引号。这包括枚举(
$color: Color = red)、带有pattern($size: Size = 1920x1080)的类型、文本的细化类型($slug: Slug = my-post),以及原生类型:domain = example.com、ip = 10.0.0.1、cidr = 10.0.0.0/8、timezone = Europe/London、semver = 1.4.2、duration = 1h30m、color = red、country = GB等。这些类型的方法和函数参数同样适用:$brand->contrast_ratio(white)、@allow(10.0.0.0/8)、@release(1.4.2-beta.1)。
引用的文本同样始终有效:$who: handle = '@joan'。
<enum name="Color" values="red, green, blue" />
<fn name="paint" params="color: Color, by: handle" value="'Painted ' + $color + ' by ' + $by" />
<let name="me" type="handle" value="@joan" />
<echo value="@paint(green, @joan)" />
<echo>{ $me == @joan }</echo>enum Color { red, green, blue }
fn paint(color: Color, by: handle) => 'Painted ' + $color + ' by ' + $by
$me: handle = @joan
echo @paint(green, @joan)
echo "{ $me == @joan }"根据模式识别自定义字面量
可见的 string 细化类型,或以单词形式书写的原生类型(domain、semver、timezone 等)的细化类型,可以为未加引号的单词指定类型。请在该细化类型本身上声明一个 pattern。该模式必须匹配整个单词,并使用其常用的正则表达式标志。单词可以用 -、+、/ 或 . 连接名称和数字,中间不加空格:$post = my-first-post、$host = api.corp.com、$v = 1.4.2。仅由数字组成的内容仍按算术处理(1+2 的结果是 3);当没有任何类型能匹配整个单词时,其中的任何部分都不会被单独解读为类型。
<type name="PasskeySessionKey" with="string" min="8" pattern="/^passkey_[a-zA-Z]+$/">
<normalize value="$value->trim()" />
</type>
<let name="key" value="passkey_abc" />
<echo value="$key" /> <!-- passkey_abc -->type PasskeySessionKey with [string] {
min: 8
normalize: $value->trim()
pattern: /^passkey_[a-zA-Z]+$/
}
$key = passkey_abc
echo $key // passkey_abcKScript 会在运行规范化和验证之前选择类型。如果多个类型都匹配该词,检查器和运行时会列出所有候选类型。请使用 $key = passkey_abc as PasskeySessionKey 选择其中一个,或使用类型化赋值,例如 $key: PasskeySessionKey = passkey_abc。当可见类型声明了相同的正则表达式和相同的标志时,检查器也会发出警告。已识别的名称、标志和枚举参数保持其原有含义。
引号会将文本保留为字符串。要检查计算值,请写入 $key = "passkey_{$kind}" as PasskeySessionKey。只要相同的声明仍然可见,重复出现的单词就会复用其类型查找结果。计算型类型转换会在每次调用时都对其输入求值。对于较短的重复字符串,KScript 可以复用完全由静态规则决定的成功转换结果。若使用自定义规范化器或验证器,它会再次运行该代码,并可以复用对结果文本成功执行的正则匹配。
同样的双引号表达式也可以用在带类型赋值的右侧。当某个细化接受不带引号的文本时,它会按字面读取花括号和变量名。
斜杠路径
slash_path 是由 / 连接的一组名称:页面在站点中的位置、菜单或分类路径、路由片段或树中的键。它看起来像 URL 路径,但从不访问磁盘。文件或文件夹是 file_path,因此该类型有自己的名称。
<let name="menu" type="slash_path" value="/My Applications/Something" />
<let name="site" type="slash_path" value="/my-website" />
<echo>{ $menu.name } { $menu.parent } { $menu.depth } { $menu.segments }</echo>
<echo>{ $site.parent.is_root } { $site->join('blog/../about') }</echo>
<let name="docs" value="/docs/guides/start" />
<echo>{ $docs->is_within(/docs) } { $docs.parent.name }</echo>
<fn name="open" params="page: slash_path" value=""Opening { $page }"" />
<echo value="@open(/help/contact)" />$menu: slash_path = /My Applications/Something
$site: slash_path = /my-website
echo "{ $menu.name } { $menu.parent } { $menu.depth } { $menu.segments }"
echo "{ $site.parent.is_root } { $site->join('blog/../about') }"
$docs = /docs/guides/start
echo "{ $docs->is_within(/docs) } { $docs.parent.name }"
fn open(page: slash_path) => "Opening { $page }"
echo @open(/help/contact)裸斜杠路径支持插值:$name和{ expression }会被计算出来,而花括号中的名称(如{id})保持原样,因为它是路由参数。包含/的值会添加更多名称。在需要斜杠路径的地方,文本都会变成斜杠路径:
<let name="id" value="42" />
<let name="section" value="'Guides'" />
<echo value="/people/$id/edit" />
<echo value="/docs/{ $section->lower() }/start" />
<echo value="/people/{id}" />
<let name="note" value="{ path: 'home' }" />
<let name="where" type="slash_path" value="$note.path" />
<echo value="$where" />$id = 42
$section = 'Guides'
echo /people/$id/edit
echo /docs/{ $section->lower() }/start
echo /people/{id}
$note = { path: 'home' }
$where: slash_path = $note.path
echo $where路由的 path: 同样是斜杠路径,因此 Get(path: /people/{id}) 与 Get(path: "/people/{id}") 指向同一路由。路由不会填充任何值:{id} 中的内容会与 URL 进行匹配。项目模板中的路由路径不加引号。
该值在生成时会被整理:' / My Apps // Notes / '变为/My Apps/Notes,/docs/./guides/../start变为/docs/start,/blog/变为/blog。斜杠路径总是以/开头,因此没有斜杠的文本会自动加上它:'home'和'home/'都是/home,而单独的/(或'')表示顶层。大小写会被保留,因此/Docs和/docs是不同的路径。..不能超出/,而\不是分隔符,所以'C:\Apps'会失败并给出原因。
| 字段或方法 | 它提供的功能 |
|---|---|
.segments |
名称依次为:['My Applications', 'Something']。/ 没有名称。 |
.name |
最后一个名称:Something,或为 / 使用 ''。 |
.parent |
slash_path 上一级的路径:/My Applications,然后是 /。对于 /,其值为 null。 |
.depth |
它有多少个名称:2。 |
.is_root |
/ 本身即为真。 |
->join(more) |
末尾的名称已整理:/docs->join('guides/../start') 即 /docs/start。more 开头的 / 会被忽略。 |
->is_within(other) |
当它是另一个路径或位于其之下时为 True。名称按完全匹配进行比较。 |
编辑器会检查代码中书写的斜杠路径(KS5012),提示其字段和方法,并将/docs/start以值的颜色显示。
文件路径
file_path用于说明文件或文件夹的位置。请不加引号直接书写,路径从脚本所在位置开始:
./data/input.txt位于脚本旁边的data文件夹中,而./本身就是脚本所在的文件夹。../shared/rates.json会先向上返回一级文件夹。重复执行可继续向上:../../rates.json。~/notes.md从您的主文件夹开始。
每个读写文件的命令都接受一个参数,因此读取谜题输入或设置的脚本无需引号,也无需拼接:
<import package="KScript.IO" />
<let name="lines" value="@read_lines(./data/input.txt)" />
<echo value="$lines->map(.to_number())->sum()" />
<let name="day" value="3" />
<let name="notes" value="@read_text(./days/day{ $day }.txt)" />
<let name="settings" value="@read_json(../shared/settings.json)" />
<do>@write_text(./out/report.txt, $notes)</do>import KScript.IO
$lines = @read_lines(./data/input.txt)
echo $lines->map(.to_number())->sum()
$day = 3
$notes = @read_text(./days/day{ $day }.txt)
$settings = @read_json(../shared/settings.json)
@write_text(./out/report.txt, $notes)当你输入路径时,编辑器会列出该位置下的文件和文件夹:在 ./ 之后会显示脚本旁边的内容,文件夹排在前面;选择某个文件夹(例如 ./data/)则会显示其中的内容。以点开头的名称(例如 .env)会在你输入点号后显示。
给包含空格或为绝对路径的路径加引号:@read_text('/var/log/app.log')、@file('C:\Reports\May 2026.pdf')。在需要file_path的任何地方,带引号的文本和变量中的文本都可以使用;相对文本(如'data/input.txt')同样从脚本所在的文件夹中读取。
文件路径会按原样保留,因此打印时与你书写的格式一致。其各个字段直接读取路径的各个部分,而不访问磁盘:
<let name="report" value="./reports/may/summary.final.pdf" />
<echo value="$report.name" /> <!-- summary.final.pdf -->
<echo value="$report.stem" /> <!-- summary.final -->
<echo value="$report.extension" /> <!-- pdf -->
<echo value="$report.folder" /> <!-- ./reports/may -->
<echo value="./reports + 'may/summary.pdf'" />$report = ./reports/may/summary.final.pdf
echo $report.name // summary.final.pdf
echo $report.stem // summary.final
echo $report.extension // pdf
echo $report.folder // ./reports/may
echo ./reports + 'may/summary.pdf'| 字段或运算符 | 它提供的功能 |
|---|---|
.name |
summary.final.pdf |
.stem |
最后一个不带扩展名的名称:summary.final。 |
.extension |
最后一个点之后的内容(不含点):pdf;如果没有点,则为 ''。 |
.folder |
它所在的文件夹,即一个 file_path:./reports/may。对于 ./ 本身,该值为 null。 |
.segments |
名称按原样书写,以 .、.. 或 ~ 开头:['.', 'reports', 'may', 'summary.final.pdf']。 |
+ 'name' |
/之后添加了更多名称的路径为:./reports + 'may'是./reports/may。 |
要了解文件本身的信息(大小、修改时间、是否存在),请使用 @file(./reports/may/summary.pdf)、@exists(...) 和 @is_folder(...)。
CSV
一个 csv 值是包含有效 CSV 的文本:以逗号分隔单元格的行,每行一条记录。可以将其写成 ```csv 块,或为变量指定 csv 类型并使用带引号的文本。无论哪种方式,如果某一行不符合 CSV 格式(例如引号未闭合),都会在编写的位置报错,包括在编辑器中以及脚本运行时。
<const name="prices">```csv
fruit,price
apple,3
plum,5
```</const>
<let name="totals" type="csv" value="'month,total'" />const $prices = ```csv
fruit,price
apple,3
plum,5
```
$totals: csv = 'month,total'第一行通常是列名。.headers 会读取这些列:
<echo value="$prices.headers" /> <!-- ['fruit', 'price']: the first line names the columns -->echo $prices.headers // ['fruit', 'price']: the first line names the columns读取单元格
->cells() 读取 csv 的单元格。单独使用,或配合 rows 标志时,返回每一行;配合 columns 时,返回每一列。row: 选取一行,column: 选取一列。行号从 0 开始计数(-1 表示最后一行),列可以用表头名称指定,也可以从 0 开始按序号指定:
<echo value="$prices->cells()" /> <!-- [{ fruit: 'apple', price: 3 }, { fruit: 'plum', price: 5 }]: every row -->
<echo value="$prices->cells(columns)" /> <!-- { fruit: ['apple', 'plum'], price: [3, 5] }: every column, by its header -->
<echo value="$prices->cells(row: 0).fruit" /> <!-- 'apple': the header line names each row's keys -->
<echo value="$prices->cells(column: 'price')" /> <!-- [3, 5]: the cells under the price header -->
<echo value="$prices->cells(row: 1, column: 'price')" /> <!-- 5: where plum's row meets the price column -->echo $prices->cells() // [{ fruit: 'apple', price: 3 }, { fruit: 'plum', price: 5 }]: every row
echo $prices->cells(columns) // { fruit: ['apple', 'plum'], price: [3, 5] }: every column, by its header
echo $prices->cells(row: 0).fruit // 'apple': the header line names each row's keys
echo $prices->cells(column: 'price') // [3, 5]: the cells under the price header
echo $prices->cells(row: 1, column: 'price') // 5: where plum's row meets the price columnrow:和rows是二选一的,column:和columns也是二选一的:同时指定某一对中的两个会报错。每对中各选一个可以一起使用:->cells(rows, column: 'price')表示每一行的价格,与->cells(column: 'price')相同。单行与所有列不能同时使用,因为一行中的单元格已经属于某一列,因此->cells(row: 0, columns)会报错,并提示改用->cells(row: 0)。
写成数字的单元格会输出为数字,因此可以直接求和。其他单元格为文本,007 这类编码也是文本,因为其开头的零会丢失。
除非第一行的每个单元格都是数字,否则它是表头;若全是数字,则视为数据。谜题输入和读数通常没有表头,因此每一行都是一行数字。第一行可能是任一情况时,请使用 header 或 not header:
<const name="readings">```csv
387
942
945
```</const>
<echo value="$readings->cells(column: 0)->sum()" /> <!-- 2274: every line is a number, so there's no header -->
<echo value="$prices->cells(not header)->count()" /> <!-- 3: the fruit,price line is a row too -->const $readings = ```csv
387
942
945
```
echo $readings->cells(column: 0)->sum() // 2274: every line is a number, so there's no header
echo $prices->cells(not header)->count() // 3: the fruit,price line is a row too单元格由逗号分隔。当 csv 中没有逗号时,则改用制表符或分号分隔,数字之间的空格也可以作为分隔符。各行所含的单元格数量可以不同:
<const name="numbers">```csv
-903 -642 -518 -585 446
692 853
```</const>
<echo value="$numbers->cells(row: 0)" /> <!-- [-903, -642, -518, -585, 446]: spaces split the numbers -->
<echo value="$numbers->cells(row: -1)->sum()" /> <!-- 1545: the last row, 692 + 853 -->
<echo value="$numbers->cells(column: 2)" /> <!-- [-518]: the third number of each row long enough to have one -->
<echo value="$numbers->cells(columns)" /> <!-- [[-903, 692], [-642, 853], [-518], [-585], [446]] -->const $numbers = ```csv
-903 -642 -518 -585 446
692 853
```
echo $numbers->cells(row: 0) // [-903, -642, -518, -585, 446]: spaces split the numbers
echo $numbers->cells(row: -1)->sum() // 1545: the last row, 692 + 853
echo $numbers->cells(column: 2) // [-518]: the third number of each row long enough to have one
echo $numbers->cells(columns) // [[-903, 692], [-642, 853], [-518], [-585], [446]]没有表头时,列会跳过长度不够到达该列的行,因此 column: 2 会取出每个有该位置数据的行的第三个数字,而 columns 对后面的列返回的列表会更短。没有任何行能到达的列会报错。有表头时每一行都包含所有列,因此在这种情况下行长度不足就是错误。
为 as: 指定一个类型后,结果会被检查并转换为该类型。行会变成该类型的记录,其单元格会被转换为相应的字段类型:
<type name="Price">
<field name="fruit" type="string" />
<field name="price" type="int" />
</type>
<let name="cheapest" value="$prices->cells(as: Price)->min(by: fn(row) => $row.price)" />
<echo value="$cheapest.fruit" /> <!-- 'apple': 3 is the lowest price -->type Price {
fruit: string
price: int
}
$cheapest = $prices->cells(as: Price)->min(by: fn(row) => $row.price)
echo $cheapest.fruit // 'apple': 3 is the lowest price它不是文件
@read_csv 读取文件,因此需要一个file_path。像@read_csv($prices)那样传入 csv 文本会报错:"'path' 参数需要一个 file_path,但这里是 csv 文本,而不是文件。"其快速修复方法是改为由它自己读取 csv:
<echo value="$prices->cells()" /> <!-- the rows, read from the text itself -->echo $prices->cells() // the rows, read from the text itself->save()将其写入文件,当名称没有扩展名时添加.csv,然后用@read_csv读回该文件:
<do>$prices->save('prices')</do> <!-- writes prices.csv -->$prices->save('prices') // writes prices.csv日期格式
date_format用于说明日期的写法。它在编写时就会被检查,因此像YYYY(年份应为yyyy)或DD(天数应为dd)这样的错误会在写下的地方直接报错,而不是之后输出异常。对日期使用->format(),对文本使用->to_date(),二者都接受一个参数,带不带引号均可:
<let name="uk" type="date_format" value="dd-MM-yyyy" />
<let name="day" value="'2026-11-22T16:30:00'->to_date()" />
<echo>{ $day->format($uk) } { $day->format(yyyy-MM-dd) } { $day->format('d MMMM yyyy, HH:mm') }</echo>
<echo>{ '22-11-2026'->to_date(dd-MM-yyyy)->format(dddd) } { $uk.example } { $uk.has_time }</echo>$uk: date_format = dd-MM-yyyy
$day = '2026-11-22T16:30:00'->to_date()
echo "{ $day->format($uk) } { $day->format(yyyy-MM-dd) } { $day->format('d MMMM yyyy, HH:mm') }"
echo "{ '22-11-2026'->to_date(dd-MM-yyyy)->format(dddd) } { $uk.example } { $uk.has_time }"| 字母 | 平均值 |
|---|---|
d, dd, ddd, dddd |
日期:7, 07, Sat, Saturday |
M, MM, MMM, MMMM |
月份: 3, 03, Mar, March |
yy, yyyy |
年份:26, 2026 |
H, HH, h, hh, tt |
24小时制中的小时数、12小时制中的小时数,以及AM或PM |
m, mm, s, ss, fff |
分钟、秒和毫秒 |
zzz, K |
与 UTC 的时差 (+01:00) 以及时区 (Z 表示 UTC) |
任何其他字母都需要加引号,例如 'at' HH:mm,但 T 和 Z 除外,它们在 ISO 8601 中代表自身(yyyy-MM-ddTHH:mm:ssZ)。空格和标点符号按原样保留。只有一个字母的格式是标准的 .NET 格式:o 是往返 ISO 8601 格式,单独的 d 是短日期。不带引号的格式不能包含空格或 :(作为参数时);此时请改写为 'd MMMM yyyy' 和 'HH:mm',或者先声明它($at: date_format = d MMMM yyyy, HH:mm)。
.tokens列出了它的各个部分(['dd', '-', 'MM', '-', 'yyyy']),.example以这种方式显示 2026 年 3 月 7 日星期六 14:05:09,->parse(text)读取以这种方式书写的文本。编辑器会在你输入日期格式时提示相应的字母。
密码
密码打印时会显示为 ********。这同样适用于 echo、日志、JSON 和错误信息。也不能用 == 进行比较,因为这样会泄露时序信息。请对密码进行哈希后再存储,并在登录时验证哈希值:
<let name="pw" type="password" value="'correct horse battery staple'" />
<echo>Password: { $pw }</echo>
<let name="stored" value="$pw->hash()" />
<echo>{ $stored->starts_with('$argon2id$') } { $pw->verify($stored) }</echo>
<let name="weak" type="password" value="'password1'" />
<echo>{ $weak->strength(min: 12, symbol).problems }</echo>
<echo>{ $weak->is_strong() }</echo>$pw: password = 'correct horse battery staple'
echo "Password: { $pw }"
$stored = $pw->hash()
echo "{ $stored->starts_with('$argon2id$') } { $pw->verify($stored) }"
$weak: password = 'password1'
echo "{ $weak->strength(min: 12, symbol).problems }"
echo "{ $weak->is_strong() }"| 方法 | 作用 |
|---|---|
->hash(algorithm: argon2id) |
PHC 格式的加盐哈希值。默认值为 argon2id;bcrypt(成本 12)适用于最多 72 字节的内容。 |
->verify(hash) |
如果密码与哈希值匹配则返回 True,比较过程耗时恒定。两种格式均可读取。 |
->needs_rehash(hash) |
当哈希值是使用其他设置生成时为 True,因此可以在下次登录时升级。 |
->strength(...) |
{ score, label, ok, problems }。0 到 4 的分数表示猜出它的难度估计值。 |
->is_strong(...) |
当 strength 未发现任何问题时为 True。 |
->reveal() |
文本本身,用于极少数需要它的地方。 |
strength和strong接受命名规则:min(默认为8)、max(长度)、upper、lower、digit和symbol(各自都必须满足)、common: false(允许最常见的密码)、not: [...](不得包含的单词,例如用户的名字)以及score(通过的最低分数,默认为3)。同样的规则也可以赋予类型,如password(min: 12)所示,这样就无法创建违反这些规则的密码。
类型使用处的参数
类型可以在使用处接受参数。它们遵循与精化类型相同的规则,且仅对该次使用有效:
<let name="work" type="email(domains: ['example.com'])" value="joan@example.com" />
<let name="id" type="uuid(v: 4)" value="3f2a8c1e-9b7d-4c2a-8e1f-0a9b8c7d6e5f" />
<let name="pin" type="password(min: 4, max: 8, common: false)" value="'1234'" />
<let name="title" type="string(min: 1, max: 80)" value="'Hello'" />
<echo>{ $work } { $id } { $pin } { $title }</echo>$work: email(domains: ['example.com']) = joan@example.com
$id: uuid(v: 4) = 3f2a8c1e-9b7d-4c2a-8e1f-0a9b8c7d6e5f
$pin: password(min: 4, max: 8, common: false) = '1234'
$title: string(min: 1, max: 80) = 'Hello'
echo "{ $work } { $id } { $pin } { $title }"| 类型 | 参数 |
|---|---|
uuid |
v(一个版本或版本列表) |
email |
domains(允许的域) |
password |
min, max, upper, lower, digit, symbol, common, not, score, algorithm |
| 任意类型 | min, max, pattern, one_of, not |
kscript.json 中的项目默认值
kscript.json 中的 "types" 为项目中每次使用内置类型设置参数。在类型使用处编写的参数优先:
{
"types": {
"uuid": { "v": 4 },
"password": { "min": 12, "symbol": true, "algorithm": "argon2id" },
"email": { "domains": ["example.com"] }
}
}精炼类型
基于一个内置类型或另一个精炼类型的类型会在其上添加规则。它没有字段:它的值就是通过这些规则的基础类型的值。
<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模式。原生类型名称为小写,已被占用的名称不能重复使用。
组合类型
由其他带字段的类型组合而成的类型,会按从左到右的顺序合并这些基类型的所有字段、规则和方法。类型自身声明的字段优先。组合类型的值可用于任何需要其某个基类型的地方:
<type name="User">
<field name="name" type="string" />
<field name="email" type="email" />
</type>
<type name="Auditable">
<field name="created" type="date" />
<validate test="$created <= @now()" message="created is in the future" />
</type>
<type name="Admin" with="User, Auditable">
<field name="level" type="int" default="1" />
</type>
<fn name="welcome" params="user: User" value="'Welcome ' + $user.name" />
<let name="admin" value="Admin({ name: 'Joan', email: 'joan@example.com', created: '2026-01-05' })" />
<echo>{ @welcome($admin) } { User->is($admin) } { $admin.level }</echo>type User {
name: string
email: email
}
type Auditable {
created: date
validate: $created <= @now(), 'created is in the future'
}
type Admin with [User, Auditable] {
level: int = 1
}
fn welcome(user: User) => 'Welcome ' + $user.name
$admin = Admin({ name: 'Joan', email: 'joan@example.com', created: '2026-01-05' })
echo "{ @welcome($admin) } { User->is($admin) } { $admin.level }"当两个基类有同名但类型不同的字段时,合并后的类型必须自己声明该字段。两个基类都有的同名方法也是如此:在合并后的类型中声明它,以选定使用哪一个。在编辑器中,合并类型上的灯泡图标会提供覆盖其从基类继承的每个方法的选项,并自动写出对应的存根。User->is($admin)用于判断某个值是否为 User,User->is(Admin)用于判断某个类型是否基于 User 构建。带字段的类型中的 validate: 规则会将这些字段视为 $name、$email 等。
构造函数
带字段的类型在创建值时可以接受其中任意字段。construct 代码块用于限定范围:它列出调用方可以传入的字段,其余字段则成为该值自身的状态。
<import package="KScript.Math" />
<type name="Point">
<construct>
<field name="x" type="number" />
<field name="y" type="number" default="0" />
<do>.length = (.x * .x + .y * .y)->sqrt()</do>
</construct>
<field name="length" type="number" />
</type>
<let name="point" value="Point(x: 3, y: 4)" />
<echo>{$point.x}, {$point.y} is {$point.length} from the origin</echo>import KScript.Math
type Point {
construct({
x: number,
y: number = 0,
}) {
.length = (.x * .x + .y * .y)->sqrt()
}
length: number
}
$point = Point(x: 3, y: 4)
echo "{$point.x}, {$point.y} is {$point.length} from the origin"- 花括号中的字段与其他字段的写法相同,以逗号分隔。较短的列表可以写在一行内:
construct({ name: string })。 - 之后的代码块是可选的。每次创建一个值时它都会运行一次,并且是在传入的字段检查之后运行,它可以设置该类型的任意字段。
construct之外的字段以其默认值开始。若没有默认值,则以空值开始:0、''、false、[]、{ }或null。- 传入
construct未列出的字段会报错,错误信息会列出它所接受的字段。编辑器会在你输入时报告该错误。 - 联合类型会先运行其基类的
construct代码块,然后再运行自身的代码块。
类型为模型的输入可以默认使用路由所持有的记录。@inject() 从输入的类型中读取模型,并以输入的名称获取路由参数:
<type name="PostSummary">
<construct>
<field name="post" type="Post" default="@inject()" />
<do>.words = .post.body->split(' ')->count()</do>
</construct>
<field name="words" type="int" />
</type>
<!-- a controller on /posts/{post} -->
<fn name="stats" value="PostSummary()" />type PostSummary {
construct({ post: Post = @inject() }) {
.words = .post.body->split(' ')->count()
}
words: int
}
// a controller on /posts/{post}
fn stats() => PostSummary()@inject(can: read) 在记录被获取时询问模型的策略:construct({ post: Post = @inject(can: read) })。
PostSummary(post: $other) 仍然接受所给的内容。若当前没有正在响应的路由,省略该输入会报错,并指出该输入。规则参见获取路由记录。
组件使用同一个块来区分页面可以设置的属性和它所保存的状态。
私有字段和方法
在字段或方法前加上 private,即可将其限制在该类型内使用。只有该类型自身的方法、其 construct 代码块,以及(对于组件而言)其 render 可以访问它。
<type name="Counter">
<construct>
<field name="start" type="int" default="0" />
<do>.count = .start</do>
</construct>
<field name="count" type="int" private="yes" />
<fn name="doubled" value=".count * 2" private="yes" />
<fn name="total" value="$this->doubled() + .count" />
</type>
<let name="counter" value="Counter(start: 2)" />
<echo value="$counter->total()" />type Counter {
construct({ start: int = 0 }) {
.count = .start
}
private count: int
private fn doubled() => .count * 2
fn total() => $this->doubled() + .count
}
$counter = Counter(start: 2)
echo $counter->total()- 类型之外的代码无法读取私有字段(
$counter.count)、为其赋值、在创建值时传入它,也无法调用私有方法($counter->doubled())。kscript check会报告每一项,同样的错误也会中止正在运行的脚本。 - 私有字段在显示值或转换为 JSON 时会被省略,因此
$counter->convert(to: json)为{"start":2}。 - 方法可以访问同类型另一个值的私有成员,例如
fn same(other: Counter) => $other.count == $count。 - 联合类型使用其所基于的类型的私有成员。
- 编辑器只在类型内部提供私有成员。
- 在模型上,私有字段仍然是一个列。它照常存储和加载,只有模型自身的方法会读取它。
- 没有
public,因为其他成员本来就是这样。
private 关乎其他代码可以使用什么,而不是保密:实时组件的状态会以签名形式传送到浏览器并返回,无论它是否私有。
从文本读取类型
可以从文本创建带字段和pattern的类型。模式中的命名分组会填充同名字段,并且每个分组都会被转换为对应字段的类型。类型内部的fn用于添加一个方法,该方法可以访问这些字段:
<import package="KScript.Math" />
<enum name="Unit" values="cm, in, mm" />
<type name="Dimensions" description="A size such as H4cmW12in: height 4 cm, width 12 inches." pattern="/^H(?<height>[\d.]+)(?<height_unit>cm|in|mm)W(?<width>[\d.]+)(?<width_unit>cm|in|mm)$/i">
<field name="height" type="number" />
<field name="height_unit" type="Unit" />
<field name="width" type="number" />
<field name="width_unit" type="Unit" />
<fn name="width_in" params="unit: Unit" value="@convert_length(.width, .width_unit, $unit)" />
</type>
<let name="size" type="Dimensions" value="H4cmW12in" />
<echo>{ $size.width } { $size.width_unit } is { $size->width_in(cm) } cm</echo>import KScript.Math
enum Unit { cm, in, mm }
/// A size such as H4cmW12in: height 4 cm, width 12 inches.
type Dimensions {
pattern: /^H(?<height>[\d.]+)(?<height_unit>cm|in|mm)W(?<width>[\d.]+)(?<width_unit>cm|in|mm)$/i
height: number
height_unit: Unit
width: number
width_unit: Unit
fn width_in(unit: Unit) => @convert_length(.width, .width_unit, $unit)
}
$size: Dimensions = H4cmW12in
echo "{ $size.width } { $size.width_unit } is { $size->width_in(cm) } cm"当文本需要的不仅仅是模式时,parse:会给出一个返回字段映射的表达式。它将文本视为$value,若使用模式,则将匹配结果视为$match。
正则表达式
正则字面量写在斜杠之间,标志位于其后。命名分组按名称返回:
<let name="date" value="/(?<year>\d{4})-(?<month>\d\d)/" />
<let name="found" value="$date->match('Due 2026-11')" />
<echo>{ $found.groups.year } { $date->test('no date') }</echo>
<echo>{ $date->replace('2026-11', '${month}/${year}') }</echo>
<echo>{ /\s*,\s*/->split('tea, coffee ,milk') }</echo>
<echo>{ /\d+/->match_all('3 cats, 12 dogs')->map(.text) }</echo>$date = /(?<year>\d{4})-(?<month>\d\d)/
$found = $date->match('Due 2026-11')
echo "{ $found.groups.year } { $date->test('no date') }"
echo "{ $date->replace('2026-11', '${month}/${year}') }"
echo "{ /\s*,\s*/->split('tea, coffee ,milk') }"
echo "{ /\d+/->match_all('3 cats, 12 dogs')->map(.text) }"->match()返回{ text, index, groups, captures },如果没有匹配则返回null。匹配时间超过一秒的正则会以错误停止,因此糟糕的模式不会使服务器挂起。在XML中,属性或文本内的<应写作<。
接受这些类型的内置函数
处理模式的字符串方法接受正则表达式字面量(连同其标志)或包含模式的文本。无论哪种方式,耗时超过一秒的匹配都会以错误中止:
<let name="title" value="'Hello World, hello'" />
<echo>{ $title->matches(/^hello/i) } { $title->find_all(/hello/i) }</echo>
<echo>{ $title->replace(/\s+/, ' ') } { 'tea, coffee ,milk'->split(/\s*,\s*/) }</echo>
<echo>{ $title->replace(/(?<w>world)/i, '[${w}]') }</echo>$title = 'Hello World, hello'
echo "{ $title->matches(/^hello/i) } { $title->find_all(/hello/i) }"
echo "{ $title->replace(/\s+/, ' ') } { 'tea, coffee ,milk'->split(/\s*,\s*/) }"
echo "{ $title->replace(/(?<w>world)/i, '[${w}]') }"->replace()和->split()仍然接受纯文本,按原样匹配。存储文件夹的list方法接受通配符(如'*.json')或针对每个名称匹配的正则表达式(如/^notes\/.*\.md$/)。
在 KScript.Terminal 中,input 读取新的类型:type="email"、handle 或 uuid 在回答不符合要求时会附带原因再次询问,type="password" 会隐藏输入的内容并将答案作为密码保存。
在 XML 中
在 XML 中,相同的类型是 <type> 的属性和元素:
<type name="Username" with="handle" max="16" not="@admin, @root">
<validate test="not $value.name->starts_with('_')" message="A username cannot start with _" />
</type>
<type name="Admin" with="User, Auditable">
<field name="level" type="int" default="1" />
</type>
<let name="who" type="Username" value="@joan" />
<type name="Point">
<construct>
<field name="x" type="number" />
<set name="doubled" value="$x * 2" />
</construct>
<field name="doubled" type="number" />
</type>type Username with [handle] {
max: 16
not: [@admin, @root]
validate: not $value.name->starts_with('_'), 'A username cannot start with _'
}
type Admin with [User, Auditable] {
level: int = 1
}
$who: Username = @joan
type Point {
construct({ x: number }) {
.doubled = .x * 2
}
doubled: number
}属于代码的规则是元素:<validate test="..." message="..." />、<normalize value="..." />和<value value=".group(1)->to_int()" />。<construct>包含调用方可以传入的字段,然后是要运行的语句。私有成员在其<field>或<fn>上带有private="yes"。kscript convert可将任一形式转换为另一种。
以后的想法
这些内容的工作方式相同,接下来可以添加:date_range,以及按国家格式书写并带有默认地区的电话号码。请告诉我们您会优先使用哪一个。