KScript documentazione
IT

Lingua

Tradotto automaticamente dall’inglese, che è la versione originale.

Il linguaggio KScript

Introduzione

Questo è il riferimento per gli script di KScript 2: il linguaggio di base che ogni script e ogni pagina usa, i pacchetti da importare per il resto e alcuni suggerimenti per gli script che girano su ogni sistema operativo. Se non conosci ancora KScript, Primi passi è una lettura più graduale per iniziare.

Variabili e output

<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

Una mappa, o una lista di mappe, da sola in echo viene stampata come JSON indentato, colorato in un terminale (a meno che NO_COLOR non sia impostato). Dentro un testo resta su una riga. echo(format: json) riformatta il testo JSON, e ->convert(to: json) dà JSON compatto.

Le variabili appartengono al blocco in cui sono dichiarate. {{ e }} sono parentesi graffe letterali.

Una variabile dichiarata con un tipo lo mantiene. Ogni assegnazione successiva viene convertita a quel tipo, come il primo valore, altrimenti lo script si ferma lì:

<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

Dopo questo, $count = 'many' è un errore nell'editor, e l'esecuzione si ferma su di esso: $count must be an int, but got the string 'many'.

"Double quotes" inseriscono espressioni in { } dopo echo, nelle assegnazioni, nei valori di ritorno e negli argomenti delle chiamate. In .kscript, KS6019 individua i riferimenti nudi e propone di racchiuderli tra parentesi graffe. 'Single quotes' mantengono il testo esattamente come scritto, quindi il testo senza nulla da riempire va lì dentro (KS6020 suggerisce la modifica). Anche il testo tra virgolette dopo echo viene stampato così com'è, con i suoi spazi: echo " - { $item }" stampa i due spazi. In XML, il testo tra <echo> e </echo> viene privato degli spazi iniziali e finali e perde il rientro comune alle sue righe, mentre i valori inseriti al suo interno non vengono toccati, con l'eccezione che un valore vuoto non lascia spazi residui e il testo non termina mai con un'interruzione di riga.

<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

Un { } tra virgolette doppie contiene sempre un'espressione, qualunque cosa inizi: una variabile, un comando, un tipo ({ Order->count() }), un numero o una somma tra parentesi. Il testo con parentesi graffe proprie, come un percorso ('/users/{id}'), un pattern ('\d{3}'), CSS o testo di traduzione ('Hello {name}'), va tra virgolette singole, oppure le graffe si raddoppiano: "/users/{{id}}". Il testo passato a @sql è l'unica eccezione: le sue { } vengono inviate come parametri, mai incollate (vedi Dati).

Espressioni

+ - * / % **, == != (debole: '3' == 3), === !== (stretto), < <= > >=, and or not, ??, ?., a ? b : c, in, letterali di lista [1, 2] e di mappa { name: 'Joan' } (una lista diventa un insieme con as set), $p.name, $list[0] (gli indici negativi contano dalla fine), intervalli 0..10 e 0..100 step 5 (fine esclusa, anche con un passo come 0.1) e 1..=10 (fine inclusa), match $x { 1 => 'one', _ => 'other' }, ->method(), |> e fn(x) => …. Scrivi and e or per combinare condizioni. Il prefisso ! ha la stessa precedenza e la stessa veridicità di not, quindi !$ready, ! $ready e not $ready sono equivalenti. Usalo su un campo (!$user.active), su un'intera condizione (if !($ready and $open) { … }) o su un'interpolazione ("{ ! null->is_null() }"). La forma null->!is_null() nega il risultato del metodo prima del successivo anello della catena. XML prevede anche una parola per ogni confronto (lt le gt ge eq ne), da usare dentro attributi tra virgolette, dato che XML non accetta un < grezzo lì; i tag di apertura abbreviati accettano < e > così come sono scritti. In un file .kscript le parole vengono segnalate (KS6012) e kscript check --fix scrive i simboli.

Quando confronti un numero con una stringa usando <, <=, > o >=, KScript confronta numericamente se la stringa può essere letta come numero. Se la lettura fallisce, il confronto restituisce false. I confronti si concatenano come in matematica, come mostra la sezione Matematica. Due date sono uguali con == solo quando sono lo stesso istante, secondi compresi.

Matematica

La matematica quotidiana ha un simbolo proprio, e ciascuno funziona allo stesso modo in uno script, in un modello e in una query di database. + somma, - sottrae, * moltiplica e / divide, mantenendo la frazione. ~/ divide in numeri interi, arrotondando per difetto. % dà il resto, che conserva il segno del numero a sinistra, %% si avvolge come un orologio, e ** eleva a potenza:

<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

Gli operatori si legano in quest'ordine, dal più stretto, quindi 2 + 3 * 4 vale 14 perché * si lega prima di +:

Livello Operatori Raggruppamento
1 . -> ?. ( ) [ ] da sinistra a destra
2 ** da destra a sinistra: 2 ** 3 ** 2 è 2 ** 9, 512
3 -x +x -2 ** 2 vale -4 perché ** ha la precedenza, quindi scrivi -(2 ** 2) oppure (-2) ** 2 (KS6023)
4 * / ~/ % %% da sinistra a destra
5 + - da sinistra a destra
6 .. ..= step un intervallo per espressione
7 |> da sinistra a destra
8 < <= > >= in una catena in una direzione: 0 <= $n < 10
9 == != === !== uno per confronto: per unirne di più usa and
10 not, and, or, ??, a ? b : c

% e %% differiscono solo quando un segno è negativo. Il resto conserva il segno del lato sinistro, come C# e JavaScript. Il modulo prende il segno del lato destro, quindi si avvolge: un'ora prima di mezzanotte è 23, non -1. Usa %% per gli orologi, i giorni della settimana e le posizioni in una lista che si avvolgono alla fine:

<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

~/ arrotonda per difetto, non verso zero, quindi si abbina a %%: ($a ~/ $b) * $b + $a %% $b è sempre $a. Funziona anche con durate e denaro, e restituisce un numero semplice:

<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

// inizia un commento, quindi non può essere una divisione intera. $hours = $minutes // $per_hour lascia $minutes invariato, e KS6022 lo segnala con una correzione che scrive ~/.

I confronti che vanno nella stessa direzione si concatenano come in matematica, così un controllo di intervallo si legge come si dice. Ogni valore nel mezzo viene calcolato una sola volta, e la catena si ferma al primo confronto falso:

<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

Una catena va in una sola direzione. 1 < $n > 0 è un errore perché non dice nulla su come si confrontano 1 e 0, quindi scrivi 1 < $n and $n > 0. == e != non si concatenano: $a == $b == $c confronterebbe vero o falso con $c, quindi scrivi $a == $b and $b == $c. Le parentesi interrompono una catena, quindi (1 < $n) == true confronta il risultato. Una catena funziona anche in una query di database: Person->where(fn(person) => 18 <= $person.age < 65) richiede age >= 18 AND age < 65. ->between() non esiste più, e il suo errore indica la catena da scrivere.

.. crea un intervallo che termina prima della fine, il che è adatto a contare da 0 e alle posizioni in una lista. ..= include anche la fine, il che è adatto a contare da 1. Passando sopra uno dei due si vede dove l'intervallo inizia e finisce:

<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

Come .., un intervallo conta all'indietro quando la fine è minore dell'inizio, quindi 3..=1 equivale a [3, 2, 1] e 1..=0 equivale a [1, 0]. Per contare fino a un valore che può essere 0, come in 1..($count + 1), usa .., che non produce valori quando $count è 0.

^ non è l'elevamento a potenza in KScript (in C# e JavaScript è un operatore bit a bit), quindi 2 ^ 10 è un errore la cui correzione scrive 2 ** 10.

I bit si manipolano con un metodo, ->bits(), invece che con simboli, perché & e | si confondono facilmente con and e or. Agisce un passo alla volta, su numeri interi:

<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

&, un singolo |, << e >> tra due valori sono errori che indicano la chiamata ->bits() da scrivere, mentre & e | offrono una correzione che scrive and o or, che di solito è ciò che si intendeva.

($hour + 24) % 24 era il vecchio modo per arrotondare un numero. KS6021 suggerisce $hour %% 24, che funziona anche per i numeri sotto -24.

+=, -=, *=, /=, ~/=, %=, %%=, **= e ??= modificano una variabile sul posto: $total += 5 equivale a $total = $total + 5. Gli spazi attorno a un operatore sono a tua scelta, ma uno spazio al suo interno lo spezza: 2 * * 10 è un errore che indica **, e la correzione rapida rimuove lo spazio.

L'editor elenca le variabili dopo un operatore e uno spazio, prima quelle del tipo del lato sinistro, e passando sopra un operatore si vede cosa fa.

Usa expression as Type per una conversione controllata, per esempio $text as int. Il tipo di destinazione può anche essere un record, un enum o un tipo raffinato dichiarato. Conversioni controllate

Flusso di controllo

<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'
  _ => {
    // …
  }
}

Ogni ramo di un match è pattern => result. Il pattern è un valore o più valori (2, 3 =>), oppure _ per qualsiasi cosa, e può essere seguito da un test when (_ when $it > 9 =>). Il risultato è un'istruzione sulla stessa riga, oppure un blocco { } di istruzioni. Un match usato come valore scrive i suoi rami allo stesso modo, con un valore come risultato di ciascuno: $label = match $choice { 1 => 'one', 2, 3 => 'a few', _ => 'many' }. I rami sono separati da un a capo o da una virgola, e viene scelto il primo ramo che corrisponde. In XML i rami sono <case is="2, 3">, <case when="…"> e <default>.

If su una riga

Quando un if esegue una sola operazione, scrivilo su una riga: la condizione, =>, poi l'istruzione. Somiglia ai rami di un match e a fn(name) => ..., e tiene i controlli di guardia e le uscite anticipate su una sola riga ciascuno.

<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 e else hanno la stessa forma, un ramo per riga:

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

L'istruzione dopo => può essere qualsiasi cosa che stia su una riga: una chiamata (if $continue => @method_call()), un'assegnazione (if $count > 2 => $label = 'many'), echo, return, break, continue, throw o exit. Finisce dove finisce la riga, quindi if $ready => echo 1; echo 2 stampa 2 in entrambi i casi. Per più istruzioni, o per un ciclo, un match o un altro if, usa un blocco { }. Il primo => fuori dalle parentesi chiude la condizione, quindi fn(fruit) => ... dentro una chiamata e @load() catch => false restano parte di essa. if $ready => { } è un errore: un blocco segue la condizione senza una freccia. XML non ha una forma su una riga, quindi kscript convert scrive <if> con l'istruzione dentro.

In XML, <if>, <elif>, <while> e <match> prendono la loro espressione direttamente nel tag di apertura: <if $user.is_logged_in> è l'abbreviazione di <if test="$user.is_logged_in">, e <match $choice> lo è di <match value="$choice">. Entrambe le forme funzionano negli script e nelle pagine; usa quella lunga quando il tag ha altri attributi. Dentro il tag, <, > e le virgolette non richiedono escape, quindi <if $n > 3> e <if $name == "Joan"> funzionano. Un > chiude il tag a meno che non abbia uno spazio su entrambi i lati e altro della condizione dopo di sé, quindi scrivi $n > 3, non $n>3. kscript convert e lo snippet <if> dell'editor usano la forma abbreviata.

I tag abbreviati rendono un file .ks.xml markup KScript anziché XML rigoroso: il parser, il formattatore e il supporto dell'editor di KScript li leggono, ma gli strumenti XML generici come xmllint li rifiuteranno. Usa test="…" se un file deve restare XML valido.

Ritorni anticipati invece di else

Dentro una funzione o un ciclo, termina un ramo in anticipo invece di scrivere else: return in una funzione, continue o break in un ciclo (agiscono solo sul ciclo della stessa funzione, mai su quello che l'ha chiamata). Il percorso principale resta così al margine sinistro e ogni caso particolare viene gestito per primo.

<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 e l'editor segnalano else e elif con KS6001 in quel caso, e in cima a uno script quando ogni ramo precedente termina già con return, break, continue, throw o exit. La correzione rapida rimuove il else (o trasforma elif in un if separato) e, quando la catena è l'ultima istruzione della funzione o del ciclo, aggiunge per te return o continue. Pagine, blocchi <live> e for…else (per una lista vuota) non vengono segnalati, perché non c'è nulla da restituire. KS6001 viene dallo standard predefinito, kscript:recommended. Per disattivarlo in un progetto, imposta "lint": { "rules": { "KS6001": "off" } } in kscript.json (o in uno standard che i tuoi progetti condividono).

Codice inutilizzato

kscript check e l'editor segnalano anche il codice che non fa nulla. Nell'editor appare in chiaro, con correzioni rapide per eliminarlo o per rinominarlo con un _ iniziale, che lo marca come inutilizzato di proposito (i nomi _ non vengono mai segnalati).

Codice Cosa viene segnalato
KS6002 Una funzione che nulla chiama. La funzione main di uno script non viene mai segnalata, perché viene eseguita da sola. Contano le chiamate dagli altri file del progetto: una funzione di libreria che un altro script importa e chiama, un controller che un file di route indica (to="people.show", oppure <Resource to="people"> per il suo index, store, show, update e destroy), e il middleware indicato in kscript.json. Una funzione che chiama solo se stessa è comunque inutilizzata.
KS6003 Una variabile, una costante o una variabile di ciclo il cui valore non viene mai letto, incluso quella che viene solo impostata. Le costanti di primo livello di uno script vengono esportate come le sue funzioni, quindi risultano usate quando un file che le importa le usa. Nelle pagine vengono controllate solo le variabili proprie di una funzione, perché un layout o un componente potrebbe leggere le altre.
KS6004 Un parametro di funzione che il corpo non legge mai. Per una lambda, solo i parametri dopo l'ultimo che legge, perché è il chiamante a decidere cosa riceve: scrivi fn(_y) => ... per mantenere la posizione.
KS6005 Un import che nessuno usa: un alias as, un nome in names="...", un intero script, oppure un pacchetto di cui non compare nessun elemento, comando, metodo o variabile.
KS6006 Non è codice inutilizzato, ma un suggerimento di stile: una lista di nomi scritta come una sola stringa in un file .kscript (Middleware(use: "log, cors")). Scrivila come array, use: [log, cors]; la correzione rapida lo fa per te. Negli attributi XML il testo è semplice, quindi use="log, cors" va bene lì.
KS6008 Nemmeno questo è codice inutilizzato: uno script in un progetto che dichiara un secondo tipo, modello, enum o tipo di errore. Ognuno va nel proprio file, con il nome del tipo, e viene importato dove è usato; l'avviso indica dove spostarlo (types/order-status.kscript). Il tipo che dà il nome al file resta lì. Gli script fuori da un progetto non vengono controllati.

Il progetto è la cartella con il kscript.json più vicino e tutto ciò che sta sotto (le cartelle nascoste, bin, obj e node_modules vengono saltate). Uno script fuori da un progetto viene controllato rispetto agli altri file della sua cartella. Una funzione che fa parte di un'API usata dall'esterno del progetto può dichiararlo con @public nel suo commento di documentazione:

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

Come KS6001, questi provengono dallo standard predefinito, kscript:recommended, come avvisi (kscript:strict li trasforma in errori). Un progetto può modificare o disattivare ciascuno in kscript.json, per esempio "lint": { "rules": { "KS6004": "off" } }.

Funzioni

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

Le funzioni possono essere chiamate prima di essere dichiarate, possono ricorrere su sé stesse ed essere passate come valori: @square è la funzione stessa. Anche le lambda sono valori e dichiarano i parametri nello stesso modo semplice: $by_age = fn(a, b) => $a.age - $b.age.

Una funzione breve legge un campo o chiama un metodo su ogni elemento. Inizia con . o ->, che rappresenta l'elemento, e funziona ovunque sia richiesta una funzione:

<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 equivale a fn(order) => $order.priority, e ->trim() equivale a fn(line) => $line->trim(). Una funzione breve è una sola catena di campi e chiamate di metodo. Per qualcosa di più, come $order.price > 10, scrivi fn(order) => ….

La funzione main

Uno script può tenere il proprio lavoro in una funzione chiamata main. Quando lo script è quello eseguito, main viene eseguita da sola una volta eseguito il codice di primo livello, quindi il codice di primo livello prepara le cose e main fa il lavoro:

<!-- 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!
  }
}
  • Il suo parametro è facoltativo. fn main() viene eseguita allo stesso modo; fn main(args: list) riceve gli argomenti dello script, la stessa lista di $args. Un secondo parametro richiede un valore predefinito, dato che non viene passato nient'altro: fn main(first, second) è un errore (KS5004).
  • Ciò che restituisce è il codice di uscita. Un numero intero che main restituisce termina lo script con quel codice, come fa exit, così un job di shell o CI può capire com'è andata. Qualsiasi altro valore, o niente, dà codice di uscita 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
}
  • Solo lo script eseguito. main appartiene allo script che esegui: kscript run, kscript greet.kscript, un programma compilato, il debugger e il comando Esegui dell'editor la chiamano tutti. Uno script importato esegue il suo codice di primo livello, ma non la sua main, quindi una libreria può conservare una main per provarla da sola.
  • Solo al primo livello. Una fn main dentro un'altra funzione, un tipo o un file di test è una funzione normale.
  • Mai inutilizzata. Nulla chiama main, quindi kscript check e l'editor non la segnalano mai come inutilizzata (KS6002). Avvisano quando anche il codice di primo livello la chiama, perché in quel caso verrebbe eseguita due volte (KS5019); rimuovi la chiamata, come fa la correzione rapida.

app.main_function in kscript.json le dà un altro nome, per ogni script del progetto:

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

Funzioni a blocco

Quando una funzione ha bisogno di più di un'espressione, usa un blocco al posto di =>. Il blocco contiene istruzioni, proprio come il corpo di fn name() { }, e return restituisce il risultato della funzione:

<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

I parametri ricevono i loro tipi dalla chiamata, come accade in fn(price) => …: $price qui è un numero perché $prices è una lista di numeri, quindi l'editor suggerisce i metodi dei numeri dopo $price-> e mostra with_tax: number[].

Un blocco può decidere con if e uscire in anticipo con 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]

Le funzioni che ricevono due parametri, come ->reduce(fn(total, item), initial?), accettano un blocco allo stesso modo:

<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

Un blocco che termina senza return restituisce null, cosa utile per ->each(), dove conta solo ciò che il blocco fa. In tutti gli altri casi la chiamata usa ciò che il blocco restituisce, quindi un blocco vuoto o che non restituisce mai un valore è un errore, nell'editor, in kscript check e all'esecuzione:

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

Il blocco può leggere e modificare le variabili intorno a sé, e le variabili che crea restano al suo interno:

<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

Una funzione a blocco è un valore come qualsiasi altra funzione, quindi può essere salvata in una variabile e chiamata: $greet = fn(name) { … }, poi $greet('Ada'). Le funzioni a blocco funzionano nei file .kscript. Un attributo XML non può contenere istruzioni, quindi lì scrivi fn(n) => value, oppure dichiari una <fn> e la passi come @name. La condizione di una query di database (->where(fn(u) => $u.age >= 18)) viene trasformata in SQL, quindi deve restare una singola espressione.

Un parametro dichiarato come any accetta qualsiasi valore. Una chiamata di metodo su di esso usa il tipo effettivo del valore. Ad esempio, $key->trim() elimina gli spazi da una stringa, segnala un errore per un numero e chiama il trim() del tipo, quando esiste. Scrivi fn trim_key(key: string) => $key->trim() per un normalizzatore di stringhe. L'editor può poi dedurre un tipo di ritorno stringa.

Argomenti con nome

Ogni chiamata può nominare i propri argomenti, in qualsiasi ordine: comandi integrati, metodi, le tue funzioni fn e le lambda.

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

Gli argomenti posizionali riempiono i parametri in ordine, e ogni name: value riempie il parametro con quel nome, così puoi saltare quelli opzionali in mezzo. Un argomento posizionale scritto dopo quelli con nome riempie il primo parametro ancora vuoto, ed è così che si legge @join_path(base: $folder, [...]). Nominare un parametro che non esiste, o darne uno due volte, è un errore con un suggerimento del tipo "intendevi". L'editor completa i nomi dei parametri dopo ( o ,.

Uno di un gruppo

Alcuni parametri sono alternative: una chiamata ne passa esattamente uno. Unisci i loro nomi con |:

<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) è un errore ("@file() accetta add: o remove:, non entrambi"), e lo è anche @file(4) ("richiede add: o remove:"). kscript check segnala entrambi prima che il codice venga eseguito. I membri di un gruppo sono sempre nominati, e quelli che una chiamata non passa valgono null nel corpo. Passare null (o false) per uno di essi equivale a non passarlo.

Scritto Significa
add|remove: file Esattamente uno tra add e remove, entrambi file.
at|after?: date Al massimo uno: il ? dopo l'ultimo nome permette a una chiamata di non passarne nessuno.
text: string | template: Template Esattamente uno, ciascuno con il proprio tipo.
(text: string | template: Template)? Lo stesso tra parentesi, con ? per al massimo uno.

Un gruppo i cui membri hanno tipi diversi richiede le parentesi quando accanto ci sono altri parametri, così è chiaro dove finisce il gruppo: fn send(to: email, (text: string | template: Template), at|after?: date). Le parentesi sono ammesse attorno a qualsiasi gruppo. Un membro non può avere un valore predefinito proprio.

Anche i comandi integrati usano i gruppi. @api() accetta uno tra post:, put:, patch: e delete:, e il ->dispatch() di un job accetta delay: o at:, non entrambi. La guida alla firma mostra un gruppo come un unico slot, il completamento smette di proporre gli altri membri una volta scritto uno, e l'editor assegna un colore unico ai nomi di un gruppo.

Flag

Un parametro vero/falso può essere scritto come parola singola: recursive lo imposta a vero e not recursive a falso, così le chiamate si leggono come una frase.

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

Scrivere overwrite: true o recursive: false funziona comunque, ma l'editor suggerisce invece il flag (KS6024), con una correzione che lo riscrive come overwrite o not recursive.

Tipi degli argomenti

Ogni argomento deve essere un valore che il suo parametro accetta. Una sola regola lo decide, e l'editor, kscript check e l'esecuzione la applicano tutti, quindi segnalano lo stesso errore con le stesse parole prima che qualcosa venga eseguito:

<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.
Il parametro accetta Accetta anche Non accetta mai
testo (string) un numero o vero/falso, scritto come testo una lista, una mappa o una funzione
un numero (number, int, float) testo che si legge come numero, come '3' altro testo, vero/falso, una lista, una mappa o una funzione
vero o falso (bool) testo che si legge come vero o falso, come 'yes' un numero, una lista, una mappa o una funzione
una lista, una mappa o una funzione qualsiasi altra cosa

Una funzione che dichiari è più rigorosa sul testo: un parametro o un risultato dichiarato come string accetta solo testo. Un numero o vero/falso è un errore nell'editor, in kscript check e all'esecuzione, così una chiamata che passa il valore sbagliato non può trasformarlo silenziosamente in testo. Metti tra virgolette un valore scritto nella chiamata, oppure trasforma un numero in testo con ->to_string(). L'editor propone entrambe come correzioni rapide.

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

Un record di un tipo dichiarato viene controllato rispetto al tipo che un parametro, un risultato o una variabile tipizzata dichiara. Un record a cui manca uno dei campi obbligatori di quel tipo è un errore prima che lo script venga eseguito, come a runtime:

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

Un { } è sempre una mappa, anche quando è scritto su due righe dopo il nome di un argomento, quindi least: { e } alla riga successiva sono una mappa, non un blocco. L'editor propone di sostituire least: { } con least.

Parametri di tipo

Una funzione che funziona allo stesso modo su qualunque tipo indica il tipo tra parentesi angolari dopo il suo nome e lo usa nei suoi parametri e nel risultato. Una chiamata lo riempie in base a ciò che riceve:

<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

Una chiamata assegna a ciascun parametro di tipo un solo tipo. @same(1, 'x') è un errore nell'editor, in kscript check e a runtime, perché a rende T un numero e b è testo. Lo è anche un risultato che non è del tipo che la chiamata ha reso T. All'interno della funzione, T è un tipo qualsiasi, quindi $items[0] non richiede controlli. Più parametri di tipo si scrivono separati da virgole: fn pair<K, V>(key: K, value: V). In XML vanno nell'attributo generics: <fn name="first" generics="T" params="items: T[]" returns="T">.

Virgole finali

Una virgola va tra gli elementi. Dopo l'ultimo elemento una virgola è ammessa solo quando la lista è scritta con un elemento per riga, così aggiungere un elemento modifica una sola riga. Prima della parentesi di chiusura sulla stessa riga è un errore, in ogni tipo di lista:

<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 e costanti

enum dichiara un insieme di valori con nome, e const un valore che non può cambiare.

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

Un enum lungo può contenere un valore per riga, senza virgole, come un tipo contiene un campo per riga. kscript fmt mette su una riga un enum che rientra nella larghezza massima della riga, e un enum più lungo un valore per riga:

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

Dove il tipo è noto, scrivi il valore di un enum con un punto iniziale: .large è Size.large, perché size è un Size (vedi Un punto iniziale più sotto). Dove nulla indica il tipo, scrivilo per esteso: Size.medium. Una lista di un enum accetta un array di essi: con fn pack_all(sizes: Size[]), scrivi @pack_all([.large, .small]). Anche i comandi predefiniti hanno parametri di tipo parola, e quelle parole si scrivono nude, senza punto: @known_folder(downloads) accetta home, desktop, documents, downloads, music, pictures, videos, appdata o temp. Size stesso è una mappa da ogni nome a se stesso, quindi 'large' in Size verifica un valore. Le dichiarazioni <const> e <enum> di primo livello sono esportate agli script che importano il file.

Un punto iniziale: .name

Un nome che inizia con un punto è un membro di qualunque cosa il punto sia atteso. Evita di scrivere il nome del tipo quando il codice intorno lo dice già:

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

Il significato del punto si legge in quest'ordine:

  1. Uno slot tipizzato. Un argomento, il valore predefinito di un campo, un confronto, un ramo di match, un elemento di lista o il ritorno tipizzato di un fn che accetta un enum: .pink è il valore di quell'enum. Uno slot che accetta una funzione, come fa ->map(.name), legge quel campo di ogni elemento.
  2. L'elemento, dentro un ciclo for. In for account in $accounts { ... }, .id è $account.id e .name = 'Ann' imposta il campo dell'elemento. Nei cicli annidati vince l'elemento più interno che ha quel nome, così il .label del ciclo interno e il .id del ciclo esterno possono convivere. Un ciclo while non ha elemento, quindi non aggiunge nulla.
  3. Il record, dentro i propri metodi. In un type, model, extend o in un metodo di componente, .text è il campo proprio del record e .save() chiama un suo metodo. .count += 1 e .color = .red impostano i suoi campi.
  4. Nessuno di questi. $c = .red è un errore, .red needs a type here, e la correzione rapida lo scrive per esteso: NoteColor.red.

Lo slot viene provato per primo. Dentro un metodo, @paint(color: .red) è NoteColor.red anche se il record ha un campo chiamato red. Un nome che l'enum non ha è del record, quindi fn current(): NoteColor => .color restituisce il color del record. Un nome che nessuno dei due ha è un errore.

L'elemento di un ciclo viene prima del record. In un metodo che cicla su righe che hanno un title, .title è quello della riga, e quello proprio del record si scrive $this.title; il controllo lo segnala e propone questa correzione.

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

Scrivere . dove va un valore suggerisce esattamente ciò che ci sta: i valori dell'enum in uno slot tipizzato, i campi dell'elemento del ciclo (poi quelli dei cicli esterni e del record) dentro un ciclo, oppure i campi e i metodi del record dentro un metodo. Passando sopra un valore si vede a cosa corrisponde, come NoteColor.pink.

Dati tipizzati

type dichiara la struttura di alcuni dati, come una risposta di un'API. I dati che passano attraverso di esso vengono controllati e trasformati in un record: una mappa che conosce il proprio tipo, così l'editor completa i suoi campi e un errore di battitura come $repo.stras viene intercettato. I campi possono anche essere email, password, handle, uuid o regex, e i tipi possono aggiungere regole ad altri tipi o unirsi a loro. Vedi Tipi e validazione.

Un tipo è un blocco con un campo per riga, 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 legge il campo da una chiave con un altro nome, e owner: User è un altro tipo, quindi anche i dati annidati vengono verificati e trasformati in un record User. Repo(data) mappa una mappa, una lista di mappe o testo JSON.

Usa $.name per cercare un valore nell'ambito corrente. Risolve lo stesso nome di $name, incluso un parametro di funzione, una variabile locale o un campo di componente.

Firme dei metodi

Un tipo può dichiarare un metodo senza scriverne il corpo: termina la riga fn con ; dove andrebbero => o { }. Quella riga è una firma di metodo, e un altro tipo che extends questo deve implementarlo. Un ? dopo il nome del metodo, come in fn details?(): string;, rende il metodo opzionale. L'editor e questa documentazione mostrano le righe di firma in corsivo, così le riconosci a colpo d'occhio dai metodi con corpo. Il controllore segnala qualsiasi metodo obbligatorio mancante o discrepanza nei nomi dei parametri, nei tipi dei parametri o nel tipo di ritorno.

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

Righe dei campi

Una riga di campo è name[?][: type] [from path] [= default | => value]. Ogni parte è facoltativa tranne il nome. Un campo con un valore e senza tipo può scrivere il valore subito dopo i due punti, layout: ```text ... ``` o symbols: { '#': '#' }, e prende il tipo dal valore:

<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)'
}
Parte Cosa fa
: type Un tipo integrato (string, int, float, number, bool, date, list, set, map, fn, any, email, password, handle, uuid, regex), un enum, un altro type, T[] per una lista, set(of: T) per un insieme di T. Le regole possono seguire tra parentesi quadre: string(min: 1). Senza di esse il campo accetta qualsiasi valore.
? dopo il nome Il valore può mancare o essere null. Questo è l'unico modo per contrassegnare un campo come facoltativo, in un type, un model, un error e un job: license?: string, non license: string? (KS6014, con una correzione rapida). T? serve per un tipo che non è proprio del campo, come un parametro che può essere null: fn show(repo: Repo?).
from path Dove leggere il valore quando non corrisponde al nome del campo: stargazers_count, owner.login, items[0].name. I dati annidati escono appiattiti. Racchiudi tra virgolette un percorso che contiene spazi.
= default Il valore quando i dati non ne hanno uno. Il campo diventa quindi facoltativo.
=> value Calcola il campo a partire dagli altri campi (sono $name, $stars e così via) invece di leggerlo.
/// sopra la riga Mostrato al passaggio del mouse e nel completamento.

Il tipo stesso accetta opzioni tra parentesi quadre: type Repo(extra: error) { … }. extra stabilisce cosa succede alle chiavi che il tipo non elenca: drop (il predefinito), keep o error. path: 'data/repo.json' ricava i campi da un campione salvato dei dati: gli oggetti diventano tipi annidati, e le chiavi che solo alcuni elementi della lista hanno diventano facoltative. Le righe nel blocco sostituiscono i campi campionati che nominano. I tipi possono fare riferimento l'uno all'altro in qualsiasi ordine e a se stessi, e i tipi di primo livello vengono esportati verso gli script che importano il file. In un progetto, dai a ciascun tipo il proprio file (types/repo.kscript, types/owner.kscript) e importa quelli che usa: import "owner.kscript" in cima a types/repo.kscript (vedi Un tipo per file).

Un tipo piccolo può anche stare su una riga, con i campi scritti come parametri fn: type Point(fields: [x: int, y: int]). kscript convert lo scrive come blocco.

In XML, un tipo è <type name="Repo"> con un elemento <field name="stars" type="int" from="stargazers_count" /> per ogni riga, oppure un attributo fields="..." per la forma su una riga. Passa gli esempi a XML per vederli.

Le liste tipizzate mantengono il tipo dei loro elementi

Una lista dichiarata con un tipo di elemento, $scores: int[] = [90, 72], lo mantiene: $scores[0] = '85' memorizza il numero 85, e $scores[1] = 'high' si ferma con "Un elemento di $scores deve essere un int". kscript check e l'editor segnalano un valore scritto sul posto che non può esserlo (KS5012).

Valori che possono essere null

Un tipo scritto con ? indica che il valore può essere null: una funzione dichiarata fn find(slug: string): Post?, un parametro post: Post?, una variabile $post: Post? = ..., oppure un campo license?: string senza valore predefinito. Leggere un campo di null, o chiamare un metodo su di esso, ferma lo script, quindi kscript check e l'editor avvisano (KS5018) quando un valore del genere viene usato prima che qualcosa lo controlli:

<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

Ciascuna di queste conta come controllo: un if, elif o while attorno all'uso (if $post != null, if $post, if $post is Post), un else dopo if $post == null, un if $post == null { return } (oppure throw, break, continue, exit) sopra di esso, e dentro una stessa espressione $post and $post.title, $post == null or $post.title == '' e $post ? $post.title : ''. Ce l'ha un record creato poco sopra con il campo indicato, $p = Post(title: 'x', summary: 'y'). Una lista, un insieme o una mappa opzionale è vuota invece che null, e i campi di un modello vengono lasciati al runtime, perché arrivano dal database.

Dove i dati incontrano un tipo

<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: accetta un tipo: as: Repo, as: int, o as: Repo[] per una lista di questi, scritto come lo scrive una dichiarazione. $repo->type() è 'Repo'. Un record funziona comunque ovunque funzioni una mappa, ma leggere o impostare un campo che il tipo non ha è un errore, e impostare un campo converte il valore nel tipo del campo.

->type() riporta il tipo degli elementi di una lista. [1, 2]->type() restituisce 'number[]', e una lista di record Repo restituisce 'Repo[]'. Le liste miste e le liste vuote senza tipo restituiscono 'any[]'. Usa ->is_a(list) per verificare se un valore è un tipo di lista qualsiasi.

Quando i dati non corrispondono, la mappatura fallisce con un unico errore Shape che elenca ogni problema con il suo percorso JSON:

Testo
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 una catch, $err.problems è una lista di mappe { path, field, message }. Repo->check($data) restituisce quella lista senza generare errori (vuota quando i dati corrispondono), Repo.fields elenca i campi, e Repo->schema() descrive il tipo come JSON Schema.

Tipi da tipi

Un tipo può essere creato a partire da un altro tipo, così un parametro o un campo segue il tipo a cui si riferisce invece di ripeterlo. Quando il tipo cambia, cambia anche tutto ciò che ne deriva, e l'editor completa, collega e verifica i nomi.

Forma Cosa fa
Post.fields Uno dei nomi di campo di Post, scritto senza altro: title. Contano i campi propri di un modello (id, le sue chiavi) e le relazioni.
Post.fields(except: [body]) Meno nomi: except: ne esclude alcuni, only: ne mantiene alcuni, relations: false esclude le relazioni e relations: only mantiene solo quelle.
Post.title Il tipo del campo title di Post, con le sue regole. Post.title(max: 80) aggiunge regole in più.
Order.address.postcode Un campo di un campo. Order.lines.item è un elemento del campo lista lines.
Self.fields, Self.title All'interno di un type o di un model, il tipo che si sta dichiarando.
draft|live Una di queste parole, scritta senza altro.
int|uuid Un valore di uno dei due tipi. Una parola che indica un tipo è quel tipo; mettila tra virgolette per intendere la parola: card|'email'.
(draft|live)[] Le parentesi raggruppano un'unione, qui per creare una lista di essa.
<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 }"

Un valore che non corrisponde viene segnalato come qualsiasi argomento tipizzato, elencando tutti i nomi che potrebbe essere:

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

Anche le opzioni integrate sono tipizzate allo stesso modo, e il passaggio del mouse, l'aiuto sulla firma e il riferimento mostrano il tipo di ciascuna:

  • Il hidden: e il guarded: di un modello accettano Self.fields[], e key: accetta Self.fields. unique: e index: accettano (Self.fields|Self.fields[])[], che è un nome o un gruppo di nomi.
  • Il unique_by: di un job accetta Self.fields[].
  • Il ModelUpdate di fields: accetta model.fields[], cioè i campi del modello che il suo model: nomina.
  • Il Index(columns:) di una migrazione accetta i campi della sua tabella.
  • I metodi indicano i campi del ricevitore allo stesso modo: $post->is_dirty(title) accetta Self.fields, ->pick([title, views]) e ->omit([body]) su un record accettano Self.fields[], e $posts->pluck(title) o ->pluck([title, views]) su una lista di record accettano Self.fields|Self.fields[]. Un nome che il ricevitore non ha è un errore con un suggerimento.
  • Le opzioni con poche parole fisse sono unioni di parole: Document(template: plain|paper|report|letter|invoice), ->sort(by:, order?: asc|desc), e Resource(only:), che accetta (index|store|show|update|destroy)[]. Una parola che è anche il nome di un tipo viene messa tra virgolette nel tipo, come in echo di format: text|'json'|'markdown', ma la si scrive senza altro: format: json.

Un campo di modello scritto status: draft|live viene memorizzato come colonna enum del database.

In un gruppo one-of, un | prima dei due punti separa i nomi e un | dopo di essi indica un'unione: id|slug: int|uuid accetta id: o slug:, cioè un int o un uuid. In un gruppo i cui membri hanno tipi diversi, un | seguito da name: inizia il membro successivo: (as: draft|live | template: Template).

Valori e metodi

I valori sono stringhe, numeri, bool, liste, mappe, date, funzioni e null, più i valori che aggiungono i pacchetti (file, risposte HTTP). Ogni valore ha dei metodi, richiamati con -> e concatenabili:

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

Usa pluck(key) per leggere un campo da ogni elemento in ordine. Passa a pluck una lista di chiavi per produrre una nuova mappa per ogni elemento. Le chiavi possono essere nomi semplici, stringhe tra virgolette o variabili.

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

Una chiave di mappa mancante dà null. I record tipizzati mantengono i consueti controlli sui campi. Una lista di input vuota dà [], e pluck([]) dà una mappa vuota per ogni elemento di input. Le chiavi ripetute compaiono una sola volta, nell'ordine richiesto.

Su una lista, contains(value), index_of(value), remove(value) e count_of(value) confrontano con ==. Per esempio, [1, '1']->count_of(1) dà 2. unique() usa l'uguaglianza stretta (===), quindi [1, '1']->unique() mantiene entrambi gli elementi.

is_empty() significa zero caratteri su una stringa, zero elementi su una lista, o zero chiavi su una mappa. Se hai usato $text->is_empty() per accettare input composto solo da spazi, usa $text->is_blank() per mantenere quel comportamento.

Testo ->is_empty() ->is_blank()
'' true true
' ' false true
'hello' false false

Un numero è sempre scritto in cifre semplici, mai con un esponente: echo 10 ** 20 stampa 100000000000000000000 e echo 0.1 ** 20 stampa 0.00000000000000000001. I numeri interi sono esatti a qualsiasi dimensione: 123456789 * 987654321 è 121932631112635269, 2 ** 100 è 1267650600228229401496703205376, e un id di 20 cifre letto da testo o JSON mantiene tutte le cifre. +, -, *, %, **, / (quando divide esattamente), ->sum(), ->product(), @gcd, @lcm e @factorial restano tutti esatti; una frazione, @sqrt e simili funzionano in normale virgola mobile. Una frazione mostra 15 cifre significative, quindi 0.1 + 0.2 stampa 0.3. Un numero intero può crescere fino a circa 30.000 cifre prima di fermarsi con un errore di Limit.

Sul testo, ->count() e le posizioni (in ->slice(), ->index_of() e $text[0]) contano la maggior parte dei caratteri come un posto e un carattere come un'emoji come due. Nessun metodo spezza a metà un carattere del genere: ->chars(), ->first(), ->last() e ->reverse() lavorano con i caratteri interi come li vede chi legge, e ->slice() e ->truncate() spostano indietro, fino a prima di esso, un taglio che cadrebbe al suo interno.

Un semplice fatto su un valore è un campo, letto con un punto e senza parentesi, allo stesso modo delle chiavi di una mappa:

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

Quindi $response.status, $file.size, $url.host e $e.status sono campi, e tutto ciò che accetta argomenti o esegue un'operazione è un metodo: $response->convert(from: json), $file->read_text(), $day->format('yyyy'). Un nome che risponde true o false inizia con is_ o has_: $response.is_ok, $ip.is_private, $list->is_empty(), $map->has(key).

Una durata è un numero e un'unità senza virgolette, come 500ms, 30s, 10m, 2h, 1d o 1w, uniti per indicarne di più (1h30m). Tutto ciò che accetta una durata ne richiede una: wait(500ms), @api($url, options: { timeout: 30s }), $cache->set(key, value, ttl: 10m). Un numero semplice è sempre in secondi.

Anni e mesi sono y e mo (m sono i minuti): 1y, 6mo, 5y10mo. Un mese o un anno non ha una lunghezza fissa, quindi questi spostano le date secondo il calendario ($date + 1mo mantiene il giorno del mese dove possibile) e vengono rifiutati dove serve una lunghezza fissa, come wait(1mo) o 1mo.hours.

L'editor completa i campi e i metodi di ogni tipo e mostra cosa fanno. Per cambiare il formato di un valore, come leggere testo JSON o scrivere righe come CSV, usa ->convert(): vedi Conversione tra formati.

Date

I fatti di calendario di una data sono campi: .year, .month, .day, .weekday, .quarter, .day_of_year, .week (il numero di settimana ISO) e .days_in_month. .is_past, .is_future, .is_today e .is_weekend la confrontano con adesso, quindi sono adatti ai template:

<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) e ->end_of(unit) danno il primo e l'ultimo istante del day, week, month, quarter o year in cui cade una data, che è ciò che serve a un report sugli "ordini di questo mese". Una settimana inizia nel primo giorno della localizzazione (lunedì in en-GB, domenica in en-US), oppure in quello indicato da 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

L'aritmetica di calendario conta unità intere. $date + 1y6mo sposta una data di anni e mesi, e così fa ->add(), che accetta qualsiasi combinazione di years:, months:, weeks: e days: (->subtract() la sposta indietro). Un mese mantiene il giorno del mese dove possibile, quindi il 31 gennaio più un mese è l'ultimo giorno di febbraio. Per ore e minuti, aggiungi o togli una durata:

<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

Una data si sposta solo di una durata. $date + 1 è un errore, perché un numero semplice è sempre in secondi, e così lo è aggiungere un bool, una lista o un'altra data. Scrivi l'unità ($date + 3d). L'unico caso in cui un numero rappresenta una data è un timestamp Unix, i secondi dal 1970, che ->to_date() legge e ->timestamp() restituisce:

<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

Sottrarre una data da un'altra dà il tempo esatto tra le due come durata. ->since(other, in: unit) conta invece giorni, settimane, mesi o anni interi, come si fa per un compleanno. ->is_same(other, unit) chiede se due date cadono nello stesso giorno (il valore predefinito), settimana, mese, trimestre o anno:

<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 deriva dall'orologio del computer, quindi nei test @with_clock(date, fn) lo fissa per @now(), @today(), i campi sopra e @format_relative().

Lavorare con il testo

Il testo ha funzioni di supporto per le operazioni che ricorrono spesso: cambiare il maiuscolo/minuscolo di un nome, tagliare in corrispondenza di un separatore, sistemare gli spazi e firmare un payload.

<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() e ->after() tagliano al primo separatore, o all'ultimo con last, e restituiscono l'intero testo quando il separatore non c'è. ->wrap(width: 60) spezza il testo tra le parole in modo che stia in una larghezza, come @terminal_width(). ->is_numeric() è vero per testi come '42' o '-3.5'.

->contains(), ->starts_with(), ->ends_with(), ->index_of() (l'ultima corrispondenza con last) e ->replace() corrispondono esattamente alle maiuscole e alle minuscole. Passa ignore_case per far corrispondere maiuscole e minuscole allo stesso modo:

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

Per verificare un webhook, calcola la firma con ->hmac(key) (SHA-256 di default, oppure sha1 o sha512) e confrontala con @secure_equals(), che richiede lo stesso tempo indipendentemente da quanto i due valori coincidono:

<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() e ->sha512() restituiscono hash in esadecimale. @escape_regex(text) esegue l'escape di ciò che un utente ha digitato, così un pattern costruito con quel testo corrisponde solo a quel testo.

Liste e mappe

Le liste si confrontano come insiemi con ->difference(other), ->intersect(other) e ->union(other). Ognuna mantiene l'ordine della prima lista, restituisce ogni elemento una sola volta e confronta gli elementi con ==, oppure con ciò che by: restituisce per ciascuno:

<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) conta gli elementi per ogni chiave, ->take_while(fn) e ->skip_while(fn) si fermano al primo elemento che non soddisfa la condizione, ->window(size, step?) restituisce sequenze sovrapposte e ->replace_at(index, item) restituisce una copia con un elemento modificato:

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

Più e meno frequenti: common

->common(count?, least, by?) conta quante volte compare ogni elemento e restituisce gli elementi in quell'ordine, una sola volta ciascuno. Senza least compaiono prima i più frequenti; con least compaiono prima i più rari. count tiene solo quel numero di elementi dall'inizio e, se lo ometti, ottieni tutti gli elementi distinti. Gli elementi che compaiono con la stessa frequenza restano nell'ordine in cui compaiono per la prima volta nella lista, e ogni elemento torna com'è, quindi i numeri restano numeri:

<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: decide cosa conta come lo stesso elemento. Qui 'Tea' e 'tea' vengono contati insieme perché entrambi diventano 'tea' in minuscolo, e ottieni indietro quello che è comparso per primo:

<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

Per moltiplicare tra loro i tre numeri più frequenti, prendili con ->common(3) e moltiplicali con ->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

Le mappe hanno gli stessi callback delle liste, che ricevono prima il valore e poi la chiave: ->filter(), ->reject(), ->any(), ->all(), ->find() (che restituisce { key, value }), ->reduce(), ->sort(by:) e ->map(). ->map_keys(fn) rinomina ogni chiave, ricevendo prima la chiave e poi il valore:

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

Insiemi

Un insieme è un gruppo di elementi in cui ogni elemento compare una sola volta. Aggiungere un elemento già presente non fa nulla, e verificare se un elemento è in un insieme è veloce qualunque sia la sua dimensione. Un insieme si scrive come una lista e si rende insieme con as set, oppure dichiarando una variabile o un campo come 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

Gli insiemi sono utilissimi per ricordare ciò che hai già visto. $seen: set = [] ne crea uno vuoto, += aggiunge un elemento e in verifica la presenza, e restano entrambi veloci man mano che l'insieme cresce:

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

+ unisce due insiemi, - toglie degli elementi e ->intersect() tiene gli elementi presenti in entrambi. Il lato destro può essere una semplice lista. set(of: string) è un insieme di un solo tipo, e ogni elemento viene convertito in quel tipo al suo ingresso, come in una lista tipizzata. $set as list restituisce gli elementi come lista. Ogni metodo degli insiemi, con esempi, si trova in Insiemi.

<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

Conversione tra formati: convert

I dati passano continuamente da un formato all'altro: un'API risponde in JSON, un file di impostazioni è in YAML, un foglio di calcolo viene salvato come CSV. Ogni valore ha un unico metodo per tutto questo, ->convert(), e si legge come una frase: converti da questo formato, a quell'altro.

from: legge un testo scritto in un formato e ti restituisce i valori che contiene. to: scrive un valore in un formato. Passa entrambi per trasformare direttamente un formato in un altro.

Formato from: lo legge to: lo scrive
json mappe, liste, testi, numeri testo json
yaml mappe, liste, testi, numeri testo yaml
csv una lista di righe testo csv
markdown, latex un documento con KScript.Document
html da Markdown con KScript.Markdown, da documenti con KScript.Document

Lettura di un testo: from

from: accetta un testo, un blocco di testo come un blocco ```yaml o ```csv, un valore json o csv, oppure una risposta HTTP (il suo corpo):

<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

Il CSV ha di default una riga di intestazione, che dà il nome alle chiavi di ogni riga. Scrivi not header quando ogni riga è un dato, e ogni riga diventa una lista delle sue celle:

<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

Controllo rispetto a un tipo: as

as: verifica ciò che è stato letto rispetto a un tipo e lo trasforma in record, così un campo mancante o errato diventa un errore sulla riga che lo legge, non una sorpresa più avanti. Una lista di record si scrive come la scrive una dichiarazione, 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

Scrittura di un formato: to

to: scrive qualsiasi valore: mappe e liste come JSON o YAML, e una lista di righe come CSV. indented distribuisce il JSON su più righe, e headers: sceglie e ordina le colonne del 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

Entrambi insieme

Passa from: e to: insieme per convertire un formato in un altro senza gestire i valori nel mezzo:

<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

Scorciatoie: from e to

Quando ti limiti a leggere o solo a scrivere, ->from(type: json) e ->to(type: csv) dicono la stessa cosa con meno parole. Accettano le stesse opzioni di ->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() è l'unico modo per cambiare formato, quindi le vecchie forme con un metodo per formato (->json(), ->yaml(), ->csv(), ->markdown(), ->to_json(), ->to_yaml(), ->to_csv(), e ->html(), ->latex() e ->markdown() di un documento) sono errori che mostrano invece la ->convert() da scrivere, con una correzione nell'editor.

Lettura di testo strutturato

I dati spesso arrivano come testo: un record per riga, gruppi di righe separati da una riga vuota, oppure un disegno fatto di caratteri. Questi metodi trasformano quel testo in liste con cui puoi lavorare.

Righe e blocchi

->lines() restituisce un testo per ogni riga. ->blocks() invece divide il testo nelle righe vuote, così ogni blocco è un gruppo di righe. Un semplice a capo resta dentro il blocco; solo una riga vuota ne inizia uno nuovo:

<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() al posto di una funzione è una scorciatoia per fn(block) => $block->lines(): il metodo viene chiamato su ogni elemento, come .name legge il campo di ogni elemento. Funziona ovunque serva una funzione, ad esempio in ->filter(.is_empty()) o ->sort(by: .age).

Divisione di una lista: split

Quando hai già una lista, ->split(separator) la taglia in più liste ogni volta che compare l'elemento separatore, e lo scarta. Passa un valore da cercare con ==, oppure una condizione vera per il separatore:

<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() su un testo taglia il testo; ->split() su una lista taglia la lista.

Numeri nel testo: numbers

->numbers() restituisce tutti i numeri scritti nel testo, in ordine, così non ti serve un pattern. Un segno meno conta come segno quando si trova subito prima di un numero senza nulla attaccato alla sua sinistra, come in x=-3; tra due numeri, come in 1-3, è un trattino, quindi ottieni 1 e 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]

Disegni fatti di caratteri: grid

->grid() trasforma le righe di caratteri in righe di singoli caratteri, quindi $grid[row][column] è un carattere. La riga 0 è quella in alto e la colonna 0 è il primo carattere:

<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

Scorrere righe e colonne: cells

->cells() legge una griglia come si leggerebbe una tabella. Da solo, o con rows, restituisce ogni riga; con columns restituisce ogni colonna, dall'alto in basso. È così che si scorre una griglia in entrambe le direzioni:

<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: sceglie una riga e column: una colonna, entrambe numerate da 0, e -1 è l'ultima. Passa entrambe per ottenere l'unica cella in cui si incontrano:

<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

Le righe possono avere lunghezze diverse, come in una mappa irregolare. Una colonna salta allora le righe troppo corte per arrivarci, quindi nessun valore viene inventato per riempire il vuoto:

<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() funziona su qualsiasi lista di liste, non solo su una griglia: [[1, 2], [3, 4]]->cells(columns) è [[1, 3], [2, 4]], che trasforma le righe in colonne.

Trovare elementi in una griglia: positions_of

->positions_of(item) restituisce ogni posizione in cui si trova un elemento in una griglia, come punti con una .row e una .column, riga per riga e da sinistra a destra. Se passi una funzione, restituisce le posizioni in cui la funzione è vera per la cella:

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

I punti funzionano bene con ->combinations(2), che restituisce ogni coppia una sola volta con il punto precedente per primo. Una funzione con due parametri riceve i due punti della coppia uno alla volta. Questo esempio conta i quadrati i cui quattro angoli sono tutti alberi, anche con altri alberi tra gli angoli:

<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

Ricerca di forme: shapes

->shapes() trova forme in un testo, un elenco, una griglia o un elenco 3D: quadrati, rettangoli, linee e cerchi integrati, e maschere, cioè forme che disegni tu. Il testo viene letto come lo legge ->grid(), una riga per linea e una cella per carattere, quindi non serve chiamare prima ->grid(). Le celle di una griglia possono contenere qualsiasi cosa, quindi per le forme integrate of: indica quali celle formano la forma: un valore come '#', oppure un'espressione regolare come /[#@]/. Ogni corrispondenza viene restituita una sola volta, come { kind, points }, e ogni punto è una cella { row, column, value }. Tra i punti di una forma possono trovarsi altre celle:

<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

Senza rotated, le forme sono dritte: quadrati e rettangoli hanno lati paralleli agli assi, e le linee corrono in orizzontale o in verticale. Con rotated possono essere inclinate, quindi un quadrato può diventare un rombo e una linea può correre in diagonale:

<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

Indica più forme per trovarle tutte. Una corrispondenza viene data una sola volta anche quando si adatta a più forme: un quadrato è anche un rettangolo, quindi viene restituito come quadrato, e .kind indica quale forma è:

<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

Una linea richiede size:, cioè quanti punti ha. Un cerchio richiede radius:, e distance: indica quanto è lontano: straight (in linea d'aria, il valore predefinito), steps (solo in orizzontale e verticale, che disegna un rombo) oppure moves (le diagonali contano come uno, che disegna un anello quadrato):

<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() funziona anche su un elenco di punti, come quelli che ->positions_of() restituisce o le righe lette da un csv. In quel caso ogni punto conta, quindi non c'è of:: $trees->shapes(square, rotated).

Forme personalizzate: maschere

Una maschera è una forma che disegni tu. Le forme integrate sanno solo dove si trovano i punti; una maschera dice esattamente cosa deve contenere ogni cella, vuoti compresi. Dichiarala come un tipo che extends Mask, e disegnala nel suo layout: un blocco di testo che raffigura la forma, un carattere per cella (oppure un'espressione regolare, per una forma di lunghezza variabile lungo una riga: layout con espressioni regolari). Ogni carattere corrisponde a una cella che contiene lo stesso carattere. L'indentazione comune a tutte le righe non fa parte del disegno, quindi indentala insieme al codice che la circonda.

Per trovare un blocco pieno due per due di #, disegnalo e passa la maschera a ->shapes() per nome:

<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 serve solo per i caratteri che significano qualcosa di diverso da sé stessi. Associa un carattere a ciò che corrisponde: un valore (t: 'taken') corrisponde a una cella che lo contiene, un'espressione regolare (/[#@]/) a una cella il cui testo vi si adatta, un fn(cell) a una cella per cui restituisce true, same alle celle che devono contenere tutte lo stesso valore (più avanti), e any a una cella che non fa parte della forma. Una cella any può contenere qualsiasi cosa, può sporgere dal bordo dell'input ed è esclusa dai punti della corrispondenza. Per trovare quattro alberi agli angoli di un quadrato tre per tre, con qualsiasi cosa in mezzo:

<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 si rivela utile quando le celle non sono singoli caratteri. Una fila di posti è una lista di parole, e una lista di valori è una riga, quindi il layout ha bisogno di una lettera per ogni parola:

<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() accetta una maschera o un elenco di maschere, e rotated le trasforma in ogni modo consentito dall'input: da destra a sinistra lungo una riga, di un quarto, di metà e di tre quarti in una griglia, e in tutti i 24 orientamenti nello spazio 3D. Le corrispondenze di più maschere vengono restituite insieme, ciascuna identificata dal proprio .kind, e maschere e forme integrate possono essere cercate in un'unica chiamata:

<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

I simboli di una maschera si possono cambiare nel punto in cui viene usata, come qualsiasi campo: Fork(symbols: { t: fn(cell) => $cell != '.', '~': any }) è la stessa V di qualsiasi cosa tranne ..

Una riga vuota nel layout inizia il livello successivo, dal livello superiore, come accade con una riga vuota nel testo in cui la maschera cerca. Ogni livello ha lo stesso numero di righe, e ogni punto di una corrispondenza in 3D ha anch'esso un layer. Un elenco 3D ($cube[layer][row][column]) viene letto allo stesso modo:

<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

Una maschera con meno livelli o righe dell'input scorre su tutto l'input: una maschera di una sola riga viene provata su ogni riga di una griglia, e una maschera piatta su ogni livello di un testo 3D o di un elenco 3D. Una maschera con più livelli o righe dà un errore che lo spiega, come "Step has 2 layers, and this is one grid."

Mask è un tipo che puoi scrivere per un parametro o un campo. Accetta qualsiasi tipo che estende Mask, sia il tipo stesso (Block) sia uno ricavato da esso (Block(symbols: ...)), e Mask[] accetta una lista di questi:

<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

Celle che concordano: same

Finora ogni simbolo confronta una cella con qualcosa di fisso. same confronta le celle tra loro: ogni cella disegnata con quel carattere deve contenere un unico valore, qualunque esso sia, e due caratteri same diversi devono contenere valori diversi. same(...) restringe il possibile valore, con un valore, un'espressione regolare o un fn(cell). Per trovare una parola che si legge uguale da entrambi i lati, come 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

Forme di lunghezza variabile: layout con espressioni regolari

Un disegno ha una dimensione fissa. Un layout può invece essere un'espressione regolare, che legge le celle lungo ogni riga, una dopo l'altra, e trova quante ne servono. Ogni cella viene letta come il suo testo, e una corrispondenza deve iniziare e finire tra le celle. Un layout con espressione regolare non ha symbols: dai un nome a una parte con (?<name>...), e il symbol di ogni punto è il nome della parte in cui è caduto:

<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

Con rotated, un layout con espressione regolare legge anche ogni riga da destra a sinistra, e in una griglia dall'alto in basso e viceversa per ogni colonna. Un elenco di parole viene letto una parola per cella, quindi /\d+/ su ['ab', '12', '34'] trova ['12', '34'].

Applicare una maschera: repeated

Con repeated, una maschera funziona come una formina per biscotti: viene applicata ripetutamente a partire dall'angolo in alto a sinistra finché copre tutto l'input, e le copie sui bordi destro e inferiore vengono tagliate. Si adatta quando ogni copia contiene ciò che contiene la prima, cella per cella (le celle any sono libere). La corrispondenza è la prima copia, e copies indica quante ne sono state applicate:

<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

Un layout con espressione regolare non ha una dimensione fissa, quindi con repeated prova prima la formina più corta e restituisce la più corta che si adatta: le prime size celle, applicate lungo la riga, devono formare la riga, e l'espressione regolare deve adattarsi a quelle celle per intero. Legge una sola riga, quindi passagli una riga alla volta:

<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

Celle che si adattano a tutto: blank

L'input a volte è danneggiato o sconosciuto. blank: indica le celle che si adattano a qualsiasi cosa, come un valore ('?'), un'espressione regolare o un fn(cell). Una cella vuota si adatta a ogni simbolo, e con same o repeated non viene confrontata, quindi le copie riempiono a vicenda i vuoti: il value di un punto è il valore completato quando un'altra copia lo conosce. blank: va indicato nella chiamata e non nella maschera, perché descrive l'input, non la forma:

<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

Anche le forme integrate accettano blank:, e of: accetta un fn(cell) oltre a un valore o a un'espressione regolare, così tutti e tre leggono le celle allo stesso modo: $field->shapes(square, of: '#', blank: '?') considera un ? come un #.

Per trovare una forma tra le righe di un elenco di codici a barre, applica la funzione a ogni riga:

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

Una maschera contiene layout, symbols e i suoi metodi, scritti con :. L'editor e kscript check segnalano una maschera scritta male, la maggior parte con una correzione: un layout mancante o vuoto, un layout fatto solo di any, una tabulazione nell'immagine, livelli di altezze diverse, un simbolo di più di un carattere o ripetuto due volte, null al posto di any, 'same' tra virgolette al posto di same, symbols accanto a un layout regex, layout = al posto di layout:, repeated su una forma predefinita, una maschera passata a ->find_all() o ->matches() (che accettano una regex), e like:, che ->shapes() non accetta più. Un simbolo che il layout non usa è un avviso (KS6026), e lo stesso vale per uno che associa un carattere a se stesso (KS6025), dato che ogni carattere corrisponde già a se stesso:

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

Nell'editor, una maschera fa parte del linguaggio. extends ‸ propone Mask, e dentro un tipo Mask, scrivendo layout si inserisce il blocco di testo; una volta che ce n'è uno, symbols viene scritto per esteso con un carattere del layout e any. Dentro symbols: { }, il completamento propone i caratteri del layout non ancora elencati, e dopo i due punti di una chiave any, same, same(/…/), un valore, un'espressione regolare e un fn(cell). Dopo layout: propone il blocco di testo e un'espressione regolare. L'aiuto alla firma mostra ->shapes(mask, rotated?, repeated?, blank?) mentre si scrive una maschera. Passando sopra un carattere del layout si vede cosa corrisponde e quante volte il layout lo usa, e ogni carattere è colorato in base a ciò che corrisponde: sé stesso o un valore come il testo, un'espressione regolare come un'espressione regolare, un fn come una funzione, e any attenuato come un commento.

Lavorare con le sequenze

Moltiplicare: product

->product(fn?) moltiplica gli elementi, come ->sum() li somma. Dato una funzione, moltiplica i risultati della funzione per ogni elemento. I numeri interi restano esatti a qualsiasi dimensione:

<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

Totali parziali: scan

->scan(fn(total, item), initial?) funziona come ->reduce() ma conserva ogni totale intermedio, così vedi come si costruisce il risultato. Senza initial, il primo elemento è il primo totale:

<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

Ogni scelta: combinations

->combinations(size) fornisce ogni modo per scegliere size elementi dalla lista quando l'ordine degli elementi scelti non conta. Ogni scelta mantiene gli elementi nell'ordine della lista, e nella stessa scelta nessun elemento viene scelto due volte.

Scegliendo 2 da ['tea', 'milk', 'juice'] funziona così: parti da tea e abbinalo a ogni elemento che segue (milk, poi juice), poi parti da milk e abbinalo a ogni elemento che segue (juice). juice non ha nulla dopo di sé, quindi non c'è altro. ['milk', 'tea'] non compare mai, perché è la stessa scelta di ['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']]

Un uso comune è controllare ogni coppia, per esempio trovare i due prezzi che sommati danno un totale:

<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

Una funzione con un parametro per ogni elemento scelto riceve gli elementi uno alla volta, così puoi dare loro un nome invece di leggere $two[0] e $two[1]. Funziona per qualunque dimensione: scelte di 3 riempiono fn(first, second, third). Una funzione con un solo parametro riceve comunque l'intera scelta:

<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

Poiché gli elementi scelti riempiono i parametri, una funzione del genere non riceve anche l'indice: con le coppie, fn(first, second) sono i due elementi della coppia.

Ogni ordine: permutazioni

->permutations(size?) fornisce ogni ordinamento, in cui l'ordine conta, quindi ['tea', 'milk'] e ['milk', 'tea'] sono entrambi presenti. Senza size ogni ordinamento usa tutti gli elementi:

<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

Combinazioni e permutazioni crescono rapidamente (10 elementi hanno 3.628.800 ordinamenti), quindi oltre un milione di liste si fermano con un errore Limit invece di esaurire la memoria.

Girare: rotate

->rotate(by) sposta ogni elemento di by posizioni verso l'inizio, e quelli che cadono davanti vanno in fondo. Un by negativo gira nell'altra direzione:

<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

Aggiungere metodi a un tipo: extend

extend aggiunge i tuoi metodi a un tipo, integrato o tuo. Dentro, ogni fn è un metodo, e $this è il valore su cui viene chiamato:

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

Puoi estendere string, number (o int e float), bool, list, set, map, fn, date, email, password, handle, uuid e regex, i valori di un pacchetto come file o response, e i tuoi type, i cui metodi vedono $this (un record) e i suoi campi come $this.name. I metodi accettano parametri, valori predefiniti e argomenti con nome come ogni fn.

Un metodo non può avere il nome di uno che il tipo già possiede, quindi un refuso o un conflitto non cambia mai ciò che fa un metodo integrato. Per sostituirne uno di proposito, scrivi 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')
}

In XML, extend è <extend type="date"> che contiene elementi <fn>, e override fn è <fn override="true">.

Dove si applicano le estensioni. I blocchi extend di un file si applicano in quel file e in ogni file che lo importa. In un progetto (una cartella con kscript.json), ogni file nella cartella extensions/ si applica a ogni script, test e pagina del progetto, senza bisogno di import. Dividile come preferisci, per esempio un file per tipo:

Testo
extensions/
  date.kscript        extend date { … }
  list.kscript        extend list { … }
  text/
    slug.kscript      extend string { … }

kscript make extension date --methods api_date,is_payday crea extensions/date.kscript come punto di partenza. Per tenerli altrove, elenca cartelle o glob in kscript.json, che sostituisce la cartella predefinita: "extensions": ["extensions", "shared/**/*.kscript"]. Due file di estensione che aggiungono lo stesso metodo allo stesso tipo sono un errore che indica entrambi. Il extend di uno script (o di un import) prevale su quello del progetto.

L'editor completa e controlla i metodi di estensione solo dove si applicano: in un file che non li dichiara, non importa e (tramite il progetto) non riceve ->api_date() sulle date, @today()->api_date() è ancora un metodo sconosciuto. Al passaggio del mouse compaiono la documentazione del metodo /// e il file che lo aggiunge, e andare alla definizione apre quel file.

Errori

Usa guard condition else { ... } per continuare solo quando una precondizione è vera. Il blocco di fallimento deve uscire dal flusso corrente con return, throw, break, continue oppure 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

Un catch postfisso conserva il valore alla sua sinistra quando la valutazione riesce. Quando lancia un errore, KScript lega l'errore a $err e valuta il fallback. Usa catch Validation => $err.message per recuperare da un solo tipo di errore, oppure catch Validation as problem => $problem.message per dare un nome al binding. Un fallback null propaga l'errore originale.

In @a() + @b() catch => 0, il gestore copre sia le chiamate sia la somma. In @a() + (@b() catch => 0), copre solo @b().

Usa throw if per sollevare un errore solo quando una condizione è vera. Dentro il suo blocco, scrivi un campo per riga. KScript valuta la condizione una sola volta. Valuta i campi solo quando la condizione è vera, quindi una risposta riuscita può omettere del tutto 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 riceve i tipi di errore che gestisce, separati da |, e as dà un nome all'errore: catch FileNotFound | Permission as e. Un catch con solo un nome in minuscolo (catch err) gestisce ogni errore. when aggiunge un test: catch Network as e when $e.status == 503. I catch vengono provati in ordine e viene eseguito il primo che corrisponde. I nomi dei tipi di errore iniziano con una maiuscola, che è il modo in cui catch li distingue dal nome della variabile.

Elementi sconosciuti, attributi e errori di sintassi vengono segnalati prima dell'avvio di uno script, quindi un refuso verso la fine non lascia un lavoro a metà.

Un errore che nessun catch intercetta viene stampato come errore KScript, con il punto in cui è avvenuto e il suo tipo, e lo script termina con codice 3:

Testo
   ERROR  app.kscript:2:11: Name: Unknown command @nope().

kscript mostra ogni errore in questo modo, negli script, nelle pagine kscript serve di errore e in tutti gli altri comandi, mai come eccezione .NET. Un errore che dipende dal computer e non dallo script riceve il tipo di errore adatto (FileNotFound, Access, IO, Network e così via), mentre un errore che kscript non si aspettava è un errore Internal, cioè un bug da segnalare. Per vedere l'eccezione .NET e lo stack trace dietro un errore, esegui con --stack-trace (prima del percorso dello script: kscript --stack-trace app.kscript) oppure imposta KSCRIPT_STACK_TRACE=1, che funziona anche per kscript serve e i programmi compilati.

Gestori su funzioni e tipi

Collega un catch a una funzione o a un metodo per gestire gli errori di ogni chiamante. Collegalo a un tipo per condividere un gestore tra i suoi metodi.

Viene eseguito per primo il gestore corrispondente più vicino. Restituisci un valore non null per recuperare. Valori come false, 0 e '' funzionano tutti. Un throw nudo, un ritorno null, oppure raggiungere la fine del gestore passa l'errore originale al gestore successivo che lo racchiude.

<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

Dentro di un gestore, throw if condition rilancia l'errore corrente quando la condizione è vera. Aggiungi un blocco payload per sollevare un nuovo errore. Un gestore che si limita a registrare l'errore lo lascia propagare. I test di catch eseguibili mostrano un gestore di metodo che passa un errore al gestore del suo tipo, e un chiamante che intercetta un errore dopo che è stato registrato.

Usa /// @throws Network per documentare un errore che può raggiungere il chiamante. Il passaggio del mouse e l'aiuto alla firma mostrano gli errori noti. Al livello principale di uno script, kscript check e l'editor avvisano quando un errore noto può sfuggire (KS5016).

Per una singola chiamata, recupera il risultato in linea con 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 }")
}

Lancia con un valore e una causa

Usa throw Error(message: ..., value: ..., cause: ...) per sollevare un errore generico con dati extra. Il nome prima delle parentesi imposta il tipo di errore. Usa Error per un errore generico, un tipo predefinito come Validation, o un tipo che dichiari tu. Gli argomenti con nome diventano campi. message: imposta la spiegazione e cause: contiene l'errore precedente quando ne incapsuli uno.

<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 }"
}
Testo
Error: Could not save profile
Rejected value: -1
Caused by: Age must be positive, got -1

Ometti cause: quando sollevi il primo errore. Usa la ricerca con parentesi quadre, come $err['value'], per i campi aggiunti direttamente a un errore predefinito. Per i campi che i chiamanti devono poter scoprire e verificare, dichiara un tipo di errore e intercetta quel tipo. I suoi campi dichiarati si leggono con la sintassi a punto, come $err.value.

Se hai già una mappa con type, message e altri campi, lanciala direttamente con throw $payload. Passare la mappa come primo argomento di Error($payload) la converte in testo del messaggio. Il costruttore dell'errore offre argomenti con nome nel completamento dell'editor.

In XML, lo stesso lancio è <throw value="Error(message: 'Could not save profile', value: $age, cause: $original)" />. L'attributo value esterno contiene l'intera espressione di errore. L'argomento value: interno è il campo extra su quell'errore. Per solo tipo e messaggio, <throw type="Validation" message="Invalid age" /> corrisponde a throw Validation "Invalid age".

Riprovare

Alcuni errori si risolvono da soli: un database occupato, un calo di rete, un'API che limita le richieste. @retry(times, work) chiama work e la richiama ogni volta che lancia un errore, fino a times chiamate in tutto. Restituisce ciò che restituisce work, oppure lancia l'ultimo errore. work riceve il tentativo, 1 per il primo:

<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 attende tra una chiamata e l'altra. when riceve l'errore e decide se riprovare, così un errore che non potrà mai riuscire fallisce subito: @retry(5, @charge, when: fn(err) => $err.type == 'Timeout').

Tipi di errore

Dichiara i tuoi tipi di errore con error. I campi funzionano come in un type, il messaggio può usarli, e extends indica che tipo di errore è:

<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 })"
}
  • Lancio. throw PersonNotFound(id: 42) crea l'errore e lo lancia. I suoi argomenti sono i suoi campi, per nome, più message: (al posto del messaggio del tipo) e cause: (l'errore che ha portato a questo). Un campo senza valore predefinito deve essere fornito, e l'editor segnala i campi mancanti e sconosciuti. throw Validation "Too short" funziona ancora per un tipo senza campi, e throw Validation(field: 'name', message: 'Too short') aggiunge campi a uno predefinito.
  • Intercettazione. catch NotFound intercetta anche PersonNotFound, perché estende NotFound. Nel catch, $e.id legge un campo, e l'editor completa i campi dei tipi nominati dal catch. Ogni errore ha type, message, line, column, file, status e cause. $e->is(NotFound) verifica il tipo nel codice, e $e->chain() lo elenca: ['PersonNotFound', 'NotFound', 'Error'].
  • Rilancio e incapsulamento. Un semplice throw dentro un catch rilancia l'errore che sta gestendo, invariato. throw $e fa lo stesso con un errore salvato. Per aggiungere contesto, incapsulalo: throw ConfigBroken(path: $path, cause: $e), poi $err.cause.message legge l'originale.
  • Crearlo senza lanciarlo. OutOfStock(item: 'tea') restituisce l'errore come valore, da restituire o lanciare più tardi.
  • Stato. status è lo stato HTTP con cui risponde una route di KScript.Http quando nulla intercetta l'errore. Un tipo eredita questo valore, insieme ai suoi campi e al suo messaggio, dal tipo che estende.
  • Esportazioni. I tipi di errore di primo livello vengono esportati, come funzioni e tipi, quindi import "errors/payment-failed.kscript" li importa. kscript make error PaymentFailed --status 402 --extends Validation --fields "order: int" ne scrive uno in errors/.

I tipi di errore predefiniti, che KScript stesso solleva, formano un albero che catch segue:

Tipo Estende Sollevato per
Error Ogni errore. catch Error intercetta tutto.
Syntax, Name, Null, Argument, Value, Const, Math Error Errori nello script: sintassi errata, nome sconosciuto, null dove serve un valore, argomenti sbagliati, valore non valido, modifica di una const, divisione per zero. Index estende Value, per una posizione fuori da una lista.
Type Error Un valore del tipo sbagliato. Shape lo estende, per dati che non entrano in un type ($e.problems elenca ogni problema).
Format Error Testo nel formato sbagliato. Json e Yaml lo estendono.
IO Error File. FileNotFound, Permission e Access lo estendono.
Network Error Richieste. Timeout lo estende, e $e.status è lo stato della risposta.
Import, Config, Input, Limit, Context, Platform, Cancelled, Retired, Http, AI, UI, Reference, Assertion, Internal Error Importazioni, impostazioni, input, limiti come la ricorsione, il posto sbagliato, il sistema operativo, uno script interrotto, funzioni ritirate, app KScript.Http, modelli linguistici, finestre desktop, i riferimenti di un documento, controlli di test non riusciti, un guasto in KScript stesso.
Validation (422), BadRequest (400), Unauthorized (401), Forbidden (403), NotFound (404), Conflict (409), TooManyRequests (429) Error Da lanciare o estendere nel tuo codice. Il numero è lo stato HTTP.
Query, Connection (503) Error KScript.Data: una query rifiutata dal database, un database che non può essere aperto. Migration: una migrazione che non può essere letta o eseguita, oppure un comando kscript db che non può procedere. ModelNotFound estende NotFound; UniqueViolation e ForeignKeyViolation estendono Conflict; MultipleRecordsFound (da ->sole()) estende Query.
JobFailed Error KScript.Queue: un job che ha esaurito i tentativi. JobTimeout estende Timeout.

Nessun nome di tipo termina con Error: sono tutti errori. (QueryError e ConnectionError ora sono Query e Connection, e catch QueryError lo segnala.)

Un nome in catch o throw che non è né dichiarato né predefinito funziona ancora (come una specie di Error), ma l'editor avvisa (KS5011), perché di solito è un refuso.

Impostazioni: $config

$config contiene le impostazioni dell'app, come il suo nome, il suo database e la sua cache. Ogni script, pagina, rotta e test può leggerle senza import. Le impostazioni si trovano in un unico posto: la sezione config di kscript.json.

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

Un'impostazione assente è null, quindi $config.port ?? 8080 funziona. I nomi non dipendono dalle maiuscole, quindi $config.app.name e $config.APP.NAME sono la stessa impostazione. Nell'editor, passando il mouse su $config.app.name si vede il suo tipo, e Vai alla definizione apre la chiave nel file che la fornisce, anche dentro stringhe interpolate.

I pacchetti leggono le proprie parti di $config: KScript.Data legge database, KScript.Cache legge cache, KScript.Mail legge mail, $log legge logging, le traduzioni leggono i18n, e l'aritmetica del denaro legge money.exchange_rates (vedi Denaro).

Ambienti. La stessa app spesso richiede altre impostazioni in un altro contesto: un database in memoria per i test, o un server reale in produzione. Mettile in kscript.<env>.json accanto a kscript.json. La sua sezione config si sovrappone a quella in kscript.json, e le mappe si uniscono campo per campo, quindi serve solo indicare le impostazioni che cambiano:

JSON
// kscript.test.json
{
  "config": {
    "database": { "connections": { "main": { "url": "sqlite::memory:" } } }
  }
}

Scegli l'ambiente con kscript --env staging script.kscript o KSCRIPT_ENV=staging. kscript test usa test.env da kscript.json (vedi Test). $config->environment() restituisce l'ambiente, o null se non ne è scelto nessuno. Il file di un ambiente contiene solo una sezione config: tutto il resto appartiene a kscript.json.

Impostazioni che richiedono codice: config.kscript. JSON non può leggere una variabile d'ambiente né calcolare un valore. Per queste impostazioni, aggiungi config.kscript accanto a kscript.json (config.ks.xml in un progetto XML). Definisce configure(environment), che riceve l'ambiente (o development se non ne è scelto nessuno) e restituisce una mappa. Quella mappa si sovrappone alle impostazioni JSON, quindi serve solo indicare le impostazioni che richiedono codice:

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

I valori mantengono i loro tipi KScript, quindi 8s resta una durata. Lo script può usare @env(), $env, file importati e pacchetti come KScript.IO, e i percorsi al suo interno partono dalla propria cartella. Viene eseguito una volta, alla prima lettura di $config da parte di uno script, e non può leggere $config da sé. kscript make config base scrive un config.kscript iniziale, e kscript make config staging scrive kscript.staging.json.

I livelli, quelli successivi prevalgono: la sezione config di kscript.json, poi kscript.<env>.json, poi config.kscript. Uno script fuori da un progetto legge config.kscript dalla propria cartella.

File .env tengono i segreti fuori dai file del progetto. .env (e .env.<env> per un ambiente) accanto a kscript.json contiene righe NAME=value, con commenti #, export davanti se preferisci, 'single quotes' letti così come sono, e "double quotes" che consentono \n e possono estendersi su più righe. ${NAME} e ${NAME:-default} usano un'altra variabile. I valori vengono letti con @env('NAME'), di solito in config.kscript, e diventano anche variabili d'ambiente a meno che una non sia già impostata, quindi KScript.AI trova ANTHROPIC_API_KEY in .env. Tieni i file .env fuori da git.

Le impostazioni personali della persona. Un'app desktop può permettere alla persona di cambiare un'impostazione senza toccare il progetto: con "app": { "user_config": true } in kscript.json, config.json nella cartella di configurazione dell'app viene sovrapposto a tutto il resto (vedi Cartelle dell'app).

config legge di nuovo le impostazioni con altre opzioni, oppure legge un altro insieme di impostazioni in una variabile. Senza into, modifica $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 elenca altri file da leggere al posto di quelli del progetto: file JSON di impostazioni, script di configurazione e file .env, in ordine, ognuno seguito dalla sua versione per l'ambiente (settings.staging.json). Un nome senza estensione indica il suo file .json, e un nome che termina con ? può mancare. Con prefix, le variabili d'ambiente sovrascrivono i file e __ crea annidamenti: SHOP_DATABASE__HOST=db.internal imposta database.host, e valori come true, false e 8080 diventano booleani e numeri. root è la cartella in cui si trovano i file, defaults riempie le impostazioni che nessun file imposta, require elenca le impostazioni che devono essere impostate, e user: true legge anche le impostazioni personali dell'utente.

$config->sources() elenca i file letti, $config->all() restituisce ogni impostazione come mappa e $config->reload() li rilegge. @parse_env(text) analizza il testo .env, e KScript.IO aggiunge @read_env(path).

kscript serve non serve mai kscript.json, kscript.<env>.json, script, file .env o file JSON config.*. Le pagine leggono le impostazioni del progetto e possono usare @env() per i valori nei suoi file .env, ma non modificano l'ambiente del processo.

Logging: $log

Ogni script ha un logger. Le voci a info e superiori vanno al terminale (stderr) finché non configuri una destinazione diversa:

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

I livelli sono trace, debug, info, warn, error e fatal. I provider decidono dove vanno le voci, e di solito si impostano nella configurazione:

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(…) ne aggiunge uno da uno script, con le stesse opzioni (replace rimuove quelli già configurati, incluso quello predefinito della console). Un provider memory conserva le voci per $log->entries(), utile nei test. Le voci che un provider trattiene, come un batch http, vengono inviate quando lo script termina o con $log->flush(). Un provider che fallisce viene segnalato una sola volta su stderr, e gli altri continuano.

I pacchetti aggiungono tipi di provider con p.LogProvider("type", description, create), e i programmi che eseguono KScript possono aggiungerne di propri con host.Logs.AddProvider(provider, level), dove un provider implementa ILogProvider.

Traduzioni: @t()

Inserisci le traduzioni in una cartella locales accanto allo script (o nella cartella del sito): locales/en.json, locales/fr.yaml, oppure una cartella per locale come locales/de/shop.json, le cui chiavi iniziano con 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
  • Plurali. Con un count, @t() sceglie zero, one, two, few, many o other secondo le regole proprie della lingua. Sono le regole CLDR per inglese, francese, portoghese, russo, ucraino, polacco, ceco, arabo, ebraico, irlandese, gallese, giapponese, cinese, coreano e altre. Una forma esatta come =0 ha la precedenza.
  • Ripieghi. Una traduzione mancante viene cercata in fr-CA, poi in fr, poi nel locale predefinito (en se non impostato). Se non si trova da nessuna parte, ottieni la chiave stessa e un avviso viene registrato una volta sola nella categoria i18n.
  • La localizzazione viene da locale(set: fr), da locale(from: …) (la corrispondenza migliore disponibile per una lista o un header Accept-Language), da $config.i18n.locale, da KSCRIPT_LOCALE, oppure dalla lingua del computer. @locale() la imposta, e @locales() elenca le localizzazioni per cui ci sono file. Una route o un middleware che imposta la localizzazione ci inserisce la @view() con cui risponde, prima della lingua richiesta, così un sito può far prevalere il proprio cookie su quello del browser.
  • Le pagine lo scelgono in quest'ordine: un prefisso di percorso (/fr/about serve about.html in francese quando esistono traduzioni francesi), ?lang=fr, un cookie lang, e poi l'Accept-Language del browser. @locale_path($request.path, 'de') fornisce il collegamento alla stessa pagina in tedesco. Il locale predefinito non ha prefisso.
  • Formattazione. Seguono il locale, oppure uno che passi come ultimo argomento:
    • @format_number(1234.5) restituisce 1.234,5 oppure 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?) restituisce 3 ore fa, tra 2 giorni oppure proprio adesso, misurato da ora se non è indicato from:;
    • @format_duration(1h30m) restituisce 1 ora 30 minuti;
    • @format_list(['tea', 'coffee', 'milk']) restituisce tè, caffè e latte, oppure tè, caffè o latte con style: 'or';
    • @format_ordinal(23) restituisce 23°, e 23e in francese;
    • @format_bytes($file.size) restituisce 1,4 MB, oppure 1,3 MiB con binary: true.
  • Impostazioni: i18n: { folder: lang, default: en-GB, locale: fr } nella configurazione, oppure translations(folder: lang, default: en-GB). @has_t(key) verifica se una chiave ha una traduzione, e @plural(count) restituisce la categoria del plurale.

Le parole per i tempi relativi, le durate, gli elenchi e gli ordinali sono integrate per inglese, francese, tedesco, spagnolo, italiano, portoghese e olandese. Per un'altra lingua, o per modificarle, aggiungi queste chiavi al suo file di traduzione: time.second fino a time.year con le forme plurali e {count}, time.ago e time.in con {time}, time.now, list.and, list.or, e ordinal con {count}:

YAML
# locales/pl.yaml
time:
  hour: { one: "{count} godzina", few: "{count} godziny", many: "{count} godzin" }
  ago: "{time} temu"

Pacchetti

KScript.Core (tutto quanto sopra) è sempre presente. Tutto il resto viene da un pacchetto, importato in cima allo script, così uno script carica solo ciò che usa: uno script da terminale non carica mai il server 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"
// …

Si possono importare solo file .kscript e .ks.xml. Una funzione che lo script dichiara da sé prevale su una importata con lo stesso nome, e una const importata resta una costante.

Pacchetto Cosa aggiunge
KScript.Terminal input(into, type, default, secret) (il tipo può essere email, handle, uuid o password), picker (un percorso di file o cartella), menu(options, multiple), progress(into, total) con ->advance(), confirm, pause, clear, @color(text, color: 'green'), @bold, @dim, @underline, @terminal_width(), @is_terminal() (non quando l'output è reindirizzato), echo(format: markdown), e l'aspetto proprio della riga di comando di kscript: info, success, warn, alert(type: error), heading, detail(name), bullets(items), task(name) { }, table(rows, columns, header, align) (vedi Output del terminale)
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). I valori file hanno i campi .name .extension .mime .size .modified… e i metodi ->read_text() ->read_bytes() ->read_json(as:) ->sha256() ->write_text(text) ->copy_to(path) ->move_to(path) ->delete().
KScript.Net Invia richieste HTTP con @api(url, options: { method, headers, body, timeout }), o le scorciatoie post:, put:, patch:, delete:, bearer:, timeout:, retries:, as:, encoding: (json, form o multipart) e query:. La risposta ha .status, .is_ok, .text, ->convert(from: json) e ->check(). Fornisce anche @download(url, to) e @query_string. Un percorso come '/api/notes' interroga le route del progetto. Vedi Chiamare la tua API.
KScript.Markdown @markdown(text) e @read_markdown(path) (html, title, meta dal front matter), ->convert(from: markdown, to: html)
KScript.Web Genera pagine con layout, componenti e blocchi live per kscript serve. Le pagine hanno KScript.IO, KScript.Markdown e KScript.Web senza doverli importare.
KScript.AI @llm(prompt, system, schema, tools, model, max_tokens), llm(into, system, schema, tools, model, max_tokens), @chat(system) con ->ask() .history ->reset(), e @fake_llm(replies) per i test. Claude, con la chiave presa da ANTHROPIC_API_KEY (vedi Modelli linguistici).
KScript.Style Fogli di stile scritti in 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) (vedi Fogli di stile).
KScript.Http Route, controller e middleware per kscript serve: un file Routes { } contiene Get Post Put Patch Delete Any Route Resource Group Middleware. I controller usano @view, @response, @redirect, @abort e @route. Vedi Route, controller e middleware.
KScript.Storage Le cartelle dell'app, nel posto giusto su ogni piattaforma: @storage(config) (anche data, cache, state, logs) con ->read ->read_json ->write ->write_json ->read_bytes ->write_bytes ->file ->move ->copy ->append ->list ->delete ->folder ->path_of, oltre a @app_name() e @app_folders(). Vedi Cartelle dell'app.
KScript.Cache $cache (in memoria) e @cache(file) con ->get ->set ->remember(key, fn, ttl: 10m) ->has ->remove ->increment ->ttl ->keys ->clear. Vedi Cache.
KScript.Data Salva i record con model, li interroga con un query builder e gestisce le modifiche allo schema con Migration e kscript db migrate. Vedi Database.
KScript.Queue Dichiara il lavoro in background con job, lo accoda con ->dispatch() e lo esegue con kscript worker. Il suo Schedule esegue le attività a orari prestabiliti. Vedi Code e job e Pianificazione delle attività.
KScript.Mail Invia email con @send_mail(to:, subject:, html:|text:|view:) tramite SMTP, nel log o su un finto server, subito oppure con queue da kscript worker. @fake_mail() le conserva per i test. Vedi Email.
KScript.Auth Accesso per le app kscript serve: @register, @attempt, @login, @logout, @user(), @is_signed_in(), $session (->get ->set ->flash …), @users(), @csrf_field(), @reset_token, @reset_password, @api_token, e i middleware auth e guest. Vedi Accesso.
KScript.Document Document(template: paper, to: 'paper.pdf') { } con Section, Paragraph, List, Table, Figure, Math, Bibliography e altro; Letter e Invoice; ->save ->pages ->words ->markdown ->latex ->html. Vedi Documenti.
KScript.UI Finestre desktop: un blocco Window { } ne apre una. Column Row Grid Text Button TextBox CheckBox Select Slider Box Spacer Timer, @close_window(). Vedi App desktop.
KScript.Test test, describe, before_each, after_each, expect, expect_error, capture, @assert, @fail, @run_script, @check_script. I file di test lo importano da soli (vedi Test degli script).

Usare qualcosa da un pacchetto non importato si interrompe con input is part of KScript.Terminal. Add import KScript.Terminal at the top of the script., e l'editor propone di aggiungere l'import. Un pacchetto è nominato solo in un import: un'istruzione non viene mai scritta con il prefisso KScript. (input, non KScript.input), e nulla viene importato in silenzio, job e dispatch inclusi (import KScript.Queue). Un progetto può importare pacchetti per ogni script in kscript.json (sotto).

Byte casuali crittograficamente sicuri

@random_bytes(count, format: hex) legge l'entropia dal sistema operativo. Passagli un numero intero di byte da 1 a 65536. L'esadecimale minuscolo usa due caratteri per byte. Il formato base64url usa caratteri sicuri per gli URL e omette il padding. Entrambi i formati sono indipendenti da @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

Numeri casuali da un seed

@random_generator(seed) crea un generatore che dà gli stessi numeri per lo stesso seed ogni volta, su ogni macchina e in ogni versione di KScript, così ciò che ne deriva può essere ricostruito in seguito: un enigma creato per una persona, o i dati di un test. Il seed è testo esadecimale di almeno 16 byte, quindi un hash ne fa uno buono, e ->hmac($secret) impedisce a chi non conosce il segreto di ricavarlo. @char_of(0) tra le parti tiene separati 'ab' + 'c' e '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() restituisce un numero intero da 0 a 4294967295 e ->float() una frazione minore di 1. Il generatore è sfc32, inizializzato con i primi 16 byte come quattro parole big-endian a 32 bit ed eseguito 15 volte all'inizio, quindi uno sfc32 in JavaScript inizializzato allo stesso modo dà gli stessi numeri. È veloce e ben distribuito, ma chi vede abbastanza dei suoi numeri può ricavare il resto: usa @random_bytes() per i segreti.

Nomi di istruzioni e argomenti

Istruzioni e argomenti seguono un unico insieme di regole in ogni pacchetto, e kscript check e la suite di test le applicano a quelle integrate:

Regola Esempi
Un'istruzione che fa qualcosa, o dichiara qualcosa, è una parola minuscola snake_case. input, table, before_each, expect_error, log_provider
Le istruzioni che descrivono una finestra, una tabella di rotte o un documento in KScript.UI, KScript.Http e KScript.Document usano PascalCase. In KScript.Data, Migration e i suoi passaggi di schema usano anche PascalCase. Button, Routes, Get, Section, Migration, CreateTable
Gli argomenti sono snake_case. Nessun nome contiene un trattino. max_tokens, must_exist, on_click, new_page
into: è la variabile che riceve un risultato. input(into: name), llm(into: reply), capture(into: out)
to: è il punto di destinazione: un file, un URL, un controller. Non indica mai una variabile. Get(path: /, to: @home), Post(path: /notes, to: @notes.add)
path: è il file che un'istruzione legge o su cui agisce. import(path: 'lib.kscript'), <include path="_nav.html">, <layout path="_layout.html">
at è una posizione, come in for item at i in $list. menu(into: choice, at: i)
Una funzione si indica come @name, come in un'espressione. spawn(fn: @job), llm(tools: [@order_status]), Get(to: @people.show)

Tre tipi di nome non sono funzioni e restano senza prefisso: un controller (Resource(to: people) è il nome con cui uno script viene importato), i nomi in una lista di middleware ([log, throttle:30, my_check], dove built-in, gruppi e funzioni condividono un'unica lista), e una variabile o un tipo in dichiarazione. In XML gli stessi argomenti sono attributi con gli stessi nomi, e una funzione si scrive senza @ (<spawn fn="job" />); kscript convert aggiunge e rimuove il prefisso.

In una pagina, on-click e gli altri gestori stanno sui tag HTML (<button on-click="$count += 1">), quindi mantengono il trattino di HTML. Sugli elementi propri di KScript, come Button, l'argomento è on_click.

Un nome delle regole precedenti è un errore che indica quello nuovo ('to' is now into.), e kscript check --fix lo rinomina. Permettere di assegnare un'istruzione ($name = input "Name? ") non fa ancora parte del linguaggio.

Output del terminale

KScript.Terminal stampa allo stesso modo dei comandi kscript, così l'output di uno script somiglia al resto dello strumento. I colori si usano solo in un terminale: l'output reindirizzato, i file e i test ricevono lo stesso testo senza di essi, e NO_COLOR, FORCE_COLOR, --ansi e --no-ansi funzionano come per kscript stesso.

<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."
Testo
Report
  People .................................................... 2
  Adding up .......................................... 2ms DONE
  ┌──────┬─────┐
  │ name │ age │
  ├──────┼─────┤
  │ Joan │  82 │
  │ Sam  │   9 │
  └──────┴─────┘
   INFO  Wrote [report.txt].
   ERROR  The file [data.csv] is empty.

Le parti [bracketed] di un'etichetta sono mostrate in grassetto. alert(type: error) scrive su stderr. I numeri in una tabella sono allineati a destra; align: ['left', 'right'] imposta ogni colonna.

Il lavoro svolto a passi ottiene una barra di avanzamento. progress(into: bar, total: n) la mostra con il suo testo come etichetta, e $bar->advance() la avanza di un passo (o ->advance(5) di cinque). In un terminale viene ridisegnata sul posto; l'output reindirizzato e i test ricevono una riga, come per un task, quando raggiunge il totale:

<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) permette alla risposta di scegliere più opzioni, come 1, 3, e salva una lista delle scelte nell'ordine del menu (e at: una lista delle loro posizioni).

Modelli linguistici: KScript.AI

KScript.AI permette a uno script di interrogare Claude. La chiave API viene dalla variabile d'ambiente ANTHROPIC_API_KEY (oppure da un token in ANTHROPIC_AUTH_TOKEN, o dal profilo salvato con ant auth login, quando è installato il comando ant), mai dallo script. ANTHROPIC_BASE_URL invia le richieste a un altro host, come un proxy. Gli script usano claude-opus-5-5 a meno che non chiedano un altro modello, o KSCRIPT_AI_MODEL ne indichi uno.

<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 e @llm(prompt, ...) pongono la stessa domanda con le stesse opzioni: system, schema, tools (una lista come [@order_status]), model e max_tokens (16.000 per impostazione predefinita). L'unica differenza sta in dove viene il prompt e dove va la risposta: l'istruzione llm prende il prompt come testo e salva la risposta in to:, mentre @llm() prende il prompt come valore e restituisce la risposta, quindi può stare dentro un'espressione. @llm() prende le sue opzioni per nome: @llm($prompt, system: 'Be brief.', max_tokens: 500).
  • Schemi: ogni campo è obbligatorio. 'string', 'number', 'int', 'bool' e 'date' indicano un tipo, 'int 1-5' dà un intervallo, 'a|b|c' elenca le scelte, una mappa è un oggetto annidato, ['string'] è una lista, e ogni altro testo descrive un campo stringa.
  • Gli strumenti sono funzioni fn. La loro params (con tipi come id: int) e description dicono al modello come chiamarle. Se uno strumento fallisce, il modello riceve l'errore e può continuare.
  • I test usano @fake_llm(replies) al posto di Claude: vedi Simulare un modello linguistico.
  • Gli errori hanno il tipo AI, quindi un try con catch e può controllare $e.type e gestire una chiave mancante, un rifiuto o una risposta troncata da max_tokens. Quando i controlli di sicurezza di Claude respingono una richiesta, l'API la ripete prima su un modello di ripiego.

Come vengono eseguiti gli script

kscript compila ogni blocco di istruzioni la prima volta che viene eseguito, quindi un ciclo o una funzione chiamata molte volte viene eseguito come codice .NET invece di essere letto di nuovo a ogni passaggio. All'interno del corpo di una funzione o di un ciclo, le variabili che il blocco dichiara vengono conservate in slot numerati invece che in uno scope, ed è ciò che rende il codice ricco di numeri (problema dello zaino, ricerca su griglia, simulazione) diverse volte più veloce. Un corpo con un ciclo, oppure uno che è stato eseguito 64 volte, viene poi compilato di nuovo in un unico metodo .NET, quindi un ciclo stretto su numeri va circa il doppio più veloce ancora. Un ciclo in quel metodo il cui lavoro riguarda numeri e liste (aritmetica, confronti, lettura e impostazione di elementi di lista, if, while e for su un intervallo) riceve anche una seconda copia che considera le sue variabili esattamente tali, il che è diverse volte più veloce ancora; nel momento in cui un valore risulta essere qualcos'altro, il ciclo prosegue nella copia generale dalla stessa istruzione. Anche una funzione che passa fn(x) => ... a un metodo come ->map() mantiene i suoi slot, purché ogni variabile letta dal callback sia impostata una sola volta, prima che il callback venga chiamato. Un ciclo su un intervallo come 0..1000000 lo percorre senza creare la lista. Nulla cambia per lo script: gli stessi valori, gli stessi errori alla stessa riga e colonna, e il debugger continua a eseguire ogni istruzione passo passo, perché uno script sotto debug viene sempre interpretato.

Alcune variabili d'ambiente servono a confrontarle, per esempio quando si segnala un bug che compare solo in una di esse: KSCRIPT_INTERPRET=1 disattiva la compilazione, KSCRIPT_NO_REGIONS=1 compila ma mantiene ogni variabile in uno scope, KSCRIPT_NO_TREES=1 mantiene gli slot ma non crea mai il metodo .NET unico, e KSCRIPT_NO_LOOPS=1 crea il metodo senza la seconda copia dei suoi cicli.

Scrivere script portabili

  • Costruisci i percorsi con @join_path(base: $dir, ['reports', 'file.txt']) (KScript.IO) invece di scrivere \ o / direttamente.
  • Trova le cartelle dell'utente con @known_folder(downloads) (KScript.IO): home, desktop, documents, downloads, music, pictures, videos, appdata o temp. Segue le impostazioni di ciascun sistema, come la posizione Download di Windows e user-dirs.dirs di Linux.
  • $os.name è windows, linux o macos, e ci sono anche $os.home, $os.temp e $os.separator; $env.HOME legge una variabile d'ambiente.
  • I numeri vengono sempre letti e stampati con . come separatore decimale, qualunque sia la lingua della macchina.