KScript 语言
简介
这是 KScript 2 脚本的参考手册,涵盖每个脚本和页面都具备的核心语言、用于其他功能的导入包,以及适用于所有操作系统的脚本技巧。如果你刚接触 KScript,建议先阅读快速入门。
变量与输出
<let name="count" value="0" /> <!-- declare -->
<let name="people" value="[{ name: 'Joan', age: 82 }]" />
<set name="count" value="$count + 1" /> <!-- change it -->
<set name="count" op="+=" value="1" />
<let name="total" value="$price * $qty" />
<const name="limit" value="10" />
<let name="n" type="int" value="$args[0]" /> <!-- convert, or stop with a clear error -->
<echo>Hello, {$name}! You have { $count } new { $count == 1 ? 'message' : 'messages' }.</echo>
<echo>{ $person.name } is { $person.age }</echo>
<echo>{ $people }</echo> <!-- a map or list of maps prints as indented JSON -->$count = 0 // declare
$people = [{ name: 'Joan', age: 82 }]
$count = $count + 1 // change it
$count += 1
$total = $price * $qty
const $limit = 10
$n: int = $args[0] // convert, or stop with a clear error
echo "Hello, {$name}! You have { $count } new { $count == 1 ? 'message' : 'messages' }."
echo "{ $person.name } is { $person.age }"
echo "{ $people }" // a map or list of maps prints as indented JSON在 echo 中单独输出映射或映射列表时,会打印为缩进的 JSON,在终端中带有颜色(除非设置了 NO_COLOR)。在文本中则保持单行。echo(format: json) 可重新格式化 JSON 文本,->convert(to: json) 则生成紧凑的 JSON。
变量属于其声明所在的代码块。{{ 和 }} 是字面上的花括号。
"Double quotes"在{ }中插入表达式,位置为echo之后、赋值语句中、返回值中以及调用参数中。在.kscript中,KS6019会检测裸引用并提议用花括号包裹。'Single quotes'会原样保留文本,因此没有需要填充内容的文本应放在其中(KS6020会给出修改建议)。echo之后的引号文本同样会原样输出,包括其中的空格:echo " - { $item }"会输出两个空格。在 XML 中,<echo>与</echo>之间的文本会去除首尾空白,并移除各行共有的缩进;填入其中的值不做处理,但空值不会留下多余空格,且文本末尾永远不会出现换行。
<let name="greeting" value=""Hello { $name }, you have { $count * 2 } points."" />
<let name="label" value="'Write $name to use a variable.'" /> <!-- kept as written -->
<let name="boxes" value=""{ 2 * 3 } boxes, { [1, 2]->count() } lists"" /> <!-- a { } always holds an expression -->
<let name="route" value="'/users/{id}'" /> <!-- text with braces of its own goes in single quotes -->$greeting = "Hello { $name }, you have { $count * 2 } points."
$label = 'Write $name to use a variable.' // kept as written
$boxes = "{ 2 * 3 } boxes, { [1, 2]->count() } lists" // a { } always holds an expression
$route = '/users/{id}' // text with braces of its own goes in single quotes双引号中的{ }总是包含一个表达式,无论它以什么开头:可以是变量、命令、类型({ Order->count() })、数字或括号中的求和。若文本本身含有花括号,例如路由('/users/{id}')、正则模式('\d{3}')、CSS 或翻译文本('Hello {name}'),则应使用单引号,或将花括号双写:"/users/{{id}}"。@sql的文本是唯一的例外:其中的{ }会作为参数传递,而不会直接粘贴(见数据)。
表达式
+ - * / % **, == != (loose: '3' == 3), === !== (strict), < <= > >=, and or not, ??, ?., a ? b : c, in, list [1, 2] and map { name: 'Joan' } literals, $p.name, $list[0] (negative indexes count from the end), ranges 0..10 and 0..100 step 5 (end excluded, also with a step such as 0.1) and 1..=10 (end included), match $x { 1 => 'one', _ => 'other' }, ->method(), |> and fn(x) => …. Write and and or to combine conditions. Prefix ! has the same precedence and truthiness as not, so !$ready, ! $ready and not $ready are equivalent. Use it on a field (!$user.active), a whole condition (if !($ready and $open) { … }), or an interpolation ("{ ! null->is_null() }"). The spelling null->!is_null() negates the method result before the next link in the chain. XML has a word for each comparison as well (lt le gt ge eq ne), for use inside quoted attributes, since XML can't hold a raw < there; the shorthand start tags accept < and > as written. In a .kscript file the words are reported (KS6012) and kscript check --fix writes the symbols.
用 <、<=、> 或 >= 比较数字与字符串时,如果该字符串可以解析为数字,KScript 会按数值比较。若解析失败,比较结果为 false。比较可以像数学中那样连锁,数学一节对此有所说明。使用 == 判断两个日期是否相等时,只有当它们是同一时刻(包括秒)才相等。
数学
日常数学运算有其自己的符号,每个符号在脚本、模板和数据库查询中的作用都相同。+ 为加法,- 为减法,* 为乘法,/ 为除法,保留小数部分。~/ 为整除,向下取整。% 给出余数,余数的符号与左侧数字一致,%% 像时钟一样循环取模,** 为乘方:
<let name="minutes" value="135" />
<let name="hours" value="$minutes / 60" /> <!-- 2.25 because / keeps the fraction -->
<let name="whole" value="$minutes ~/ 60" /> <!-- 2 because 60 fits into 135 twice -->
<let name="left" value="$minutes % 60" /> <!-- 15 because 135 - 2 * 60 leaves 15 -->
<let name="behind" value="-7 % 3" /> <!-- -1 because % keeps the sign of -7 -->
<let name="area" value="4 ** 2" /> <!-- 16 because 4 * 4 is 16 -->
<let name="kilobyte" value="2 ** 10" /> <!-- 1024 because ten 2s are multiplied -->$minutes = 135
$hours = $minutes / 60 // 2.25 because / keeps the fraction
$whole = $minutes ~/ 60 // 2 because 60 fits into 135 twice
$left = $minutes % 60 // 15 because 135 - 2 * 60 leaves 15
$behind = -7 % 3 // -1 because % keeps the sign of -7
$area = 4 ** 2 // 16 because 4 * 4 is 16
$kilobyte = 2 ** 10 // 1024 because ten 2s are multiplied运算符按以下顺序结合,从最紧密到最松散,因此 2 + 3 * 4 的结果是 14,因为 * 先于 + 结合:
| 优先级 | 运算符 | 分组 |
|---|---|---|
| 1 | . -> ?. ( ) [ ] |
从左到右 |
| 2 | ** |
从右到左:2 ** 3 ** 2 即 2 ** 9,512 |
| 3 | -x +x |
-2 ** 2的结果是 -4,因为**先结合,因此应写作-(2 ** 2)或(-2) ** 2(KS6023)。 |
| 4 | * / ~/ % %% |
从左到右 |
| 5 | + - |
从左到右 |
| 6 | .. ..= step |
每个表达式只能有一个范围 |
| 7 | |> |
从左到右 |
| 8 | < <= > >= in |
单向链:0 <= $n < 10 |
| 9 | == != === !== |
每个比较一个;要连接更多请使用 and |
| 10 | not, and, or, ??, a ? b : c |
% 与 %% 只有在符号为负时才有区别。余数的符号与左侧一致,与 C# 和 JavaScript 相同。取模的符号与右侧一致,因此会循环:午夜前一小时是 23,而不是 -1。对于时钟、星期以及在列表末尾循环的位置,请使用 %%:
<let name="hour" value="9 - 12" /> <!-- -3 because 3 hours before 9 -->
<let name="late" value="$hour % 24" /> <!-- -3 because % keeps the sign of -3 -->
<let name="clock" value="$hour %% 24" /> <!-- 21 because %% wraps back round the clock -->
<let name="days" value="['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']" />
<let name="today" value="0" /> <!-- 'mon' is at 0 -->
<let name="yesterday" value="$days[($today - 1) %% 7]" /> <!-- 'sun' because -1 wraps round to the last day -->
<let name="spare" value="-15m %% 1h" /> <!-- 45m because durations wrap the same way -->$hour = 9 - 12 // -3 because 3 hours before 9
$late = $hour % 24 // -3 because % keeps the sign of -3
$clock = $hour %% 24 // 21 because %% wraps back round the clock
$days = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
$today = 0 // 'mon' is at 0
$yesterday = $days[($today - 1) %% 7] // 'sun' because -1 wraps round to the last day
$spare = -15m %% 1h // 45m because durations wrap the same way~/ 向下取整,而不是向零取整,因此它与 %% 配对使用:($a ~/ $b) * $b + $a %% $b 始终等于 $a。它也适用于时长和金额,并返回普通数字:
<let name="balance" value="-7" />
<let name="weeks" value="$balance ~/ 2" /> <!-- -4 because it rounds down, not toward zero -->
<let name="rest" value="$balance %% 2" /> <!-- 1 because -4 * 2 + 1 is -7 -->
<let name="runtime" value="2h10m" />
<let name="episodes" value="$runtime ~/ 25m" /> <!-- 5 because five 25m episodes fit into 2h10m -->
<let name="spare" value="$runtime %% 25m" /> <!-- 5m because 2h10m - 5 * 25m leaves 5m -->$balance = -7
$weeks = $balance ~/ 2 // -4 because it rounds down, not toward zero
$rest = $balance %% 2 // 1 because -4 * 2 + 1 is -7
$runtime = 2h10m
$episodes = $runtime ~/ 25m // 5 because five 25m episodes fit into 2h10m
$spare = $runtime %% 25m // 5m because 2h10m - 5 * 25m leaves 5m// 开始一段注释,因此它不能是整数除法。$hours = $minutes // $per_hour 不会处理 $minutes,而 KS6022 会指出这一点,并给出写作 ~/ 的修复方案。
方向相同的比较可以像数学中那样连写,因此范围检查读起来与口头表述一致。中间的每个值只计算一次,链条在第一个为假的比较处停止:
<let name="score" value="42" />
<let name="passed" value="0 <= $score < 100" /> <!-- true because 42 is from 0 up to (not including) 100 -->
<let name="top" value="90 <= $score <= 100" /> <!-- false because 42 is below 90 -->
<let name="falling" value="10 > 7 >= 7 > 1" /> <!-- true because each step goes down or stays the same -->$score = 42
$passed = 0 <= $score < 100 // true because 42 is from 0 up to (not including) 100
$top = 90 <= $score <= 100 // false because 42 is below 90
$falling = 10 > 7 >= 7 > 1 // true because each step goes down or stays the same连写的比较必须朝同一方向。1 < $n > 0 是错误的,因为它没有说明 1 与 0 的大小关系,应写成 1 < $n and $n > 0。== 和 != 也不能连写:$a == $b == $c 会与 $c 比较出真或假,应写成 $a == $b and $b == $c。括号会中断连写,因此 (1 < $n) == true 比较的是结果。连写在数据库查询中同样适用:Person->where(fn(person) => 18 <= $person.age < 65) 表示 age >= 18 AND age < 65。->between() 已被移除,其错误信息会指出应改用的连写形式。
.. 生成的范围不包含终点,适合从 0 开始计数以及表示列表中的位置。..= 则包含终点,适合从 1 开始计数。将鼠标悬停在任一项上,可以看到范围的起点和终点:
<let name="positions" value="0..3" /> <!-- [0, 1, 2] because .. stops before 3 -->
<let name="places" value="1..=3" /> <!-- [1, 2, 3] because ..= takes in 3 -->
<let name="quarters" value="0..=1 step 0.25" /> <!-- [0, 0.25, 0.5, 0.75, 1] because a step lands on 1 -->
<let name="odd" value="1..=10 step 2" /> <!-- [1, 3, 5, 7, 9] because no step lands on 10 -->
<let name="monday" value="'2026-11-30'->to_date()" />
<let name="week" value="$monday..=$monday + 6d" /> <!-- seven dates because ..= takes in the Sunday -->$positions = 0..3 // [0, 1, 2] because .. stops before 3
$places = 1..=3 // [1, 2, 3] because ..= takes in 3
$quarters = 0..=1 step 0.25 // [0, 0.25, 0.5, 0.75, 1] because a step lands on 1
$odd = 1..=10 step 2 // [1, 3, 5, 7, 9] because no step lands on 10
$monday = '2026-11-30'->to_date()
$week = $monday..=$monday + 6d // seven dates because ..= takes in the Sunday与 .. 类似,当范围的终点小于起点时,范围会递减,因此 3..=1 等同于 [3, 2, 1],1..=0 等同于 [1, 0]。若要向上计数到一个可能为 0 的值(如 1..($count + 1)),请保留 ..,当 $count 为 0 时它不会产生任何值。
^ 在 KScript 中不是幂运算(在 C# 和 JavaScript 中它是按位运算符),因此 2 ^ 10 是一个错误,其修复建议会写成 2 ** 10。
位运算通过一个方法 ->bits() 完成,而不是使用符号,因为 & 和 | 很容易被误认为 and 和 or。该方法逐步作用于整数:
<let name="read" value="4" />
<let name="write" value="2" />
<let name="permissions" value="6" /> <!-- read and write, because 4 + 2 is 6 -->
<let name="can_read" value="$permissions->bits(and: $read) == $read" /> <!-- true because 6 has the 4 bit -->
<let name="with_run" value="$permissions->bits(or: 1)" /> <!-- 7 because or: adds the 1 bit -->
<let name="toggled" value="$permissions->bits(xor: $write)" /> <!-- 4 because xor: flips the 2 bit off -->
<let name="doubled" value="$permissions->bits(shift: 1)" /> <!-- 12 because each bit moves one place left -->
<let name="halved" value="$permissions->bits(shift: -1)" /> <!-- 3 because a negative shift moves right -->
<let name="flipped" value="$permissions->bits(invert)" /> <!-- -7 because every bit flips -->$read = 4
$write = 2
$permissions = 6 // read and write, because 4 + 2 is 6
$can_read = $permissions->bits(and: $read) == $read // true because 6 has the 4 bit
$with_run = $permissions->bits(or: 1) // 7 because or: adds the 1 bit
$toggled = $permissions->bits(xor: $write) // 4 because xor: flips the 2 bit off
$doubled = $permissions->bits(shift: 1) // 12 because each bit moves one place left
$halved = $permissions->bits(shift: -1) // 3 because a negative shift moves right
$flipped = $permissions->bits(invert) // -7 because every bit flips单独的 &、单独的 |、<< 以及位于两个值之间的 >> 都是错误,错误信息会指出应改用的 ->bits() 调用。& 和 | 会给出修复建议,写成 and 或 or,这通常才是原意。
($hour + 24) % 24是旧的数字取整写法。KS6021建议改用$hour %% 24,它对小于 -24 的数字同样有效。
+=、-=、*=、/=、~/=、%=、%%=、**= 和 ??= 会就地修改变量:$total += 5 等同于 $total = $total + 5。运算符两侧的空格由你决定,但运算符内部的空格会将其拆分:2 * * 10 是一个错误,错误信息会指出 **,其快速修复会删除该空格。
编辑器会在运算符和空格之后列出变量,左侧类型的变量排在前面;将鼠标悬停在运算符上,可以看到它的作用。
使用expression as Type进行带检查的转换,例如$text as int。目标类型也可以是已声明的记录、枚举或精化类型。带检查的转换
控制流
<if $n < 10>
<!-- … -->
</if>
<elif $n < 100>
<!-- … -->
</elif>
<else>
<!-- … -->
</else>
<for each="p" in="$people">
<!-- … -->
</for>
<for each="i" at="n" in="0..10 step 2">
<!-- … -->
</for>
<for each="key, value" in="$map">
<!-- … -->
</for>
<while $queue->count() > 0>
<!-- … -->
<break />
<!-- … -->
<continue />
<!-- … -->
</while>
<match $choice>
<case is="1">
<echo>One</echo>
</case>
<case is="2, 3">
<!-- … -->
</case>
<case when="$it > 9">
<echo>Out of range</echo>
</case>
<default>
<!-- … -->
</default>
</match>if $n < 10 {
// …
} elif $n < 100 {
// …
} else {
// …
}
for p in $people {
// …
}
for i at n in 0..10 step 2 {
// …
}
for key, value in $map {
// …
}
while $queue->count() > 0 {
// …
break
// …
continue
// …
}
match $choice {
1 => echo "One"
2, 3 => {
// …
}
_ when $it > 9 => echo "Out of range"
_ => {
// …
}
}match的每个分支都是pattern => result。模式可以是一个值或多个值(2, 3 =>),也可以是_以匹配任意值,之后还可以跟一个when测试(_ when $it > 9 =>)。结果可以是同一行中的一条语句,也可以是{ }块。把match用作值时,分支的写法相同,每个结果都是一个值:$label = match $choice { 1 => 'one', 2, 3 => 'a few', _ => 'many' }。分支之间用换行或逗号分隔,取第一个匹配的分支。在XML中,分支元素是<case is="2, 3">、<case when="…">和<default>。
单行if
当if只做一件事时,把它写在一行上:条件、=>,然后是语句。它的写法与match的分支以及fn(name) => ...相似,让保护检查和提前退出都只占一行。
<let name="basket" value="['apple', 'plum', 'pear']" />
<let name="budget" value="3" />
<!-- The guard is one line, so the main path stays at the left edge. -->
<if $basket->is_empty()>
<exit />
</if>
<!-- 3 items and a budget of 3: the test is true, so the line prints. -->
<if $basket->count() >= $budget>
<echo>The basket is full</echo>
</if>
<for each="fruit" in="$basket">
<!-- 'plum' is skipped, because continue moves on to the next fruit. -->
<if $fruit == 'plum'>
<continue />
</if>
<echo value="$fruit" />
</for>
<!--
apple
pear
-->$basket = ['apple', 'plum', 'pear']
$budget = 3
// The guard is one line, so the main path stays at the left edge.
if $basket->is_empty() => exit
// 3 items and a budget of 3: the test is true, so the line prints.
if $basket->count() >= $budget => echo "The basket is full"
for fruit in $basket {
// 'plum' is skipped, because continue moves on to the next fruit.
if $fruit == 'plum' => continue
echo $fruit
}
// apple
// pearelif和else的写法相同,每个分支占一行:
<let name="temperature" value="18" />
<!-- 18 is not below 5, but it is below 20, so 'Mild' is printed. -->
<if $temperature < 5>
<echo>Cold</echo>
</if>
<elif $temperature < 20>
<echo>Mild</echo>
</elif>
<else>
<echo>Warm</echo>
</else>$temperature = 18
// 18 is not below 5, but it is below 20, so 'Mild' is printed.
if $temperature < 5 => echo 'Cold'
elif $temperature < 20 => echo 'Mild'
else => echo 'Warm'=>之后的语句可以是任何能放在一行中的内容:调用(if $continue => @method_call())、赋值(if $count > 2 => $label = 'many')、echo、return、break、continue、throw或exit。它在行尾结束,因此无论哪种写法,if $ready => echo 1; echo 2都会输出2。如需多条语句或循环,请使用match、另一个if或{ }块。括号外第一个=>用于结束条件,因此调用内部的fn(fruit) => ...和@load() catch => false仍属于该调用。if $ready => { }是错误写法:条件后面跟块时不能加箭头。XML没有单行形式,kscript convert会把语句写在<if>之内。
在XML中,<if>、<elif>、<while>和<match>直接在开始标签中书写表达式:<if $user.is_logged_in>是<if test="$user.is_logged_in">的简写,<match $choice>是<match value="$choice">的简写。两种写法在脚本和页面中都可用;当标签还有其他属性时,使用完整写法。在标签内部,<、>和引号无需转义,因此<if $n > 3>和<if $name == "Joan">可以直接使用。>会结束标签,除非它两侧都有空格且条件的后续内容仍在其后,所以应写$n > 3而不是$n>3。kscript convert以及编辑器中的<if>代码片段都使用简写形式。
简写标签使.ks.xml文件成为KScript标记,而非严格的XML:KScript自带的解析器、格式化工具和编辑器支持它,但xmllint等通用XML工具会拒绝它。如果文件必须保持有效的XML,请坚持使用test="…"。
用提前返回代替else
在函数或循环内部,应尽早结束分支,而不是写else:函数中用return,循环中用continue或break(它们只作用于同一函数中的循环,绝不作用于调用它的那个循环)。这样主路径保持在最左侧,每种特殊情况都会先被处理。
<fn name="grade" params="score: number">
<if $score >= 90>
<return value="'A'" />
</if>
<if $score >= 75>
<return value="'B'" />
</if>
<return value="'C'" />
</fn>
<echo>{ @grade(82) }</echo>fn grade(score: number) {
if $score >= 90 => return 'A'
if $score >= 75 => return 'B'
return 'C'
}
echo "{ @grade(82) }"kscript check和编辑器会对else与elif发出 KS6001 警告;当其前面的每个分支都已以return、break、continue、throw或exit结束时,脚本顶部也会发出该警告。快速修复会删除else(或将elif改为独立的if),并且当该链式结构是函数或循环的最后一条语句时,会自动添加return或continue。页面、<live>代码块以及for…else(用于空列表)不会被标记,因为此时没有可返回的内容。KS6001 来自默认的标准,即kscript:recommended。若要为某个项目关闭它,请在kscript.json中(或在项目共用的标准中)设置"lint": { "rules": { "KS6001": "off" } }。
未使用的代码
kscript check和编辑器还会指出不起作用的代码。在编辑器中,这些代码会以淡色显示,并提供快速修复:删除它,或在名称前加上前导_,以表明它被有意标记为未使用(_名称永远不会被报告)。
| 代码 | 标记的内容 |
|---|---|
| KS6002 | 没有被调用的函数。项目中其他文件的调用同样算数:另一脚本导入并调用的库函数、路由文件指定的控制器(to="people.show",或其index、store、show、update和destroy方法对应的<Resource to="people">),以及kscript.json中指定的中间件。仅调用自身的函数仍被视为未使用。 |
| KS6003 | 其值从未被读取的变量、常量或循环变量,包括仅被赋值过的变量。脚本顶层的常量与函数一样会被导出,因此当导入它的文件使用它们时,它们被视为已使用。在页面中,只检查函数自身的变量,因为布局或组件可能读取其他变量。 |
| KS6004 | 函数体从未读取的函数参数。对于lambda,只标记最后一个被读取的参数之后的参数,因为由调用者决定传入什么:若要保留参数位置,请写fn(_y) => ...。 |
| KS6005 | 未被使用的导入:as别名、names="..."中的名称、整个脚本,或者其任何元素、命令、方法或变量都未出现的包。 |
| KS6006 | 这不是未使用的代码,而是一条风格提示:在.kscript文件中,用一个字符串写成的名称列表(Middleware(use: "log, cors"))。应改写为数组,use: [log, cors];快速修复会自动完成此操作。XML属性本身就是文本,因此use="log, cors"在那里是可以接受的。 |
| KS6008 | 这同样不是未使用的代码:它指的是项目中的某个脚本声明了第二个类型、模型、枚举或错误类型。每个类型都应放在以其命名的单独文件中,并在使用处导入;警告会说明应将其移动到哪里(types/order-status.kscript)。与文件同名的类型可以保留。项目之外的脚本不做检查。 |
项目是指最近的kscript.json所在的文件夹及其下的所有内容(隐藏文件夹、bin、obj和node_modules会被跳过)。项目之外的脚本会与其所在文件夹中的其他文件进行比对。若函数是项目外部使用的API的一部分,可以在其文档注释中加上@public来声明:
<!---
Kept for scripts that still call it.
@public
-->
<fn name="titlecase" params="text: string" value="$text->upper()" />/// Kept for scripts that still call it.
/// @public
fn titlecase(text: string) => $text->upper()与 KS6001 一样,这些规则来自默认的标准,即kscript:recommended,以警告形式出现(kscript:strict会将其变为错误)。项目可以在kscript.json中更改或关闭其中每一条,例如"lint": { "rules": { "KS6004": "off" } }。
函数
<fn name="greet" params="who: string, greeting = 'Hello'">
<return value="$greeting + ', ' + $who + '!'" />
</fn>
<fn name="square" params="n: number" value="$n * $n" />
<echo>{ @greet('World') } { 4 |> @square() }</echo>
<do>@greet('Kyle')</do>
<spawn fn="background_job" />fn greet(who: string, greeting = 'Hello') {
return $greeting + ', ' + $who + '!'
}
fn square(n: number) => $n * $n
echo "{ @greet('World') } { 4 |> @square() }"
@greet('Kyle')
spawn(fn: @background_job)函数可以在声明之前调用、可以递归,也可以作为参数传递:@square 本身就是该函数。Lambda 同样是值,并以相同的简单方式声明其参数:$by_age = fn(a, b) => $a.age - $b.age。
简短的函数会对每个元素读取字段或调用方法。它以 . 或 -> 开头,代表当前元素,可用于任何需要函数的地方:
<let name="urgent" value="$orders->sort(by: .priority)->filter(.paid)" />
<let name="by_shop" value="$orders->group_by(.shop.name)" />
<let name="lines" value="$lines->map(->trim()->upper())" />$urgent = $orders->sort(by: .priority)->filter(.paid)
$by_shop = $orders->group_by(.shop.name)
$lines = $lines->map(->trim()->upper()).priority 等同于 fn(order) => $order.priority,->trim() 等同于 fn(line) => $line->trim()。简短的函数是由字段和方法调用组成的单个链式表达式。对于更复杂的情况,例如 $order.price > 10,请改写为 fn(order) => …。
块函数
当函数需要不止一个表达式时,请使用代码块代替 =>。该代码块包含语句,与 fn name() { } 的函数体相同,并由 return 给出函数的结果:
<let name="prices" value="[3, 7, 12]" />
<let name="with_tax">$prices->map(fn(price) {
$taxed = $price * 1.5 // 4.5 for the first price, because 3 * 1.5 is 4.5
return $taxed->round() // 5, because 4.5 rounds up
})</let>
<!-- $with_tax is [5, 11, 18]: the block ran once for each price -->$prices = [3, 7, 12]
$with_tax = $prices->map(fn(price) {
$taxed = $price * 1.5 // 4.5 for the first price, because 3 * 1.5 is 4.5
return $taxed->round() // 5, because 4.5 rounds up
})
// $with_tax is [5, 11, 18]: the block ran once for each price参数的类型由调用处推断,与 fn(price) => … 中的情况相同:这里 $price 是数字,因为 $prices 是数字列表,因此编辑器会在 $price-> 之后建议数字方法,并显示 with_tax: number[]。
代码块可以用 if 做判断,也可以用 return 提前退出:
<let name="scores" value="[42, 97, 61, 88]" />
<let name="passed">$scores->filter(fn(score) {
if $score < 60 {
return false // 42 is dropped here, because it is under 60
}
return $score % 2 == 0 // 97 and 61 are dropped, because they are odd
})</let>
<!-- $passed is [88] -->$scores = [42, 97, 61, 88]
$passed = $scores->filter(fn(score) {
if $score < 60 {
return false // 42 is dropped here, because it is under 60
}
return $score % 2 == 0 // 97 and 61 are dropped, because they are odd
})
// $passed is [88]带两个参数的函数(例如 ->reduce(fn(total, item), initial?))同样可以接受代码块:
<let name="basket" value="[{ name: 'apple', cost: 2 }, { name: 'melon', cost: 5 }]" />
<let name="total">$basket->reduce(fn(sum, item) {
return $sum + $item.cost // 2 after the apple, then 7, because the melon adds 5
}, 0)</let>
<!-- $total is 7 -->$basket = [{ name: 'apple', cost: 2 }, { name: 'melon', cost: 5 }]
$total = $basket->reduce(fn(sum, item) {
return $sum + $item.cost // 2 after the apple, then 7, because the melon adds 5
}, 0)
// $total is 7以 return 结束的代码块会返回 null,适用于 ->each() 这类只关心代码块所执行操作的场景。在其他场景中,调用会使用代码块的返回值,因此空的或从不返回值的代码块是错误的,无论在编辑器中、在 kscript check 中还是运行时都会报错:
<let name="words" value="['fig', 'kiwi']" />
<let name="longest">$words->common(1, by: fn(word) {
})</let>
<!-- Error: This fn block is empty, so it gives null each time it is called, and 'by' uses what it gives. -->$words = ['fig', 'kiwi']
$longest = $words->common(1, by: fn(word) {
})
// Error: This fn block is empty, so it gives null each time it is called, and 'by' uses what it gives.代码块可以读取并修改其周围的变量,它所创建的变量则只在代码块内部有效:
<let name="seen" value="0" />
<do>['x', 'y', 'z']->each(fn(letter) {
$seen = $seen + 1 // the outer $seen goes up, because the block changes the variable around it
$shout = $letter->upper() // $shout exists only inside the block
echo $shout // X, then Y, then Z, because the block runs once per letter
})</do>
<!-- $seen is 3 -->$seen = 0
['x', 'y', 'z']->each(fn(letter) {
$seen = $seen + 1 // the outer $seen goes up, because the block changes the variable around it
$shout = $letter->upper() // $shout exists only inside the block
echo $shout // X, then Y, then Z, because the block runs once per letter
})
// $seen is 3块函数与其他函数一样是一个值,因此可以保存在变量中并被调用:先写 $greet = fn(name) { … },再调用 $greet('Ada')。块函数可用于 .kscript 文件。XML 属性无法容纳语句,因此在那里应写成 fn(n) => value,或者声明一个 <fn> 并将其作为 @name 传递。数据库查询的条件(->where(fn(u) => $u.age >= 18))会被转换为 SQL,因此它必须保持为单个表达式。
声明为 any 的参数可以接受任何值。对其进行的方法调用会使用该值的实际类型。例如,$key->trim() 会去除字符串的首尾空白,对数字则会报错,并且在该类型存在自己的 trim() 时会调用它。对于字符串规范化,请写成 fn trim_key(key: string) => $key->trim()。这样编辑器便可推断出字符串的返回类型。
命名参数
任何调用都可以按任意顺序为参数命名:内置命令、方法、你自己定义的 fn 函数以及 Lambda 均可。
<echo>{ @known_folder(name: 'downloads') }</echo>
<echo>{ @greet(greeting: 'Hi', who: 'Kyle') }</echo>
<echo>{ @range(1, step: 2, end: 10) }</echo>
<echo>{ 'abc'->pad(char: '*', width: 6, start) }</echo>
<echo>{ @join_path(base: $folder, ['archive', $name]) }</echo>echo "{ @known_folder(name: 'downloads') }"
echo "{ @greet(greeting: 'Hi', who: 'Kyle') }"
echo "{ @range(1, step: 2, end: 10) }"
echo "{ 'abc'->pad(char: '*', width: 6, start) }"
echo "{ @join_path(base: $folder, ['archive', $name]) }"位置参数按顺序填充参数,每个 name: value 则填充同名的参数,因此你可以跳过中间的可选参数。写在命名参数之后的位置参数会填充第一个仍为空的参数,@join_path(base: $folder, [...]) 的读法即是如此。为不存在的参数命名,或为同一参数重复赋值,都会报错,并附带“你是否想要”的提示。编辑器会在 ( 或 , 之后补全参数名。
互斥组
部分参数是互斥的选项:一次调用只能传入其中之一。用 | 连接它们的名称:
<fn name="file" params="note_id: int, add|remove: string, notify: bool = true">
<let name="change" value="$add != null ? "Added { $add }" : "Removed { $remove }"" />
<let name="told" value="$notify ? ', and told its owner' : ''" />
<return value=""{ $change } on note { $note_id }{ $told }"" />
</fn>
<echo value="@file(4, add: 'plan.png')" />
<echo value="@file(4, remove: 'old.png', not notify)" />fn file(note_id: int, add|remove: string, notify: bool = true) {
$change = $add != null ? "Added { $add }" : "Removed { $remove }"
$told = $notify ? ', and told its owner' : ''
return "{ $change } on note { $note_id }{ $told }"
}
echo @file(4, add: 'plan.png')
echo @file(4, remove: 'old.png', not notify)@file(4, add: $a, remove: $b) 是错误的(“@file() 只接受 add: 或 remove:,不能两者都传”),@file(4) 同样是错误的(“需要 add: 或 remove:”)。kscript check 会在代码运行前同时报告这两种情况。组内成员始终需要命名,调用时未传入的成员在函数体中为 null。为其中某个成员传入 null(或 false)等同于未传入。
| 写法 | 含义 |
|---|---|
add|remove: file |
add 与 remove 两个文件中恰好一个。 |
at|after?: date |
至多一个:最后一个名称后的 ? 允许调用时两者都不传。 |
text: string | template: Template |
恰好一个,且各自有自己的类型。 |
(text: string | template: Template)? |
同样的含义,用方括号表示,其中 ? 表示至多一个。 |
当一个组的成员类型不同,而该组旁边还有其他参数时,需要使用方括号,以明确组的结束位置:fn send(to: email, (text: string | template: Template), at|after?: date)。任何组都允许加方括号。组内成员不能有自己的默认值。
内置命令也使用互斥组。@api() 接受 post:、put:、patch: 和 delete: 之一,作业的 ->dispatch() 接受 delay: 或 at:,二者不能同时使用。签名帮助会将一个组显示为一个位置,一旦写入了其中一个成员,补全便不再提供组内其他成员,而且编辑器会为一个组的名称使用同一种颜色。
标志
布尔类型的参数可以写成单独的词:recursive 将其设为真,not recursive 将其设为假,因此调用读起来像一句话。
<let name="all" value="@files($folder, pattern: '*.txt', recursive)" />
<echo>{ $data->convert(to: json, indented) }</echo>
<fn name="save" params="path: string, overwrite: bool = false">
<!-- … -->
</fn>
<do>@save('out.txt', overwrite)</do>$all = @files($folder, pattern: '*.txt', recursive)
echo "{ $data->convert(to: json, indented) }"
fn save(path: string, overwrite: bool = false) {
// …
}
@save('out.txt', overwrite)写成overwrite: true或recursive: false同样可行,但编辑器会建议改用标志(KS6024),并给出将其改写为overwrite或not recursive的修复方案。
参数类型
每个实参都必须是其参数所接受的值。一条规则决定了这一点,编辑器、kscript check 和运行时都应用同一规则,因此它们会在代码运行前以相同的措辞报告同样的错误:
<let name="rolls" value="[4, 6, 6, 2]" />
<do>$rolls->common(1, least)</do> <!-- [2]: least on its own is true -->
<do>$rolls->common(1, not least)</do> <!-- [6]: not least is false -->
<do>$rolls->common(1, least: 'yes')</do> <!-- [2]: text that reads as true or false is converted -->
<do>$rolls->common('1')</do> <!-- [6]: text that reads as a number is converted -->
<do>$rolls->common(1, least: {})</do>
<!-- Error: The 'least' argument needs true or false, but this is a map. It is a flag: write least on its own for true, or not least for false. -->
<do>$rolls->common(fn() => 2)</do>
<!-- Error: The 'count' argument needs a number, but this is a function. -->
<do>$rolls->common(1, by: 3)</do>
<!-- Error: The 'by' argument needs a function, but this is a number. -->
<do>['fig']->union('fig')</do>
<!-- Error: The 'other' argument needs a list, but 'fig' is text. -->$rolls = [4, 6, 6, 2]
$rolls->common(1, least) // [2]: least on its own is true
$rolls->common(1, not least) // [6]: not least is false
$rolls->common(1, least: 'yes') // [2]: text that reads as true or false is converted
$rolls->common('1') // [6]: text that reads as a number is converted
$rolls->common(1, least: {})
// Error: The 'least' argument needs true or false, but this is a map. It is a flag: write least on its own for true, or not least for false.
$rolls->common(fn() => 2)
// Error: The 'count' argument needs a number, but this is a function.
$rolls->common(1, by: 3)
// Error: The 'by' argument needs a function, but this is a number.
['fig']->union('fig')
// Error: The 'other' argument needs a list, but 'fig' is text.| 参数接受 | 同时也接受 | 从不接受 |
|---|---|---|
文本(string) |
以文本形式写出的数字或真/假 | 列表、映射或函数 |
数字(number、int、float) |
可被读作数字的文本,例如 '3' |
其他文本、真/假、列表、映射或函数 |
真或假(bool) |
可被读作真或假的文本,例如 'yes' |
数字、列表、映射或函数 |
| 列表、映射或函数 | 其他任何值 |
{ } 始终是映射,即使它写在参数名后面的两行中,因此下一行的 least: { 和 } 是映射而不是代码块。编辑器会提供将 least: { } 替换为 least 的选项。
尾随逗号
列表中的项之间用逗号分隔。只有当列表每行写一项时,才允许在最后一项后加逗号,这样增加一项时只需改动一行。若在同一行的结束括号前加逗号,则在任何类型的列表中都是错误的:
<let>$label = fn(name,) => $name</let> <!-- Error: Nothing follows this comma. -->
<let>$sizes = [1, 2,]</let> <!-- Error, and the same for { size: 1, } and ->take(2,) -->
<set name="sizes">[
1,
2, // fine: the list is written one per line
]</set>$label = fn(name,) => $name // Error: Nothing follows this comma.
$sizes = [1, 2,] // Error, and the same for { size: 1, } and ->take(2,)
$sizes = [
1,
2, // fine: the list is written one per line
]枚举与常量
enum 用于声明一组命名值,const 用于声明一个不可更改的值。
<enum name="Size" values="small, medium, large" />
<const name="max_items" value="10" />
<fn name="pack" params="size: Size, gift: bool = false" value="'Packing ' + $size" />
<echo>{ @pack(.large) } { @pack(size: .small, gift) } { Size.medium }</echo>enum Size { small, medium, large }
const $max_items = 10
fn pack(size: Size, gift: bool = false) => 'Packing ' + $size
echo "{ @pack(.large) } { @pack(size: .small, gift) } { Size.medium }"长枚举可以每行放一个值,且不需要逗号,就像类型每行放一个字段一样。kscript fmt 会把能放进行宽的枚举放在同一行,较长的枚举则每行放一个值:
<enum name="Topping" values="mozzarella
pepperoni
mushrooms
green_peppers
black_olives
pineapple
jalapenos" />enum Topping {
mozzarella
pepperoni
mushrooms
green_peppers
black_olives
pineapple
jalapenos
}在已知类型的情况下,枚举的值前面要加一个前导点:.large 即 Size.large,因为 size 是 Size(参见下文的前导点)。若没有任何信息说明类型,则需完整书写:Size.medium。枚举的列表使用枚举值的数组:使用 fn pack_all(sizes: Size[]) 时,写作 @pack_all([.large, .small])。内置命令也有单词参数,这些单词直接书写,不加点:@known_folder(downloads) 接受 home、desktop、documents、downloads、music、pictures、videos、appdata 或 temp。Size 本身是一个从每个名称映射到其自身的映射,因此 'large' in Size 可用于检查某个值。顶层的 <const> 和 <enum> 声明会导出给导入该文件的脚本。
前导点: .name
以点号开头的名称是所在位置所期望的类型的成员。当周围的代码已经说明了类型时,可以省去写类型名称:
<enum name="NoteColor" values="yellow, pink, blue, red" />
<type name="Note">
<field name="text" type="string" />
<field name="color" type="NoteColor" default=".yellow" />
<fn name="label" value=".text->upper()" />
<fn name="urgent" value=".color == .red" />
<fn name="kind" returns="string" value="match .color {
.red => 'Urgent'
_ => 'Normal'
}" />
</type>
<fn name="paint" params="color: NoteColor" returns="string" value=""painted { $color }"" />
<let name="note" value="Note(text: 'milk', color: .pink)" />
<echo>{ $note->label() } { $note->kind() } { $note->urgent() } { @paint(color: .blue) }</echo>
<let name="people" value="[{ name: 'Ann', age: 31 }, { name: 'Bo', age: 25 }]" />
<echo value="$people->sort(by: .age)->map(.name)" />enum NoteColor { yellow, pink, blue, red }
type Note {
text: string
color: NoteColor = .yellow
fn label() => .text->upper()
fn urgent() => .color == .red
fn kind(): string => match .color {
.red => 'Urgent'
_ => 'Normal'
}
}
fn paint(color: NoteColor): string => "painted { $color }"
$note = Note(text: 'milk', color: .pink)
echo "{ $note->label() } { $note->kind() } { $note->urgent() } { @paint(color: .blue) }"
$people = [{ name: 'Ann', age: 31 }, { name: 'Bo', age: 25 }]
echo $people->sort(by: .age)->map(.name)点号的含义按以下顺序读取:
- 一个带类型的槽位。 参数、字段的默认值、比较、匹配分支、列表项,或接受枚举的带类型
fn的返回值:.pink即该枚举的值。接受函数的槽位(如->map(.name))会读取每个项目的该字段。 - 循环中的项,位于
for循环内。 在for account in $accounts { ... }中,.id的值为$account.id,.name = 'Ann'用于设置该项的字段。在嵌套循环中,同名的最内层项优先,因此内层循环的.label与外层循环的.id可以并列使用。while循环没有项,因此不会添加任何内容。 - 记录自身,在其自身的方法内。 在
type、model、extend或组件方法中,.text是记录自身的字段,.save()调用其自身的方法。.count += 1和.color = .red用于设置其字段。 - 这些都不是。
$c = .red是一个错误,.red needs a type here,快速修复会把它完整写出:NoteColor.red。
先尝试槽位。在方法内部,@paint(color: .red) 即为 NoteColor.red,即使记录中有名为 red 的字段也是如此。枚举中没有的名称属于记录自身,因此 fn current(): NoteColor => .color 返回记录的 color。两者都没有的名称则会报错。
循环的 item 位于 record 之前。在遍历带有 title 的行的方法中,.title 属于该行,而记录自身的则写作 $this.title;检查器会指出这一点并提供该修复方法。
<type name="Tag">
<field name="label" type="string" />
</type>
<type name="Row">
<field name="id" type="int" />
<field name="name" type="string" />
<field name="tags" type="Tag[]" default="[]" />
</type>
<let name="rows" type="Row[]" value="[Row(id: 1, name: 'Ann', tags: [Tag(label: 'new')])]" />
<for each="row" in="$rows">
<echo>{ .id } { .name->upper() }</echo>
<for each="tag" in=".tags">
<echo>{ .id } { .label }</echo>
</for>
</for>type Tag {
label: string
}
type Row {
id: int
name: string
tags: Tag[] = []
}
$rows: Row[] = [Row(id: 1, name: 'Ann', tags: [Tag(label: 'new')])]
for row in $rows {
echo "{ .id } { .name->upper() }"
for tag in .tags {
echo "{ .id } { .label }"
}
}在值的位置输入 . 时,会精确提示适合填入的内容:在有类型的位置提示枚举的值;在循环中提示循环项的字段(然后是外层循环的字段,最后是记录的字段);在方法中提示记录的字段和方法。将鼠标悬停在某个值上,会显示它所代表的含义,例如 NoteColor.pink。
类型化数据
type用于声明某些数据(例如 API 响应)的结构。经过它的数据会被检查并转换为记录:这是一种知道自身类型的映射,因此编辑器能够补全其字段,且像$repo.stras这样的拼写错误会被捕获。字段也可以是email、password、handle、uuid或regex,类型还可以为其他类型添加规则或与其他类型合并。参见类型与校验。
类型是一个代码块,每行一个字段,name: type:
<type name="User">
<field name="login" type="string" />
<field name="id" type="int" />
</type>
<type name="Repo">
<field name="name" type="string" />
<field name="stars" type="int" from="stargazers_count" />
<field name="owner" type="User" />
</type>
<let name="repo" value="Repo({ name: 'kscript', stargazers_count: 12, owner: { login: 'kyle', id: 1 } })" />
<echo>{ $repo.name } has { $repo.stars } stars, owned by { $repo.owner.login }</echo>type User {
login: string
id: int
}
type Repo {
name: string
stars: int from stargazers_count
owner: User
}
$repo = Repo({ name: 'kscript', stargazers_count: 12, owner: { login: 'kyle', id: 1 } })
echo "{ $repo.name } has { $repo.stars } stars, owned by { $repo.owner.login }"stars: int from stargazers_count 从名称不同的键中读取字段,owner: User 是另一个类型,因此嵌套的数据也会经过检查并转换为 User 记录。Repo(data) 将映射、映射列表或 JSON 文本进行映射。
使用 $.name 在当前作用域中查找某个值。它解析名称的方式与 $name 相同,包括函数参数、局部变量或组件字段。
方法签名
类型可以声明一个方法而不编写其方法体:在 fn 行末尾使用 ; 代替 => 或 { } 的位置。这一行即为方法签名,而 extends 此类型的其他类型必须实现它。方法名后的 ?(如 fn details?(): string;)会使该方法变为可选。编辑器和本文档会以斜体显示签名行,便于一眼区分它们与带方法体的方法。检查器会报告任何缺失的必需方法,或其参数名称、参数类型、返回类型不匹配的情况。
<type name="Summary">
<fn name="label" params="prefix: string" returns="string" signature=";" />
<fn name="details" optional="?" returns="string" signature=";" />
</type>
<type name="NoteSummary" extends="Summary">
<field name="title" type="string" />
<fn name="label" params="prefix: string" returns="string" value="$prefix + .title" />
</type>type Summary {
fn label(prefix: string): string;
fn details?(): string;
}
type NoteSummary extends Summary {
title: string
fn label(prefix: string): string => $prefix + .title
}字段行
字段行的格式为 name[?][: type] [from path] [= default | => value]。除名称外,每个部分都是可选的。带值但不带类型的字段可以在冒号后直接书写值,如 layout: ```text ... ``` 或 symbols: { '#': '#' },并从该值推断其类型:
<enum name="Visibility" values="public, private, internal" />
<type name="Repo" description="A GitHub repository.">
<field name="name" type="string" />
<field name="stars" type="int" from="stargazers_count" description="How many people starred it." />
<field name="owner" type="User" />
<field name="owner_name" type="string" from="owner.login" />
<field name="topics" type="string[]" default="[]" />
<field name="license?" type="string" from="license.name" />
<field name="visibility" type="Visibility" />
<field name="updated" type="date" from="updated_at" />
<field name="label" value="$name + ' (' + $stars + ' stars)'" />
</type>enum Visibility { public, private, internal }
/// A GitHub repository.
type Repo {
name: string
/// How many people starred it.
stars: int from stargazers_count
owner: User
owner_name: string from owner.login
topics: string[] = []
license?: string from license.name
visibility: Visibility
updated: date from updated_at
label => $name + ' (' + $stars + ' stars)'
}| 部分 | 作用 |
|---|---|
: type |
A built-in (string, int, float, number, bool, date, list, map, fn, any, email, password, handle, uuid, regex), an enum, another type, T[] for a list. Rules can follow in brackets: string(min: 1). Without it the field takes any value. |
名称后的 ? |
该值可以缺失或为 null。这是将字段标记为可选的唯一方式,适用于 type、model、error 和 job:使用 license?: string,而不是 license: string?(KS6014,附带快速修复)。T? 适用于并非字段自身类型的情况,例如可能为 null 的参数:fn show(repo: Repo?)。 |
from path |
当值不在字段名对应的位置时,从何处读取:stargazers_count、owner.login、items[0].name。嵌套数据会被展平。包含空格的路径需加引号。 |
= default |
数据中没有该值时使用的值。此时字段为可选。 |
=> value |
根据其他字段(即 $name、$stars 等)计算该字段,而不是读取它。 |
行上方的 /// |
在悬停和补全时显示。 |
The type itself takes options in brackets: type Repo(extra: error) { … }. extra says what happens to keys the type doesn't list: drop (the default), keep or error. path: "data/repo.json" takes the fields from a saved sample of the data: objects become nested types, and keys only some list items have become optional. Lines in the block replace the sampled fields they name. Types can refer to each other in any order and to themselves, and top-level types are exported to scripts that import the file. In a project, give each type its own file (types/repo.kscript, types/owner.kscript) and import the ones it uses: import "owner.kscript" at the top of types/repo.kscript (see One type per file).
小型类型也可以写在一行中,字段的写法类似 fn 参数:type Point(fields: [x: int, y: int])。kscript convert 则将其写成代码块形式。
在 XML 中,类型是 <type name="Repo">,每行对应一个 <field name="stars" type="int" from="stargazers_count" /> 元素;单行形式则使用 fields="..." 属性。将示例切换为 XML 即可查看。
数据与类型的交汇处
<let name="repo" value="@api($url, as: Repo)" /> <!-- KScript.Net: ->check()->convert(from: json, as: Repo) -->
<let name="repos" value="@read_json(./repos.json, as: Repo)" /> <!-- KScript.IO; a list maps item by item -->
<let name="user" value="$text->convert(from: json, as: User)" />
<set name="user" value="User($data)" /> <!-- a map, a list or JSON text -->
<let name="repo" type="Repo" value="$data" /> <!-- also on const and plain assignment -->
<fn name="show" params="repo: Repo, tags: string[]">
<!-- … -->
</fn>$repo = @api($url, as: Repo) // KScript.Net: ->check()->convert(from: json, as: Repo)
$repos = @read_json(./repos.json, as: Repo) // KScript.IO; a list maps item by item
$user = $text->convert(from: json, as: User)
$user = User($data) // a map, a list or JSON text
$repo: Repo = $data // also on const and plain assignment
fn show(repo: Repo, tags: string[]) {
// …
}as: 接受一个类型:as: Repo、as: int,或用 as: Repo[] 表示其列表,写法与声明相同。$repo->type() 为 'Repo'。记录在任何能用映射的地方仍然有效,但读取或设置该类型不具备的字段会报错,设置字段时会将值转换为该字段的类型。
->type() 返回列表的元素类型。[1, 2]->type() 返回 'number[]',由 Repo 记录组成的列表返回 'Repo[]'。混合列表和无类型的空列表返回 'any[]'。使用 ->is_a(list) 判断某个值是否为任意类型的列表。
当数据不符合要求时,映射会失败,并抛出一个 Shape 错误,列出每个问题及其 JSON 路径:
The response from https://api.github.com/... doesn't fit Repo (2 problems):
$.stargazers_count: needs an int, but got the string 'lots'.
$.visibility: must be a Visibility (public, private, internal), but got the string 'secret'.在 catch 中,$err.problems 是一个由 { path, field, message } 映射组成的列表。Repo->check($data) 在数据符合时返回该列表(否则为空),且不会抛出异常;Repo.fields 列出各字段;Repo->schema() 以 JSON Schema 的形式描述该类型。
由类型派生类型
一个类型可以由另一个类型派生而来,这样参数或字段就能跟随其所代表的类型,而无需重复声明。当原类型发生变化时,由它派生的所有类型也随之变化,编辑器会对名称进行补全、链接并检查。
| 表单 | 它是什么 |
|---|---|
Post.fields |
Post 的某个字段名,直接写出:title。模型自身的字段(id 及其键)和关系都可以使用。 |
Post.fields(except: [body]) |
更少的名称:except: 去掉部分名称,only: 保留部分名称,relations: false 去掉关系,relations: only 仅保留关系。 |
Post.title |
Post 的 title 字段的类型及其规则。Post.title(max: 80) 在此基础上添加规则。 |
Order.address.postcode |
字段的字段。Order.lines.item 是列表字段 lines 中的一项。 |
Self.fields, Self.title |
在 type 或 model 内部,指正在声明的类型。 |
draft|live |
其中一个词,直接写出。 |
int|uuid |
任一类型的值。表示类型的名称即为该类型;若要表示这个词本身,请加引号:card|'email'。 |
(draft|live)[] |
方括号用于对联合类型分组,这里用于构成其列表。 |
<type name="Post">
<field name="title" type="string(min: 3)" />
<field name="body" type="string" />
<field name="tags" type="string[]" />
<field name="sorted_by" type="Self.fields" default="'title'" />
</type>
<fn name="column" params="by: Post.fields(except: [tags])" value=""sorted by { $by }"" />
<fn name="retitle" params="title: Post.title" value=""renamed to { $title }"" />
<fn name="tag" params="tag: Post.tags.item" value=""tagged { $tag }"" />
<fn name="publish" params="post: Post, as: draft|live = 'live'" value=""{ $post.title } is { $as }"" />
<fn name="find" params="id: int|uuid" value=""found { $id }"" />
<let name="post" value="Post({ title: 'Hello', body: '…', tags: [] })" />
<echo>{ @column(by: body) }, { @retitle('Hello again') }, { @tag('news') }</echo>
<echo>{ @publish($post, as: draft) }, { @find(42) }, { $post.sorted_by }</echo>type Post {
title: string(min: 3)
body: string
tags: string[]
sorted_by: Self.fields = 'title'
}
fn column(by: Post.fields(except: [tags])) => "sorted by { $by }"
fn retitle(title: Post.title) => "renamed to { $title }"
fn tag(tag: Post.tags.item) => "tagged { $tag }"
fn publish(post: Post, as: draft|live = 'live') => "{ $post.title } is { $as }"
fn find(id: int|uuid) => "found { $id }"
$post = Post({ title: 'Hello', body: '…', tags: [] })
echo "{ @column(by: body) }, { @retitle('Hello again') }, { @tag('news') }"
echo "{ @publish($post, as: draft) }, { @find(42) }, { $post.sorted_by }"无法匹配的值会像其他任何带类型参数一样报告,并列出它可能是的所有名称:
'titel' isn't one of Post's fields. Use title, body, tags or sorted_by.
'drafty' isn't one of these words. Did you mean draft? Use draft or live.
The 'id' argument of @find() doesn't fit int|uuid: needs int or uuid, but got the string 'nope'.内置选项同样带有类型,悬停提示、签名帮助和参考文档都会显示每个选项的类型:
- 模型的
hidden:和guarded:接受Self.fields[],key:接受Self.fields。unique:和index:接受(Self.fields|Self.fields[])[],即一个名称或一组名称。 - 作业的
unique_by:接受Self.fields[]。 ModelUpdate的fields:接受model.fields[],即其model:所指定模型的字段。- 迁移的
Index(columns:)接受其表的字段。 - 方法同样以这种方式引用接收者的字段:
$post->is_dirty(title)接受Self.fields,记录上的->pick([title, views])和->omit([body])接受Self.fields[],记录列表上的$posts->pluck(title)或->pluck([title, views])接受Self.fields|Self.fields[]。接收者没有的名称会报错,并给出建议。 - 带有少量固定词的选项即为词联合类型:
Document(template: plain|paper|report|letter|invoice)、->sort(by:, order?: asc|desc),以及接受(index|store|show|update|destroy)[]的Resource(only:)。若某个词同时也是某个类型的名称,则在该类型中加引号,如echo的format: text|'json'|'markdown',但仍直接写出:format: json。
写作 status: draft|live 的模型字段会存储为数据库的枚举列。
在一组 one-of 中,冒号前的 | 用于分隔名称,冒号后的 | 表示联合类型:id|slug: int|uuid 接受 id: 或 slug:,即整数或 uuid。在成员类型各不相同的组中,| 后接 name: 表示开始下一个成员:(as: draft|live | template: Template)。
值与方法
值包括字符串、数字、布尔值、列表、映射、日期、函数和 null,另外值包 还会添加更多类型(文件、HTTP 响应)。每个值都有方法,使用 -> 调用并可链式连接:
<echo>{ $name->trim()->upper() }</echo>
<echo>{ $people->filter(fn(p) => $p.age >= 18)->map(.name)->join(', ') }</echo>
<echo>{ $people |> sort(by: .name) |> first() }</echo>
<echo>{ @now()->add(days: 7)->format(pattern: 'd MMMM yyyy') }</echo>echo "{ $name->trim()->upper() }"
echo "{ $people->filter(fn(p) => $p.age >= 18)->map(.name)->join(', ') }"
echo "{ $people |> sort(by: .name) |> first() }"
echo "{ @now()->add(days: 7)->format(pattern: 'd MMMM yyyy') }"使用 pluck(key) 按顺序读取每一项的某个字段。给 pluck 传入一个键的列表,即可为每一项生成一个新映射。键可以是裸名称、带引号的字符串或变量。
<let name="people" value="[{ name: 'Joan', age: 82 }, { name: 'Sam' }]" />
<let name="names" value="$people->pluck(name)" /> <!-- ['Joan', 'Sam'] -->
<let name="cards" value="$people->pluck([name, age])" /> <!-- [{ name: 'Joan', age: 82 }, { name: 'Sam', age: null }] -->
<let name="labels" value="$people->pluck(['name'])" /> <!-- [{ name: 'Joan' }, { name: 'Sam' }] -->$people = [{ name: 'Joan', age: 82 }, { name: 'Sam' }]
$names = $people->pluck(name) // ['Joan', 'Sam']
$cards = $people->pluck([name, age]) // [{ name: 'Joan', age: 82 }, { name: 'Sam', age: null }]
$labels = $people->pluck(['name']) // [{ name: 'Joan' }, { name: 'Sam' }]映射中缺失的键会得到 null。带类型的记录仍保留其常规字段检查。空的输入列表得到 [],pluck([]) 为每个输入项生成一个空映射。重复的键只出现一次,并按请求的顺序排列。
在列表上,contains(value)、index_of(value)、remove(value) 和 count_of(value) 使用 == 进行比较。例如,[1, '1']->count_of(1) 得到 2。unique() 使用严格相等(===),因此 [1, '1']->unique() 会保留两项。
is_empty() 在字符串上表示零个字符,在列表上表示零项,在映射上表示零个键。如果你曾用 $text->is_empty() 来接受仅含空白的输入,请改用 $text->is_blank() 以保留该行为。
| 文本 | ->is_empty() |
->is_blank() |
|---|---|---|
'' |
true |
true |
' ' |
false |
true |
'hello' |
false |
false |
数字总是以普通数字书写,从不使用指数形式:echo 10 ** 20 输出 100000000000000000000,echo 0.1 ** 20 输出 0.00000000000000000001。整数在任何大小下都是精确的:123456789 * 987654321 为 121932631112635269,2 ** 100 为 1267650600228229401496703205376,从文本或 JSON 读取的 20 位 id 会保留每一位数字。+、-、*、%、**、/(整除时)、->sum()、->product()、@gcd、@lcm 和 @factorial 都保持精确;小数、@sqrt 等则使用普通浮点运算。小数显示 15 位有效数字,因此 0.1 + 0.2 输出 0.3。整数最多可增长到约 30,000 位,超出后会以 Limit 错误停止。
对于文本,->count() 以及位置(在 ->slice()、->index_of() 和 $text[0] 中)大多数字符计为一个位置,而表情符号等字符计为两个。没有任何方法会把这样的字符切开:->chars()、->first()、->last() 和 ->reverse() 都以读者所见的完整字符为单位工作,->slice() 和 ->truncate() 会把落在字符中间的切分点移回到该字符之前。
关于值的简单事实是字段,直接用点号读取,无需方括号,与读取映射的键方式相同:
<import package="KScript.IO" />
<let name="day" value="'2026-11-19'->to_date()" />
<let name="file" value="@file(./notes.txt)" />
<echo>{ $day.year } { $day.weekday } { $file.name } { $file.size }</echo>import KScript.IO
$day = '2026-11-19'->to_date()
$file = @file(./notes.txt)
echo "{ $day.year } { $day.weekday } { $file.name } { $file.size }"因此 $response.status、$file.size、$url.host 和 $e.status 是字段,而任何接受参数或执行操作的都是方法:$response->convert(from: json)、$file->read_text()、$day->format('yyyy')。返回真或假的名称以 is_ 或 has_ 开头:$response.is_ok、$ip.is_private、$list->is_empty()、$map->has(key)。
时长是一段时间:一个数字加一个单位,不加引号,例如 500ms、30s、10m、2h、1d 或 1w,也可组合使用(1h30m)。所有需要时长的地方都接受它:wait(500ms)、@api($url, options: { timeout: 30s })、$cache->set(key, value, ttl: 10m)。纯数字总是表示秒。
年和月分别为 y 和 mo(m 表示分钟):1y、6mo、5y10mo。月和年没有固定长度,因此这些单位按日历移动日期($date + 1mo 会尽可能保留月中的日),而在需要固定长度的地方(如 wait(1mo) 或 1mo.hours)会被拒绝。
编辑器会为每种类型补全字段和方法,并显示其作用。若要更改值的格式,例如读取 JSON 文本或将行写成 CSV,请使用 ->convert():参见 格式之间的转换。
日期
日期的日历属性是字段:.year、.month、.day、.weekday、.quarter、.day_of_year、.week(ISO 周数)和 .days_in_month。.is_past、.is_future、.is_today 和 .is_weekend 将其与当前时间比较,因此适用于模板:
<let name="post" value="{ title: 'Launch', published_at: '2030-01-01 09:00'->to_date() }" />
<echo value="$post.published_at.is_future ? 'Coming soon' : $post.title" />$post = { title: 'Launch', published_at: '2030-01-01 09:00'->to_date() }
echo $post.published_at.is_future ? 'Coming soon' : $post.title->start_of(unit) 和 ->end_of(unit) 分别给出日期所在 day、week、month、quarter 或 year 的第一刻与最后一刻,这正是“本月订单”报表所需要的。一周从区域设置的第一天开始(en-GB 为周一,en-US 为周日),或由 week_start: 指定的那一天:
<let name="now" value="'2026-11-19 14:30'->to_date()" />
<let name="from" value="$now->start_of(month)" /> <!-- 2026-11-01 00:00 -->
<let name="to" value="$now->end_of(month)" /> <!-- 2026-11-30 23:59:59 -->
<let name="monday" value="$now->start_of(week, week_start: monday)" /> <!-- 2026-11-16 -->$now = '2026-11-19 14:30'->to_date()
$from = $now->start_of(month) // 2026-11-01 00:00
$to = $now->end_of(month) // 2026-11-30 23:59:59
$monday = $now->start_of(week, week_start: monday) // 2026-11-16日历运算按整数单位计算。$date + 1y6mo 按年和月移动日期,->add() 也是如此,它接受 years:、months:、weeks: 和 days: 的任意组合(->subtract() 则向后移动)。月份会尽可能保留月中的日,因此 1 月 31 日加一个月得到 2 月的最后一天。对于小时和分钟,请加上或减去一个时长:
<let name="due" value="'2026-11-30'->to_date()->add(months: 1, days: 2)" /> <!-- 2027-01-01 -->
<let name="last_week" value="@today()->subtract(weeks: 1)" />
<let name="renewal" value="'2026-01-31'->to_date() + 1y1mo" /> <!-- 2027-02-28 -->
<let name="meeting" value="'2026-11-30 09:00'->to_date() + 1h30m" /> <!-- 10:30 -->$due = '2026-11-30'->to_date()->add(months: 1, days: 2) // 2027-01-01
$last_week = @today()->subtract(weeks: 1)
$renewal = '2026-01-31'->to_date() + 1y1mo // 2027-02-28
$meeting = '2026-11-30 09:00'->to_date() + 1h30m // 10:30日期只能通过时长移动。$date + 1 是错误的,因为在其他地方纯数字都表示秒,加上布尔值、列表或另一个日期同样是错误的。请写明单位($date + 3d)。唯一将数字视为日期的情形是 Unix 时间戳,即自 1970 年起的秒数,->to_date() 读取它,->timestamp() 将其返回:
<let name="created" value="1795996800->to_date()" /> <!-- 2026-11-30 00:00 UTC -->
<let name="seconds" value="$created->timestamp()" /> <!-- 1795996800 -->$created = 1795996800->to_date() // 2026-11-30 00:00 UTC
$seconds = $created->timestamp() // 1795996800两个日期相减会得到它们之间的精确时长。->since(other, in: unit) 则改为按整天、整周、整月或整年计数,就像计算生日那样。->is_same(other, unit) 判断两个日期是否处于同一天(默认)、同一周、同一月、同一季度或同一年:
<let name="start" value="'2026-11-30 09:00'->to_date()" />
<let name="took" value="'2026-11-30 10:30'->to_date() - $start" /> <!-- 1h30m -->
<let name="born" value="'1990-12-01'->to_date()" />
<let name="age" value="'2026-11-19'->to_date()->since($born, in: years)" /> <!-- 35 -->
<let name="same" value="@today()->is_same(@now(), day)" /> <!-- true -->$start = '2026-11-30 09:00'->to_date()
$took = '2026-11-30 10:30'->to_date() - $start // 1h30m
$born = '1990-12-01'->to_date()
$age = '2026-11-19'->to_date()->since($born, in: years) // 35
$same = @today()->is_same(@now(), day) // truenow 取自计算机时钟,因此在测试中 @with_clock(date, fn) 会为 @now()、@today()、上述字段以及 @format_relative() 固定其值。
处理文本
文本提供了一些反复用到的辅助功能:更改名称的大小写、按分隔符切分、整理空格以及为负载签名。
<echo value="'Order Total'->case(snake)" /> <!-- order_total -->
<echo value="'order_total'->case(camel)" /> <!-- orderTotal -->
<echo value="'order total'->case(pascal)" /> <!-- OrderTotal -->
<echo value="'orderTotal'->case(kebab)" /> <!-- order-total -->
<let name="email" value="'joan@example.com'" />
<echo>{ $email->before('@') } at { $email->after('@') }</echo> <!-- joan at example.com -->
<echo value="'archive.tar.gz'->after('.', last)" /> <!-- gz -->
<echo value="' too many spaces '->squish()" /> <!-- too many spaces -->
<let name="words" value="'Hello, world!'->words()" /> <!-- ['Hello', 'world'] -->
<echo value="'4242424242424242'->mask('*', keep_end: 4)" />echo 'Order Total'->case(snake) // order_total
echo 'order_total'->case(camel) // orderTotal
echo 'order total'->case(pascal) // OrderTotal
echo 'orderTotal'->case(kebab) // order-total
$email = 'joan@example.com'
echo "{ $email->before('@') } at { $email->after('@') }" // joan at example.com
echo 'archive.tar.gz'->after('.', last) // gz
echo ' too many spaces '->squish() // too many spaces
$words = 'Hello, world!'->words() // ['Hello', 'world']
echo '4242424242424242'->mask('*', keep_end: 4)->before() 和 ->after() 在第一个分隔符处切分,使用 last 时则在最后一个分隔符处切分;若找不到分隔符,则返回整个文本。->wrap(width: 60) 在单词之间断行,使文本适合某个宽度,例如 @terminal_width()。->is_numeric() 对于 '42' 或 '-3.5' 这类文本为真。
->contains()、->starts_with()、->ends_with()、->index_of()(最后一个与last匹配)和->replace()严格区分大小写。传入ignore_case可使大小写匹配不区分:
<let name="query" value="'TEA'" />
<echo value="'Green tea'->contains($query, ignore_case)" /> <!-- true -->$query = 'TEA'
echo 'Green tea'->contains($query, ignore_case) // true要校验 webhook,先用->hmac(key)计算签名(默认 SHA-256,也可用sha1或sha512),再与@secure_equals()比较。该比较所用时间与两者相同部分的多少无关:
<let name="body" value="'{"id": 1}'" />
<let name="signature" value="$body->hmac('whsec_test')" />
<echo value="@secure_equals($signature, $body->hmac('whsec_test'))" /> <!-- true -->$body = '{"id": 1}'
$signature = $body->hmac('whsec_test')
echo @secure_equals($signature, $body->hmac('whsec_test')) // true->md5()、->sha1()、->sha256()和->sha512()返回十六进制哈希值。@escape_regex(text)会转义用户输入的内容,使由其构建的模式只匹配该文本。
列表与映射
列表用->difference(other)、->intersect(other)和->union(other)按集合比较。每个函数都保留第一个列表的顺序,每项只保留一次,并通过==匹配项目,或通过by:为每项给出的结果进行匹配:
<let name="left" value="[1, 2, 3, 4]->difference([2, 4])" /> <!-- [1, 3] -->
<let name="both" value="['tea', 'milk']->union(['milk', 'sugar'])" /> <!-- ['tea', 'milk', 'sugar'] -->
<let name="people" value="[{ id: 1, name: 'Ada' }, { id: 2, name: 'Bo' }]" />
<let name="kept" value="$people->intersect([{ id: 2 }], by: fn(p) => $p.id)" /> <!-- [{ id: 2, name: 'Bo' }] -->$left = [1, 2, 3, 4]->difference([2, 4]) // [1, 3]
$both = ['tea', 'milk']->union(['milk', 'sugar']) // ['tea', 'milk', 'sugar']
$people = [{ id: 1, name: 'Ada' }, { id: 2, name: 'Bo' }]
$kept = $people->intersect([{ id: 2 }], by: fn(p) => $p.id) // [{ id: 2, name: 'Bo' }]->count_by(fn)统计每个键对应的项目数,->take_while(fn)和->skip_while(fn)在遇到第一个不满足条件的项目时停止,->window(size, step?)返回重叠的子序列,->replace_at(index, item)返回修改了一个项目后的副本:
<let name="counts" value="['apple', 'avocado', 'banana']->count_by(fn(fruit) => $fruit->first())" /> <!-- { a: 2, b: 1 } -->
<let name="pairs" value="['mon', 'tue', 'wed', 'thu']->window(2)" /> <!-- [['mon', 'tue'], ['tue', 'wed'], ['wed', 'thu']] -->
<let name="fixed" value="['tea', 'tae', 'milk']->replace_at(1, 'juice')" /> <!-- ['tea', 'juice', 'milk'] -->$counts = ['apple', 'avocado', 'banana']->count_by(fn(fruit) => $fruit->first()) // { a: 2, b: 1 }
$pairs = ['mon', 'tue', 'wed', 'thu']->window(2) // [['mon', 'tue'], ['tue', 'wed'], ['wed', 'thu']]
$fixed = ['tea', 'tae', 'milk']->replace_at(1, 'juice') // ['tea', 'juice', 'milk']最常见与最少见:common
->common(count?, least, by?)统计每个项目出现的次数,并按该次数顺序返回各项,每项只出现一次。不带least时最常见的排在前面;带least时最少见的排在前面。count只保留前面指定数量的项目,不指定时返回所有不重复的项目。出现次数相同的项目保持它们在列表中首次出现的顺序,且每项原样返回,因此数字仍为数字:
<let name="basket" value="['apple', 'pear', 'apple', 'fig', 'fig', 'apple']" />
<!-- apple occurs 3 times, fig 2 times, pear once. -->
<echo value="$basket->common()" /> <!-- ['apple', 'fig', 'pear'] because that is most to least -->
<echo value="$basket->common(1)" /> <!-- ['apple'] because it is the 1st most common -->
<echo value="$basket->common(2)" /> <!-- ['apple', 'fig'] because those are the top 2 -->
<echo value="$basket->common(1, least)" /> <!-- ['pear'] because it is the 1st least common -->
<echo value="$basket->common(least)" /> <!-- ['pear', 'fig', 'apple'] because that is least to most -->$basket = ['apple', 'pear', 'apple', 'fig', 'fig', 'apple']
// apple occurs 3 times, fig 2 times, pear once.
echo $basket->common() // ['apple', 'fig', 'pear'] because that is most to least
echo $basket->common(1) // ['apple'] because it is the 1st most common
echo $basket->common(2) // ['apple', 'fig'] because those are the top 2
echo $basket->common(1, least) // ['pear'] because it is the 1st least common
echo $basket->common(least) // ['pear', 'fig', 'apple'] because that is least to mostby:决定什么算作相同的项目。这里'Tea'和'tea'会被合并计算,因为二者都会转换为'tea',返回的是先出现的那一个:
<let name="drinks" value="['Tea', 'milk', 'tea']" />
<echo value="$drinks->common(1, by: fn(drink) => $drink->lower())" /> <!-- ['Tea'] because 'Tea' and 'tea' count as one, twice -->$drinks = ['Tea', 'milk', 'tea']
echo $drinks->common(1, by: fn(drink) => $drink->lower()) // ['Tea'] because 'Tea' and 'tea' count as one, twice要把出现次数最多的三个数字相乘,先用->common(3)取出它们,再用->product()相乘:
<let name="readings" value="[12, 7, 12, 9, 7, 12, 3]" />
<let name="top" value="$readings->common(3)" /> <!-- [12, 7, 9] because 12 occurs 3 times, 7 twice, then 9 comes before 3 -->
<echo value="$top->product()" /> <!-- 756 because 12 * 7 * 9 is 756 -->$readings = [12, 7, 12, 9, 7, 12, 3]
$top = $readings->common(3) // [12, 7, 9] because 12 occurs 3 times, 7 twice, then 9 comes before 3
echo $top->product() // 756 because 12 * 7 * 9 is 756映射拥有与列表相同的回调函数,参数依次为值和键:->filter()、->reject()、->any()、->all()、->find()(其结果为{ key, value })、->reduce()、->sort(by:)和->map()。->map_keys(fn)会重命名每个键,参数依次为键和值:
<let name="stock" value="{ apples: 3, pears: 0, plums: 2 }" />
<let name="empty" value="$stock->reject(fn(n) => $n > 0)" /> <!-- { pears: 0 } -->
<let name="order" value="$stock->sort(by: fn(n) => $n, order: desc)->keys()" /> <!-- ['apples', 'plums', 'pears'] -->
<let name="renamed" value="{ first_name: 'Ada' }->map_keys(fn(key) => $key->case(camel))" /> <!-- { firstName: 'Ada' } -->$stock = { apples: 3, pears: 0, plums: 2 }
$empty = $stock->reject(fn(n) => $n > 0) // { pears: 0 }
$order = $stock->sort(by: fn(n) => $n, order: desc)->keys() // ['apples', 'plums', 'pears']
$renamed = { first_name: 'Ada' }->map_keys(fn(key) => $key->case(camel)) // { firstName: 'Ada' }在格式之间转换:convert
数据经常需要在不同格式之间转换:API 返回 JSON,配置文件是 YAML,电子表格保存为 CSV。所有值都通过同一个方法->convert()完成,读起来就像一句话:从这种格式,转换为那种格式。
from:读取某种格式的文本并返回其中的值。to:将值写成某种格式。两者结合使用,即可把一种格式直接转换为另一种格式。
| 格式 | from:读取 |
to:写入 |
|---|---|---|
json |
映射、列表、文本、数字 | json 文本 |
yaml |
映射、列表、文本、数字 | yaml 文本 |
csv |
由行组成的列表 | csv 文本 |
markdown, latex |
文档 | 使用 KScript.Document |
html |
通过 KScript.Markdown 从 Markdown 读取,通过 KScript.Document 从文档读取 |
读取文本:from
from:接受文本、文本块(如```yaml或```csv块)、json或csv值,或 HTTP 响应(取其正文):
<let name="order" value="'{"fruit": "apple", "count": 3}'->convert(from: json)" />
<echo value="$order.count" /> <!-- 3 because the json text is now a map with a count key -->
<let name="settings">```yaml
theme: dark
size: 12
```</let>
<echo value="$settings->convert(from: yaml).size" /> <!-- 12 because the yaml is read into a map -->$order = '{"fruit": "apple", "count": 3}'->convert(from: json)
echo $order.count // 3 because the json text is now a map with a count key
$settings = ```yaml
theme: dark
size: 12
```
echo $settings->convert(from: yaml).size // 12 because the yaml is read into a mapCSV 默认包含标题行,用于为每行的键命名。当每一行都是数据时,写not header,此时每行就是由其单元格组成的列表:
<let name="prices">```csv
fruit,price
apple,3
plum,5
```</let>
<echo value="$prices->convert(from: csv)[0].fruit" /> <!-- 'apple' because the header line names the fruit column -->
<echo value="$prices->convert(from: csv, not header)[0]" /> <!-- ['fruit', 'price'] because without a header the first line is a row too -->$prices = ```csv
fruit,price
apple,3
plum,5
```
echo $prices->convert(from: csv)[0].fruit // 'apple' because the header line names the fruit column
echo $prices->convert(from: csv, not header)[0] // ['fruit', 'price'] because without a header the first line is a row too按类型校验:as
as:会根据某个类型校验读取到的内容,并将其转换为记录,因此缺失或错误的字段会在读取它的那一行报错,而不会在之后产生意外。记录列表的写法与声明相同,即Fruit[]:
<type name="Fruit">
<field name="fruit" type="string" />
<field name="price" type="int" />
</type>
<let name="prices">```csv
fruit,price
apple,3
plum,5
```</let>
<let name="fruits" value="$prices->convert(from: csv, as: Fruit[])" />
<echo value="$fruits[0].price + 1" /> <!-- 4 because as: Fruit[] turned the '3' cell into the int 3 -->type Fruit {
fruit: string
price: int
}
$prices = ```csv
fruit,price
apple,3
plum,5
```
$fruits = $prices->convert(from: csv, as: Fruit[])
echo $fruits[0].price + 1 // 4 because as: Fruit[] turned the '3' cell into the int 3写入格式:to
to:可以写入任意值:映射和列表写成 JSON 或 YAML,由行组成的列表写成 CSV。indented将 JSON 分散到多行,headers:用于挑选并排列 CSV 的列:
<let name="basket" value="[{ fruit: 'apple', count: 3 }, { fruit: 'plum', count: 5 }]" />
<echo value="$basket->convert(to: json)" /> <!-- [{"fruit":"apple","count":3},{"fruit":"plum","count":5}] on one line -->
<echo value="$basket->convert(to: json, indented)" /> <!-- the same json, one key a line, for people to read -->
<echo value="$basket->convert(to: csv, headers: ['count'])" /> <!-- "count", then "3" and "5" because only the count column is asked for -->$basket = [{ fruit: 'apple', count: 3 }, { fruit: 'plum', count: 5 }]
echo $basket->convert(to: json) // [{"fruit":"apple","count":3},{"fruit":"plum","count":5}] on one line
echo $basket->convert(to: json, indented) // the same json, one key a line, for people to read
echo $basket->convert(to: csv, headers: ['count']) // "count", then "3" and "5" because only the count column is asked for同时使用两者
同时传入from:和to:,即可在不处理中间值的情况下将一种格式转换为另一种格式:
<let name="settings">```yaml
theme: dark
size: 12
```</let>
<echo value="$settings->convert(from: yaml, to: json)" /> <!-- {"theme":"dark","size":12} because the yaml is read, then written as json -->$settings = ```yaml
theme: dark
size: 12
```
echo $settings->convert(from: yaml, to: json) // {"theme":"dark","size":12} because the yaml is read, then written as json简写:from 与 to
只读取或只写入时,->from(type: json)和->to(type: csv)表达相同的意思,但更简短。它们接受与->convert()相同的选项:
<let name="order" value="'{"fruit": "apple"}'->from(type: json)" />
<echo value="$order.fruit" /> <!-- 'apple' because ->from(type: json) is ->convert(from: json) -->
<echo value="[{ fruit: 'plum' }]->to(type: json)" /> <!-- [{"fruit":"plum"}] because ->to(type: json) is ->convert(to: json) -->$order = '{"fruit": "apple"}'->from(type: json)
echo $order.fruit // 'apple' because ->from(type: json) is ->convert(from: json)
echo [{ fruit: 'plum' }]->to(type: json) // [{"fruit":"plum"}] because ->to(type: json) is ->convert(to: json)->convert()是改变格式的唯一方式,因此旧的一格式一方法写法(->json()、->yaml()、->csv()、->markdown()、->to_json()、->to_yaml()、->to_csv(),以及文档的->html()、->latex()和->markdown())会报错,并提示应改用的->convert()写法,编辑器中还附有修复建议。
读取结构化文本
数据常常以文本形式到达:每行一条记录、以空行分隔的多组行,或用字符绘制的图形。这些方法可将文本转换为便于处理的列表。
行与块
->lines()按行返回文本,每行一项。->blocks()则在空行处切分文本,因此每个块是一组行。单个换行符保留在块内,只有空行才会开始新的块:
<let name="pantry">```text
tea
milk
flour
sugar
eggs
```</let>
<let name="shelves" value="$pantry->blocks()" />
<!-- ['tea\nmilk', 'flour\nsugar\neggs'] because the blank line after milk starts a second block -->
<let name="counts" value="$shelves->map(.lines()->count())" />
<!-- [2, 3] because the first block has 2 lines and the second has 3 -->$pantry = ```text
tea
milk
flour
sugar
eggs
```
$shelves = $pantry->blocks()
// ['tea\nmilk', 'flour\nsugar\neggs'] because the blank line after milk starts a second block
$counts = $shelves->map(.lines()->count())
// [2, 3] because the first block has 2 lines and the second has 3在函数的位置上使用.lines()是fn(block) => $block->lines()的简写:即对每个项目调用该方法,就像.name读取每个项目的字段一样。凡是可以放函数的地方它都能使用,例如->filter(.is_empty())或->sort(by: .age)。
切分列表:split
已有列表时,->split(separator)会在分隔项出现的位置把列表切开,并丢弃分隔项。可以用==指定要匹配的值,也可以提供对分隔项为真的判断条件:
<let name="lines" value="['tea', 'milk', '', 'juice']" />
<echo value="$lines->split('')" /> <!-- [['tea', 'milk'], ['juice']] because '' is the separator -->
<echo value="$lines->split(.is_empty())" /> <!-- [['tea', 'milk'], ['juice']] because the check is true for '' -->
<echo value="[5, 0, 7, 8, 0]->split(0)" /> <!-- [[5], [7, 8], []] because a separator at the end leaves an empty list after it -->$lines = ['tea', 'milk', '', 'juice']
echo $lines->split('') // [['tea', 'milk'], ['juice']] because '' is the separator
echo $lines->split(.is_empty()) // [['tea', 'milk'], ['juice']] because the check is true for ''
echo [5, 0, 7, 8, 0]->split(0) // [[5], [7, 8], []] because a separator at the end leaves an empty list after it->split()作用于文本时切分文本;->split()作用于列表时切分列表。
文本中的数字:numbers
->numbers()按顺序返回文本中写出的每个数字,无需为此编写模式。当负号紧接在数字前、其左侧没有任何相连字符时,它被视为符号,如x=-3;当它位于两个数字之间,如1-3,则视为连字符,结果为1和3:
<echo value="'move 3 boxes from -1 to 12'->numbers()" /> <!-- [3, -1, 12] because -1 has a space before its minus -->
<echo value="'pages 4-9'->numbers()" /> <!-- [4, 9] because the minus joins 4 and 9, so it is a dash -->
<echo value="'price 2.50, qty 4'->numbers()" /> <!-- [2.5, 4] -->echo 'move 3 boxes from -1 to 12'->numbers() // [3, -1, 12] because -1 has a space before its minus
echo 'pages 4-9'->numbers() // [4, 9] because the minus joins 4 and 9, so it is a dash
echo 'price 2.50, qty 4'->numbers() // [2.5, 4]用字符绘制的图形:grid
->grid()将多行字符转换为由单个字符组成的行,因此$grid[row][column]即为一个字符。第 0 行为最上面一行,第 0 列为第一个字符:
<let name="garden">```text
#.#
..#
```</let>
<let name="plot" value="$garden->grid()" />
<!-- [['#', '.', '#'], ['.', '.', '#']] -->
<echo value="$plot[0][1]" /> <!-- '.' because row 0 is '#.#' and column 1 is its second character -->
<echo value="$plot[1][2]" /> <!-- '#' because row 1 is '..#' and column 2 is its last character -->$garden = ```text
#.#
..#
```
$plot = $garden->grid()
// [['#', '.', '#'], ['.', '.', '#']]
echo $plot[0][1] // '.' because row 0 is '#.#' and column 1 is its second character
echo $plot[1][2] // '#' because row 1 is '..#' and column 2 is its last character遍历行与列:cells
->cells()像读取表格一样读取网格。单独使用或与rows一起使用时返回每一行;与columns一起使用时按从上到下的顺序返回每一列。这就是在两个方向上遍历网格的方式:
<let name="garden">```text
#.#
..#
```</let>
<let name="plot" value="$garden->grid()" />
<for each="row" in="$plot->cells(rows)">
<echo value="$row->join('')" />
</for>
<!-- '#.#' then '..#' because each row is one line of the picture -->
<for each="column" in="$plot->cells(columns)">
<echo value="$column->join('')" />
</for>
<!-- '#.' then '..' then '##' because each column reads one character from every line, top to bottom -->
<echo value="$plot->cells(columns)->map(fn(column) => $column->count_of('#'))" />
<!-- [1, 0, 2] because only the last column has a # in both rows -->$garden = ```text
#.#
..#
```
$plot = $garden->grid()
for row in $plot->cells(rows) {
echo $row->join('')
}
// '#.#' then '..#' because each row is one line of the picture
for column in $plot->cells(columns) {
echo $column->join('')
}
// '#.' then '..' then '##' because each column reads one character from every line, top to bottom
echo $plot->cells(columns)->map(fn(column) => $column->count_of('#'))
// [1, 0, 2] because only the last column has a # in both rowsrow:选取一行,column:选取一列,二者均从 0 开始计数,-1表示最后一项。两者同时给出时,即可取到它们交汇处的那一个单元格:
<let name="garden">```text
#.#
..#
```</let>
<let name="plot" value="$garden->grid()" />
<echo value="$plot->cells(row: 0)" /> <!-- ['#', '.', '#'] because row 0 is the top line -->
<echo value="$plot->cells(column: -1)" /> <!-- ['#', '#'] because -1 is the last column, and both lines end in # -->
<echo value="$plot->cells(row: 1, column: 0)" /> <!-- '.' because row 1 is '..#' and column 0 is its first character -->$garden = ```text
#.#
..#
```
$plot = $garden->grid()
echo $plot->cells(row: 0) // ['#', '.', '#'] because row 0 is the top line
echo $plot->cells(column: -1) // ['#', '#'] because -1 is the last column, and both lines end in #
echo $plot->cells(row: 1, column: 0) // '.' because row 1 is '..#' and column 0 is its first character行的长度可以不同,例如不规则的地图。此时某列会跳过长度不够到达该列的行,不会为填补空缺而凭空生成内容:
<let name="steps">```text
#.#
#
```</let>
<echo value="$steps->grid()->cells(columns)" />
<!-- [['#', '#'], ['.'], ['#']] because the second line only reaches column 0 -->$steps = ```text
#.#
#
```
echo $steps->grid()->cells(columns)
// [['#', '#'], ['.'], ['#']] because the second line only reaches column 0->cells()适用于任何列表的列表,而不仅限于网格:[[1, 2], [3, 4]]->cells(columns)即[[1, 3], [2, 4]],它会把行转换为列。
在网格中查找:positions_of
->positions_of(item)返回某个项目在网格中出现的每个位置,位置为带有.row和.column的点,按行从上到下、每行从左到右排列。若给定一个函数,则返回该函数对单元格为真的位置:
<let name="garden">```text
#.#
..#
```</let>
<let name="trees" value="$garden->grid()->positions_of('#')" />
<!-- [{ row: 0, column: 0 }, { row: 0, column: 2 }, { row: 1, column: 2 }] because those are the three #s, top line first -->
<echo value="$trees->contains({ row: 1, column: 2 })" /> <!-- true because there is a # at row 1, column 2 -->
<echo value="$trees->contains({ row: 1, column: 0 })" /> <!-- false because row 1 starts with a . -->$garden = ```text
#.#
..#
```
$trees = $garden->grid()->positions_of('#')
// [{ row: 0, column: 0 }, { row: 0, column: 2 }, { row: 1, column: 2 }] because those are the three #s, top line first
echo $trees->contains({ row: 1, column: 2 }) // true because there is a # at row 1, column 2
echo $trees->contains({ row: 1, column: 0 }) // false because row 1 starts with a .点与->combinations(2)配合得很好,它会返回每一对点各一次,且较早的点排在前面。带有两个参数的函数会依次接收这对点的两个点。下面的例子统计四个角均为树的正方形数量,即使角之间还夹着其他树:
<let name="field">```text
#.##.
.....
.#...
##.##
```</let>
<let name="trees" value="$field->grid()->positions_of('#')" />
<echo value="$trees->combinations(2)->count_of(fn(left, right) {
// only two trees on the same row can be a square's top corners
if $left.row != $right.row {
return false
}
// the gap between them is the square's width, so the bottom corners sit that many rows down
$size = $right.column - $left.column
return $trees->contains({ row: $left.row + $size, column: $left.column })
and $trees->contains({ row: $left.row + $size, column: $right.column })
})" />
<!-- 1 because only the trees at columns 0 and 3 of row 0 have trees 3 rows below both of them -->$field = ```text
#.##.
.....
.#...
##.##
```
$trees = $field->grid()->positions_of('#')
echo $trees->combinations(2)->count_of(fn(left, right) {
// only two trees on the same row can be a square's top corners
if $left.row != $right.row {
return false
}
// the gap between them is the square's width, so the bottom corners sit that many rows down
$size = $right.column - $left.column
return $trees->contains({ row: $left.row + $size, column: $left.column })
and $trees->contains({ row: $left.row + $size, column: $right.column })
})
// 1 because only the trees at columns 0 and 3 of row 0 have trees 3 rows below both of them查找形状:shapes
->shapes() 可在文本、列表、网格或三维列表中查找形状:内置的正方形、长方形、直线和圆形,以及您自己绘制的遮罩(masks)。文本按 ->grid() 的读取方式处理,每行为一行、每个字符为一个单元格,因此无需先调用 ->grid()。网格的单元格可以存放任何内容,因此对于内置形状,of: 会指定哪些单元格构成该形状:可以是 '#' 这样的值,也可以是 /[#@]/ 这样的正则表达式。每个匹配结果只返回一次,格式为 { kind, points },其中每个点都是一个单元格 { row, column, value }。形状的各点之间可以夹有其他单元格:
<let name="field">```text
#.##.
.....
.#...
##.##
```</let>
<echo value="$field->shapes(square, of: '#')->count()" />
<!-- 1 because the #s at columns 0 and 3 of row 0 have #s 3 rows below both of them -->$field = ```text
#.##.
.....
.#...
##.##
```
echo $field->shapes(square, of: '#')->count()
// 1 because the #s at columns 0 and 3 of row 0 have #s 3 rows below both of them如果不使用 rotated,形状保持水平:正方形和长方形的边保持水平,直线横向或纵向延伸。使用 rotated 后,形状可以倾斜,因此正方形可以是菱形,直线也可以斜向延伸:
<let name="kite">```text
..#..
.#.#.
..#..
```</let>
<echo value="$kite->shapes(square, of: '#')->count()" /> <!-- 0 because no four #s make a square with level sides -->
<echo value="$kite->shapes(square, of: '#', rotated)->count()" /> <!-- 1 because the four #s make a diamond, a square on its corner -->$kite = ```text
..#..
.#.#.
..#..
```
echo $kite->shapes(square, of: '#')->count() // 0 because no four #s make a square with level sides
echo $kite->shapes(square, of: '#', rotated)->count() // 1 because the four #s make a diamond, a square on its corner同时指定多个形状即可一次查找全部。即使一个匹配结果符合多种形状,也只返回一次:正方形同时也是长方形,因此它会作为正方形返回,.kind 会指明它的类型:
<let name="plot">```text
@@@.
@..@
@@@@
```</let>
<echo value="$plot->shapes(rectangle, of: '@')->count()" /> <!-- 4 because three rectangles share rows 0 and 2, and one shares rows 1 and 2 -->
<echo value="$plot->shapes(square, rectangle, of: '@')->map(.kind)" />
<!-- ['square', 'rectangle', 'rectangle', 'rectangle'] because the 2 by 2 one is a square, so it isn't a rectangle as well -->
<echo value="$plot->shapes(line, of: '@', size: 4)->count()" /> <!-- 1 because only the bottom row has 4 @s in a row -->
<echo value="$plot->shapes(line, of: '@', size: 3, rotated)->count()" /> <!-- 4 because rotated lets lines run diagonally too -->$plot = ```text
@@@.
@..@
@@@@
```
echo $plot->shapes(rectangle, of: '@')->count() // 4 because three rectangles share rows 0 and 2, and one shares rows 1 and 2
echo $plot->shapes(square, rectangle, of: '@')->map(.kind)
// ['square', 'rectangle', 'rectangle', 'rectangle'] because the 2 by 2 one is a square, so it isn't a rectangle as well
echo $plot->shapes(line, of: '@', size: 4)->count() // 1 because only the bottom row has 4 @s in a row
echo $plot->shapes(line, of: '@', size: 3, rotated)->count() // 4 because rotated lets lines run diagonally too直线需要 size: 指定其点数。圆形需要 radius:,distance: 用于指定距离的计算方式:straight(直线距离,默认值)、steps(仅横向和纵向距离,绘制出菱形)或 moves(对角线距离计为一步,绘制出正方形环):
<let name="pond">```text
.~.
~.~
.~.
```</let>
<echo value="$pond->shapes(circle, of: '~', radius: 1)->count()" /> <!-- 1 because the four ~s are each 1 away from the middle -->
<echo value="$pond->shapes(circle, of: '~', radius: 1, distance: moves)->count()" /> <!-- 0 because with moves the corners are 1 away too, and they aren't ~ -->$pond = ```text
.~.
~.~
.~.
```
echo $pond->shapes(circle, of: '~', radius: 1)->count() // 1 because the four ~s are each 1 away from the middle
echo $pond->shapes(circle, of: '~', radius: 1, distance: moves)->count() // 0 because with moves the corners are 1 away too, and they aren't ~->shapes() 同样适用于点的列表,例如 ->positions_of() 返回的结果,或从 csv 读取的行。此时每个点都会计入,因此不需要 of::$trees->shapes(square, rotated)。
自定义形状:遮罩(masks)
A mask is a shape you draw. Built-in shapes only know where the points are; a mask says exactly what every cell must hold, gaps included. Declare it as a type that extends Mask, and draw it in its layout: a text block that pictures the shape, one character a cell. Every character matches a cell that holds the same character. The indentation every line shares isn't part of the picture, so indent it with the code around it.
要查找由 # 组成的实心 2×2 方块,请先绘制它,然后通过名称将遮罩传递给 ->shapes():
<type name="Block" description="Four #s packed into a square." extends="Mask">
<field name="layout" default="```text
##
##
```" />
</type>
<let name="roof">```text
###.
###.
...#
```</let>
<let name="blocks" value="$roof->shapes(Block)" /> <!-- the matches, top left first -->
<echo value="$blocks->count()" /> <!-- 2 because the block fits at columns 0-1 and again at columns 1-2 -->
<echo value="$blocks->first().kind" /> <!-- 'Block' because a mask's match is named after its type -->
<echo value="$blocks->first().points->map(.column)" /> <!-- [0, 1, 0, 1] because the first block covers columns 0 and 1 of rows 0 and 1 -->/// Four #s packed into a square.
type Block extends Mask {
layout: ```text
##
##
```
}
$roof = ```text
###.
###.
...#
```
$blocks = $roof->shapes(Block) // the matches, top left first
echo $blocks->count() // 2 because the block fits at columns 0-1 and again at columns 1-2
echo $blocks->first().kind // 'Block' because a mask's match is named after its type
echo $blocks->first().points->map(.column) // [0, 1, 0, 1] because the first block covers columns 0 and 1 of rows 0 and 1symbols is only for the characters that mean something other than themselves. It maps a character to what it matches: a value (t: 'taken') matches a cell that holds it, a regex (/[#@]/) a cell whose text fits, a fn(cell) a cell it gives true for, and any a cell that isn't part of the shape. An any cell can hold anything, can hang over the edge of the input, and is left out of the match's points. To find four trees at the corners of a three-by-three square, with anything between them:
<type name="Corners" description="Trees at the four corners of a 3x3 square, anything between." extends="Mask">
<field name="layout" default="```text
#.#
...
#.#
```" />
<field name="symbols" default="{ '.': any }" />
</type>
<let name="orchard">```text
#.#.#
.#...
#.#.#
```</let>
<echo value="$orchard->shapes(Corners)->count()" /> <!-- 2 because the corners fit at columns 0-2 and at columns 2-4 -->
<echo value="$orchard->shapes(Corners)->first().points->map(.symbol)" />
<!-- ['#', '#', '#', '#'] because . is any, so its cells aren't part of the match, even the # in the middle -->/// Trees at the four corners of a 3x3 square, anything between.
type Corners extends Mask {
layout: ```text
#.#
...
#.#
```
symbols: { '.': any }
}
$orchard = ```text
#.#.#
.#...
#.#.#
```
echo $orchard->shapes(Corners)->count() // 2 because the corners fit at columns 0-2 and at columns 2-4
echo $orchard->shapes(Corners)->first().points->map(.symbol)
// ['#', '#', '#', '#'] because . is any, so its cells aren't part of the match, even the # in the middle当单元格不是单个字符时,symbols 就体现出其价值。一排座位是一个单词列表,而一个值的列表是一行,因此布局需要为每个单词分配一个字母:
<type name="QuietPair" description="Two free seats side by side, with a taken seat on each side." extends="Mask">
<field name="layout" default="```text
tfft
```" />
<field name="symbols" default="{ t: 'taken', f: 'free' }" />
</type>
<let name="row" value="['free', 'taken', 'free', 'free', 'taken', 'taken']" />
<echo value="$row->shapes(QuietPair)->count()" /> <!-- 1 because only seats 1 to 4 read taken, free, free, taken -->/// Two free seats side by side, with a taken seat on each side.
type QuietPair extends Mask {
layout: ```text
tfft
```
symbols: { t: 'taken', f: 'free' }
}
$row = ['free', 'taken', 'free', 'free', 'taken', 'taken']
echo $row->shapes(QuietPair)->count() // 1 because only seats 1 to 4 read taken, free, free, taken->shapes() 可接受一个遮罩或一个遮罩列表,rotated 会将每个遮罩在输入允许的所有方向上进行变换:沿行从后向前,在网格中旋转四分之一、二分之一和四分之三圈,在三维中则有全部 24 种旋转方式。多个遮罩的匹配结果会一并返回,并通过各自的 .kind 命名,并且可以在一次调用中同时查找遮罩和内置形状:
<type name="Fork" description="Three trees in a V, with anything between them." extends="Mask">
<field name="layout" default="```text
t~t
~t~
```" />
<field name="symbols" default="{ t: /[#@]/, '~': any }" />
</type>
<type name="Gap" description="Two trees with a clearing between them." extends="Mask">
<field name="layout" default="```text
#.#
```" />
</type>
<let name="wood">```text
#.@
.#.
#.#
```</let>
<echo value="$wood->shapes(Fork)->count()" /> <!-- 1 because the V fits only with its point at the bottom -->
<echo value="$wood->shapes(Fork, rotated)->count()" /> <!-- 4 because turned a quarter, a half and three quarters, it fits once each way -->
<echo value="$wood->shapes([Fork, Gap], rotated)->map(.kind)" />
<!-- ['Fork', 'Fork', 'Fork', 'Fork', 'Gap', 'Gap'] because the bottom row and the left column are each #.# -->
<echo value="$wood->shapes(Fork)->first().points->map(.symbol)" />
<!-- ['t', 't', 't'] because ~ is any, so its cells aren't part of the match -->/// Three trees in a V, with anything between them.
type Fork extends Mask {
layout: ```text
t~t
~t~
```
symbols: { t: /[#@]/, '~': any }
}
/// Two trees with a clearing between them.
type Gap extends Mask {
layout: ```text
#.#
```
}
$wood = ```text
#.@
.#.
#.#
```
echo $wood->shapes(Fork)->count() // 1 because the V fits only with its point at the bottom
echo $wood->shapes(Fork, rotated)->count() // 4 because turned a quarter, a half and three quarters, it fits once each way
echo $wood->shapes([Fork, Gap], rotated)->map(.kind)
// ['Fork', 'Fork', 'Fork', 'Fork', 'Gap', 'Gap'] because the bottom row and the left column are each #.#
echo $wood->shapes(Fork)->first().points->map(.symbol)
// ['t', 't', 't'] because ~ is any, so its cells aren't part of the match与任何字段一样,遮罩的符号可以在使用处进行修改:Fork(symbols: { t: fn(cell) => $cell != '.', '~': any }) 与 . 之外的任何字符匹配同一个 V。
布局中的空行表示下一层的开始,自上而下依次排列,与遮罩所匹配的文本中空行的含义相同。每一层的行数必须相同,三维匹配结果中的每个点也都有一个 layer。三维列表($cube[layer][row][column])的读取方式相同:
<type name="Step" description="A step: one block on the top layer, with two under it on the layer below." extends="Mask">
<field name="layout" default="```text
#.
##
```" />
<field name="symbols" default="{ '.': any }" />
</type>
<let name="tower">```text
#..
...
##.
.#.
```</let>
<echo value="$tower->shapes(Step)->count()" /> <!-- 1 because the one block on the top layer has a block under it, and another beside that -->
<echo value="$tower->shapes(Step)->first().points->map(.layer)" /> <!-- [0, 1, 1] because one point is on the top layer and two are on the layer below -->/// A step: one block on the top layer, with two under it on the layer below.
type Step extends Mask {
layout: ```text
#.
##
```
symbols: { '.': any }
}
$tower = ```text
#..
...
##.
.#.
```
echo $tower->shapes(Step)->count() // 1 because the one block on the top layer has a block under it, and another beside that
echo $tower->shapes(Step)->first().points->map(.layer) // [0, 1, 1] because one point is on the top layer and two are on the layer below层数或行数少于输入的遮罩会在整个输入上滑动:单行遮罩会沿网格的每一行尝试匹配,而单层遮罩则会在三维文本或三维列表的每一层中尝试匹配。层数或行数多于输入的遮罩会报错,并给出提示,例如"Step has 2 layers, and this is one grid."
Mask 是一种可用于参数或字段的类型。它接受任何继承自 Mask 的类型,既可以是类型本身(Block),也可以是由其构造的类型(Block(symbols: ...)),而 Mask[] 接受它们的列表:
<type name="Block" description="Four #s packed into a square." extends="Mask">
<field name="layout" default="```text
##
##
```" />
</type>
<fn name="count_in" params="input: string, shape: Mask" returns="int" value="$input->shapes($shape)->count()" />
<fn name="count_all" params="input: string, shapes: Mask[]" returns="int" value="$input->shapes($shapes)->count()" />
<let name="roof">```text
###.
###.
...#
```</let>
<echo value="@count_in($roof, Block)" /> <!-- 2 because Block fits twice in the roof -->
<echo value="@count_in($roof, Block(symbols: { '#': /[#.]/ }))" /> <!-- 6 because now a . counts as well, so every 2x2 window fits -->
<echo value="@count_all($roof, [Block, Block(symbols: { '#': '.' })])" /> <!-- 2 because no 2x2 of the roof is all .s, so only Block's 2 count -->/// Four #s packed into a square.
type Block extends Mask {
layout: ```text
##
##
```
}
fn count_in(input: string, shape: Mask): int => $input->shapes($shape)->count()
fn count_all(input: string, shapes: Mask[]): int => $input->shapes($shapes)->count()
$roof = ```text
###.
###.
...#
```
echo @count_in($roof, Block) // 2 because Block fits twice in the roof
echo @count_in($roof, Block(symbols: { '#': /[#.]/ })) // 6 because now a . counts as well, so every 2x2 window fits
echo @count_all($roof, [Block, Block(symbols: { '#': '.' })]) // 2 because no 2x2 of the roof is all .s, so only Block's 2 countA mask holds layout, symbols and its own methods, written with :. The editor and kscript check report a mask written wrong, most with a fix: a missing or empty layout, a layout that is all any, a tab in the picture, layers of different heights, a symbol that is more than one character or is listed twice, null for any, layout = for layout:, and like:, which ->shapes() no longer takes. A symbol the layout doesn't use is a warning (KS6026), and so is one that maps a character to itself (KS6025), since every character already matches itself:
<type name="Block" extends="Mask">
<field name="layout" default="```text
##
```" />
<field name="symbols" default="{ '#': '#' }" /> <!-- the warning: '#' already matches '#'. -->
</type>type Block extends Mask {
layout: ```text
##
```
symbols: { '#': '#' } // the warning: '#' already matches '#'.
}In the editor, a mask is part of the language. extends ‸ offers Mask, and inside a Mask type, typing layout writes the text block; once it has one, symbols comes written out with a character of the layout and any. Inside symbols: { }, completion offers the layout's characters not yet listed. Hovering a character of the layout says what it matches and how often the layout uses it, and each character is coloured by what it matches: itself or a value like text, a regex like a regex, a fn like a function, and any dimmed like a comment.
按序列工作
相乘:product
->product(fn?) 对各项求积,正如 ->sum() 对各项求和。给定一个函数时,它会对函数为每一项返回的结果求积。整数无论多大都保持精确:
<echo value="[2, 3, 4]->product()" /> <!-- 24 because 2 * 3 * 4 is 24 -->
<let name="boxes" value="[{ width: 2, height: 5 }, { width: 3, height: 1 }]" />
<echo value="$boxes->product(fn(box) => $box.width)" /> <!-- 6 because 2 * 3 is 6 -->
<echo value="[942, 945, 571]->product()" /> <!-- 508298490 -->echo [2, 3, 4]->product() // 24 because 2 * 3 * 4 is 24
$boxes = [{ width: 2, height: 5 }, { width: 3, height: 1 }]
echo $boxes->product(fn(box) => $box.width) // 6 because 2 * 3 is 6
echo [942, 945, 571]->product() // 508298490累计值:scan
->scan(fn(total, item), initial?) 的用法与 ->reduce() 类似,但会保留过程中的每一个累计值,便于您了解结果是如何逐步形成的。若不使用 initial,则第一项即为第一个累计值:
<let name="spending" value="[5, 2, 8, 1]" />
<echo value="$spending->scan(fn(total, amount) => $total + $amount)" />
<!-- [5, 7, 15, 16] because 5, then 5 + 2, then 7 + 8, then 15 + 1 -->
<echo value="$spending->scan(fn(total, amount) => $total - $amount, 20)" />
<!-- [15, 13, 5, 4] because the budget starts at 20 and each amount comes off it -->$spending = [5, 2, 8, 1]
echo $spending->scan(fn(total, amount) => $total + $amount)
// [5, 7, 15, 16] because 5, then 5 + 2, then 7 + 8, then 15 + 1
echo $spending->scan(fn(total, amount) => $total - $amount, 20)
// [15, 13, 5, 4] because the budget starts at 20 and each amount comes off it全部组合:combinations
->combinations(size) 给出列表中所有从中选取 size 个项目的方式,且不考虑所选项目的顺序。每次选取中的项目都保持列表原有顺序,同一次选取中不会重复选同一项。
从 ['tea', 'milk', 'juice'] 中选 2 个的过程如下:先以 tea 开始,与其后的每个项目配对(milk,然后是 juice);再以 milk 开始,与其后的每个项目配对(juice)。juice 之后已没有项目,因此到此为止。['milk', 'tea'] 永远不会出现,因为它与 ['tea', 'milk'] 是同一种选取:
<let name="drinks" value="['tea', 'milk', 'juice']" />
<echo value="$drinks->combinations(2)" />
<!-- [['tea', 'milk'], ['tea', 'juice'], ['milk', 'juice']] because 3 drinks give 3 ways to pick 2 -->
<echo value="$drinks->combinations(3)" />
<!-- [['tea', 'milk', 'juice']] because there is only one way to pick all 3 -->
<echo value="$drinks->combinations(1)" />
<!-- [['tea'], ['milk'], ['juice']] -->$drinks = ['tea', 'milk', 'juice']
echo $drinks->combinations(2)
// [['tea', 'milk'], ['tea', 'juice'], ['milk', 'juice']] because 3 drinks give 3 ways to pick 2
echo $drinks->combinations(3)
// [['tea', 'milk', 'juice']] because there is only one way to pick all 3
echo $drinks->combinations(1)
// [['tea'], ['milk'], ['juice']]一种常见用法是检查每一对组合,例如查找两个价格之和等于某个总额的组合:
<let name="prices" value="[15, 40, 25, 60]" />
<let name="pair" value="$prices->combinations(2)->find(fn(two) => $two->sum() == 65)" />
<!-- [40, 25] because 15 + 40, 15 + 25 and 15 + 60 aren't 65, but 40 + 25 is -->$prices = [15, 40, 25, 60]
$pair = $prices->combinations(2)->find(fn(two) => $two->sum() == 65)
// [40, 25] because 15 + 40, 15 + 25 and 15 + 60 aren't 65, but 40 + 25 is如果函数的参数个数与所选项目数相同,每个参数会依次接收对应项目,因此你可以为它们命名,而无需读取 $two[0] 和 $two[1]。此方式适用于任意大小:选取 3 个时填充 fn(first, second, third)。只有一个参数的函数仍会接收整个选取结果:
<let name="prices" value="[15, 40, 25, 60]" />
<echo value="$prices->combinations(2)->count_of(fn(cheaper, dearer) => $cheaper + $dearer > 70)" />
<!-- 3 because 15 + 60, 40 + 60 and 25 + 60 are over 70, and no other pair is -->
<let name="sides" value="[3, 4, 5, 9]" />
<echo value="$sides->combinations(3)->count_of(fn(shortest, middle, longest) => $shortest ** 2 + $middle ** 2 == $longest ** 2)" />
<!-- 1 because only 3, 4 and 5 make a right-angled triangle: 9 + 16 is 25 -->
<echo value="$sides->combinations(3)->map(fn(three) => $three->sum())" />
<!-- [12, 16, 17, 18] because a function with one parameter gets each pick as a list -->$prices = [15, 40, 25, 60]
echo $prices->combinations(2)->count_of(fn(cheaper, dearer) => $cheaper + $dearer > 70)
// 3 because 15 + 60, 40 + 60 and 25 + 60 are over 70, and no other pair is
$sides = [3, 4, 5, 9]
echo $sides->combinations(3)->count_of(fn(shortest, middle, longest) => $shortest ** 2 + $middle ** 2 == $longest ** 2)
// 1 because only 3, 4 and 5 make a right-angled triangle: 9 + 16 is 25
echo $sides->combinations(3)->map(fn(three) => $three->sum())
// [12, 16, 17, 18] because a function with one parameter gets each pick as a list由于所选项目依次填入参数,这样的函数无法同时获得索引:以两两配对为例,fn(first, second) 就是该配对的两个项目。
所有排列:permutations
->permutations(size?) 给出所有排列,其中顺序有影响,因此 ['tea', 'milk'] 和 ['milk', 'tea'] 都会出现。若不使用 size,每种排列都会用到全部项目:
<echo value="['tea', 'milk', 'juice']->permutations()" />
<!--
6 orderings: [['tea', 'milk', 'juice'], ['tea', 'juice', 'milk'], ['milk', 'tea', 'juice'], ...]
because there are 3 choices for first, 2 for second and 1 for third, and 3 * 2 * 1 is 6
-->
<echo value="['tea', 'milk', 'juice']->permutations(2)->count()" />
<!-- 6 because 3 choices for first and 2 for second -->echo ['tea', 'milk', 'juice']->permutations()
// 6 orderings: [['tea', 'milk', 'juice'], ['tea', 'juice', 'milk'], ['milk', 'tea', 'juice'], ...]
// because there are 3 choices for first, 2 for second and 1 for third, and 3 * 2 * 1 is 6
echo ['tea', 'milk', 'juice']->permutations(2)->count()
// 6 because 3 choices for first and 2 for second组合与排列增长很快(10 个项目有 3,628,800 种排列),因此超过一百万个列表时会以 Limit 错误停止,而不是耗尽内存。
循环移位:rotate
->rotate(by) 会把每个项目向前移动 by 个位置,从前端移出的项目则放到末尾。负数的 by 则向相反方向移动:
<let name="week" value="['mon', 'tue', 'wed', 'thu']" />
<echo value="$week->rotate(1)" /> <!-- ['tue', 'wed', 'thu', 'mon'] because mon moves from the front to the end -->
<echo value="$week->rotate(-1)" /> <!-- ['thu', 'mon', 'tue', 'wed'] because thu moves from the end to the front -->$week = ['mon', 'tue', 'wed', 'thu']
echo $week->rotate(1) // ['tue', 'wed', 'thu', 'mon'] because mon moves from the front to the end
echo $week->rotate(-1) // ['thu', 'mon', 'tue', 'wed'] because thu moves from the end to the front为类型添加方法:extend
extend 可为某个类型添加你自己的方法,无论该类型是内置的还是你自定义的。在其中,每个 fn 是一个方法,$this 是被调用该方法的值:
<extend type="date">
<fn name="api_date" description="The date as text for an API: 2026-11-21." value="$this->format('yyyy-MM-dd')" />
<fn name="is_payday" value="$this.day == 25" />
</extend>
<extend type="list">
<fn name="second" value="$this[1]" />
</extend>
<extend type="string">
<fn name="slug" value="$this->lower()->trim()->replace(' ', '-')" />
</extend>
<echo>{ '2026-11-25'->to_date()->api_date() } { '2026-11-25'->to_date()->is_payday() }</echo>
<echo>{ ['a', 'b', 'c']->second() } { 'Hello World'->slug() } { 'Hello World' |> slug() }</echo>extend date {
/// The date as text for an API: 2026-11-21.
fn api_date() => $this->format('yyyy-MM-dd')
fn is_payday() => $this.day == 25
}
extend list {
fn second() => $this[1]
}
extend string {
fn slug() => $this->lower()->trim()->replace(' ', '-')
}
echo "{ '2026-11-25'->to_date()->api_date() } { '2026-11-25'->to_date()->is_payday() }"
echo "{ ['a', 'b', 'c']->second() } { 'Hello World'->slug() } { 'Hello World' |> slug() }"You can extend string, number (or int and float), bool, list, map, fn, date, email, password, handle, uuid and regex, a package's values such as file or response, and your own types, whose methods see $this (a record) and its fields as $this.name. Methods take parameters, defaults and named arguments like any fn.
方法不能与该类型已有方法同名,因此拼写错误或命名冲突不会改变内置方法的行为。若要有意替换某个方法,请编写 override:
<extend type="date">
<fn name="to_string" override="yes" value="$this->format('d MMMM yyyy')" />
</extend>extend date {
override fn to_string() => $this->format('d MMMM yyyy')
}在 XML 中,extend 是包含 <fn> 元素的 <extend type="date">,而 override fn 则是 <fn override="true">。
扩展的适用范围。文件中自身的 extend 代码块仅适用于该文件以及导入它的每个文件。在项目中(即含有 kscript.json 的文件夹),extensions/ 文件夹中的每个文件都会应用于项目中的每个脚本、测试和页面,无需导入。你可以按需拆分,例如每个类型一个文件:
extensions/
date.kscript extend date { … }
list.kscript extend list { … }
text/
slug.kscript extend string { … }kscript make extension date --methods api_date,is_payday 会写入 extensions/date.kscript 作为起始内容。若要将它们放在其他位置,可在 kscript.json 中列出文件夹或通配符,这会替换默认文件夹:"extensions": ["extensions", "shared/**/*.kscript"]。两个扩展文件为同一类型添加同名方法会报错,错误信息会同时指出两个文件。脚本自身的 extend(或导入文件中的)优先于项目中的定义。
编辑器只在扩展方法适用的范围内提供补全和检查:在既未声明、也未导入(或通过项目获得)->api_date() 的文件中,日期上的方法 @today()->api_date() 仍会被视为未知方法。悬停时会显示该方法的 /// 文档以及添加它的文件,跳转到定义则会打开该文件。
错误
仅当前置条件成立时才继续执行,请使用guard condition else { ... }。失败块必须通过return、throw、break、continue或exit离开当前流程。
<fn name="save_age" params="age: int, enabled: bool">
<guard test="$enabled">
<return value="'Skipped'" />
</guard>
<if $age < 0>
<throw value="{
type: 'Validation'
message: "Age cannot be negative: { $age }"
}" />
</if>
<return value="'Saved'" />
</fn>
<echo value="@save_age(-1, true) catch => $err.message" />fn save_age(age: int, enabled: bool) {
guard $enabled else {
return 'Skipped'
}
throw if $age < 0 {
type: 'Validation'
message: "Age cannot be negative: { $age }"
}
return 'Saved'
}
echo @save_age(-1, true) catch => $err.message后缀catch在求值成功时保留其左侧的值。当求值抛出错误时,KScript会将该错误绑定到$err并计算备用值。若只想处理某一种错误类型,请使用catch Validation => $err.message;若要为绑定命名,请使用catch Validation as problem => $problem.message。备用值为null时,会将原始错误继续向上抛出。
在@a() + @b() catch => 0中,处理器同时覆盖调用和加法运算。在@a() + (@b() catch => 0)中,它只覆盖@b()。
当某个条件成立时才抛出错误,请使用throw if。在其代码块内,每行写一个字段。KScript只对条件求值一次,且仅当条件为真时才对字段求值,因此成功的响应可以完全省略e。
<fn name="result" params="reply: map">
<if $reply->has('e')>
<throw value="{
type: 'Network'
message: "Host refused: {$reply.e.message}"
code: $reply.e.code
}" />
</if>
<return value="$reply.r" />
</fn>
<try>
<echo value="@result({ r: 'ready' })" />
<catch type="Network" as="err">
<echo>Request failed ({$err['code']}): {$err.message}</echo>
</catch>
</try>fn result(reply: map) {
throw if $reply->has('e') {
type: 'Network'
message: "Host refused: {$reply.e.message}"
code: $reply.e.code
}
return $reply.r
}
try {
echo @result({ r: 'ready' })
} catch Network as err {
echo "Request failed ({$err['code']}): {$err.message}"
}<try>
<let name="data" value="@read_json($path)" />
<catch type="FileNotFound">
<echo>No file at {$path}, using defaults.</echo>
</catch>
<catch as="err">
<echo>Failed: {$err.message} (line {$err.line})</echo>
</catch>
<finally>
<echo>done</echo>
</finally>
</try>
<throw type="Validation">Age must be positive, got {$age}</throw>try {
$data = @read_json($path)
} catch FileNotFound {
echo "No file at {$path}, using defaults."
} catch err {
echo "Failed: {$err.message} (line {$err.line})"
} finally {
echo "done"
}
throw Validation "Age must be positive, got {$age}"catch接受它所处理的错误类型,类型之间用|连接,as用于为错误命名:catch FileNotFound | Permission as e。只有小写名称的catch(catch err)会处理所有错误。when用于添加测试:catch Network as e when $e.status == 503。catch按顺序尝试,第一个匹配的会被执行。错误类型名称以大写字母开头,这是catch区分它们与变量名的方式。
未知元素、属性和语法错误会在脚本启动之前报告,因此末尾的一个拼写错误不会让任务只完成一半。
未被捕获的错误会以KScript错误的形式打印出来,包括错误发生的位置和类型,脚本以退出码3结束:
ERROR app.kscript:2:11: Name: Unknown command @nope().kscript对所有失败都以这种方式显示,包括脚本、kscript serve错误页面以及所有其他命令,绝不会以.NET异常的形式出现。由计算机而非脚本引起的失败会获得与之匹配的错误类型(FileNotFound、Access、IO、Network等),而kscript未预料到的失败则是Internal错误,这是值得报告的缺陷。若要查看错误背后的.NET异常和堆栈跟踪,请使用--stack-trace运行(放在脚本路径之前:kscript --stack-trace app.kscript),或设置KSCRIPT_STACK_TRACE=1,该设置同样适用于kscript serve和已编译的程序。
函数与类型上的处理器
将catch附加到函数或方法上,即可为每个调用者处理错误。将其附加到类型上,则可在该类型的所有方法之间共享同一处理器。
最近的匹配处理器会先运行。返回一个非null值即可恢复。false、0和''等值均可使用。单独的throw、null返回值,或处理器执行到末尾,都会把原始错误传递给下一个外层处理器。
<type name="Directory">
<field name="fallback" type="string" />
<fn name="lookup" params="key: string">
<if !$key->is_blank()>
<return value="$key" />
</if>
<if !$this.fallback->is_blank()>
<return value="$this.fallback" />
</if>
<throw type="Validation">A key is required</throw>
</fn>
<catch type="Validation" as="err">
<return value="$err.message" />
</catch>
</type>
<let name="directory" value="Directory(fallback: 'guest')" />
<echo value="$directory->lookup('owner')" /> <!-- owner -->
<echo value="$directory->lookup('')" /> <!-- guest -->
<let name="empty" value="Directory(fallback: '')" />
<echo value="$empty->lookup('')" /> <!-- A key is required -->type Directory {
fallback: string
fn lookup(key: string) {
if !$key->is_blank() => return $key
if !$this.fallback->is_blank() => return $this.fallback
throw Validation "A key is required"
}
} catch Validation as err {
return $err.message
}
$directory = Directory(fallback: 'guest')
echo $directory->lookup('owner') // owner
echo $directory->lookup('') // guest
$empty = Directory(fallback: '')
echo $empty->lookup('') // A key is required在处理程序内部,当条件成立时,throw if condition 会重新抛出当前错误。添加 payload 块可以抛出新的错误。仅记录错误的处理程序会让错误继续向上传播。可运行的 catch 测试展示了方法处理程序将错误传递给其类型的处理程序,以及调用方在错误被记录后捕获该错误。
使用/// @throws Network记录可能传递给调用方的错误。悬停提示与签名帮助会显示已知错误。在脚本顶层,若某个已知错误可能逸出,kscript check与编辑器会发出警告(KS5016)。
对于单次调用,使用 catch 以内联方式获取结果。
<echo value="@testing(1, 2) catch Error => $err.message" />
<fn name="testing" params="arg1: number, arg2: number">
<throw value="Error(message: "{ $arg1 } and { $arg2 }")" />
</fn>echo @testing(1, 2) catch Error => $err.message
fn testing(arg1: number, arg2: number) {
throw Error(message: "{ $arg1 } and { $arg2 }")
}带值和原因抛出错误
使用 throw Error(message: ..., value: ..., cause: ...) 抛出带有额外数据的通用错误。括号前的名称决定错误类型。Error 用于通用错误,Validation 等内置类型,或你自己声明的类型。具名参数会成为字段。message: 设置说明,cause: 在你包装先前错误时保存该错误。
<let name="age" value="-1" />
<try>
<try>
<throw type="Validation">Age must be positive, got {$age}</throw>
<catch type="Validation" as="original">
<throw value="Error(
message: 'Could not save profile',
value: $age,
cause: $original
)" />
</catch>
</try>
<catch type="Error" as="err">
<echo>{ $err.type }: { $err.message }</echo>
<echo>Rejected value: { $err['value'] }</echo>
<echo>Caused by: { $err.cause.message }</echo>
</catch>
</try>$age = -1
try {
try {
throw Validation "Age must be positive, got {$age}"
} catch Validation as original {
throw Error(
message: 'Could not save profile',
value: $age,
cause: $original
)
}
} catch Error as err {
echo "{ $err.type }: { $err.message }"
echo "Rejected value: { $err['value'] }"
echo "Caused by: { $err.cause.message }"
}Error: Could not save profile
Rejected value: -1
Caused by: Age must be positive, got -1抛出第一个错误时可省略 cause:。对于直接添加到内置错误上的字段,使用方括号查找,例如 $err['value']。对于希望调用方能够发现并进行类型检查的字段,请声明错误类型并捕获该类型。其声明的字段可以用点语法读取,例如 $err.value。
如果你已经有一个包含 type、message 及其他字段的映射,可以用 throw $payload 直接抛出该映射。将映射作为第一个参数传给 Error($payload) 会将其转换为消息文本。错误构造函数在编辑器补全中提供具名参数。
在 XML 中,同样的抛出写作 <throw value="Error(message: 'Could not save profile', value: $age, cause: $original)" />。外层 XML 的 value 属性保存整个错误表达式。内层 value: 参数是该错误上的额外字段。若只需类型和消息,<throw type="Validation" message="Invalid age" /> 对应 throw Validation "Invalid age"。
重试
某些失败会自行消失:数据库繁忙、网络短暂中断,或 API 正在限流。@retry(times, work) 会调用 work,并在每次抛出错误时再次调用,总共最多 times 次。它返回 work 的结果,或抛出最后一个错误。work 会接收尝试次数,第一次为 1:
<fn name="fetch_rates" params="attempt: int">
<if $attempt < 3>
<throw type="Timeout">The rates service is busy</throw>
</if>
<return value="{ eur: 0.86 }" />
</fn>
<let name="rates" value="@retry(3, @fetch_rates, backoff: 100ms)" />
<echo value="$rates.eur" />fn fetch_rates(attempt: int) {
if $attempt < 3 => throw Timeout "The rates service is busy"
return { eur: 0.86 }
}
$rates = @retry(3, @fetch_rates, backoff: 100ms)
echo $rates.eurbackoff 在两次调用之间等待。when 会接收错误并决定是否重试,因此永远不会成功的错误会立即失败:@retry(5, @charge, when: fn(err) => $err.type == 'Timeout')。
错误类型
使用error声明你自己的错误类型。字段的用法与type中相同,消息中也可以使用这些字段,extends用于说明该错误属于哪种类型:
<error name="PersonNotFound" message="No person with id {$id}" description="No person has that id." extends="NotFound">
<field name="id" type="int" />
</error>
<error name="OutOfStock" status="409" message="{$item} is out of stock">
<field name="item" type="string" />
<field name="left" type="int" default="0" />
</error>
<fn name="find_person" params="id: int">
<throw value="PersonNotFound(id: $id)" />
</fn>
<try>
<do>@find_person(42)</do>
<catch type="NotFound" as="e">
<echo>{ $e.message } ({ $e.type }, status { $e.status })</echo>
</catch>
</try>/// No person has that id.
error PersonNotFound(message: "No person with id {$id}") extends NotFound {
id: int
}
error OutOfStock(status: 409, message: "{$item} is out of stock") {
item: string
left: int = 0
}
fn find_person(id: int) {
throw PersonNotFound(id: $id)
}
try {
@find_person(42)
} catch NotFound as e {
echo "{ $e.message } ({ $e.type }, status { $e.status })"
}- 抛出。
throw PersonNotFound(id: 42)创建错误并将其抛出。它的参数包括按名称指定的字段,以及message:(代替类型的默认消息)和cause:(导致此错误的先前错误)。没有默认值的字段必须提供,编辑器会标记缺失和未知的字段。throw Validation "Too short"对于没有字段的类型仍然有效,throw Validation(field: 'name', message: 'Too short')则为内置类型添加字段。 - 捕获。
catch NotFound也会捕获PersonNotFound,因为它继承自NotFound。在 catch 中,$e.id读取一个字段,编辑器会补全 catch 所指定类型的字段。每个错误都有type、message、line、column、file、status和cause。$e->is(NotFound)在代码中检查类型,$e->chain()列出它:['PersonNotFound', 'NotFound', 'Error']。 - 重新抛出与包装。在 catch 中,单独的
throw会原样重新抛出正在处理的错误。throw $e对已保存的错误做同样的事。要添加上下文,请包装它:throw ConfigBroken(path: $path, cause: $e),然后$err.cause.message读取原始错误。 - 不抛出地创建。
OutOfStock(item: 'tea')将错误作为值返回,以便稍后返回或抛出。 - 状态码。
status是当没有任何处理程序捕获该错误时,KScript.Http 路由返回的 HTTP 状态码。类型会继承它,以及它的字段和消息,继承自其所扩展的类型。 - 导出。顶层错误类型会像函数和类型一样被导出,因此
import "errors/payment-failed.kscript"可以引入它们。kscript make error PaymentFailed --status 402 --extends Validation --fields "order: int"将其写入errors/。
KScript 自身抛出的内置错误类型形成一棵树,catch 遵循这棵树:
| 类型 | 继承自 | 引发于 |
|---|---|---|
Error |
每个错误。catch Error 捕获所有错误。 |
|
Syntax, Name, Null, Argument, Value, Const, Math |
Error |
脚本中的错误:语法错误、未知名称、需要值时却为 null、参数错误、值错误、修改 const、除以零。Index 继承自 Value,用于列表之外的位置。 |
Type |
Error |
错误类型的值。Shape 继承它,用于不符合 type 的数据($e.problems 列出每个问题)。 |
Format |
Error |
格式错误的文本。Json 和 Yaml 继承它。 |
IO |
Error |
文件。FileNotFound、Permission 和 Access 继承它。 |
Network |
Error |
请求。Timeout 继承它,$e.status 是响应的状态码。 |
Import, Config, Input, Limit, Context, Platform, Cancelled, Retired, Http, AI, UI, Reference, Assertion, Internal |
Error |
导入、设置、输入、递归等限制、错误的位置、操作系统、已停止的脚本、已废弃的功能、KScript.Http 应用、语言模型、桌面窗口、文档引用、失败的测试检查,以及 KScript 自身的故障。 |
Validation (422), BadRequest (400), Unauthorized (401), Forbidden (403), NotFound (404), Conflict (409), TooManyRequests (429) |
Error |
供你自己的代码抛出或继承。数字即 HTTP 状态码。 |
Query, Connection (503) |
Error |
KScript.Data:数据库拒绝执行的查询,或无法打开的数据库。Migration:无法读取或运行的迁移,或无法继续执行的kscript db命令。ModelNotFound扩展NotFound;UniqueViolation与ForeignKeyViolation扩展Conflict;MultipleRecordsFound(来自->sole())扩展Query。 |
JobFailed |
Error |
KScript.Queue:已用完重试次数的任务。JobTimeout扩展Timeout。 |
没有类型名以 Error 结尾:它们都是错误。(QueryError 和 ConnectionError 现在分别是 Query 和 Connection,catch QueryError 对此有说明。)
catch 或 throw 中的名称既未声明也非内置时仍然可用(作为 Error 的一种),但编辑器会对其发出警告(KS5011),因为它通常是拼写错误。
设置:$config
$config 保存应用自身的设置,例如其名称、数据库和缓存。每个脚本、页面、路由和测试都无需导入即可读取它。所有设置都存放在同一处:kscript.json 中的 config 部分。
{
"name": "shop",
"config": {
"app": { "name": "Shop" },
"database": { "connections": { "main": { "url": "sqlite:data/shop.sqlite" } } },
"features": ["search", "cart"]
}
}<echo value="$config.app.name" />
<let name="timeout" value="$config->get('http.timeout', 30)" /> <!-- a path, and a default when it isn't set -->
<if $config->has('features')>
<echo>{ $config.features->join(', ') }</echo>
</if>
<let name="key" value="$config->require('api.key')" /> <!-- stops with a clear message when it's missing -->echo $config.app.name
$timeout = $config->get('http.timeout', 30) // a path, and a default when it isn't set
if $config->has('features') => echo "{ $config.features->join(', ') }"
$key = $config->require('api.key') // stops with a clear message when it's missing不存在的设置返回 null,因此 $config.port ?? 8080 可以正常工作。名称不区分大小写,因此 $config.app.name 和 $config.APP.NAME 是同一个设置。在编辑器中,将鼠标悬停在 $config.app.name 上会显示其类型;“转到定义”会打开提供该键的文件,插值字符串中的键也适用。
各个包读取$config中各自的部分:KScript.Data 读取database,KScript.Cache 读取cache,KScript.Mail 读取mail,$log读取logging,翻译读取i18n,货币运算读取money.exchange_rates(参见货币)。
环境。同一个应用在不同场景下通常需要不同的设置,例如测试用的内存数据库,或生产环境中的真实服务器。将这些设置放在 kscript.json 旁边的 kscript.<env>.json 中。它的 config 部分会覆盖 kscript.json 中的对应部分,映射会逐字段合并,因此只需包含发生变化的设置:
// kscript.test.json
{
"config": {
"database": { "connections": { "main": { "url": "sqlite::memory:" } } }
}
}使用kscript --env staging script.kscript或KSCRIPT_ENV=staging选择运行环境。kscript test使用来自kscript.json的test.env(参见测试)。$config->environment()返回当前环境;若未选择任何环境则返回 null。环境文件只包含一个config部分:其他内容都应放在kscript.json中。
需要代码的设置:config.kscript。JSON 无法读取环境变量或进行计算。对于这些设置,请在 kscript.json 旁边添加 config.kscript(XML 项目中为 config.ks.xml)。它定义 configure(environment),该函数接收环境(未选择环境时为 development)并返回一个映射。该映射会覆盖 JSON 设置,因此只需包含需要代码的设置:
<!-- config.kscript -->
<fn name="configure" params="environment: string">
<let name="url" value="@env('DATABASE_URL', default: '')" />
<return value="{
database: { connections: { main: $url->is_blank() ? {} : { url: $url } } }
http: { timeout: $environment == 'production' ? 8s : 30s }
}" />
</fn>// config.kscript
fn configure(environment: string) {
$url = @env('DATABASE_URL', default: '')
return {
database: { connections: { main: $url->is_blank() ? {} : { url: $url } } }
http: { timeout: $environment == 'production' ? 8s : 30s }
}
}这些值保留其 KScript 类型,因此 8s 仍然是时长。脚本中可以使用 @env()、$env、导入的文件以及 KScript.IO 等包,其中的路径从脚本自身所在文件夹开始。它只在脚本首次读取 $config 时运行一次,且不能读取 $config 本身。kscript make config base 会写入一个初始的 config.kscript,kscript make config staging 会写入 kscript.staging.json。
各层级按从前到后叠加,后面的层级优先:kscript.json 的 config 部分,然后是 kscript.<env>.json,最后是 config.kscript。项目之外的脚本会从其自身文件夹读取 config.kscript。
.env 文件可将机密信息保存在项目文件之外。.env(若针对某个环境,则为 .env.<env>)与 kscript.json 并列存放,其中包含 NAME=value 行,可以使用 # 注释,前面可加 export,'single quotes' 按原样读取,"double quotes" 则允许 \n 并可跨行。${NAME} 和 ${NAME:-default} 会引用其他变量。这些值由 @env('NAME') 读取,通常位于 config.kscript 中;除非某个变量已经设置,否则它们也会成为环境变量,因此 KScript.AI 能在 .env 中找到 ANTHROPIC_API_KEY。请勿将 .env 文件提交到 git。
用户自己的设置。桌面应用可以让用户更改设置而无需修改项目:在kscript.json中使用"app": { "user_config": true },应用配置文件夹中的config.json会覆盖其他所有设置(参见应用文件夹)。
config 会以其他选项重新读取设置,或将另一组设置读入某个变量。若不使用 into,则会改变 $config:
<config env="production" />
<config files="themes/dark.json" into="theme" /> <!-- a separate set of settings in $theme -->
<config files="settings.json, secrets.kscript?, .env?" prefix="SHOP_" defaults="{ server: { port: 8080 } }" require="database.host" />config(env: 'production')
config(files: ['themes/dark.json'], into: theme) // a separate set of settings in $theme
config(files: ['settings.json', 'secrets.kscript?', '.env?'], prefix: 'SHOP_', defaults: { server: { port: 8080 } }, require: ['database.host'])files 列出要读取的其他文件(代替项目自身的文件):JSON 设置文件、配置脚本以及 .env 文件,按顺序读取,每个文件后可跟其对应环境的版本(settings.staging.json)。没有扩展名的名称表示其 .json 文件,以 ? 结尾的名称则可以缺失。使用 prefix 时,环境变量会覆盖文件中的设置,且 __ 会进行嵌套:SHOP_DATABASE__HOST=db.internal 设置 database.host,而 true、false 和 8080 等值会转换为布尔值和数字。root 是这些文件所在的文件夹,defaults 会为未被任何文件设置的项填充默认值,require 列出必须设置的项,user: true 还会读取用户自己的设置。
$config->sources() 列出已读取的文件,$config->all() 以映射形式给出所有设置,$config->reload() 则重新读取它们。@parse_env(text) 解析 .env 文本,KScript.IO 则添加 @read_env(path)。
kscript serve 不会提供 kscript.json、kscript.<env>.json、脚本、.env 文件或 config.* JSON 文件。页面可以读取项目的设置,并可对其 .env 文件中的值使用 @env(),但不会改动进程环境。
日志记录:$log
每个脚本都有一个日志记录器。info 及以上级别的条目会输出到终端(stderr),直到你为它们设置其他去处为止:
<log>Import started</log>
<log level="warn" category="payments" fields="{ order: $order.id }">Card declined for {$customer.name}</log>
<do>$log->info('Saved', { id: $id, size: $bytes })</do>
<let name="db" value="$log->named('db')->with({ host: $config.database.host })" />
<do>$db->debug('Connected')</do> <!-- category db, with a host field -->
<if $log->is_enabled(debug)>
<do>$log->debug($everything->convert(to: json))</do>
</if>
<try>
<do>@read_json(./missing.json)</do>
<catch as="err">
<do>$log->error('Could not read the file', $err)</do> <!-- error, error_type and error_line fields -->
</catch>
</try>log "Import started"
log(level: warn, category: 'payments', fields: { order: $order.id }) "Card declined for {$customer.name}"
$log->info('Saved', { id: $id, size: $bytes })
$db = $log->named('db')->with({ host: $config.database.host })
$db->debug('Connected') // category db, with a host field
if $log->is_enabled(debug) => $log->debug($everything->convert(to: json))
try {
@read_json(./missing.json)
} catch err {
$log->error('Could not read the file', $err) // error, error_type and error_line fields
}级别为 trace、debug、info、warn、error 和 fatal。提供程序决定条目的输出位置,通常在配置中设置:
// kscript.json
{
"config": {
"logging": {
"level": "info", // the lowest level written (default info)
"levels": { "db": "debug" }, // per category; db also covers db.queries
"providers": [
{ "type": "console", "level": "warn" }, // stderr, coloured at a terminal; stream: stdout, format: json, time: HH:mm:ss.fff
{ "type": "file", "path": "logs/app.log", "format": "json" }, // text, or json lines; roll: daily writes app-2026-11-20.log
{ "fn": "notify", "level": "error" } // a fn in the script, called with each entry
]
}
}
}log_provider(…) 可从脚本中添加一个提供程序,选项与之相同(replace 会移除已设置的提供程序,包括默认的控制台提供程序)。memory 提供程序会为 $log->entries() 保留日志条目,这在测试中很有用。被提供程序暂存的条目(例如 http 批量发送的条目)会在脚本结束时或调用 $log->flush() 时发送。若某个提供程序失败,其错误会在 stderr 上报告一次,其他提供程序继续运行。
Packages add provider types with p.LogProvider("type", description, create), and programs that run KScript can add their own with host.Logs.AddProvider(provider, level), where a provider implements ILogProvider.
翻译:@t()
将翻译放在脚本旁边的 locales 文件夹中(或放在站点文件夹中):locales/en.json、locales/fr.yaml,或者每个语言区域一个文件夹,例如 locales/de/shop.json,其键以 shop. 开头。
# locales/fr.yaml
hello: Bonjour, {name} !
cart:
items:
"=0": Votre panier est vide
one: "{count} article"
other: "{count} articles"<locale set="fr" />
<echo>{ @t('hello', { name: $user.name }) }</echo> <!-- Bonjour, Ann ! -->
<echo>{ @t('cart.items', { count: $cart->count() }) }</echo> <!-- 3 articles -->
<echo>{ @format_currency($total, 'EUR') } { @format_date(@today(), 'long') }</echo> <!-- 9,50 € 20 novembre 2026 -->locale(set: 'fr')
echo "{ @t('hello', { name: $user.name }) }" // Bonjour, Ann !
echo "{ @t('cart.items', { count: $cart->count() }) }" // 3 articles
echo "{ @format_currency($total, 'EUR') } { @format_date(@today(), 'long') }" // 9,50 € 20 novembre 2026- 复数形式。使用
count时,@t()会依据该语言自身的规则选择zero、one、two、few、many或other。这些是英语、法语、葡萄牙语、俄语、乌克兰语、波兰语、捷克语、阿拉伯语、希伯来语、爱尔兰语、威尔士语、日语、中文、韩语等语言的 CLDR 规则。精确形式(如=0)优先。 - 回退。若缺少某个翻译,会依次在
fr-CA、fr以及默认语言区域(除非另行设置,为en)中查找。若各处都找不到,则返回键本身,并在i18n类别下记录一次警告。 - 语言区域来自以下来源:
locale(set: fr)、locale(from: …)(列表或 Accept-Language 标头中最佳匹配项)、$config.i18n.locale、KSCRIPT_LOCALE,或计算机的语言设置。@locale()会给出当前语言区域,@locales()则列出存在对应文件的语言区域。 - 页面按以下顺序选择语言区域:路径前缀(当存在法语翻译时,
/fr/about会以法语提供about.html)、?lang=fr、langCookie,最后是浏览器的 Accept-Language。@locale_path($request.path, 'de')会给出指向同一页面德语版本的链接。默认语言区域没有前缀。 - 格式化。这些会遵循当前语言区域,或遵循作为最后一个参数传入的语言区域:
@format_number(1234.5)输出 1,234.5 或 1 234,5;@format_percent(0.25);@format_currency(9.5, 'GBP');@format_date(date, 'short' | 'medium' | 'long' | 'full' | 'time' | 'datetime' | 'd MMMM yyyy');@format_relative(date, from?)输出 3 hours ago、in 2 days 或 just now,除非给出from:,否则以当前时间为基准;@format_duration(1h30m)输出 1 hour 30 minutes;@format_list(['tea', 'coffee', 'milk'])输出 tea, coffee and milk,使用style: 'or'时输出 tea, coffee or milk;@format_ordinal(23)输出 23rd,法语中输出 23e;@format_bytes($file.size)输出 1.4 MB,使用binary: true时输出 1.3 MiB。
- 设置:配置中的
i18n: { folder: lang, default: en-GB, locale: fr },或translations(folder: lang, default: en-GB)。@has_t(key)检查某个键是否有翻译,@plural(count)则给出复数类别。
相对时间、时长、列表和序数的词语已为英语、法语、德语、西班牙语、意大利语、葡萄牙语和荷兰语内置。对于其他语言,或要修改这些词语,请在对应的翻译文件中添加这些键:time.second 至 time.year(带复数形式),以及 {count}、time.ago 和 time.in(配合 {time}、time.now、list.and、list.or),还有 ordinal(配合 {count}):
# locales/pl.yaml
time:
hour: { one: "{count} godzina", few: "{count} godziny", many: "{count} godzin" }
ago: "{time} temu"包
KScript.Core(上述全部内容)始终可用。其余功能均来自包,在脚本顶部导入,因此脚本只加载它所使用的部分:终端脚本永远不会加载 Web 服务器。
<import package="KScript.Terminal" />
<import package="KScript.Math" as="math" /> <!-- commands stay under the prefix: @math.sqrt(2) -->
<import path="lib/strings.kscript" as="str" /> <!-- another script's top-level functions and constants -->
<import names="slugify" path="lib/strings.kscript" />
<!-- … -->import KScript.Terminal
import KScript.Math as math // commands stay under the prefix: @math.sqrt(2)
import "lib/strings.kscript" as str // another script's top-level functions and constants
import slugify from "lib/strings.kscript"
// …只能导入 .kscript 和 .ks.xml 文件。脚本自行声明的函数优先于导入的同名函数,导入的 const 仍保持为常量。
| 包 | 它的新增功能 |
|---|---|
KScript.Terminal |
input(into, type, default, secret)(类型可为email、handle、uuid或password)、picker(文件或文件夹路径)、menu(options, multiple)、progress(into, total)搭配->advance()、confirm、pause、clear、@color(text, color: 'green')、@bold、@dim、@underline、@terminal_width()、@is_terminal()(输出为管道时不适用)、echo(format: markdown),以及kscript命令行自身的外观:info、success、warn、alert(type: error)、heading、detail(name)、bullets(items)、task(name) { }、table(rows, columns, header, align)(参见终端输出) |
KScript.Math |
@sqrt @round(x, digits: 2) @clamp(x, min: 0, max: 10) @logarithm @sin @cos @atan2 @hypot @gcd @factorial @random(low: 1, high: 6) @random_bytes(16, format: hex) @pick @shuffle @sum @average @median @stdev @variance @mode @percentile(values, 95), $pi $e |
KScript.IO |
@read_text @read_lines @read_json @write_text @append_text @write_json @files(folder, pattern: '*.txt', recursive) @folders @file(path) @exists @join_path(base: $dir, ['a', 'b.txt']) @known_folder(downloads),@move(from, to) @copy(from, to) @delete(path) @create_folder(path)。文件值具有字段 .name .extension .mime .size .modified……以及方法 ->read_text() ->read_bytes() ->read_json(as:) ->sha256() ->write_text(text) ->copy_to(path) ->move_to(path) ->delete()。 |
KScript.Net |
使用@api(url, options: { method, headers, body, timeout })发送 HTTP 请求,或使用简写形式post:、put:、patch:、delete:、bearer:、timeout:、retries:、as:、encoding:(json、form 或 multipart)以及query:。响应包含.status、.is_ok、.text、->convert(from: json)和->check()。另外提供@download(url, to)和@query_string。诸如'/api/notes'之类的路径会访问项目自身的路由。参见调用你自己的 API。 |
KScript.Markdown |
@markdown(text) 和 @read_markdown(path)(front matter 中的 html、title、meta),->convert(from: markdown, to: html) |
KScript.Web |
使用布局、组件和 kscript serve 的实时块渲染页面。页面无需导入即可使用 KScript.IO、KScript.Markdown 和 KScript.Web。 |
KScript.AI |
@llm(prompt, system, schema, tools, model, max_tokens)、llm(into, system, schema, tools, model, max_tokens)、@chat(system),配合->ask() .history ->reset(),以及用于测试的@fake_llm(replies)。Claude 使用来自ANTHROPIC_API_KEY的密钥(参见语言模型)。 |
KScript.Style |
用 KScript 编写的样式表(.ks.css、.ks.scss、.ks.sass);@up、@down、@between、@rem、@fluid、@adjust_lightness、@lighten、@darken、@mix、@alpha、@contrast_color、@css_var、@css_vars;@stylesheet(path, vars)(参见样式表)。 |
KScript.Http |
用于kscript serve的路由、控制器与中间件:Routes { }文件包含Get Post Put Patch Delete Any Route Resource Group Middleware。控制器使用@view、@response、@redirect、@abort和@route。参见路由、控制器与中间件。 |
KScript.Storage |
应用自身的文件夹,位于各平台的正确位置:@storage(config)(另有 data、cache、state、logs),包含 ->read ->read_json ->write ->write_json ->read_bytes ->write_bytes ->file ->move ->copy ->append ->list ->delete ->folder ->path_of,另外还有 @app_name() 和 @app_folders()。请参阅 应用文件夹。 |
KScript.Cache |
$cache(内存中)以及带有@cache(file)的->get->set->remember(key, fn, ttl: 10m)->has->remove->increment->ttl->keys->clear。参见缓存。 |
KScript.Data |
使用model存储记录,通过查询构建器进行查询,并使用Migration和kscript db migrate管理架构变更。请参阅数据库。 |
KScript.Queue |
使用job声明后台工作,用->dispatch()将其加入队列,并用kscript worker运行。其Schedule会在设定的时间运行任务。参见队列和作业与调度任务。 |
KScript.Mail |
通过 SMTP 发送带有 @send_mail(to:, subject:, html:|text:|view:) 的电子邮件,可以发送到日志或模拟器,立即发送,或通过 kscript worker 使用 queue 发送。@fake_mail() 会保留邮件用于测试。另请参阅 邮件。 |
KScript.Auth |
为 kscript serve 应用登录:@register、@attempt、@login、@logout、@user()、@is_signed_in()、$session(->get ->set ->flash …)、@users()、@csrf_field()、@reset_token、@reset_password、@api_token,以及 auth 和 guest 中间件。参见 登录。 |
KScript.Document |
Document(template: paper, to: "paper.pdf") { } with Section, Paragraph, List, Table, Figure, Math, Bibliography and more; Letter and Invoice; ->save ->pages ->words ->markdown ->latex ->html. See Documents. |
KScript.UI |
Window { } 块可以打开一个桌面窗口。Column Row Grid Text Button TextBox CheckBox Select Slider Box Spacer Timer,@close_window()。参见 桌面应用。 |
KScript.Test |
test、describe、before_each、after_each、expect、expect_error、capture、@assert、@fail、@run_script、@check_script。测试文件会自行导入它(参见 测试脚本)。 |
使用未导入包中的内容时会以 input is part of KScript.Terminal. Add import KScript.Terminal at the top of the script. 停止,编辑器会提供添加导入的选项。包只能在 import 中命名:语句绝不会写成带 KScript. 前缀的形式(写 input,而不是 KScript.input),并且不会静默导入任何内容,包括 job 和 dispatch(import KScript.Queue)。项目可以为 kscript.json(见下文)中的每个脚本导入包。
加密安全的随机字节
@random_bytes(count, format: hex) 从操作系统读取熵。传入 1 到 65536 之间的整数字节数。小写十六进制每字节使用两个字符。base64url 格式使用 URL 安全字符且省略填充。两种格式都与 @random_seed() 无关。
<import package="KScript.Math" />
<let name="key" value="@random_bytes(16)" /> <!-- 32 hex characters -->
<let name="url_token" value="@random_bytes(16, format: base64url)" /> <!-- 22 characters -->import KScript.Math
$key = @random_bytes(16) // 32 hex characters
$url_token = @random_bytes(16, format: base64url) // 22 characters语句和参数的命名
所有包中的语句及其参数都遵循同一套规则,kscript check 和测试套件会检查内置语句是否符合这些规则:
| 规则 | 示例 |
|---|---|
执行某项操作或声明某项内容的语句,使用小写的 snake_case 单词。 |
input, table, before_each, expect_error, log_provider |
在 KScript.UI、KScript.Http 和 KScript.Document 中描述窗口、路由表或文档的语句使用 PascalCase。在 KScript.Data 中,Migration 及其架构步骤也使用 PascalCase。 |
Button, Routes, Get, Section, Migration, CreateTable |
参数使用 snake_case。任何名称都不含连字符。 |
max_tokens, must_exist, on_click, new_page |
into: 是接收结果的变量。 |
input(into: name), llm(into: reply), capture(into: out) |
to: 表示目标位置:文件、URL 或控制器。它绝不表示变量名。 |
Get(path: /, to: @home), Post(path: /notes, to: @notes.add) |
path: 是语句读取或操作的文件。 |
import(path: "lib.kscript"), <include path="_nav.html">, <layout path="_layout.html"> |
at 是一个位置,如 for item at i in $list 中所示。 |
menu(into: choice, at: i) |
函数的写法为 @name,与表达式中的写法相同。 |
spawn(fn: @job), llm(tools: [@order_status]), Get(to: @people.show) |
有三类名称不是函数,保持裸写:控制器(Resource(to: people) 是脚本被导入时使用的名称)、中间件列表中的名称([log, throttle:30, my_check],其中内置项、分组和函数共享同一列表),以及被声明的变量或类型。在 XML 中,相同的参数以同名属性形式出现,函数则不带 @ 书写(<spawn fn="job" />);kscript convert 用于添加和移除它。
在页面中,on-click 及其他事件处理器位于 HTML 标签上(<button on-click="$count += 1">),因此保留 HTML 的连字符。在 KScript 自有元素上,例如 Button,参数为 on_click。
采用这些规则之前的旧名称会报错并提示新名称('to' is now into.),kscript check --fix 可将其重命名。允许语句被赋值($name = input "Name? ")尚未成为该语言的一部分。
终端输出
KScript.Terminal 的打印方式与 kscript 命令相同,因此脚本的输出看起来与该工具的其他部分一致。颜色仅在终端中使用:管道输出、文件和测试得到的是不含颜色的相同文本,NO_COLOR、FORCE_COLOR、--ansi 和 --no-ansi 的作用与其对 kscript 本身的作用相同。
<import package="KScript.Terminal" />
<let name="people" value="[{ name: 'Joan', age: 82 }, { name: 'Sam', age: 9 }]" />
<heading>Report</heading>
<detail name="People">{ $people->count() }</detail>
<task name="Adding up">
<let name="total" value="1 + 2" />
</task>
<table rows="$people" />
<info>Wrote [report.txt].</info>
<alert type="error">The file [data.csv] is empty.</alert>import KScript.Terminal
$people = [{ name: 'Joan', age: 82 }, { name: 'Sam', age: 9 }]
heading "Report"
detail(name: 'People') "{ $people->count() }"
task(name: 'Adding up') {
$total = 1 + 2
}
table(rows: $people)
info "Wrote [report.txt]."
alert(type: error) "The file [data.csv] is empty."Report
People .................................................... 2
Adding up .......................................... 2ms DONE
┌──────┬─────┐
│ name │ age │
├──────┼─────┤
│ Joan │ 82 │
│ Sam │ 9 │
└──────┴─────┘
INFO Wrote [report.txt].
ERROR The file [data.csv] is empty.标签中的 [bracketed] 部分以粗体显示。alert(type: error) 写入 stderr。表格中的数字右对齐;align: ['left', 'right'] 设置每一列。
分步完成的工作会显示进度条。progress(into: bar, total: n) 以其文本作为标签显示进度条,$bar->advance() 将其推进一步(->advance(5) 则推进五步)。在终端中会原地重绘;管道输出和测试则在达到总数时输出一行,与任务输出类似:
<import package="KScript.Terminal" />
<let name="files" value="['a.csv', 'b.csv', 'c.csv']" />
<progress into="bar" total="$files->count()">Importing</progress>
<for each="_file" in="$files">
<do>$bar->advance()</do>
</for>import KScript.Terminal
$files = ['a.csv', 'b.csv', 'c.csv']
progress(into: bar, total: $files->count()) "Importing"
for _file in $files {
$bar->advance()
}menu(multiple: true) 允许回答选择多个选项,例如 1, 3,并按菜单顺序存储它们的列表(以及 at: 存储它们位置的列表)。
语言模型:KScript.AI
KScript.AI 让脚本可以向 Claude 发起请求。API 密钥来自 ANTHROPIC_API_KEY 环境变量(或来自 ANTHROPIC_AUTH_TOKEN 中的令牌,或在安装了 ant 命令时由 ant auth login 保存的配置文件),而不是来自脚本本身。ANTHROPIC_BASE_URL 会把请求发送到其他主机,例如代理服务器。除非脚本指定了其他模型,或 KSCRIPT_AI_MODEL 指定了某个模型,否则脚本使用 claude-opus-5-5。
<import package="KScript.AI" />
<!-- One question, one answer. -->
<echo>{ @llm('Write a haiku about XML.') }</echo>
<!-- A prompt written as a template, with a system prompt. -->
<let name="customer" value="{ name: 'Ann' }" />
<let name="message" value="'My order is late arrived.'" />
<llm into="reply" system="You answer customer emails politely and briefly.">{$customer.name} wrote: {$message}</llm>
<!-- Structured output: the answer is a map with these fields. -->
<let name="report" value="'The login page spins forever on Safari.'" />
<llm into="ticket" schema="{ category: 'bug|feature|question', urgency: 'int 1-5', summary: 'one line' }">Triage this report: {$report}</llm>
<echo>{$ticket.category} ({$ticket.urgency}): {$ticket.summary}</echo>
<!-- Tools: the model may call your fn functions, and sees what they return. -->
<fn name="order_status" params="id: int" description="The shipping status of an order." value="$id == 42 ? 'shipped' : 'unknown'" />
<llm into="answer" tools="order_status">Where is order 42?</llm>
<!-- A conversation that remembers what was said. -->
<let name="chat" value="@chat('You are a patient maths tutor.')" />
<echo>{ $chat->ask('What is a prime number?') }</echo>
<echo>{ $chat->ask('Is 91 one?') }</echo>import KScript.AI
// One question, one answer.
echo "{ @llm('Write a haiku about XML.') }"
// A prompt written as a template, with a system prompt.
$customer = { name: 'Ann' }
$message = 'My order is late arrived.'
llm(into: reply, system: 'You answer customer emails politely and briefly.') "{$customer.name} wrote: {$message}"
// Structured output: the answer is a map with these fields.
$report = 'The login page spins forever on Safari.'
llm(into: ticket, schema: { category: 'bug|feature|question', urgency: 'int 1-5', summary: 'one line' }) "Triage this report: {$report}"
echo "{$ticket.category} ({$ticket.urgency}): {$ticket.summary}"
// Tools: the model may call your fn functions, and sees what they return.
/// The shipping status of an order.
fn order_status(id: int) => $id == 42 ? 'shipped' : 'unknown'
llm(into: answer, tools: [@order_status]) "Where is order 42?"
// A conversation that remembers what was said.
$chat = @chat('You are a patient maths tutor.')
echo "{ $chat->ask('What is a prime number?') }"
echo "{ $chat->ask('Is 91 one?') }"llm和@llm(prompt, ...)询问相同的问题,选项也相同:system、schema、tools(如[@order_status]这样的列表)、model和max_tokens(默认为 16,000)。唯一的区别在于提示从哪里来、答案放到哪里:llm语句以提示作为其文本,并将答案存入to:;而@llm()以提示作为一个值,并返回答案,因此可以放在表达式中使用。@llm()则按名称接收其选项:@llm($prompt, system: 'Be brief.', max_tokens: 500)。- 模式:每个字段都是必填的。
'string'、'number'、'int'、'bool'和'date'用于指定类型,'int 1-5'给出取值范围,'a|b|c'列出可选值,映射是嵌套对象,['string']是列表,其他任何文本都表示字符串字段。 - 工具是
fn函数。它们的params(包括id: int等类型)和description会告诉模型如何调用它们。如果某个工具失败,模型会收到错误信息,并可以继续执行。 - 测试使用
@fake_llm(replies)代替Claude:参见模拟语言模型。 - 错误的类型为
AI,因此可以使用try配合catch e来检查$e.type,并处理缺失的密钥、请求被拒绝,或回答因max_tokens被截断的情况。当 Claude 的安全检查拒绝某个请求时,API 会先用备用模型重试该请求。
编写可移植的脚本
- 使用
@join_path(base: $dir, ['reports', 'file.txt'])(KScript.IO)构建路径,而不是硬编码\或/。 - 使用
@known_folder(downloads)(KScript.IO)查找用户的文件夹:home、desktop、documents、downloads、music、pictures、videos、appdata或temp。它会遵循各系统自身的设置,例如 Windows 的下载位置和 Linux 的user-dirs.dirs。 $os.name是windows、linux或macos,$os.home、$os.temp和$os.separator也在其中;$env.HOME用于读取环境变量。- 无论机器使用何种语言,数字始终以
.作为小数分隔符进行解析和输出。