KScript ドキュメント
JA

言語

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

言語

関数

<fn name="greet" params="who: string, greeting = 'Hello'">
  <return value="$greeting + ', ' + $who + '!'" />
</fn>
<fn name="square" params="n: number" value="$n * $n" />

<echo>{ @greet('World') } { 4 |> @square() }</echo>
<do>@greet('Kyle')</do>
<spawn fn="background_job" />
fn greet(who: string, greeting = 'Hello') {
  return $greeting + ', ' + $who + '!'
}
fn square(n: number) => $n * $n

echo "{ @greet('World') } { 4 |> @square() }"
@greet('Kyle')
spawn(fn: @background_job)

関数は宣言より前に呼び出すことができ、再帰的に呼び出すこともでき、引数として受け渡すこともできます。@square は関数そのものです。ラムダも値であり、パラメータも同じくそのまま宣言します: $by_age = fn(a, b) => $a.age - $b.age。

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

<let name="urgent" value="$orders->sort(by: .priority)->filter(.paid)" />
<let name="by_shop" value="$orders->group_by(.shop.name)" />
<let name="lines" value="$lines->map(->trim()->upper())" />
$urgent = $orders->sort(by: .priority)->filter(.paid)
$by_shop = $orders->group_by(.shop.name)
$lines = $lines->map(->trim()->upper())

.priorityはfn(order) => $order.priorityです。また、->trim()はfn(line) => $line->trim()です。短い関数は、フィールドとメソッド呼び出しの連鎖ひとつで構成されます。$order.price > 10のような、それ以上の処理が必要な場合は、fn(order) => …と記述してください。

ブロック関数

関数に複数の式が必要な場合は、=>の代わりにブロックを指定します。ブロックには、fn name() { }の本体と同様にステートメントを記述します。returnは関数の結果を返します:

<let name="prices" value="[3, 7, 12]" />

<let name="with_tax">$prices->map(fn(price) {
    $taxed = $price * 1.5          // 4.5 for the first price, because 3 * 1.5 is 4.5
    return $taxed->round()        // 5, because 4.5 rounds up
  })</let>
<!-- $with_tax is [5, 11, 18]: the block ran once for each price -->
$prices = [3, 7, 12]

$with_tax = $prices->map(fn(price) {
  $taxed = $price * 1.5          // 4.5 for the first price, because 3 * 1.5 is 4.5
  return $taxed->round()        // 5, because 4.5 rounds up
})
// $with_tax is [5, 11, 18]: the block ran once for each price

パラメーターの型は呼び出しから決まります。fn(price) => …の場合と同じです。ここでは$priceは数値です。$pricesが数値のリストなので、エディターは$price->の後に数値のメソッドを提案し、with_tax: number[]を表示します。

ブロックはifで判断し、returnで早期に抜けることができます:

<let name="scores" value="[42, 97, 61, 88]" />

<let name="passed">$scores->filter(fn(score) {
    if $score &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'

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

末尾のカンマ

リストの項目の間にはカンマを置きます。最後の項目の後ろのカンマは、リストが項目ごとに1行ずつ書かれている場合にのみ使えます。こうすると、項目を追加しても変更される行は1行だけになります。同じ行で閉じ括弧の前にカンマを置くと、どの種類のリストでもエラーになります:

<let>$label = fn(name,) => $name</let> <!-- Error: Nothing follows this comma. -->
<let>$sizes = [1, 2,]</let> <!-- Error, and the same for { size: 1, } and ->take(2,) -->

<set name="sizes">[
    1,
    2,                                // fine: the list is written one per line
  ]</set>
$label = fn(name,) => $name          // Error: Nothing follows this comma.
$sizes = [1, 2,]                     // Error, and the same for { size: 1, } and ->take(2,)

$sizes = [
  1,
  2,                                // fine: the list is written one per line
]

列挙型と定数

enum は名前付きの値の集合を宣言し、const は変更できない値を宣言します。

<enum name="Size" values="small, medium, large" />
<const name="max_items" value="10" />
<fn name="pack" params="size: Size, gift: bool = false" value="'Packing ' + $size" />

<echo>{ @pack(.large) } { @pack(size: .small, gift) } { Size.medium }</echo>
enum Size { small, medium, large }
const $max_items = 10
fn pack(size: Size, gift: bool = false) => 'Packing ' + $size

echo "{ @pack(.large) } { @pack(size: .small, gift) } { Size.medium }"

long enum は、型がフィールドを1行に1つずつ持つのと同じように、値を1行に1つずつ持てます。カンマは不要です。kscript fmt は行幅に収まる enum を1行に書き、それより長い enum は値を1行に1つずつ書きます:

<enum name="Topping" values="mozzarella
    pepperoni
    mushrooms
    green_peppers
    black_olives
    pineapple
    jalapenos" />
enum Topping {
  mozzarella
  pepperoni
  mushrooms
  green_peppers
  black_olives
  pineapple
  jalapenos
}

型が分かっている場合、enum の値は先頭にドットを付けて書きます。.large は Size.large であり、size は Size だからです(下の 先頭のドット を参照)。型を示すものがない場合は、完全な形で書きます: Size.medium。enum のリストは、その値の配列を取ります。fn pack_all(sizes: Size[]) を使う場合は、@pack_all([.large, .small]) と書きます。組み込みコマンドにも単語のパラメーターがあり、それらの単語はドットを付けずにそのまま書きます。@known_folder(downloads) は home、desktop、documents、downloads、music、pictures、videos、appdata、temp のいずれかを取ります。Size 自体は、各名前からそれ自身への対応を表すマップなので、'large' in Size で値を確認できます。ファイルの最上位にある <const> と <enum> の宣言は、そのファイルをインポートするスクリプトに公開されます。

先頭のドット: .name

ドットで始まる名前は、その場所が期待する型のメンバーを指します。周囲のコードですでに型が示されている場合は、型名を書かずに済みます:

<enum name="NoteColor" values="yellow, pink, blue, red" />

<type name="Note">
  <field name="text" type="string" />
  <field name="color" type="NoteColor" default=".yellow" />

  <fn name="label" value=".text->upper()" />
  <fn name="urgent" value=".color == .red" />
  <fn name="kind" returns="string" value="match .color {
      .red => 'Urgent'
      _ => 'Normal'
    }" />
</type>

<fn name="paint" params="color: NoteColor" returns="string" value="&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などのように、その値が何を表すかが表示されます。