Инструкции
У каждой инструкции есть запись в XML. kscript convert преобразует одно в другое:
| .kscript | XML |
|---|---|
$n = 3 (впервые) |
<let name="n" value="3" /> |
$n = 4, $total += 1 (после) |
<set name="n" value="4" />, <set name="total" op="+=" value="1" /> |
const $config = { retries: 3 } |
<const name="config" value="…" /> |
$count: int = $raw |
<let name="count" type="int" value="$raw" /> |
@greet('Hi') |
<do>@greet('Hi')</do> |
echo "Hello, { $name }" |
<echo>Hello, { $name }</echo> |
echo $list[1], echo(format: json) $data |
<echo value="$list[1]" /> |
if a { } elif b { } else { } |
<if test>, <elif test>, <else> |
if a => return, elif b => @f(), else => echo 'c' |
то же самое, с одной инструкцией внутри |
for item in $list { }, for key, value in $map { } |
<for each in> |
for item at i in $list { } |
<for each="item" at="i" in="$list"> |
while test { }, break, continue |
<while test>, <break/>, <continue/> |
match $x { 1, 2 => { }, _ when $x > 9 => { }, _ => { } } |
<match value>, <case is>, <case when>, <default> |
fn greet(who: string, hi = 'Hello') { } |
<fn name="greet" params="who: string, hi = 'Hello'"> |
fn double(x: int) => $x * 2 |
<fn name="double" params="x: int" value="$x * 2" /> |
return $x, exit 1 |
<return value="$x" />, <exit code="1" /> |
@load() catch NotFound => 'Missing' |
То же выражение в атрибутах выражений XML |
try { } catch NotFound as err { } catch err { } finally { } |
<try> с <catch type as> и <finally> внутри (when test добавляет проверку к catch) |
throw Validation "Bad {$x}" |
<throw type="Validation">Bad {$x}</throw> |
import KScript.Math as math |
<import package="KScript.Math" as="math" /> |
import "lib/s.kscript" as s |
<import path="lib/s.kscript" as="s" /> |
import slugify from "lib/s.kscript" |
<import path="lib/s.kscript" names="slugify" /> |
enum Size { small, medium, large } |
<enum name="Size" values="small, medium, large" /> |
type Repo(extra: error) { … } |
<type name="Repo" extra="error"> с <field> внутри |
stars: int from stargazers_count (в типе) |
<field name="stars" type="int" from="stargazers_count" /> |
topics?: string[] = [], label => $name + '!' |
<field name="topics?" type="string[]" default="[]" />, <field name="label" value="$name + '!'" /> |
type Admin with [User, Auditable] { … } |
<type name="Admin" with="User, Auditable"> |
type Age with [int] { min: 0; max: 150 } |
<type name="Age" with="int" min="0" max="150" /> |
validate: $value > 0, 'too small' (в типе) |
<validate test="$value > 0" message="too small" /> |
normalize: $value->lower() (в типе) |
<normalize value="$value->lower()" /> |
value: .group(1)->to_int() (в типе) |
<value value=".group(1)->to_int()" /> |
fn area() => $w * $h (в типе) |
<fn name="area" value="$w * $h" /> внутри <type> |
Строка поля в блоке type — это name[?][: type] [from path] [= default | => value]; заключите путь в кавычки, если в нём есть пробелы. См. Строки полей, чтобы узнать, что делает каждая часть. В блоке типа также могут быть строки правил (min:, max:, pattern:, one_of:, not:, parse:, validate:, normalize: и value:), методы fn и один блок construct({ fields }) { statements }, поля которого — то, что может передать вызывающая сторона. В render компонента можно указать, где он рисуется вместо параметров (fn render(window)); это surface="window" на <fn>, а компонент рисуется оператором с его именем (NoteCard(title: 'Milk'), <NoteCard title="Milk" />). Строка вида max: int по-прежнему является полем: значение правила — это значение, а не тип. Правила описаны в разделе Типы и проверка.
Любое другое имя — это элемент: name(attribute: value, ...) "text" { children }, каждая часть необязательна.
<input into="old_dir">Move files from: </input>
<Row gap="8" wrap="yes">
<Button variant="primary" on_click="$playing">{ $playing ? 'Pause' : 'Play' }</Button>
</Row>input(into: old_dir) "Move files from: "
Row(gap: 8, wrap) {
Button(variant: primary, on_click: $playing) "{ $playing ? 'Pause' : 'Play' }"
}