KScript ドキュメント
JA

言語

英語から自動翻訳されています。原文は英語です。

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 JSON

echo に単独で渡したマップ、またはマップのリストは、インデントされた JSON として表示されます。ターミナルでは色付きで表示されます(NO_COLOR が設定されていない場合)。テキストの中では 1 行のままです。echo(format: json) は JSON テキストを整形し、->convert(to: json) はコンパクトな JSON を返します。

変数は、宣言されたブロックに属します。{{ と }} は文字どおりの波かっこです。

型を指定して宣言された変数は、その型を保持します。以降の代入はすべて、最初の値と同様にその型へ変換されます。変換できない場合はスクリプトがそこで停止します:

<let name="count" type="int" value="'3'" /> <!-- 3, because '3' reads as an int -->
<set name="count" value="4.0" /> <!-- 4: still an int -->
<set name="count" op="+=" value="1" /> <!-- 5 -->
$count: int = '3' // 3, because '3' reads as an int
$count = 4.0 // 4: still an int
$count += 1 // 5

その後、$count = 'many' はエディターでエラーになり、実行時にはそこで停止します: $count must be an int, but got the string 'many'。

"Double quotes" は、代入、戻り値、呼び出しの引数などで、{ } の後の echo 内の式を補間します。.kscript では、KS6019 が裸の参照を見つけ、波括弧で囲むことを提案します。'Single quotes' は書かれたとおりのテキストを保持するため、埋める値がないテキストはそこに入れてください(KS6020 が変更を提案します)。echo の後の引用テキストも、スペースを含めてそのまま出力されます。たとえば echo " - { $item }" は二つのスペースを出力します。XML では、<echo> と </echo> の間のテキストは前後の空白が取り除かれ、行に共通するインデントも取り除かれます。ただし埋め込まれた値はそのまま扱われます。ただし、空の値は余分な空白を残さず、テキストが改行で終わることもありません。

<let name="greeting" value="&quot;Hello { $name }, you have { $count * 2 } points.&quot;" />
<let name="label" value="'Write $name to use a variable.'" /> <!-- kept as written -->
<let name="boxes" value="&quot;{ 2 * 3 } boxes, { [1, 2]->count() } lists&quot;" /> <!-- 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 に渡すテキストは例外で、その { } はパラメータとして送られ、そのまま埋め込まれることはありません(データを参照)。

式

+ - * / % **、== !=(緩い比較: '3' == 3)、=== !==(厳密)、< <= > >=、and or not、??、?.、a ? b : c、in、リストリテラル [1, 2] とマップリテラル { name: 'Joan' }(as set を使うとリストを集合に変換できます)、$p.name、$list[0](負のインデックスは末尾から数えます)、範囲 0..10 と 0..100 step 5(終端は含まれません。0.1 のようなステップ指定も可)、1..=10(終端を含む)、match $x { 1 => 'one', _ => 'other' }、->method()、|>、fn(x) => …。条件を組み合わせるには and と or を書きます。前置の ! は not と同じ優先順位と真偽判定を持つため、!$ready、! $ready、not $ready は同じ意味です。フィールド(!$user.active)、条件全体(if !($ready and $open) { … })、補間("{ ! null->is_null() }")に使えます。null->!is_null() と書くと、連鎖の次の要素の前にメソッドの結果を否定します。XML には各比較演算子に対応する語もあります(lt le gt ge eq ne)。XML では生の < を引用符付き属性の中に書けないため、そこで使います。省略形の開始タグでは < と > をそのまま書けます。.kscript ファイルでは、これらの語は(KS6012 として)指摘され、kscript check --fix は記号を書きます。

<、<=、>、>=で数値と文字列を比較する場合、文字列を数値として解析できれば、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 &lt;= $score &lt; 100" /> <!-- true because 42 is from 0 up to (not including) 100 -->
<let name="top" value="90 &lt;= $score &lt;= 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' }。そこでは分岐の { } ブロックがその return の値を返し、分岐は値を返す代わりに throw できます。分岐は改行かカンマで区切り、最初に一致した分岐が使われます。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
// pear

elif と 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 どこからも呼び出されない関数です。スクリプトの main 関数は、自動で実行されるため、報告されることはありません。プロジェクト内の他のファイルからの呼び出しは数えられます。たとえば、別のスクリプトが import して呼び出すライブラリ関数、ルートファイルが指定するコントローラー(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。

lambda のパラメーターには、関数と同じ書き方で型を付けられます。引数はその型に変換され、変換できなければ関数と同じようにスクリプトが停止します:

<let name="area" value="fn(width: number, height: number) => $width * $height" />
<echo value="$area('3', 4)" /> <!-- 12: '3' reads as a number -->
<echo value="['a', 'b']->map(fn(s: string) => $s->upper())" />
$area = fn(width: number, height: number) => $width * $height
echo $area('3', 4)                          // 12: '3' reads as a number
echo ['a', 'b']->map(fn(s: string) => $s->upper())

短い関数は、各項目のフィールドを読み取るか、メソッドを呼び出します。関数は項目を表す . または -> から始まり、関数を使える場所ならどこでも使えます:

<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) => …と記述してください。

main 関数

スクリプトは、main という名前の関数に処理を書くことができます。実行されるスクリプトである場合、main はトップレベルのコードが実行された後に自動で実行されます。そのため、トップレベルのコードで準備を行い、main が処理を担当します:

<!-- greet.kscript, run with: kscript greet.kscript Ada Grace -->
<let name="greeting" value="'Hello'" /> <!-- the top-level code runs first -->

<fn name="main" params="args: list">
  <!-- $args is ['Ada', 'Grace'], the words after the script's name -->
  <for each="name" in="$args">
    <echo>{ $greeting }, { $name }!</echo> <!-- Hello, Ada! then Hello, Grace! -->
  </for>
</fn>
// greet.kscript, run with: kscript greet.kscript Ada Grace
$greeting = 'Hello'            // the top-level code runs first

fn main(args: list) {
  // $args is ['Ada', 'Grace'], the words after the script's name
  for name in $args {
    echo "{ $greeting }, { $name }!"    // Hello, Ada! then Hello, Grace!
  }
}
  • パラメーターは省略可能です。 fn main() も同じ方法で実行されます。fn main(args: list) はスクリプトの引数を受け取ります。これは $args と同じリストです。他に値が渡されないため、2つ目のパラメーターには既定値が必要です。fn main(first, second) は エラー(KS5004)になります。
  • 戻り値は終了コードです。 main が返す整数は、exit と同様に、その終了コードでスクリプトを終了させます。これにより、シェルや CI ジョブが結果を判断できます。それ以外の値、または何も返さない場合は、終了コード 0 になります:
<fn name="main" params="args: list" returns="int">
  <if $args->count() == 0>
    <echo>Name a file to read.</echo>
    <return value="2" /> <!-- exit code 2: the script wasn't given what it needs -->
  </if>
  <echo>Reading { $args[0] }</echo>
  <return value="0" /> <!-- exit code 0: all went well -->
</fn>
fn main(args: list): int {
  if $args->count() == 0 {
    echo 'Name a file to read.'
    return 2                     // exit code 2: the script wasn't given what it needs
  }
  echo "Reading { $args[0] }"
  return 0                       // exit code 0: all went well
}
  • 実行されるスクリプトだけに属します。 main は、実行するスクリプトに属します。kscript run、kscript greet.kscript、コンパイル済みプログラム、デバッガー、エディターの実行コマンドはすべて、これを呼び出します。import されたスクリプトは、トップレベルのコードは実行しますが、main は決して実行しません。そのため、ライブラリは main を残して、単独で試せるようにできます。
  • トップレベルでのみ有効です。 別の関数、型、テストファイルの中にある fn main は、通常の関数です。
  • 未使用として報告されることはありません。 main を呼び出すものがないため、kscript check とエディターは、未使用として報告することはありません(KS6002)。トップレベルのコードからも呼び出されている場合は、2回実行されてしまうため警告されます(KS5019)。クイックフィックスと同様に、その呼び出しを削除してください。

kscript.json の app.main_function により、プロジェクト内のすべてのスクリプトに別の名前が付きます:

JSON
{
  "app": { "main_function": "start" }   // fn start runs by itself; a fn main is then an ordinary function
}

ブロック関数

関数に複数の式が必要な場合は、=>の代わりにブロックを指定します。ブロックには、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 &lt; 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 7

returnで終わらないブロックはnullを返します。これは、ブロックが何をするかだけが重要な->each()に適しています。それ以外の場所では、呼び出しはブロックが返す値を使うため、空のブロックや値を返さないブロックはエラーになります。エディター、kscript check、実行時のいずれでもエラーになります:

<let name="words" value="['fig', 'kiwi']" />
<let name="longest">$words->common(1, by: fn(word) {
  })</let>
<!-- Error: This fn block is empty, so it gives null each time it is called, and 'by' uses what it gives. -->
$words = ['fig', 'kiwi']
$longest = $words->common(1, by: fn(word) {
})
// Error: This fn block is empty, so it gives null each time it is called, and 'by' uses what it gives.

このブロックは周囲の変数を読み取って変更でき、ブロック内で作成した変数はブロックの内側に残ります:

<let name="seen" value="0" />
<do>['x', 'y', 'z']->each(fn(letter) {
    $seen = $seen + 1              // the outer $seen goes up, because the block changes the variable around it
    $shout = $letter->upper()      // $shout exists only inside the block
    echo $shout                   // X, then Y, then Z, because the block runs once per letter
  })</do>
<!-- $seen is 3 -->
$seen = 0
['x', 'y', 'z']->each(fn(letter) {
  $seen = $seen + 1              // the outer $seen goes up, because the block changes the variable around it
  $shout = $letter->upper()      // $shout exists only inside the block
  echo $shout                   // X, then Y, then Z, because the block runs once per letter
})
// $seen is 3

ブロック関数は他の関数と同じ値なので、変数に保持して呼び出すことができます:$greet = fn(name) { … }、そして$greet('Ada')。ブロック関数は.kscriptファイルで動作します。XML属性には文を入れられないため、そこではfn(n) => valueと書くか、<fn>を宣言して@nameとして渡します。データベースクエリの条件(->where(fn(u) => $u.age >= 18))はSQLに変換されるため、単一の式のままにしておく必要があります。

anyとして宣言されたパラメータは、あらゆる値を受け付けます。そのパラメータに対するメソッド呼び出しでは、値の実際の型が使われます。例えば、$key->trim()は文字列の前後の空白を取り除き、数値に対してはエラーを発生させ、その型独自のtrim()が存在する場合はそれを呼び出します。文字列の正規化にはfn trim_key(key: string) => $key->trim()と書きます。これにより、エディターは戻り値の型が文字列であると推論できます。

名前付き引数

任意の呼び出しでは、引数に名前を付けて任意の順序で渡せます。組み込みコマンド、メソッド、独自のfn関数、ラムダのいずれでも使えます。

<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 ? &quot;Added { $add }&quot; : &quot;Removed { $remove }&quot;" />
  <let name="told" value="$notify ? ', and told its owner' : ''" />
  <return value="&quot;{ $change } on note { $note_id }{ $told }&quot;" />
</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'

宣言された1つの型のレコードは、パラメーター、結果、または型付き変数が宣言する型に照らして検査されます。その型の必須フィールドのいずれかを欠くレコードは、実行時と同様に、スクリプトの実行前にエラーになります:

<type name="Post">
  <field name="title" type="string" />
</type>

<type name="Comment">
  <field name="body" type="string" />
</type>

<fn name="headline" params="post: Post" value="$post.title->upper()" />

<echo value="@headline(Comment(body: 'First!'))" />
<!-- Error: The 'post' argument needs Post, but this value is a Comment, which has no title field. -->
type Post {
  title: string
}

type Comment {
  body: string
}

fn headline(post: Post) => $post.title->upper()

echo @headline(Comment(body: 'First!'))
// Error: The 'post' argument needs Post, but this value is a Comment, which has no title field.

{ }は、引数名の後に2行にわたって書かれている場合でも常にマップです。そのため、次の行にあるleast: {と}はブロックではなくマップとして扱われます。エディタはleast: { }をleastに置き換えることを提案します。

型パラメーター

どの型に対しても同じように動作する関数は、名前の後の山括弧に型を書き、その型をパラメーターと結果で使います。呼び出し時には、与えられた値から型が決まります:

<fn name="first" generics="T" params="items: T[]" returns="T">
  <return value="$items[0]" />
</fn>

<fn name="same" generics="T" params="a: T, b: T" returns="bool" value="$a == $b" />

<echo value="@first([3, 4])->round()" /> <!-- 3: @first() of a list of numbers is a number -->
<echo value="@first(['fig'])->upper()" /> <!-- FIG -->
<echo value="@same('a', 'b')" /> <!-- false -->
fn first<T>(items: T[]): T {
  return $items[0]
}

fn same<T>(a: T, b: T): bool => $a == $b

echo @first([3, 4])->round()       // 3: @first() of a list of numbers is a number
echo @first(['fig'])->upper()      // FIG
echo @same('a', 'b')               // false

1回の呼び出しで、各型パラメーターには1つの型が割り当てられます。@same(1, 'x') は、エディター、kscript check、実行時のいずれでもエラーです。a が T を数値にし、b をテキストにするためです。呼び出しが T として決めた型と異なる結果も、同様にエラーです。関数の中では、T は任意の型なので、$items[0] に検査は必要ありません。複数の型パラメーターはカンマで区切って書きます: fn pair<K, V>(key: K, value: V)。XML では generics 属性に書きます: <fn name="first" generics="T" params="items: T[]" returns="T">。

末尾のカンマ

リストの項目の間にはカンマを置きます。最後の項目の後ろのカンマは、リストが項目ごとに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="&quot;painted { $color }&quot;" />

<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)

ドットが何を意味するかは、次の順序で読みます。

  1. 型付きスロット。 引数、フィールドの既定値、比較、マッチアーム、リストの要素、またはenumを受け取る型付きfnの戻り値のことです。.pinkはそのenumの値になります。関数を受け取るスロット(->map(.name)など)の場合は、各要素のそのフィールドを読み取ります。
  2. ループforの中の要素です。 for account in $accounts { ... }では、.idは$account.idであり、.name = 'Ann'は要素のフィールドを設定します。ネストされたループでは、その名前を持つ最も内側の要素が優先されるため、内側のループの.labelと外側のループの.idを並べて置くことができます。whileループには要素がないため、何も追加しません。
  3. レコード自身のメソッド内でのレコード。 type、model、extend、またはコンポーネントのメソッド内では、.textはレコード自身のフィールドを指し、.save()は自身のメソッドを呼び出します。.count += 1と.color = .redはそのフィールドを設定します。
  4. どれでもありません。 $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 組み込み型(string、int、float、number、bool、date、list、set、map、fn、any、email、password、handle、uuid、regex)、enum、別のtype、リストのT[]、Tの集合のset(of: T)。角かっこでルールを続けられます:string(min: 1)。これを省略すると、フィールドは任意の値を受け付けます。
名前の後の? 値がない場合や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など)から値を計算します。読み取るのではありません。
行の上の/// ホバーと補完で表示されます。

型自体には括弧でオプションを指定できます: type Repo(extra: error) { … }。extra は、型に記載されていないキーの扱いを指定します: drop(既定)、keep、error。path: 'data/repo.json' は保存されたデータのサンプルからフィールドを取り込みます。オブジェクトは入れ子の型になり、一部のリスト項目にしか現れないキーはオプションになります。ブロック内の行は、名前が指定されたサンプルのフィールドを置き換えます。型は任意の順序で互いを参照でき、自分自身も参照できます。トップレベルの型は、そのファイルをインポートするスクリプトに公開されます。プロジェクトでは、型ごとに専用のファイル(types/repo.kscript、types/owner.kscript)を作り、使う型をインポートしてください。インポートは types/repo.kscript の先頭に import "owner.kscript" と書きます(1ファイルに1型を参照)。

小さな型は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に切り替えてください。

型付きリストは項目の型を保持する

項目の型 $scores: int[] = [90, 72] を指定して宣言されたリストは、その型を保持します。$scores[0] = '85' は数値 85 を格納し、$scores[1] = 'high' は "An item of $scores must be an int" で停止します。kscript check とエディターは、その型になり得ない値をその場に書いた場合を報告します(KS5012)。

null になる可能性のある値

? を付けて書かれた型は、値が null になる可能性があることを示します。fn find(slug: string): Post? と宣言された関数、post: Post? のパラメーター、$post: Post? = ... の変数、既定値のない license?: string のフィールドがこれに当たります。null のフィールドを読んだり、null に対してメソッドを呼び出したりすると、スクリプトは停止します。そのため、kscript check とエディターは、そのような値が何も検査されないまま使われると警告します(KS5018):

<type name="Post">
  <field name="title" type="string" />
  <field name="summary?" type="string" />
</type>

<fn name="find" params="slug: string" returns="Post?">
  <return value="$slug == 'hello' ? Post(title: 'Hello') : null" />
</fn>

<let name="post" value="@find('hello')" />
<if $post == null>
  <exit />
</if>
<echo value="$post.title" /> <!-- fine: the line above stops when it is null -->
<echo value="($post.summary ?? 'no summary')->upper()" /> <!-- fine: ?? gives a default -->
type Post {
  title: string
  summary?: string
}

fn find(slug: string): Post? {
  return $slug == 'hello' ? Post(title: 'Hello') : null
}

$post = @find('hello')
if $post == null => exit
echo $post.title                                // fine: the line above stops when it is null
echo ($post.summary ?? 'no summary')->upper()   // fine: ?? gives a default

次のいずれも検査とみなされます。使用箇所を囲む if、elif、while(if $post != null、if $post、if $post is Post)、else の後の if $post == null、その上にある if $post == null { return }(または throw、break、continue、exit)、そして1つの式の中の $post and $post.title、$post == null or $post.title == ''、$post ? $post.title : ''。フィールドを指定して直前に作ったレコード($p = Post(title: 'x', summary: 'y'))も検査されています。省略可能なリスト、セット、マップは null ではなく空になります。モデルのフィールドは、データベースから来るため実行時の判断に任されます。

strict な型

strict で始まるファイルは、その型に従うことが求められます。すべての値にチェッカーが証明できる型が必要で、型の誤りはスクリプトのどの部分も実行される前に停止させるエラーになります:

<strict />

<fn name="area" params="width: number, height: number" value="$width * $height" />

<let name="total" value="0" /> <!-- a number: the value proves it -->
<let name="names" type="string[]" value="[]" /> <!-- an empty list says what it will hold -->
<for each="size" in="[2, 3]">
  <set name="total" op="+=" value="@area($size, 2)" />
</for>
<echo value="$total" />
strict

fn area(width: number, height: number) => $width * $height

$total = 0                      // a number: the value proves it
$names: string[] = []           // an empty list says what it will hold
for size in [2, 3] {
  $total += @area($size, 2)
}
echo $total

strict なファイルでは:

  • 型の誤りはエラーです。間違った型の値(KS5005)、値にないフィールドやメソッド(KS5010、KS5003)、型に合わない値(KS5012)、null の可能性がある値をチェックせずに使うこと(KS5018)は、警告ではなくエラーです。kscript check がこれらを報告し、kscript run、serve、test はスクリプトを開始しません。lint.rules の設定で無効にすることはできません。
  • パラメーターは型を明示する(KS6007)か、デフォルト値から取ります:fn greet(who = 'world')。lambda のパラメーターは使われる場所から型を取るか([1, 2]->map(fn(n) => $n * 2) のように)、明示します:fn(n: number) => $n * 2。
  • それ以外はすべて、チェッカーが証明できる型が必要です(KS5020)。変数は値から型を取るか($n = 0、$repo = Repo(name: 'x'))、明示します($n: int = $args[0])。チェッカーは次のものに型を書くよう求めます:空のリスト($names: string[] = [])、型が混在するリスト、null($found: Repo? = null)、異なる型の値が代入される変数、JSON など型のないデータから読んだ値、推論できない関数の結果(fn first(items: list): string)、型もデフォルト値もないフィールド。
  • any は、値が本当に何でもあり得るときに書ける型です:$data: any = $text->convert(from: json)。そこから読んだ値には再び型が必要です:$count: int = $data.count。

strict はファイルの先頭、import 以外のすべてより前に置きます。XML では <kscript> の最初の要素としての <strict /> です。プロジェクトのすべてのスクリプトを strict にするには、kscript.json に "strict": true を設定します。import された strict なファイルは読み込み時にチェックされるので、それを import するスクリプトも開始されません。

データと型が出会う場所

<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="&quot;sorted by { $by }&quot;" />
<fn name="retitle" params="title: Post.title" value="&quot;renamed to { $title }&quot;" />
<fn name="tag" params="tag: Post.tags.item" value="&quot;tagged { $tag }&quot;" />
<fn name="publish" params="post: Post, as: draft|live = 'live'" value="&quot;{ $post.title } is { $as }&quot;" />
<fn name="find" params="id: int|uuid" value="&quot;found { $id }&quot;" />

<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)                  // true

nowはコンピュータの時計から得られるので、テストでは@with_clock(date, fn)が@now()、@today()、上記のフィールド、@format_relative()のために値を固定します。

テキストの扱い

テキストには、繰り返し出てくる作業のためのヘルパーがあります。名前の大文字・小文字の変換、区切り文字での分割、空白の整理、ペイロードの署名などです。

<echo value="'Order Total'->case(snake)" /> <!-- order_total -->
<echo value="'order_total'->case(camel)" /> <!-- orderTotal -->
<echo value="'order total'->case(pascal)" /> <!-- OrderTotal -->
<echo value="'orderTotal'->case(kebab)" /> <!-- order-total -->

<let name="email" value="'joan@example.com'" />
<echo>{ $email->before('@') } at { $email->after('@') }</echo> <!-- joan at example.com -->
<echo value="'archive.tar.gz'->after('.', last)" /> <!-- gz -->

<echo value="'  too   many    spaces '->squish()" /> <!-- too many spaces -->
<let name="words" value="'Hello, world!'->words()" /> <!-- ['Hello', 'world'] -->
<echo value="'4242424242424242'->mask('*', keep_end: 4)" />
echo 'Order Total'->case(snake)           // order_total
echo 'order_total'->case(camel)           // orderTotal
echo 'order total'->case(pascal)          // OrderTotal
echo 'orderTotal'->case(kebab)            // order-total

$email = 'joan@example.com'
echo "{ $email->before('@') } at { $email->after('@') }" // joan at example.com
echo 'archive.tar.gz'->after('.', last)  // gz

echo '  too   many    spaces '->squish()   // too many spaces
$words = 'Hello, world!'->words()       // ['Hello', 'world']
echo '4242424242424242'->mask('*', keep_end: 4)

->before()と->after()は最初の区切り文字で切り、lastを付けると最後の区切り文字で切ります。区切り文字がない場合はテキスト全体を返します。->wrap(width: 60)は、@terminal_width()のような幅に収まるように単語の間で改行します。->is_numeric()は'42'や'-3.5'のようなテキストに対して真になります。

->contains()、->starts_with()、->ends_with()、->index_of()(最後の一致はlast)と->replace()は大文字と小文字を正確に区別して一致させます。大文字と小文字を区別せずに一致させるにはignore_caseを渡してください:

<let name="query" value="'TEA'" />
<echo value="'Green tea'->contains($query, ignore_case)" /> <!-- true -->
$query = 'TEA'
echo 'Green tea'->contains($query, ignore_case) // true

Webhookの署名を確認するには、->hmac(key)で署名を計算し(デフォルトはSHA-256です。sha1またはsha512も使用できます)、その結果を@secure_equals()と比較します。この比較は、一致する部分の長さに関係なく、常に同じ時間がかかります。

<let name="body" value="'{&quot;id&quot;: 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 most

by:は、何を同じ項目とみなすかを決めます。ここでは'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' }

集合

集合は、各項目が一度だけ現れる項目の集まりです。既に存在する項目を追加しても何も起こらず、ある項目が集合に含まれるかを調べるのは、集合がどれだけ大きくても素早く行えます。集合はas setでリストから作るか、変数やフィールドをsetとして宣言して書きます:

<let name="line" value="'rr?gb?r'" />
<let name="colours" value="$line->chars() as set" /> <!-- ['r', '?', 'g', 'b'] because each character goes in once -->
<echo value="($colours - ['?'])->count()" /> <!-- 3 because r, g and b are left once ? is taken away -->
$line = 'rr?gb?r'
$colours = $line->chars() as set   // ['r', '?', 'g', 'b'] because each character goes in once
echo ($colours - ['?'])->count()   // 3 because r, g and b are left once ? is taken away

集合は、既に見たものを記憶するのに最も役立ちます。$seen: set = []で空の集合を作り、+=で追加し、inで確認します。どちらも集合が大きくなっても速く動作します:

<let name="seen" type="set" value="[]" />
<for each="place" in="['home', 'shop', 'home', 'park']">
  <if $place in $seen>
    <echo>back at { $place }</echo> <!-- back at home, once, because home was seen before -->
  </if>
  <set name="seen" op="+=" value="$place" />
</for>
$seen: set = []
for place in ['home', 'shop', 'home', 'park'] {
  if $place in $seen {
    echo "back at { $place }"   // back at home, once, because home was seen before
  }
  $seen += $place
}

+は二つの集合を結合し、-は項目を取り除き、->intersect()は両方に含まれる項目を残します。右辺は普通のリストでも構いません。set(of: string)は単一の型の集合で、型付きリストと同様に、項目は追加されるときにその型へ変換されます。$set as listは項目をリストとして返します。すべての集合メソッドの例は集合にあります。

<type name="Post">
  <field name="title" type="string" />
  <field name="tags" type="set(of: string)" default="[]" />
</type>

<let name="post" value="Post({ title: 'Hello', tags: ['news', 'tech', 'news'] })" />
<echo value="$post.tags" /> <!-- ['news', 'tech'] because the second 'news' is already in the set -->
<echo value="$post.tags->overlaps(['tech'])" /> <!-- true -->
<echo value="$post.tags->is_subset(of: ['news', 'tech', 'sport'])" /> <!-- true because both tags are in the list -->
type Post {
  title: string
  tags: set(of: string) = []
}

$post = Post({ title: 'Hello', tags: ['news', 'tech', 'news'] })
echo $post.tags                         // ['news', 'tech'] because the second 'news' is already in the set
echo $post.tags->overlaps(['tech'])     // true
echo $post.tags->is_subset(of: ['news', 'tech', 'sport']) // true because both tags are in the list

形式間の変換: 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="'{&quot;fruit&quot;: &quot;apple&quot;, &quot;count&quot;: 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 map

CSVはデフォルトでヘッダー行があり、各行のキーを名前付けします。すべての行がデータである場合は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="'{&quot;fruit&quot;: &quot;apple&quot;}'->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 rows

row:は一つの行を、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 them

rotated を指定しない場合、図形は水平・垂直に配置されます。正方形と長方形の辺は水平・垂直で、直線は横または縦に伸びます。rotated を指定すると、図形は傾くことができ、正方形がひし形になったり、直線が斜めになったりします:

<let name="kite">```text
    ..#..
    .#.#.
    ..#..
    ```</let>

<echo value="$kite->shapes(square, of: '#')->count()" /> <!-- 0 because no four #s make a square with level sides -->
<echo value="$kite->shapes(square, of: '#', rotated)->count()" /> <!-- 1 because the four #s make a diamond, a square on its corner -->
$kite = ```text
..#..
.#.#.
..#..
```

echo $kite->shapes(square, of: '#')->count()            // 0 because no four #s make a square with level sides
echo $kite->shapes(square, of: '#', rotated)->count()   // 1 because the four #s make a diamond, a square on its corner

複数の図形名を指定すると、それらすべてを見つけます。一つの一致が複数の図形に当てはまる場合でも、一度だけ返されます。たとえば正方形は長方形でもあるため、正方形として返されます。どの図形かは .kind で確認できます:

<let name="plot">```text
    @@@.
    @..@
    @@@@
    ```</let>

<echo value="$plot->shapes(rectangle, of: '@')->count()" /> <!-- 4 because three rectangles share rows 0 and 2, and one shares rows 1 and 2 -->
<echo value="$plot->shapes(square, rectangle, of: '@')->map(.kind)" />
<!-- ['square', 'rectangle', 'rectangle', 'rectangle'] because the 2 by 2 one is a square, so it isn't a rectangle as well -->

<echo value="$plot->shapes(line, of: '@', size: 4)->count()" /> <!-- 1 because only the bottom row has 4 @s in a row -->
<echo value="$plot->shapes(line, of: '@', size: 3, rotated)->count()" /> <!-- 4 because rotated lets lines run diagonally too -->
$plot = ```text
@@@.
@..@
@@@@
```

echo $plot->shapes(rectangle, of: '@')->count()                 // 4 because three rectangles share rows 0 and 2, and one shares rows 1 and 2
echo $plot->shapes(square, rectangle, of: '@')->map(.kind)
// ['square', 'rectangle', 'rectangle', 'rectangle'] because the 2 by 2 one is a square, so it isn't a rectangle as well

echo $plot->shapes(line, of: '@', size: 4)->count()             // 1 because only the bottom row has 4 @s in a row
echo $plot->shapes(line, of: '@', size: 3, rotated)->count()    // 4 because rotated lets lines run diagonally too

直線には size:(点の数)が必要です。円には radius: が必要で、distance: で距離の測り方を指定します。straight(直線距離、デフォルト)、steps(縦横のみ。ひし形になります)、moves(斜めも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)。

独自の図形: マスク

マスクは、描画する形状です。組み込みの形状は、点がどこにあるかしか分かりません。マスクは、すべてのセルが何を保持すべきか(空きを含む)を正確に示します。extends Mask を満たす型として宣言し、その layout で描画してください。これは、形状を描いたテキストブロックです。1文字が1セルに対応します(行に沿って任意の長さの形状には、正規表現を使うこともできます: 正規表現レイアウト)。各文字は、同じ文字を保持するセルと一致します。すべての行に共通するインデントは、形状の一部ではないため、周囲のコードに合わせてインデントしてください。

# の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 1

symbols は、それ自体とは異なる意味を持つ文字のためだけに使います。文字を、それが一致する対象に対応付けます。値(t: 'taken')は、その値を持つセルに一致し、正規表現(/[#@]/)は、テキストが合うセルに一致します。fn(cell) は、真を返すセルに一致し、same は、すべて同じ値を持つ必要があるセル(below)に一致し、any は、図形の一部でないセルに一致します。any のセルは何でも持てて、入力の端からはみ出してもよく、一致の点からは除外されます。3x3の正方形の角にある4本の木を、その間は何でもよい形で見つけるには:

<type name="Corners" description="Trees at the four corners of a 3x3 square, anything between." extends="Mask">
  <field name="layout" default="```text
      #.#
      ...
      #.#
      ```" />
  <field name="symbols" default="{ '.': any }" />
</type>

<let name="orchard">```text
    #.#.#
    .#...
    #.#.#
    ```</let>

<echo value="$orchard->shapes(Corners)->count()" /> <!-- 2 because the corners fit at columns 0-2 and at columns 2-4 -->
<echo value="$orchard->shapes(Corners)->first().points->map(.symbol)" />
<!-- ['#', '#', '#', '#'] because . is any, so its cells aren't part of the match, even the # in the middle -->
/// Trees at the four corners of a 3x3 square, anything between.
type Corners extends Mask {
  layout: ```text
    #.#
    ...
    #.#
    ```
  symbols: { '.': any }
}

$orchard = ```text
#.#.#
.#...
#.#.#
```

echo $orchard->shapes(Corners)->count()                         // 2 because the corners fit at columns 0-2 and at columns 2-4
echo $orchard->shapes(Corners)->first().points->map(.symbol)
// ['#', '#', '#', '#'] because . is any, so its cells aren't part of the match, even the # in the middle

symbols は、セルが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 count

同じであるセル: same

これまでのシンボルはすべて、セルを固定の何かと比較するものです。same はセル同士を比較します。その文字で描かれたすべてのセルは、値が何であれ同じ値を持つ必要があり、2つの異なる same の文字は異なる値を持つ必要があります。same(...) は、その値の範囲を、値、正規表現、fn(cell) で絞り込みます。読み返しても同じになる単語、たとえば oxxo を見つけるには:

<type name="Mirror" description="Two letters, then the same two backwards, like 'abba'." extends="Mask">
  <field name="layout" default="```text
      xyyx
      ```" />
  <field name="symbols" default="{ x: same(/[a-z]/), y: same(/[a-z]/) }" />
</type>

<echo value="'ioxxoj'->shapes(Mirror)->count()" /> <!-- 1 because only 'oxxo' reads the same letters out and back -->
<echo value="'ioxxoj'->shapes(Mirror)->first().points->map(.value)" /> <!-- ['o', 'x', 'x', 'o'] because x is o and y is x there -->
<echo value="'aaaa'->shapes(Mirror)->count()" /> <!-- 0 because x and y are different characters, so they hold different letters -->
/// Two letters, then the same two backwards, like 'abba'.
type Mirror extends Mask {
  layout: ```text
    xyyx
    ```
  symbols: { x: same(/[a-z]/), y: same(/[a-z]/) }
}

echo 'ioxxoj'->shapes(Mirror)->count()                       // 1 because only 'oxxo' reads the same letters out and back
echo 'ioxxoj'->shapes(Mirror)->first().points->map(.value)   // ['o', 'x', 'x', 'o'] because x is o and y is x there
echo 'aaaa'->shapes(Mirror)->count()                         // 0 because x and y are different characters, so they hold different letters

任意の長さの図形: 正規表現のレイアウト

絵は固定のサイズです。代わりにレイアウトを正規表現にすると、各行に沿ってセルを前から順に読み、必要なだけ一致させられます。各セルはそのテキストとして読まれ、一致は必ずセルの間で始まり、終わります。正規表現のレイアウトには symbols がありません。部分には (?<name>...) で名前を付け、各点の symbol は、その点が含まれた部分の名前になります:

<type name="PartNumber" description="A part number: digits side by side, each one named a digit." extends="Mask">
  <field name="layout" default="/(?&lt;digit>\d)+/" />
</type>

<let name="schematic">```text
    467..114
    ...*....
    ..35.633
    ```</let>

<echo value="$schematic->shapes(PartNumber)->count()" /> <!-- 4 because 467, 114, 35 and 633 are each a run of digits -->
<echo value="$schematic->shapes(PartNumber)->first().points->map(.column)" /> <!-- [0, 1, 2] because 467 fills the first three columns of row 0 -->
<echo value="$schematic->shapes(PartNumber)->first().points->map(.symbol)" /> <!-- ['digit', 'digit', 'digit'] because each cell fell in the digit part -->
/// A part number: digits side by side, each one named a digit.
type PartNumber extends Mask {
  layout: /(?<digit>\d)+/
}

$schematic = ```text
467..114
...*....
..35.633
```

echo $schematic->shapes(PartNumber)->count()                         // 4 because 467, 114, 35 and 633 are each a run of digits
echo $schematic->shapes(PartNumber)->first().points->map(.column)    // [0, 1, 2] because 467 fills the first three columns of row 0
echo $schematic->shapes(PartNumber)->first().points->map(.symbol)    // ['digit', 'digit', 'digit'] because each cell fell in the digit part

rotated を指定すると、正規表現のレイアウトは各行を後ろから前へも読み、グリッドでは各列を上下両方向に読みます。単語のリストは1セルに1単語として読まれるため、/\d+/ を ['ab', '12', '34'] に使うと ['12', '34'] を見つけられます。

マスクの押印: repeated

repeated を指定すると、マスクは抜き型のように働きます。左上から何度も押印され、入力全体を覆うまで繰り返されます。右端と下端の押印はちょうど切り取られます。セルごとに、2つ目以降の押印が最初の押印と同じ内容を持つ場合に一致します(any のセルは自由です)。一致は最初の押印で、copies は押印された回数を示します:

<type name="Checker" description="One black and one white tile, and the same two swapped below." extends="Mask">
  <field name="layout" default="```text
      #.
      .#
      ```" />
</type>

<let name="floor">```text
    #.#.#
    .#.#.
    #.#.#
    ```</let>

<echo value="$floor->shapes(Checker, repeated)->count()" /> <!-- 1 because the whole floor is a checkerboard -->
<echo value="$floor->shapes(Checker, repeated)->first().copies" /> <!-- 6 because 2 rows of 3 stamps cover it, the last row and column cut off -->
<echo value="'#..'->shapes(Checker, repeated)->count()" /> <!-- 0 because the third cell should be # like the first -->
/// One black and one white tile, and the same two swapped below.
type Checker extends Mask {
  layout: ```text
    #.
    .#
    ```
}

$floor = ```text
#.#.#
.#.#.
#.#.#
```

echo $floor->shapes(Checker, repeated)->count()            // 1 because the whole floor is a checkerboard
echo $floor->shapes(Checker, repeated)->first().copies     // 6 because 2 rows of 3 stamps cover it, the last row and column cut off
echo '#..'->shapes(Checker, repeated)->count()             // 0 because the third cell should be # like the first

正規表現のレイアウトには固定のサイズがないため、repeated を指定すると、最も短い抜き型から試し、合う最短のものを返します。行に沿って押印される最初の size のセルが行を構成し、正規表現がそれらのセル全体に合う必要があります。1行だけを読むため、1行ずつ渡してください:

<type name="Instructions" description="A printer's instructions: one or more colours, read along a row." extends="Mask">
  <field name="layout" default="/[roygbv]+/" />
</type>

<let name="printed" value="'rgbrgbrgbr'->shapes(Instructions, repeated)->first()" />
<echo value="$printed.points->map(.value)->join('')" /> <!-- 'rgb' because rgb, stamped and cut off, prints rgbrgbrgbr -->
<echo value="$printed.copies" /> <!-- 4 because the fourth rgb is cut off after its r -->
/// A printer's instructions: one or more colours, read along a row.
type Instructions extends Mask {
  layout: /[roygbv]+/
}

$printed = 'rgbrgbrgbr'->shapes(Instructions, repeated)->first()
echo $printed.points->map(.value)->join('')   // 'rgb' because rgb, stamped and cut off, prints rgbrgbrgbr
echo $printed.copies                          // 4 because the fourth rgb is cut off after its r

どんなものにも合うセル: blank

入力が壊れていたり不明だったりすることがあります。blank: は、どんな値にも合うセルを指定します。値('?')、正規表現、fn(cell) のいずれかで指定できます。空白のセルはすべてのシンボルに合い、same や repeated を使う場合は比較されないため、押印同士が互いの空白を埋め合います。点の value は、別の押印がその値を知っている場合、埋められた値になります。blank: はマスクではなく呼び出し側に書きます。入力の性質を表すもので、図形の性質ではないからです:

<type name="Instructions" description="A printer's instructions: one or more colours, read along a row." extends="Mask">
  <field name="layout" default="/[roygbv]+/" />
</type>

<let name="cutter" value="'o??v???y'->shapes(Instructions, repeated, blank: '?')->first()" />
<echo value="$cutter.points->count()" /> <!-- 5 because no shorter cutter agrees with every colour that can be read -->
<echo value="$cutter.points->map(.value)->join('')" /> <!-- 'o?yv?' because the y comes from the second copy, and two cells are never read -->
<echo value="'???'->shapes(Instructions, repeated, blank: '?')->first().points->count()" /> <!-- 1 because a barcode of blanks fits one instruction -->
/// A printer's instructions: one or more colours, read along a row.
type Instructions extends Mask {
  layout: /[roygbv]+/
}

$cutter = 'o??v???y'->shapes(Instructions, repeated, blank: '?')->first()
echo $cutter.points->count()                     // 5 because no shorter cutter agrees with every colour that can be read
echo $cutter.points->map(.value)->join('')       // 'o?yv?' because the y comes from the second copy, and two cells are never read
echo '???'->shapes(Instructions, repeated, blank: '?')->first().points->count()   // 1 because a barcode of blanks fits one instruction

組み込みの図形も blank: を受け取り、of: は値や正規表現に加えて fn(cell) も受け取るため、3つすべてが同じようにセルを読みます。$field->shapes(square, of: '#', blank: '?') は ? を # として数えます。

バーコードのリストの行の中から図形を見つけるには、各行に対して適用します:

<type name="Instructions" description="A printer's instructions: one or more colours, read along a row." extends="Mask">
  <field name="layout" default="/[roygbv]+/" />
</type>

<let name="barcodes">```text
    rgbrgbrgbr
    ?rv
    ??b?????
    ```</let>

<echo value="$barcodes->lines()->sum(fn(barcode) => $barcode->shapes(Instructions, repeated, blank: '?')->first().points->count())" />
<!-- 6 because rgbrgbrgbr needs 3 instructions, ?rv needs 2 (vr) and ??b????? needs 1 (b) -->
/// A printer's instructions: one or more colours, read along a row.
type Instructions extends Mask {
  layout: /[roygbv]+/
}

$barcodes = ```text
rgbrgbrgbr
?rv
??b?????
```

echo $barcodes->lines()->sum(fn(barcode) => $barcode->shapes(Instructions, repeated, blank: '?')->first().points->count())
// 6 because rgbrgbrgbr needs 3 instructions, ?rv needs 2 (vr) and ??b????? needs 1 (b)

マスクは layout、symbols と、: で書く独自のメソッドを持ちます。エディタと kscript check は、誤って書かれたマスクを報告し、多くの場合は修正方法も示します。対象は、レイアウトの欠落または空、すべてが any のレイアウト、絵にタブがある場合、高さの異なるレイヤー、一文字より長い、または二度記載された記号、any の代わりの null、same のための引用符付きの 'same'、正規表現レイアウトの隣にある symbols、layout: の代わりの layout =、組み込みの図形への repeated、->matches() や ->find_all() に渡されたマスク(正規表現を取る)、そして ->shapes() がもう受け付けない like: です。レイアウトが使わない記号は警告(KS6026)になり、文字を自分自身に対応させる記号も警告(KS6025)になります。すべての文字はすでに自分自身に一致するためです:

<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 '#'.
}

エディタでは、マスクは言語の一部です。extends ‸ は Mask を提案し、Mask 型の中では layout と入力するとテキストブロックが書かれます。一度書かれると、symbols はレイアウトの文字と any を使って展開されます。symbols: { } の中では、まだリストにない、レイアウトの文字が補完されます。キーのコロンの後では any、same、same(/…/)、値、正規表現、fn(cell) が補完されます。layout: の後ではテキストブロックと正規表現が提案されます。シグネチャのヘルパーは、マスクを書いている間 ->shapes(mask, rotated?, repeated?, blank?) を表示します。レイアウトの文字にカーソルを合わせると、それが何に一致するか、そしてレイアウトで何回使われているかが分かります。また、各文字は一致する対象によって色分けされます。それ自身の文字、テキストのような値、正規表現のような正規表現、fn のような関数、そして any はコメントのように薄く表示されます。

数列を扱う

掛け算: 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() }"

次のものを拡張できます: string、number(または int と float)、bool、list、set、map、fn、date、email、password、handle、uuid、regex、パッケージの値(file や response など)、そして独自の type。独自の型のメソッドからは、$this(レコード)とそのフィールドが $this.name として見えます。メソッドは、他のどの 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: &quot;Age cannot be negative: { $age }&quot;
      }" />
  </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: &quot;Host refused: {$reply.e.message}&quot;
        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 やコンパイル済みのプログラムでも使えます。

値の位置で throw する

throw は文であると同時に値でもあるので、match の分岐、?? の右辺、? : の片側は、値を返す代わりにエラーで停止できます。書き方は文と同じで、型とダブルクォートで囲んだメッセージ、メッセージだけ、型から作ったエラー、捕捉したエラーのいずれかです。値を返すことはないので、どの型が期待される場所にも置け、チェッカーは残りの部分から型を読み取ります。int を返すと宣言した関数は、その match を throw 分岐で終えられます。

<fn name="press" params="display: int, button: string" returns="int">
  <return value="match $button {
      '[oct]' => $display * 8
      '[two]' => $display * 2
      // Every other button stops here, with the button in the message.
      _ => throw Validation &quot;No press for { $button } yet&quot;
    }" />
</fn>

<!-- 32 because [oct] has an arm -->
<echo value="@press(4, '[oct]') catch => $err.message" />
<!-- 'No press for [mem] yet' because no arm fits [mem] -->
<echo value="@press(4, '[mem]') catch => $err.message" />
fn press(display: int, button: string): int {
  return match $button {
    '[oct]' => $display * 8
    '[two]' => $display * 2
    // Every other button stops here, with the button in the message.
    _ => throw Validation "No press for { $button } yet"
  }
}

// 32 because [oct] has an arm
echo @press(4, '[oct]') catch => $err.message
// 'No press for [mem] yet' because no arm fits [mem]
echo @press(4, '[mem]') catch => $err.message

?? の後の throw は左側の値がないときだけ実行されるので、必ず何かを見つける必要がある検索はそれを 1 行で書けます:

<let name="prices" value="{ tea: 3, coffee: 4 }" />

<fn name="price_of" params="item: string, prices: map" returns="int">
  <return value="$prices[$item] ?? throw NotFound &quot;There is no price for { $item }&quot;" />
</fn>

<echo value="@price_of('tea', $prices) catch NotFound => 0" /> <!-- 3 because tea has a price, so the throw never ran -->
<echo value="@price_of('cake', $prices) catch NotFound => 0" /> <!-- 0 because cake has no price, so the throw ran -->
$prices = { tea: 3, coffee: 4 }

fn price_of(item: string, prices: map): int {
  return $prices[$item] ?? throw NotFound "There is no price for { $item }"
}

echo @price_of('tea', $prices) catch NotFound => 0      // 3 because tea has a price, so the throw never ran
echo @price_of('cake', $prices) catch NotFound => 0     // 0 because cake has no price, so the throw ran

? : も同じで、選ばれた側だけが実行されます:$count > 0 ? $count : throw Validation "A basket holds at least one item"。catch のフォールバックに単独の throw を書くと、捕捉したエラーをそのまま再び返します:@load() catch => throw。

複数の値が必要な分岐は、match 文の分岐と同じように、文の { } ブロックを持てます。その return が分岐の値を返し、ブロックからは $it と match の周りの変数が見えます:

<let name="limit" value="2" />
<let name="label">match 3 {
    1 => 'one'
    _ => {
      if $it > $limit {
        // 'more than 2' because 3 is over the limit
        return "more than { $limit }"
      }
      return 'a few'
    }
  }</let>
<echo value="$label" /> <!-- 'more than 2' -->
$limit = 2
$label = match 3 {
  1 => 'one'
  _ => {
    if $it > $limit {
      // 'more than 2' because 3 is over the limit
      return "more than { $limit }"
    }
    return 'a few'
  }
}
echo $label                            // 'more than 2'

分岐の => の後の { は、先にキーとコロンが来るとき(_ => { name: 'Ada' })はマップを開き、それ以外は空の { } も含めて文のブロックを開きます。エディターは両方を同じように扱います。throw の後ではエラー型を、分岐のブロック内では文を補完し、throw とその型に色を付け、こうして投げたエラーがスクリプトの外に出る可能性があるときは警告します(KS5016)。

関数と型のハンドラー

catch を関数やメソッドに付けると、すべての呼び出し元のエラーを処理できます。型に付けると、そのメソッド全体でハンドラーを共有できます。

最も近い一致するハンドラーが最初に実行されます。回復するには null 以外の値を返します。false、0、'' などの値はすべて使えます。単なる throw、null の戻り値、またはハンドラーの末尾に到達した場合は、元のエラーが次の外側のハンドラーに渡されます。

<type name="Directory">
  <field name="fallback" type="string" />

  <fn name="lookup" params="key: string">
    <if !$key->is_blank()>
      <return value="$key" />
    </if>
    <if !$this.fallback->is_blank()>
      <return value="$this.fallback" />
    </if>
    <throw type="Validation">A key is required</throw>
  </fn>
  <catch type="Validation" as="err">
    <return value="$err.message" />
  </catch>
</type>

<let name="directory" value="Directory(fallback: 'guest')" />
<echo value="$directory->lookup('owner')" /> <!-- owner -->
<echo value="$directory->lookup('')" /> <!-- guest -->

<let name="empty" value="Directory(fallback: '')" />
<echo value="$empty->lookup('')" /> <!-- A key is required -->
type Directory {
  fallback: string

  fn lookup(key: string) {
    if !$key->is_blank() => return $key
    if !$this.fallback->is_blank() => return $this.fallback
    throw Validation "A key is required"
  }
} catch Validation as err {
  return $err.message
}

$directory = Directory(fallback: 'guest')
echo $directory->lookup('owner')  // owner
echo $directory->lookup('')       // guest

$empty = Directory(fallback: '')
echo $empty->lookup('')           // A key is required

throw if conditionの中でハンドラーが実行されると、条件が成り立つ場合は現在のエラーを再スローします。payloadブロックを追加すると新しいエラーを発生させられます。エラーをログに記録するだけのハンドラーでは、エラーは伝播したままになります。実行可能なcatchテストでは、メソッドハンドラーがエラーをその型のハンドラーに渡す例や、ログに記録された後のエラーを呼び出し元が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: &quot;{ $arg1 } and { $arg2 }&quot;)" />
</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: を省きます。ここでの value: のように組み込みのエラーに追加したフィールドは、同じファイル内でその型(またはその型が継承する型)を受け取る catch であればドット記法($err.value)で読め、エディターが補完します。エラーが別のファイルで投げられる場合は、角かっこで読みます: $err['value']。どの呼び出し側からも見えて型チェックできるフィールドにするには、エラー型を宣言し、その型を catch します。

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.eur

backoffは呼び出しの間に待機します。whenにはエラーが渡され、再試行するかどうかを返します。そのため、決して成功しない間違いは即座に失敗します: @retry(5, @charge, when: fn(err) => $err.type == 'Timeout')。

順に試す

値によっては複数の候補のどれかである場合があり、それを確かめるには、うまくいくまで各解釈を試すしかありません。try each $value |> first, second は各項目を順にその値で呼び出し、最初の結果を返します。項目には型(NumberEntry($label) を呼ぶとラベルをチェックします)または関数を指定できます:

<fn name="digits" params="text: string" description="The number in text that is only digits." returns="int">
  <if not $text->matches(/^[0-9]+$/)>
    <throw type="Validation">'{$text}' isn't digits</throw>
  </if>
  <return value="$text->to_int()" />
</fn>

<fn name="word" params="text: string" description="The number in a word: one, two or three." returns="int">
  <let name="numbers" value="{ one: 1, two: 2, three: 3 }" />
  <if not $numbers->has($text)>
    <throw type="Validation">'{$text}' isn't a number word</throw>
  </if>
  <return value="$numbers[$text]" />
</fn>

<echo value="try each '12' |> @digits, @word" /> <!-- 12, because @digits reads it -->
<echo value="try each 'two' |> @digits, @word" /> <!-- 2, because @digits throws and @word reads it -->
<echo value="try each 'many' |> @digits, @word, _ => 0" /> <!-- 0, because neither reads it -->

<!-- A longer list goes one item per line, each after a comma. -->
<fn name="reading" params="text: string" returns="int" value="try each $text |>
    @digits,
    @word,
    _ => 0" />

<echo value="@reading('three')" /> <!-- 3, because @word reads it -->
/// The number in text that is only digits.
fn digits(text: string): int {
  if not $text->matches(/^[0-9]+$/) => throw Validation "'{$text}' isn't digits"
  return $text->to_int()
}

/// The number in a word: one, two or three.
fn word(text: string): int {
  $numbers = { one: 1, two: 2, three: 3 }
  if not $numbers->has($text) => throw Validation "'{$text}' isn't a number word"
  return $numbers[$text]
}

echo try each '12' |> @digits, @word          // 12, because @digits reads it
echo try each 'two' |> @digits, @word         // 2, because @digits throws and @word reads it
echo try each 'many' |> @digits, @word, _ => 0 // 0, because neither reads it

// A longer list goes one item per line, each after a comma.
fn reading(text: string): int => try each $text |>
  @digits,
  @word,
  _ => 0

echo @reading('three')  // 3, because @word reads it

Shape(型に合わない値)または Validation をスローした項目は、値を次の項目に渡します。それ以外のエラーは本当の失敗なので、呼び出し元まで伝わります。項目内でのゼロ除算が「これではない」と誤解されることはありません。

どの項目も値を受け付けない場合に備えて、match と同じように最後の行を _ => value にできます。これがない場合、どれも受け付けなければ、値と試したすべての項目を示す Shape エラーが 1 つ発生します: the string 'many' fits none of @digits, @word.

呼び出しの括弧の中では、項目のカンマが呼び出し自体のカンマとして読まれてしまうため、try each を独自の括弧で囲んでください: expect((try each 'one' |> @digits, @word), same: 1)。

型のファクトリは、通常その型から作られた型に対する try each です。

エラー型

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 セクションです。

JSON
{
  "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 のものに上書きされ、マップはフィールドごとにマージされるため、変更する設定だけを書けば十分です:

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 です。プロバイダーがエントリーの出力先を決定し、通常は設定で指定します:

JSON
// 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.で始まります。

YAML
# 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() は、ファイルがあるロケールを一覧表示します。ロケールを設定するルートやミドルウェアは、応答する @view() をそのロケールで描画します。リクエストの希望言語より優先されるため、サイトは独自の Cookie をブラウザーの設定より優先させられます。
  • ページは次の順序でロケールを選びます:パスの接頭辞(翻訳がある場合、/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}付き):

YAML
# 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) @random_generator(seed) @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') { } と Section、Paragraph、List、Table、Figure、Math、Bibliography など;Letter と Invoice;->save ->pages ->words ->markdown ->latex ->html。ドキュメントをご覧ください。
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

シードからの乱数

@random_generator(seed) は、どのマシンでも、どの KScript のバージョンでも、同じシードに対して常に同じ数値を返すジェネレーターを作ります。そのため、これで作ったものは後から再現できます。たとえば、ある人のために作ったパズルや、テストのデータなどです。シードは、少なくとも 16 バイトの 16 進テキストです。ハッシュを使うと適切なシードになります。->hmac($secret) は、秘密を知らない人がそれを推測できないようにします。パーツの間の @char_of(0) は、'ab' + 'c' と 'a' + 'bc' が混ざらないようにします:

<import package="KScript.Math" />

<let name="rng" value="@random_generator(['2026', 'L1', 'player-7']->join(@char_of(0))->hmac('season-secret'))" />
<let name="roll" value="$rng->int(1, 6)" /> <!-- a whole number from 1 to 6 -->
<let name="is_rare" value="$rng->float() &lt; 0.1" /> <!-- true one time in ten -->
<let name="colour" value="$rng->pick(['red', 'green'])" /> <!-- one of the items -->
<let name="order" value="$rng->shuffle([1, 2, 3, 4])" /> <!-- a shuffled copy -->
import KScript.Math

$rng = @random_generator(['2026', 'L1', 'player-7']->join(@char_of(0))->hmac('season-secret'))
$roll = $rng->int(1, 6)                  // a whole number from 1 to 6
$is_rare = $rng->float() < 0.1           // true one time in ten
$colour = $rng->pick(['red', 'green'])   // one of the items
$order = $rng->shuffle([1, 2, 3, 4])     // a shuffled copy

->next() は 0 から 4294967295 までの整数を返し、->float() は 1 未満の小数を返します。ジェネレーターは sfc32 で、シードの最初の 16 バイトを、ビッグエンディアンの 32 ビット語4つとして読み込み、最初に 15 回実行します。そのため、同じ方法でシードされた JavaScript の sfc32 は同じ数値を返します。高速で分散も良好ですが、十分な数の値を見た者は残りを推測できます。秘密には @random_bytes() を使ってください。

文と引数の名前

すべてのパッケージで、文とその引数は同じ規則に従います。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はまず代替モデルで再試行します。

スクリプトの実行方法

kscript は、文のブロックを初回実行時にコンパイルします。そのため、ループや何度も呼び出される関数は、毎回読み直されることなく .NET コードとして実行されます。関数本体やループ本体の中では、そのブロックが宣言する変数は、スコープではなく番号付きのスロットに保持されます。これにより、数値を多用するコード(ナップサック問題、グリッド探索、シミュレーションなど)が数倍速くなります。ループを含む本体、または64回実行された本体は、単一の .NET メソッドに再コンパイルされます。そのため、数値に対する密なループは、さらに約2倍速く実行されます。そのメソッド内のループで、処理が数値とリスト(算術、比較、リスト項目の読み書き、範囲に対する if、while、for)である場合、変数がまさにその型であると仮定する2つ目のコピーも作られ、さらに数倍速くなります。値が別の型だと判明した時点で、同じ文から汎用コピーでループが続きます。fn(x) => ... を ->map() などのメソッドに渡す関数も、コールバックが読む各変数が、コールバック呼び出しの前に1回だけ設定されている限り、スロットを保持します。0..1000000 のような範囲に対するループは、リストを作らずにその範囲を数えます。スクリプトの動作は何も変わりません。同じ値、同じ行と列での同じエラーになります。デバッガーは引き続きすべての文をステップ実行できます。デバッグ中のスクリプトは常にインタープリターで実行されるためです。

これらを比較するための環境変数がいくつかあります。たとえば、特定の方式でのみ発生するバグを報告する場合に使います。KSCRIPT_INTERPRET=1 はコンパイルを無効にします。KSCRIPT_NO_REGIONS=1 はコンパイルしますが、すべての変数をスコープに保持します。KSCRIPT_NO_TREES=1 はスロットを保持しますが、単一の .NET メソッドは決して作りません。KSCRIPT_NO_LOOPS=1 は、ループの2つ目のコピーなしでメソッドを作ります。

ポータブルなスクリプトの書き方

  • \ や / をハードコードする代わりに、@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 は環境変数を読み取ります。
  • 数値は、マシンの言語に関係なく、常に . を小数点として解析および出力されます。