KScript docs
EN

The language

Functions

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

Functions can be called before they are declared, recurse, and be passed around: @square is the function itself. Lambdas are values too, and declare their parameters the same bare way: $by_age = fn(a, b) => $a.age - $b.age.

A short function reads a field or calls a method on each item. It starts with . or ->, which stands for the item, and works anywhere a function goes:

<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 is fn(order) => $order.priority, and ->trim() is fn(line) => $line->trim(). A short function is one chain of fields and method calls. For anything more, such as $order.price > 10, write fn(order) => ….

Block functions

When a function needs more than one expression, give it a block instead of =>. The block holds statements, just like the body of fn name() { }, and return gives the function's result:

<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

The parameters get their types from the call, as they do in fn(price) => …: $price is a number here because $prices is a list of numbers, so the editor suggests number methods after $price-> and shows with_tax: number[].

A block can decide with if and leave early with 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]

Functions that take two parameters, such as ->reduce(fn(total, item), initial?), take a block in the same way:

<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

A block that ends without return gives null, which suits ->each(), where only what the block does matters. Everywhere else the call uses what the block gives, so a block that is empty or never returns a value is an error, in the editor, in kscript check and when it runs:

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

The block can read and change the variables around it, and the variables it makes stay inside it:

<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

A block function is a value like any other function, so it can be kept in a variable and called: $greet = fn(name) { … }, then $greet('Ada'). Block functions work in .kscript files. An XML attribute can't hold statements, so there you write fn(n) => value, or declare a <fn> and pass it as @name. A database query's condition (->where(fn(u) => $u.age >= 18)) is turned into SQL, so it must stay a single expression.

A parameter declared as any accepts any value. A method call on it uses the value's actual type. For example, $key->trim() trims a string, raises an error for a number, and calls the type's own trim() when one exists. Write fn trim_key(key: string) => $key->trim() for a string normalizer. The editor can then infer a string return type.

Named arguments

Any call can name its arguments, in any order: built-in commands, methods, your own fn functions and lambdas.

<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]) }"

Positional arguments fill parameters in order, and each name: value fills the parameter of that name, so you can skip optional ones in between. A positional argument written after named ones fills the first parameter still empty, which is how @join_path(base: $folder, [...]) reads. Naming a parameter that doesn't exist, or giving one twice, is an error with a "did you mean" hint. The editor completes parameter names after ( or ,.

One of a group

Some parameters are alternatives: a call passes exactly one of them. Join their names with |:

<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) is an error ("@file() takes add: or remove:, not both"), and so is @file(4) ("needs add: or remove:"). kscript check reports both before the code runs. The members of a group are always named, and the ones a call doesn't pass are null in the body. Passing null (or false) for one counts as not passing it.

Written Means
add|remove: file Exactly one of add and remove, both files.
at|after?: date At most one: the ? after the last name lets a call pass neither.
text: string | template: Template Exactly one, each with its own type.
(text: string | template: Template)? The same in brackets, with ? for at most one.

A group whose members have different types needs brackets when other parameters sit beside it, so it's clear where the group ends: fn send(to: email, (text: string | template: Template), at|after?: date). Brackets are allowed around any group. A member can't have a default of its own.

Built-in commands use groups too. @api() takes one of post:, put:, patch: and delete:, and a job's ->dispatch() takes delay: or at:, not both. Signature help shows a group as one slot, completion stops offering the other members once one is written, and the editor gives a group's names one colour.

Flags

A true/false parameter can be written as a bare word: recursive sets it to true and not recursive to false, so calls read like a sentence.

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

Writing overwrite: true or recursive: false works too, but the editor suggests the flag instead (KS6024), with a fix that rewrites it as overwrite or not recursive.

Argument types

Each argument must be a value its parameter takes. One rule decides this, and the editor, kscript check and the run all apply it, so they report the same mistake in the same words before anything runs:

<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.
The parameter takes It also takes It never takes
text (string) a number or true/false, written as text a list, a map or a function
a number (number, int, float) text that reads as a number, such as '3' other text, true/false, a list, a map or a function
true or false (bool) text that reads as true or false, such as 'yes' a number, a list, a map or a function
a list, a map or a function anything else

A { } is always a map, even when it is written over two lines after an argument's name, so least: { and } on the next line is a map, not a block. The editor offers to replace least: { } with least.

Trailing commas

A comma goes between items. After the last item, a comma is allowed only when the list is written one item per line, so adding an item changes one line. Before the closing bracket on the same line it is an error, in every kind of list:

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

Enums and consts

enum declares a set of named values, and const a value that can't change.

<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 }"

A long enum can hold one value per line, with no commas, the way a type holds one field per line. kscript fmt puts an enum that fits in the line width on one line, and a longer one one value per line:

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

Where the type is known, write an enum's value with a leading dot: .large is Size.large, because size is a Size (see A leading dot below). Where nothing says the type, write it in full: Size.medium. A list of an enum takes an array of them: with fn pack_all(sizes: Size[]), write @pack_all([.large, .small]). Built-in commands have word parameters too, and those words are written bare, without the dot: @known_folder(downloads) takes home, desktop, documents, downloads, music, pictures, videos, appdata or temp. Size itself is a map from each name to itself, so 'large' in Size checks a value. Top-level <const> and <enum> declarations are exported to scripts that import the file.

A leading dot: .name

A name that starts with a dot is a member of whatever the place it is written expects. It saves writing the type's name when the code around it already says it:

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

What the dot means is read in this order:

  1. A typed slot. An argument, a field's default, a comparison, a match arm, a list item or a typed fn's return that takes an enum: .pink is that enum's value. A slot that takes a function, as ->map(.name) does, reads that field of each item.
  2. The item, inside a for loop. In for account in $accounts { ... }, .id is $account.id and .name = 'Ann' sets the item's field. In nested loops the innermost item that has the name wins, so the inner loop's .label and the outer loop's .id can sit side by side. A while loop has no item, so it adds nothing.
  3. The record, inside its own methods. In a type, model, extend or component method, .text is the record's own field and .save() calls its own method. .count += 1 and .color = .red set its fields.
  4. None of these. $c = .red is an error, .red needs a type here, and the quick fix writes it in full: NoteColor.red.

The slot is tried first. Inside a method, @paint(color: .red) is NoteColor.red even if the record has a field called red. A name the enum doesn't have is the record's own, so fn current(): NoteColor => .color returns the record's color. A name neither has is an error.

A loop's item comes before the record. In a method that loops over rows that have a title, .title is the row's, and the record's own is written $this.title; the checker says so and offers that fix.

<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 }"
  }
}

Typing . where a value goes suggests exactly what fits: the enum's values in a typed slot, the loop item's fields (then the outer loops' and the record's) inside a loop, or the record's fields and methods inside a method. Hovering a value shows what it stands for, such as NoteColor.pink.

Edit this page on GitHub