KScript言語
はじめに
これは KScript 2 のスクリプトのリファレンスです。すべてのスクリプトとページが持つコア言語、残りの機能のためにインポートするパッケージ、そしてあらゆる OS で動くスクリプトのためのヒントを扱います。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 JSONecho に単独で渡したマップ、またはマップのリストは、インデントされた JSON として表示されます。ターミナルでは色付きで表示されます(NO_COLOR が設定されていない場合)。テキストの中では 1 行のままです。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を返します。比較は数学と同様に連鎖します(数学の節で示されます)。2つの日付は、==で比較したときに、秒まで含めて同じ瞬間の場合にのみ等しくなります。
数式
日常的な計算には独自の記号があり、それぞれスクリプト、テンプレート、データベースクエリで同じように動作します。+は加算、-は減算、*は乗算、/は除算で、小数を保持します。~/は整数の除算で、切り捨てます。%は余りを返し、左側の数の符号を保ちます。%%は時計のように循環します。**は累乗です:
<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 |
式ごとに範囲は1つ |
| 7 | |> |
左から右 |
| 8 | < <= > >= in |
一方向の連鎖: 0 <= $n < 10 |
| 9 | == != === !== |
比較ごとに1つ。andでさらに連結します |
| 10 | not, and, or, ??, a ? b : c |
%と%%は、符号が負の場合にのみ異なります。余りはC#やJavaScriptと同様に、左辺の符号を保ちます。Modは右辺の符号を取るため、循環します。真夜中の1時間前は-1ではなく23です。時計、曜日、末尾で循環するリストの位置には%%を使います:
<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~/は0に向かってではなく、切り捨てで丸めます。そのため%%と組み合わせます。($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と記述します。
ビットは記号ではなく、1つのメソッド->bits()で操作します。&や|はandやorと簡単に取り違えられてしまうためです。整数に対して1ステップずつ処理します:
<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&、単一の|、<<、>> で2つの値の間に置かれたものはエラーで、書き込むべき->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 です。パターンは1つの値、または複数の値 (2, 3 =>) で、どれにも当てはまらない場合は _ を使います。さらに when の判定を後に続けられます (_ when $it > 9 =>)。結果は同じ行の1つの文、または { } ブロック内の複数の文になります。値として使う match では、各分岐の結果に値を書きます: $label = match $choice { 1 => 'one', 2, 3 => 'a few', _ => 'many' }。分岐は改行またはカンマで区切り、最初に当てはまった分岐が実行されます。XML では分岐は <case is="2, 3">、<case when="…">、<default> で書きます。
1行の if
if が1つの処理しか行わない場合は、1行で書けます。条件、=>、そして文の順に並べます。これは match の分岐や fn(name) => ... と同じ形なので、ガードチェックや早期終了を1行ずつに収められます。
<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 も同じ形で、1行に1つの分岐を書きます:
<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'=> の後の文は1行に収まるものなら何でも書けます: 呼び出し (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 には1行形式がないため、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 ファイルは厳密な XML ではなく KScript のマークアップになります。KScript 自身のパーサー、フォーマッター、エディタのサポートでは読めますが、xmllint などの一般的な XML ツールは拒否します。ファイルを有効な XML のままにする必要がある場合は test="…" を使ってください。
else を使わない早期 return
関数やループの中では、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 | 関数本体が読まないパラメーター。ラムダの場合は、呼び出し側がどの値を渡すかを決めるため、最後に読まれるパラメーターより後のものだけが対象です。位置を保つには fn(_y) => ... と書いてください。 |
| KS6005 | どこにも使われないインポート: as の別名、names="..." の中の名前、スクリプト全体、またはどの要素、コマンド、メソッド、変数も現れないパッケージ。 |
| KS6006 | 未使用のコードではありませんが、スタイルのヒントです: .kscript ファイルで名前のリストが1つの文字列として書かれている場合 (Middleware(use: "log, cors")) です。配列として書いてください: use: [log, cors]。クイックフィックスが自動で変換します。XML の属性はテキストなので、そこでは use="log, cors" で問題ありません。 |
| KS6008 | これも未使用のコードではありません。プロジェクト内でスクリプトが2つ目の型、モデル、列挙型、またはエラー型を宣言している場合です。それぞれ専用のファイルに、その名前を付けて置き、使う場所でインポートしてください。警告は移動先を示します (types/order-status.kscript)。ファイル名になっている型はそのまま残ります。プロジェクトの外のスクリプトはチェックされません。 |
プロジェクトとは、最も近い kscript.json があるフォルダとその配下すべてを指します (隠しフォルダ、bin、obj、node_modules はスキップされます)。プロジェクトの外のスクリプトは、同じフォルダ内の他のファイルに対してチェックされます。プロジェクト外から使われる API の一部である関数は、その doc コメントに @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 は関数そのものです。ラムダも値であり、パラメータも同じくそのまま宣言します: $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?)のように2つのパラメータを取る関数も、同じようにブロックを受け取ります:
<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 7returnで終わらないブロックは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関数、ラムダのいずれでも使えます。
<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, [...]) の読み方がこれです。存在しないパラメーター名を指定したり、同じパラメーターを二回指定したりするとエラーになり、「もしかして」のヒントが表示されます。エディターは ( または , の後でパラメーター名を補完します。
グループのいずれか1つ
一部のパラメーターは代替関係にあり、1回の呼び出しではそのうちの1つだけを渡します。それらの名前は|で結合してください:
<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() takes add: or remove:, not both"、つまり「@file() は add: か remove: のどちらか一方のみを受け取り、両方は指定できません」)。@file(4)もエラーです("needs add: or remove:"、「add: か remove: の指定が必要です」)。kscript checkはコードの実行前に両方を報告します。グループのメンバーは常に名前付きで指定され、呼び出しで渡されなかったものは本体でnullになります。一方にnull(またはfalse)を渡した場合は、渡さなかったものとして扱われます。
| 書き方 | 意味 |
|---|---|
add|remove: file |
addとremoveのどちらか一方のみを指定してください。どちらもファイルです。 |
at|after?: date |
最大で1つです。最後の名前の後にある?を使うと、呼び出しで何も渡さないことも可能になります。 |
text: string | template: Template |
ちょうど1つで、それぞれ独自の型を持ちます。 |
(text: string | template: Template)? |
?を使い、最大で1つまでの場合を角括弧で囲んで同じ内容を示します。 |
他の引数と並んでいるとき、型の異なるメンバーを含むグループには、グループがどこで終わるかを明確にするために括弧が必要です: fn send(to: email, (text: string | template: Template), at|after?: date)。どのグループにも括弧を付けることができます。メンバー自身に既定値を持たせることはできません。
組み込みコマンドもグループを使います。@api() は post:、put:、patch:、delete: のいずれか1つを取り、ジョブの ->dispatch() は delay: か at: のどちらか一方のみで、両方は指定できません。シグネチャヘルプではグループを1つのスロットとして表示し、いずれかが記述されると補完は残りのメンバーを提示しなくなります。また、エディタはグループの名前を1つの色で表示します。
フラグ
真偽値のパラメータは、単独の単語として書くことができます。recursive は true に、not recursive は false に設定するため、呼び出しを文章のように読むことができます。
<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、実行時のすべてが同じ1つの規則を適用するため、何かを実行する前に、同じ誤りを同じ言葉で報告します:
<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.| パラメーターは | 加えて取るもの | それは決して効きません |
|---|---|---|
text (string) |
数値または真偽値を、テキストとして記述します。 | リスト、マップ、または関数 |
数値 (number, int, float) |
数字のように見えるテキスト(例:'3') |
テキスト、true/false、リスト、マップ、関数などの other |
true または false (bool) |
'yes' など、真または偽として解釈されるテキスト |
数値、リスト、マップ、または関数 |
| リスト、マップ、または関数 | それ以外 |
宣言した関数では、テキストの扱いがより厳密になります。stringと宣言されたパラメーターや戻り値はテキストのみを受け付けます。数値や真偽値はエディター内、kscript check内、および実行時にエラーになるため、誤った値を渡す呼び出しが、黙ってテキストに変換されることはありません。呼び出しで書いた値は引用符で囲むか、->to_string()を使って数値をテキストに変換してください。エディターはこの両方を簡単な修正候補として提示します。
<fn name="count_trees" params="input: string" value="$input->grid()->count()" />
<do>@count_trees(1)</do>
<!-- Error: The 'input' argument needs string, but this value is a number, not text. -->
<do>@count_trees('1')</do> <!-- fine: '1' is text -->
<let name="trees" value="3" />
<do>@count_trees($trees->to_string())</do> <!-- fine: the number 3, turned into the text '3' -->fn count_trees(input: string) => $input->grid()->count()
@count_trees(1)
// Error: The 'input' argument needs string, but this value is a number, not text.
@count_trees('1') // fine: '1' is text
$trees = 3
@count_trees($trees->to_string()) // fine: the number 3, turned into the text '3'{ }は、引数名の後に2行にわたって書かれている場合でも常にマップです。そのため、次の行にあるleast: {と}はブロックではなくマップとして扱われます。エディタはleast: { }をleastに置き換えることを提案します。
末尾のカンマ
リストの項目の間にはカンマを置きます。最後の項目の後ろのカンマは、リストが項目ごとに1行ずつ書かれている場合にのみ使えます。こうすると、項目を追加しても変更される行は1行だけになります。同じ行で閉じ括弧の前にカンマを置くと、どの種類のリストでもエラーになります:
<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 }"long enum は、型がフィールドを1行に1つずつ持つのと同じように、値を1行に1つずつ持てます。カンマは不要です。kscript fmt は行幅に収まる enum を1行に書き、それより長い enum は値を1行に1つずつ書きます:
<enum name="Topping" values="mozzarella
pepperoni
mushrooms
green_peppers
black_olives
pineapple
jalapenos" />enum Topping {
mozzarella
pepperoni
mushrooms
green_peppers
black_olives
pineapple
jalapenos
}型が分かっている場合、enum の値は先頭にドットを付けて書きます。.large は Size.large であり、size は Size だからです(下の 先頭のドット を参照)。型を示すものがない場合は、完全な形で書きます: Size.medium。enum のリストは、その値の配列を取ります。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)ドットが何を意味するかは、次の順序で読みます。
- 型付きスロット。 引数、フィールドの既定値、比較、マッチアーム、リストの要素、またはenumを受け取る型付き
fnの戻り値のことです。.pinkはそのenumの値になります。関数を受け取るスロット(->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と完全な形で記述されます。
スロットが最初に試されます。メソッド内では、レコードにredという名前のフィールドがあっても、@paint(color: .red)はNoteColor.redです。列挙型にない名前はレコード自身のものなので、fn current(): NoteColor => .colorはレコードのcolorを返します。どちらにも存在しない名前はエラーになります。
ループの項目は、レコードより前に来ます。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 も指定でき、型には他の型へのルールを追加したり、型同士を結合したりできます。型と検証を参照してください。
型は、1行に1フィールドを書くブロックです。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).
小さな型は1行にまとめることもできます。フィールドはfnの引数のように書きます:type Point(fields: [x: int, y: int])。kscript convertを使うとブロックとして書けます。
XMLでは、型は<type name="Repo">で、各行には<field name="stars" type="int" from="stargazers_count" />要素を、1行形式には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)を使います。
データが型に合わない場合、マッピングは1つの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の1要素です。 |
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)、Resource(only:)は(index|store|show|update|destroy)[]を取ります。型名にもなっている語は型の中で引用符付きになります(例:echoのformat: text|'json'|'markdown')が、書くときは修飾なしでformat: jsonと書きます。
status: draft|liveと書かれたモデルフィールドは、データベースのenum列として保存されます。
one-ofグループでは、コロンの前の|が名前を区切り、コロンの後の|は共用体になります: id|slug: int|uuidはid:またはslug:、つまりintか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にキーのリストを渡すと、項目ごとに新しいマップを1つずつ作ります。キーは修飾なしの名前、引用符付きの文字列、または変数で指定できます。
<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([])は入力項目ごとに空のマップを1つずつ返します。同じキーが繰り返されても、要求された順序で1回だけ現れます。
リストに対するcontains(value)、index_of(value)、remove(value)、count_of(value)は==で比較します。例えば[1, '1']->count_of(1)は2になります。unique()は厳密な等価(===)を使うので、[1, '1']->unique()は両方の項目を残します。
is_empty()は、文字列では0文字、リストでは0個の項目、マップでは0個のキーを意味します。空白だけの入力も受け付けるために$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桁まで大きくなることができ、それを超えると制限エラーで停止します。
テキストでは、->count()と位置(->slice()、->index_of()、$text[0]内)は、ほとんどの文字を1か所として数え、絵文字のような文字は2か所として数えます。どのメソッドもそのような文字を途中で切ることはありません: ->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')。trueかfalseを返す名前は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日に1か月足すと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)は2つの日付が同じ日(既定)、週、月、四半期、年にあるかを問います:
<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) // trueWebhookの署名を確認するには、->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()は、ハッシュを16進数で返します。@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上位3つの数値を掛け合わせるには、->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()が示され、エディターで修正できます。
構造化されたテキストの読み取り
データは多くの場合テキストとして届きます。1行に1レコード、空行で区切られた行のグループ、または文字で描かれた図などです。これらのメソッドは、そのテキストを扱えるリストに変換します。
行とブロック
->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() は、テキスト、リスト、グリッド、3Dリストの中から図形を見つけます。組み込みの正方形、長方形、直線、円、そして描いて作るマスクです。テキストは ->grid() と同じように読まれ、1行が1つの行、1文字が1つのセルとして扱われるため、事前に ->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 themrotated を指定しない場合、図形は水平・垂直に配置されます。正方形と長方形の辺は水平・垂直で、直線は横または縦に伸びます。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(斜めも1として数える。正方形の輪になります)のいずれかです:
<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)。
独自の図形: マスク
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.
# の2x2の塊を見つけるには、それを描いてマスクを作り、名前を使って ->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 middlesymbols は、セルが1文字でない場合に役立ちます。座席の並びは単語のリストで、値のリストは1行なので、各単語に文字を割り当てる必要があります:
<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() は1つのマスクまたはそのリストを受け取り、rotated は各マスクを入力が許すすべての向きに変換します。行は前後逆、グリッドでは4分の1、2分の1、4分の3回転、3Dでは24通りのすべての向きです。複数のマスクの一致は、それぞれの .kind で名前付けされ、まとめて返されます。マスクと組み込みの図形は、1回の呼び出しで一緒に検索できます:
<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として扱います。
レイアウトの空行は、マスクが検索するテキストの空行と同じように、次のレイヤーの始まりを示します。上のレイヤーが先頭です。すべてのレイヤーの行数は同じである必要があり、3Dの一致の各点にも layer があります。3Dリスト($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レイヤーや行数が入力より少ないマスクは、入力全体をスライドします。1行のマスクはグリッドの各行で試され、平面のマスクは3Dテキストや3Dリストの各レイヤーで試されます。入力より多いマスクはエラーになり、"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']]よくある用途は、すべての組を調べることです。たとえば、合計金額になる 2 つの価格を見つける場合などです:
<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) を埋めます。パラメーターが 1 つの関数は、組み合わせ全体を受け取ります:
<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選ばれた要素がパラメーターを埋めるため、このような関数はインデックスを同時には受け取りません。組が 2 個の場合、fn(first, second) はその組の 2 つの要素です。
すべての順序: 順列
->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 通りの並び順があります)。そのため、100 万件を超えるリストでは、メモリ不足になる代わりに 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/ フォルダー内のすべてのファイルが、インポートなしでプロジェクト内のすべてのスクリプト、テスト、ページに適用されます。たとえば型ごとに 1 ファイルなど、好きなように分割できます:
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"]。同じ型に同じメソッドを追加する 2 つの拡張ファイルはエラーになり、両方のファイル名が示されます。スクリプト自身の 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 に束縛し、代替値を評価します。1種類のエラーだけを処理するには catch Validation => $err.message を、束縛名を指定するには catch Validation as problem => $problem.message を使います。代替値が null の場合は、元のエラーが伝播します。
@a() + @b() catch => 0 では、ハンドラーは呼び出しと加算の両方をカバーします。@a() + (@b() catch => 0) では、@b() だけをカバーします。
条件が成り立つときだけエラーを発生させるには throw if を使います。そのブロックの中では、1行につき1つのフィールドを書きます。KScript は条件を1回だけ評価します。フィールドは条件が真のときだけ評価されるため、成功した応答では 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 err) を持つ catch はすべてのエラーを処理します。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 requiredthrow if conditionの中でハンドラーが実行されると、条件が成り立つ場合は現在のエラーを再スローします。payloadブロックを追加すると新しいエラーを発生させられます。エラーをログに記録するだけのハンドラーでは、エラーは伝播したままになります。実行可能なcatchテストでは、メソッドハンドラーがエラーをその型のハンドラーに渡す例や、ログに記録された後のエラーを呼び出し元が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: ...)を使うと、追加のデータを持つ汎用エラーを発生させられます。括弧の前の名前がエラーの型を決めます。汎用エラー、Validationなどの組み込み型、または自分で宣言した型にはErrorを使います。名前付き引数はフィールドになります。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']のような括弧によるキー参照を使います。呼び出し元が見つけて型チェックできるべきフィールドには、エラー型を宣言して、その型をcatchします。宣言されたフィールドは、$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する。
catch NotFoundはPersonNotFoundもcatchします。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はすべてをcatchします。 |
|
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 |
インポート、設定、入力、再帰などの上限、誤った場所、OS、停止したスクリプト、廃止された機能、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}は別の変数を参照します。値は通常config.kscript内で@env('NAME')によって読み取られます。また、まだ設定されていなければ環境変数にもなるため、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(…) はスクリプトから、同じオプションで1つ追加します(replace は既に設定されているもの(既定のコンソールを含む)を削除します)。memory プロバイダは$log->entries() 用にエントリを保持するため、テストで便利です。httpバッチなど、プロバイダが保留しているエントリは、スクリプトの終了時または $log->flush() の実行時に送信されます。失敗したプロバイダは stderr に一度だけ報告され、他のプロバイダは処理を続けます。
パッケージはp.LogProvider("type", description, create)でプロバイダーの型を追加でき、KScript を実行するプログラムはhost.Logs.AddProvider(provider, level)で独自の型を追加できます。プロバイダーは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、langクッキー、そしてブラウザの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を返します。
- 設定:configの
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)(typeには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 |
@send_mail(to:, subject:, html:|text:|view:) を使って SMTP でメールを送信します。送信先はログまたはフェイクで、今すぐ、または kscript worker から queue を使って送ります。@fake_mail() はテストのためにメールを保持します。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 までの整数を指定します。小文字の 16 進数では、1 バイトにつき 2 文字を使います。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) |
関数ではない名前が 3 種類あり、ハイフンなしのまま使います。コントローラー(Resource(to: people) はスクリプトをインポートする際の名前)、ミドルウェアの一覧内の名前([log, throttle:30, my_check]。組み込み、グループ、関数が一つの一覧を共有します)、宣言される変数や型です。XML では同じ引数が同名の属性になり、関数は @ を付けずに書きます(<spawn fn="job" />)。kscript convert は付け外しを行います。
ページでは、on-click などのハンドラーは HTML タグ(<button on-click="$count += 1">)に付くため、HTML のハイフンを使います。Button のような KScript 独自の要素では、引数は 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() は一段階進め(5 段階なら ->advance(5))ます。ターミナルでは同じ位置で再描画されます。パイプ出力とテストでは、タスクの場合と同様に、合計に達したときに 1 行だけ出力されます:
<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 環境変数から取得します(ant コマンドがインストールされている場合は、ANTHROPIC_AUTH_TOKEN のトークン、または保存された ant auth login プロファイルから取得します)。スクリプトから直接指定することはありません。ANTHROPIC_BASE_URL を使うと、プロキシなど別のホストにリクエストを送信できます。スクリプトは、別のモデルを指定しない限り claude-opus-5-5 を使用します。KSCRIPT_AI_MODEL でモデルを指定することもできます。
<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によって、モデルに呼び出し方が伝えられます。ツールが失敗した場合は、そのエラーがモデルに伝えられ、処理を続行できます。 - テストでは、Claudeの代わりに
@fake_llm(replies)を使用します。詳しくは言語モデルのフェイク化をご覧ください。 - エラーは
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は環境変数を読み取ります。- 数値は、マシンの言語に関係なく、常に
.を小数点として解析および出力されます。