KScript docs
EN

The language

Typed data

type declares the shape of some data, such as an API response. Data that passes through it is checked and turned into a record: a map that knows its type, so the editor completes its fields and a typo like $repo.stras is caught. Fields can also be email, password, handle, uuid or regex, and types can add rules to other types or join them. See Types and validation.

A type is a block with one field per line, 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 reads the field from a key with another name, and owner: User is another type, so the nested data is checked and turned into a User record too. Repo(data) maps a map, a list of maps or JSON text.

Use $.name to look up a value in the current scope. It resolves the same name as $name, including a function parameter, local variable or component field.

Method signatures

A type may declare a method without writing its body: end the fn line with ; where the => or { } would go. That line is a method signature, and another type that extends this one must implement it. A ? after the method's name, as in fn details?(): string;, makes the method optional. The editor and these docs show signature lines in italics, so you can tell them from methods with a body at a glance. The checker reports any missing required method or mismatch in its parameter names, parameter types, or return type.

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

Field lines

A field line is name[?][: type] [from path] [= default | => value]. Each part is optional except the name. A field with a value and no type may write the value straight after the colon, layout: ```text ... ``` or symbols: { '#': '#' }, and takes its type from the value:

<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)'
}
Part What it does
: type A built-in (string, int, float, number, bool, date, list, set, map, fn, any, email, password, handle, uuid, regex), an enum, another type, T[] for a list, set(of: T) for a set of T. Rules can follow in brackets: string(min: 1). Without it the field takes any value.
? after the name The value can be missing or null. This is the one way to mark an optional field, in a type, a model, an error and a job: license?: string, not license: string? (KS6014, with a quick fix). T? is for a type that isn't a field's own, such as a parameter that may be null: fn show(repo: Repo?).
from path Where to read the value when it isn't the field's name: stargazers_count, owner.login, items[0].name. Nested data comes out flat. Quote a path that has spaces.
= default The value when the data has none. The field is then optional.
=> value Works the field out from the other fields (they are $name, $stars and so on) instead of reading it.
/// above the line Shown on hover and in completion.

The type itself takes options in brackets: type Repo(extra: error) { … }. extra says what happens to keys the type doesn't list: drop (the default), keep or error. path: 'data/repo.json' takes the fields from a saved sample of the data: objects become nested types, and keys only some list items have become optional. Lines in the block replace the sampled fields they name. Types can refer to each other in any order and to themselves, and top-level types are exported to scripts that import the file. In a project, give each type its own file (types/repo.kscript, types/owner.kscript) and import the ones it uses: import "owner.kscript" at the top of types/repo.kscript (see One type per file).

A small type can also go on one line, with the fields written like fn parameters: type Point(fields: [x: int, y: int]). kscript convert writes it as a block.

In XML, a type is <type name="Repo"> with a <field name="stars" type="int" from="stargazers_count" /> element for each line, or a fields="..." attribute for the one-line form. Switch the examples to XML to see them.

Typed lists keep their item type

A list declared with an item type, $scores: int[] = [90, 72], keeps it: $scores[0] = '85' stores the number 85, and $scores[1] = 'high' stops with "An item of $scores must be an int". kscript check and the editor report a value written in place that can't be one (KS5012).

Values that may be null

A type written with ? says the value may be null: a function declared fn find(slug: string): Post?, a parameter post: Post?, a variable $post: Post? = ..., or a field license?: string with no default. Reading a field of null, or calling a method on it, stops the script, so kscript check and the editor warn (KS5018) when such a value is used before anything checks it:

<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

Any of these counts as a check: an if, elif or while around the use (if $post != null, if $post, if $post is Post), an else after if $post == null, an if $post == null { return } (or throw, break, continue, exit) above it, and inside one expression $post and $post.title, $post == null or $post.title == '' and $post ? $post.title : ''. A record made just above with the field given, $p = Post(title: 'x', summary: 'y'), has it. An optional list, set or map is empty rather than null, and a model's fields are left to the run, since they come from the database.

Strict types

A file that starts with strict is held to its types. Every value must have a type that the checker can prove, and a type mistake is an error that stops the script before any of it runs:

<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

In a strict file:

  • Type mistakes are errors. A value of the wrong type (KS5005), a field or method the value doesn't have (KS5010, KS5003), a value that doesn't fit its type (KS5012) and a value that may be null used without a check (KS5018) are errors, not warnings. kscript check reports them, and kscript run, serve and test won't start the script. No lint.rules setting turns them off.
  • Parameters say their type (KS6007), or take it from a default: fn greet(who = 'world'). A lambda's parameter takes its type from where it is used, as in [1, 2]->map(fn(n) => $n * 2), or says it: fn(n: number) => $n * 2.
  • Everything else needs a type the checker can prove (KS5020). A variable takes its type from its value ($n = 0, $repo = Repo(name: 'x')) or says it ($n: int = $args[0]). The checker asks you to write the type of an empty list ($names: string[] = []), a list of mixed items, null ($found: Repo? = null), a variable given values of different types, a value read from untyped data such as JSON, a function result it can't work out (fn first(items: list): string) and a field with no type or default.
  • any is a type you can write when a value really can be anything: $data: any = $text->convert(from: json). A value read from it needs a type again: $count: int = $data.count.

strict goes at the top of the file, before anything but imports. In XML it is <strict /> as the first element of <kscript>. To make every script in a project strict, set "strict": true in kscript.json. An imported strict file is checked when it is loaded, so a script that imports it doesn't start either.

Where data meets a type

<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: takes a type: as: Repo, as: int, or as: Repo[] for a list of them, written as a declaration writes it. $repo->type() is 'Repo'. A record still works everywhere a map does, but reading or setting a field the type doesn't have is an error, and setting a field converts the value to the field's type.

->type() reports a list's element type. [1, 2]->type() returns 'number[]', and a list of Repo records returns 'Repo[]'. Mixed lists and untyped empty lists return 'any[]'. Use ->is_a(list) to test whether a value is any kind of list.

When the data doesn't fit, mapping fails with one Shape error that lists every problem with its JSON path:

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

In a catch, $err.problems is a list of { path, field, message } maps. Repo->check($data) returns that list without throwing (empty when the data fits), Repo.fields lists the fields, and Repo->schema() describes the type as JSON Schema.

Types from types

A type can be made from another type, so a parameter or field follows the type it's about instead of repeating it. When the type changes, everything made from it changes too, and the editor completes, links and checks the names.

Form What it is
Post.fields One of Post's field names, written bare: title. A model's own fields (id, its keys) and relations count.
Post.fields(except: [body]) Fewer names: except: drops some, only: keeps some, relations: false drops relations and relations: only keeps only them.
Post.title The type of Post's title field, with its rules. Post.title(max: 80) adds rules on top.
Order.address.postcode A field of a field. Order.lines.item is one item of the list field lines.
Self.fields, Self.title Inside a type or model, the type being declared.
draft|live One of these words, written bare.
int|uuid A value of either type. A word that names a type is the type; quote it to mean the word: card|'email'.
(draft|live)[] Brackets group a union, here to make a list of it.
<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 }"

A value that doesn't fit is reported the way any typed argument is, listing every name it could be:

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

Built-in options are typed the same way, and hover, signature help and the reference show each one's type:

  • A model's hidden: and guarded: take Self.fields[], and key: takes Self.fields. unique: and index: take (Self.fields|Self.fields[])[], which is a name or a group of names.
  • A job's unique_by: takes Self.fields[].
  • ModelUpdate's fields: takes model.fields[], the fields of the model its model: names.
  • A migration's Index(columns:) takes the fields of its table.
  • Methods name the receiver's fields the same way: $post->is_dirty(title) takes Self.fields, ->pick([title, views]) and ->omit([body]) on a record take Self.fields[], and $posts->pluck(title) or ->pluck([title, views]) on a list of records takes Self.fields|Self.fields[]. A name the receiver doesn't have is an error with a suggestion.
  • Options with a few fixed words are word unions: Document(template: plain|paper|report|letter|invoice), ->sort(by:, order?: asc|desc), and Resource(only:), which takes (index|store|show|update|destroy)[]. A word that is also a type's name is quoted in the type, as in echo's format: text|'json'|'markdown', but you still write it bare: format: json.

A model field written status: draft|live is stored as a database enum column.

In a one-of group, a | before the colon separates the names and a | after it is a union: id|slug: int|uuid takes id: or slug:, either an int or a uuid. In a group whose members have different types, a | followed by name: starts the next member: (as: draft|live | template: Template).