KScript documentazione
IT

Lingua

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

Tipi e validazione

Tipi raffinati

Un tipo costruito su un tipo integrato, o su un altro tipo raffinato, aggiunge regole ad esso. Non ha campi: i suoi valori sono i valori del tipo base che superano le regole.

<type name="Age" with="int" min="0" max="150" />

<type name="Slug" with="string" pattern="/^[a-z0-9]+(-[a-z0-9]+)*$/">
  <normalize value="$value->trim()->lower()" />
</type>

<type name="Username" with="handle" max="16" not="[@admin, @root]" />

<let name="age" type="Age" value="42" />
<let name="slug" type="Slug" value="' Hello-World '" />
<echo>{ $age } { $slug }</echo>
<try>
  <let name="too_old" type="Age" value="200" />
  <catch as="err">
    <echo value="$err.message" />
  </catch>
</try>
type Age with [int] { min: 0; max: 150 }

type Slug with [string] {
  pattern: /^[a-z0-9]+(-[a-z0-9]+)*$/
  normalize: $value->trim()->lower()
}

type Username with [handle] {
  max: 16
  not: [@admin, @root]
}

$age: Age = 42
$slug: Slug = ' Hello-World '
echo "{ $age } { $slug }"
try {
  $too_old: Age = 200
} catch err {
  echo $err.message
}

Scrivi ogni regola su una riga separata, oppure separa più regole su una riga con un punto e virgola. Una virgola dopo il valore di una regola, come in min: 8,, è un errore di sintassi. Una regola validate accetta una virgola tra il suo test e il suo messaggio.

Regola Cosa verifica
min, max Il valore di un numero, oppure la lunghezza di un testo o di una lista.
pattern Il testo deve corrispondere. È un letterale regex come /^[a-z]+$/i, oppure un testo tra virgolette.
one_of Il valore deve essere uno di questi.
not Il valore non deve essere uno di questi.
validate: test, 'message' Qualsiasi espressione, con il valore come $value. Se ne possono dare diverse; ciascuna che fallisce aggiunge il suo messaggio.
normalize: expression Valuta un'espressione con il valore base in $value. Se l'espressione fornisce una funzione, KScript passa il valore base a quella funzione. Le regole verificano il valore restituito.
factory(value) => ... Ciò in cui viene trasformato un valore di questo tipo: un valore di un tipo derivato da esso. factory: ... legge il valore come $value. Vedi Factory.
value: expression Cosa rappresenta un valore ovunque venga usato, calcolato per ultimo, una volta superate tutte le regole. $value è il valore controllato, e il risultato può essere di un altro tipo. Vedi Cosa rappresenta un valore.

Un valore viene prima convertito nel tipo base, poi normalizzato, poi controllato rispetto alle regole e, per ultima, la sua regola value, se ce l'ha, calcola cosa rappresenta. Un valore che non passa segnala ogni regola violata. Le regole su un campo funzionano allo stesso modo: title: string(min: 1).

Chiamare un tipo crea un valore di esso, verificato allo stesso modo: Age(42), Slug(' Hello-World '). Ogni tipo dichiarato funziona così (Repo($data), Size('small')), e il suo nome va sempre scritto nudo, senza $.

Leggere ciò che il pattern ha catturato

Un tipo con un pattern spesso ha bisogno di una parte del proprio testo: il numero in [/3], l'unità in 12 cm. Invece di tagliare il testo, metti quella parte tra parentesi nel pattern e leggila con .group() dentro i metodi del tipo. Il gruppo 1 è il primo gruppo che si apre, 2 il successivo, e 0 è l'intera corrispondenza:

<type name="DivisionEntry" with="string" pattern="/^\[\/0*([1-9][0-9]*)\]$/">
  <fn name="apply_to" params="display: int" description="The display after pressing this button: divided by its number, rounded down." returns="int" value="($display / .group(1)->to_int())->floor()" />
</type>

<let name="button" value="DivisionEntry('[/05]')" />
<echo value="$button->apply_to(100)" /> <!-- 20, because group 1 is '5': the 0 before it is outside the brackets -->
type DivisionEntry with [string] {
  pattern: /^\[\/0*([1-9][0-9]*)\]$/

  /// The display after pressing this button: divided by its number, rounded down.
  fn apply_to(display: int): int => ($display / .group(1)->to_int())->floor()
}

$button = DivisionEntry('[/05]')
echo $button->apply_to(100)  // 20, because group 1 is '5': the 0 before it is outside the brackets

Un gruppo con nome, scritto (?<name>...), si legge con il suo nome. Conta comunque nella numerazione, quindi .group('amount') e .group(1) qui sotto leggono la stessa parte:

<type name="Measure" with="string" pattern="/^(?&lt;amount>[0-9]+) *(?&lt;unit>cm|mm|m)$/">
  <fn name="amount" returns="int" value=".group('amount')->to_int()" />
  <fn name="unit" returns="string" value=".group('unit')" />
</type>

<let name="shelf" value="Measure('120 cm')" />
<echo value="$shelf->amount() + 30" /> <!-- 150, because .group('amount') is the text '120', read as a number -->
<echo value="$shelf->unit()" /> <!-- cm -->
<echo value="$shelf->group(1)" /> <!-- 120: the same group as 'amount', by its number -->
type Measure with [string] {
  pattern: /^(?<amount>[0-9]+) *(?<unit>cm|mm|m)$/

  fn amount(): int => .group('amount')->to_int()
  fn unit(): string => .group('unit')
}

$shelf = Measure('120 cm')
echo $shelf->amount() + 30  // 150, because .group('amount') is the text '120', read as a number
echo $shelf->unit()          // cm
echo $shelf->group(1)        // 120: the same group as 'amount', by its number

.group() legge il valore dopo che normalize è stato eseguito, perché quello è il testo su cui è stato verificato il pattern. Aggiungi raw per leggere invece il testo così come è stato dato. Un gruppo che non ha partecipato alla corrispondenza, o un testo raw che il pattern non riconosce, dà null:

<type name="Measure" with="string" pattern="/^(?&lt;amount>[0-9]+) *(?&lt;unit>cm|mm|m)$/">
  <normalize value="$value->lower()" />

  <fn name="unit" returns="string" value=".group('unit')" />
  <fn name="unit_as_written" returns="string" value=".group('unit', raw)" />
</type>

<let name="shelf" value="Measure('120 CM')" />
<echo value="$shelf" /> <!-- 120 cm, because normalize lowered it -->
<echo value="$shelf->unit()" /> <!-- cm, read from the normalized text -->
<echo value="$shelf->unit_as_written()" /> <!-- CM, read from the text as it was given -->
type Measure with [string] {
  pattern: /^(?<amount>[0-9]+) *(?<unit>cm|mm|m)$/
  normalize: $value->lower()

  fn unit(): string => .group('unit')
  fn unit_as_written(): string => .group('unit', raw)
}

$shelf = Measure('120 CM')
echo $shelf               // 120 cm, because normalize lowered it
echo $shelf->unit()       // cm, read from the normalized text
echo $shelf->unit_as_written()  // CM, read from the text as it was given

.group() c'è su ogni tipo che ha un pattern e dei metodi o una regola value, nelle sue regole validate e value, e anche sui suoi valori dall'esterno ($shelf->group(1)). Un tipo fatto da un altro legge il proprio pattern quando ne ha uno, altrimenti il più vicino da cui è fatto, quindi ogni tipo creato da una factory legge i gruppi del proprio pattern. Chiedere un gruppo che il pattern non ha è un errore Value che elenca i gruppi che ha, e l'editor lo segnala dove lo scrivi:

Testo
.group(3) is past the last group. Measure's pattern /^(?<amount>[0-9]+) *(?<unit>cm|mm|m)$/ has 2 groups: .group(0) is the whole match, .group(1) to .group(2) the groups, and .group('amount'), .group('unit') by name.

Nell'editor, .group( propone i numeri e i nomi che il pattern ha, e un nome scritto male ha una correzione rapida verso quello più simile.

Cosa rappresenta un valore

A volte il testo che un tipo controlla non è il valore con cui vuoi lavorare. Un tasto del microonde scritto x11 significa "per 11": il tipo deve controllare il testo e poi lasciare che il resto dello script usi il numero. Una regola value dice cosa rappresenta un valore del tipo ovunque venga usato:

<type name="MultiplierEntry" with="string" pattern="/^x(\d+)$/">
  <normalize value="$value->trim()->lower()" />
  <value value=".group(1)->to_int()" />
</type>

<let name="button" value="MultiplierEntry(' X11 ')" />
<echo value="$button" /> <!-- 11, because value: reads group 1 of 'x11' as a number -->
<echo value="$button + 1" /> <!-- 12, because $button is the number 11 wherever it is used -->
type MultiplierEntry with [string] {
  normalize: $value->trim()->lower()
  pattern: /^x(\d+)$/
  value: .group(1)->to_int()
}

$button = MultiplierEntry(' X11 ')
echo $button      // 11, because value: reads group 1 of 'x11' as a number
echo $button + 1  // 12, because $button is the number 11 wherever it is used

I passaggi vengono eseguiti sempre nello stesso ordine, e ognuno ha il proprio compito:

  1. Il valore viene convertito nel tipo base: qui, testo.
  2. normalize lo ripulisce, e il risultato è ancora il tipo base: ' X11 ' diventa 'x11'.
  3. Le regole (pattern, min, max, one_of, not e validate) controllano quel testo ripulito.
  4. value calcola cosa rappresenta il valore: 11. Viene eseguito solo una volta superate tutte le regole, quindi può contare su di esse.

Dentro la regola value, $value è il testo controllato, e .group() legge ciò che il pattern ha catturato. Il risultato può essere di qualsiasi tipo. Va bene anche una funzione, che riceve il testo controllato:

<type name="Shouted" with="string" min="1">
  <value value="fn(text) => &quot;{$text->upper()}!&quot;" />
</type>

<echo value="Shouted('hello')" /> <!-- HELLO!, because the fn is given the checked text 'hello' -->
type Shouted with [string] {
  min: 1
  value: fn(text) => "{$text->upper()}!"
}

echo Shouted('hello')  // HELLO!, because the fn is given the checked text 'hello'

I metodi del tipo vedono il valore come viene rappresentato: in un metodo, $value è il risultato della regola value. .group() legge ancora il testo controllato, quindi un metodo può usare entrambi:

<type name="MultiplierEntry" with="string" pattern="/^x(\d+)$/">
  <value value=".group(1)->to_int()" />

  <fn name="apply_to" params="display: int" returns="int" value="$display * $value" />
  <fn name="label" returns="string" value="&quot;times {.group(1)}&quot;" />
</type>

<let name="button" value="MultiplierEntry('x3')" />
<echo value="$button->apply_to(20)" /> <!-- 60, because $value is the number 3 -->
<echo value="$button->label()" /> <!-- times 3, read from the checked text 'x3' -->
<echo value="$button->is_odd()" /> <!-- true: $button reads as 3, so it has a number's methods -->
type MultiplierEntry with [string] {
  pattern: /^x(\d+)$/
  value: .group(1)->to_int()

  fn apply_to(display: int): int => $display * $value
  fn label(): string => "times {.group(1)}"
}

$button = MultiplierEntry('x3')
echo $button->apply_to(20)  // 60, because $value is the number 3
echo $button->label()       // times 3, read from the checked text 'x3'
echo $button->is_odd()      // true: $button reads as 3, so it has a number's methods

Un valore mantiene il suo tipo, quindi passarlo a un parametro di quel tipo non controlla il numero come se fosse testo. Un parametro accetta anche il testo stesso e lo calcola allo stesso modo:

<type name="MultiplierEntry" with="string" pattern="/^x(\d+)$/">
  <value value=".group(1)->to_int()" />
</type>

<fn name="add_ten" params="entry: MultiplierEntry" returns="int" value="$entry + 10" />

<echo value="@add_ten(MultiplierEntry('x5'))" /> <!-- 15, because the value already has the type -->
<echo value="@add_ten('x6')" /> <!-- 16, because 'x6' is checked, then read as 6 -->
type MultiplierEntry with [string] {
  pattern: /^x(\d+)$/
  value: .group(1)->to_int()
}

fn add_ten(entry: MultiplierEntry): int => $entry + 10

echo @add_ten(MultiplierEntry('x5'))  // 15, because the value already has the type
echo @add_ten('x6')                    // 16, because 'x6' is checked, then read as 6

Un tipo creato da uno con una regola value rappresenta lo stesso risultato, a meno che non abbia una propria regola value. Le sue regole controllano ancora il testo, quindi possono usare anche .group():

<type name="MultiplierEntry" with="string" pattern="/^x(\d+)$/">
  <value value=".group(1)->to_int()" />
</type>

<type name="BigMultiplier" with="MultiplierEntry">
  <validate test=".group(1)->to_int() > 10" message="must be over 10" />
</type>

<echo value="BigMultiplier('x12') * 2" /> <!-- 24, because BigMultiplier reads as MultiplierEntry's number -->
type MultiplierEntry with [string] {
  pattern: /^x(\d+)$/
  value: .group(1)->to_int()
}

type BigMultiplier with [MultiplierEntry] {
  validate: .group(1)->to_int() > 10, 'must be over 10'
}

echo BigMultiplier('x12') * 2  // 24, because BigMultiplier reads as MultiplierEntry's number

Un tipo ha al massimo una regola value, e solo un tipo creato da un unico altro tipo può averne una: un tipo con campi rappresenta già il proprio record. Una colonna di database di un tipo così salva il testo controllato e ricalcola il risultato quando la riga viene letta.

Nell'editor, -> su un valore del tipo propone i metodi del risultato (qui, quelli di un numero) insieme a quelli del tipo, e un metodo di testo su di esso viene segnalato, perché fallirebbe in esecuzione.

Conversioni verificate con as

Usa expression as Type quando ti serve un valore tipizzato dentro un'espressione. KScript valuta l'espressione una volta, poi applica la stessa conversione, normalizzazione e validazione di un'assegnazione tipizzata. Un controllo fallito solleva un errore nel cast.

<type name="PasskeySessionKey" with="string" min="8" pattern="/^passkey_[a-zA-Z]+$/">
  <normalize value="fn(c) => $c->trim()" />
  <fn name="length">
    <return value="$value->count()" />
  </fn>
</type>

<fn name="key_length" params="key: PasskeySessionKey" value="$key->count()" />

<let name="kind" value="'login'" />
<let name="session_key" value="&quot;passkey_{$kind}&quot; as PasskeySessionKey" />
<echo value="$session_key" /> <!-- passkey_login -->
<echo value="$session_key->count()" /> <!-- 13 -->
<echo value="$session_key->length()" /> <!-- 13 -->
<echo value="@key_length($session_key)" /> <!-- 13 -->
type PasskeySessionKey with [string] {
  min: 8
  normalize: fn(c) => $c->trim()
  pattern: /^passkey_[a-zA-Z]+$/
  fn length() {
    return $value->count()
  }
}

fn key_length(key: PasskeySessionKey) => $key->count()

$kind = 'login'
$session_key = "passkey_{$kind}" as PasskeySessionKey
echo $session_key  // passkey_login
echo $session_key->count()  // 13
echo $session_key->length()  // 13
echo @key_length($session_key)  // 13

La barra di apertura viene prima dell'ancora ^ in un letterale regex. Qui il normalizzatore riceve la stringa prima che il pattern venga eseguito. Puoi anche scrivere direttamente normalize: $value->trim().

as set e as list passano da una lista a un insieme. Un insieme conserva ogni elemento una sola volta, quindi ['tea', 'milk', 'tea'] as set contiene due elementi, e $set as list li restituisce come lista nell'ordine in cui sono stati aggiunti:

<let name="drinks" value="['tea', 'milk', 'tea'] as set" />
<echo value="$drinks->count()" /> <!-- 2 -->
<echo value="($drinks as list)->type()" /> <!-- string[] -->
$drinks = ['tea', 'milk', 'tea'] as set
echo $drinks->count()          // 2
echo ($drinks as list)->type() // string[]

Un helper può risiedere sul tipo stesso. Il normalizzatore può chiamarlo con @trim_key($value) oppure passare la funzione come normalize: @trim_key. Entrambe le forme usano la stringa in ingresso. KScript trova helper dichiarati più avanti nel blocco, metodi ereditati e funzioni dichiarate nel modulo circostante. Un metodo sul tipo ha la precedenza su una funzione di modulo con lo stesso nome.

<type name="KeyText" with="string">
  <normalize value="@trim_key($value)" />
  <fn name="trim_key" params="key: string" value="$key->trim()" />
</type>
<echo value="KeyText('  passkey_Login  ')" /> <!-- passkey_Login -->
type KeyText with [string] {
  normalize: @trim_key($value)
  fn trim_key(key: string) => $key->trim()
}
echo KeyText('  passkey_Login  ')  // passkey_Login

Un PasskeySessionKey supporta i metodi di string e i propri metodi. All'interno di un metodo raffinato, $value è il valore sottostante e $this è il ricevitore raffinato, quindi $this->length() può chiamare un altro metodo del tipo. Un raffinamento eredita i metodi dalla sua base e può sostituirne uno dichiarando lo stesso nome. Usa $value per chiamare il metodo integrato sottostante. Puoi anche passare la chiave a una funzione tipizzata come key_length. In un metodo di record, $this.field legge un campo del record.

Il bersaglio può anche essere un tipo integrato ($text as int), un tipo con regole locali ($name as string(min: 2)), oppure una lista ($rows as Repo[]). Un bersaglio opzionale come PasskeySessionKey? accetta null e valida ogni valore non nullo. Racchiudi tra parentesi un'espressione aritmetica per convertirne il risultato, come in ($a + $b) as int.

Convertire un numero con as int, una variabile tipizzata ($n: int = 3.9) o un parametro int elimina la parte frazionaria e dà 3. I dati verificati rispetto a un tipo sono più rigidi: un campo int, un elemento int[] o un raffinamento di int segnala un numero che non è intero (needs a whole number, but got a number (12.9)) invece di troncarlo. Un testo come 'NaN' o 'Infinity' non è un numero, e un numero semplice come '1.5' non è una data.

I tuoi tipi nativi

kscript make native scrive un tipo raffinato su natives/ che funziona come uno integrato. Ogni script del progetto può usarlo senza import, allo stesso modo della cartella extensions/. I suoi valori si scrivono senza virgolette dove il tipo legge testo, vengono verificati ovunque il tipo sia usato (assegnazioni, argomenti, una chiamata del tipo e corpi di richiesta), e l'editor verifica i valori scritti nel codice:

ComandoCosa fa
kscript make native Sku --pattern '/^[A-Z]{3}-\d{4}$/' --normalize '$value->trim()->upper()'Testo in un pattern, prima ripulito.
kscript make native Percent --base int --min 0 --max 100Un intero da 0 a 100.
kscript make native Username --base handle --max 16 --not @admin,@rootUn handle, con nomi non ammessi.
kscript make native CompanySite --base url --validate '$value.host->ends_with("example.com"), "Use a company site"'Un URL con una regola propria.
kscript make native Multiplier --pattern '/^x(\d+)$/' --value '.group(1)->to_int()'Testo come x11 che rappresenta il numero 11.

Il primo scrive natives/sku.kscript:

<type name="Sku" with="string" description="Sku: a native type built on string. A value that breaks a rule fails where it is made, and the editor checks the values written in code." pattern="/^[A-Z]{3}-\d{4}$/">
  <normalize value="$value->trim()->upper()" />
  <!-- Rules: normalize, pattern, min, max, one_of, not, validate and value. Add methods with fn. -->
</type>
/// Sku: a native type built on string. A value that breaks a rule fails where it is made, and the editor checks the values written in code.
type Sku with [string] {
  normalize: $value->trim()->upper()
  pattern: /^[A-Z]{3}-\d{4}$/
  // Rules: normalize, pattern, min, max, one_of, not, validate and value. Add methods with fn.
}

Poi, in qualsiasi script del progetto:

<let name="sku" type="Sku" value="abc-1234" /> <!-- ABC-1234 -->
<fn name="price" params="of: Sku" value="10" />
$sku: Sku = abc-1234   // ABC-1234
fn price(of: Sku) => 10

--base seleziona il tipo base, che di default è string. Accetta tipi nativi come url, domain e country, oppure un altro raffinamento. Le regole sono --pattern, --min, --max, --one-of a,b, --not a,b, --normalize, --validate "test, 'message'" e --value, che dice cosa rappresenta un valore (vedi Cosa rappresenta un valore). Dichiara i metodi con fn nel corpo del tipo e richiamali con ->.

Il blocco contiene solo le regole e i metodi fn, mai istruzioni. Codice come echo o if va dentro un metodo, e l'editor lo segnala come errore altrove nel blocco, indicando cosa contiene il blocco:

<type name="Percent" with="int" min="0" max="100">
  <!-- A method: code goes in here. echo or if on its own line in the block is an error. -->
  <fn name="is_full" value="$value == 100" />
</type>
type Percent with [int] {
  min: 0
  max: 100

  // A method: code goes in here. echo or if on its own line in the block is an error.
  fn is_full() => $value == 100
}

Lo stesso vale per il blocco di ogni dichiarazione: un tipo record contiene i suoi campi, regole, construct e metodi; un model i suoi campi, regole validate: e metodi; un job i suoi campi e le sue funzioni handle, failed e middleware; un errore i suoi campi; un blocco extend i suoi metodi; e un enum i suoi valori. Il completamento in un blocco suggerisce solo ciò che può contenere. In un progetto XML, il file è un elemento <type> in natives/sku.ks.xml.

I tipi e gli enum in ogni file sotto natives/ (anche nelle sottocartelle) sono i tipi nativi del progetto. "natives" in kscript.json indica altre cartelle o glob, e kscript make native scrive nella prima cartella elencata:

JSON
{ "natives": ["src/types", "shared/**/*.kscript"] }

Un tipo che uno script dichiara da sé prevale su un tipo di progetto con lo stesso nome.

Factory: un tipo, più varianti

A volte un tipo di valore arriva in più forme, e ogni forma ha bisogno della propria regola e del proprio comportamento. La tastiera di un forno a microonde ha i tasti numerici (7), i tasti moltiplicatori ([*2]) e un tasto di cancellazione (<). Sono tutti pulsanti, ma ciascuno viene letto in modo diverso e fa qualcosa di diverso quando lo premi.

Dai al tipo padre una factory. Indica in cosa viene trasformato un valore del tipo e restituisce un valore di un tipo derivato dal padre con with [Parent]. Ognuno di questi tipi mantiene la propria regola. La factory tipica è un try each, che prova ogni tipo a turno:

<type name="MicrowaveButton" with="string" factory="fn(label) => try each $label |> NumberEntry, MultiplierEntry, BackspaceEntry">
  <validate test="not $value->contains(' ')" message="a label has no spaces" />

  <fn name="apply" params="total: int" returns="int" value="$total" />
</type>

<type name="NumberEntry" with="MicrowaveButton" pattern="/^[0-9]+$/">
  <fn name="apply" params="total: int" returns="int" value="$total * 10 ** $value->count() + $value->to_int()" />
</type>

<type name="MultiplierEntry" with="MicrowaveButton" pattern="/^\[\*([0-9]+)\]$/">
  <fn name="apply" params="total: int" returns="int" value="$total * .group(1)->to_int()" />
</type>

<type name="BackspaceEntry" with="MicrowaveButton" one_of="['&lt;']">
  <fn name="apply" params="total: int" returns="int" value="$total ~/ 10" />
</type>
type MicrowaveButton with [string] {
  validate: not $value->contains(' '), 'a label has no spaces'
  factory(label) => try each $label |> NumberEntry, MultiplierEntry, BackspaceEntry

  fn apply(total: int): int => $total
}

type NumberEntry with [MicrowaveButton] {
  pattern: /^[0-9]+$/
  fn apply(total: int): int => $total * 10 ** $value->count() + $value->to_int()
}

type MultiplierEntry with [MicrowaveButton] {
  pattern: /^\[\*([0-9]+)\]$/
  fn apply(total: int): int => $total * .group(1)->to_int()
}

type BackspaceEntry with [MicrowaveButton] {
  one_of: ['<']
  fn apply(total: int): int => $total ~/ 10
}

Chiamare il padre legge un'etichetta e restituisce ciò che la factory ne ha ricavato. Ogni valore mantiene il proprio tipo, e il suo testo resta l'etichetta:

<let name="button" value="MicrowaveButton('[*11]')" />
<echo value="$button" /> <!-- [*11] -->
<echo value="$button->is_a(MultiplierEntry)" /> <!-- true, because [*11] matches MultiplierEntry's pattern -->
<echo value="$button->is_a(MicrowaveButton)" /> <!-- true, because a MultiplierEntry is still a MicrowaveButton -->
<echo value="MicrowaveButton('7')->is_a(NumberEntry)" /> <!-- true -->
$button = MicrowaveButton('[*11]')
echo $button                           // [*11]
echo $button->is_a(MultiplierEntry)    // true, because [*11] matches MultiplierEntry's pattern
echo $button->is_a(MicrowaveButton)    // true, because a MultiplierEntry is still a MicrowaveButton
echo MicrowaveButton('7')->is_a(NumberEntry)  // true

factory(label) => ... dà un nome al valore. factory: ... è la stessa factory con il valore come $value, così come lo leggono validate: e normalize::

<type name="Reply" with="string" factory="try each $value |> ShortReply, AnyReply" />

<type name="ShortReply" with="Reply" max="3" />

<type name="AnyReply" with="Reply" min="1" />

<echo value="Reply('ok')->is_a(ShortReply)" /> <!-- true, because ShortReply is tried first -->
<echo value="Reply('hello')->is_a(AnyReply)" /> <!-- true, because hello is too long for ShortReply -->
type Reply with [string] {
  factory: try each $value |> ShortReply, AnyReply
}

type ShortReply with [Reply] {
  max: 3
}

type AnyReply with [Reply] {
  min: 1
}

echo Reply('ok')->is_a(ShortReply)     // true, because ShortReply is tried first
echo Reply('hello')->is_a(AnyReply)    // true, because hello is too long for ShortReply

Perché una factory

Poiché ogni valore mantiene il proprio tipo, il codice che riceve un MicrowaveButton non deve mai chiedersi di che variante si tratta: chiamare un metodo esegue la versione del tipo stesso, o quella del padre se il tipo non ne dichiara una.

<type name="MicrowaveButton" with="string" factory="fn(label) => try each $label |> NumberEntry, MultiplierEntry, BackspaceEntry">
  <fn name="apply" params="total: int" returns="int" value="$total" />
</type>

<type name="NumberEntry" with="MicrowaveButton" pattern="/^[0-9]+$/">
  <fn name="apply" params="total: int" returns="int" value="$total * 10 ** $value->count() + $value->to_int()" />
</type>

<type name="MultiplierEntry" with="MicrowaveButton" pattern="/^\[\*([0-9]+)\]$/">
  <fn name="apply" params="total: int" returns="int" value="$total * .group(1)->to_int()" />
</type>

<type name="BackspaceEntry" with="MicrowaveButton" one_of="['&lt;']">
  <fn name="apply" params="total: int" returns="int" value="$total ~/ 10" />
</type>

<fn name="parse_buttons" params="input: string" returns="MicrowaveButton[]" value="
  $input->split(' ')->map(fn(label) => MicrowaveButton($label))" />

<fn name="calculate" params="buttons: MicrowaveButton[]" returns="int" value="
  $buttons->reduce(fn(total, button) => $button->apply($total), 0)" />

<let name="buttons" value="@parse_buttons('1 2 [*3] &lt;')" />
<echo value="@calculate($buttons)" /> <!-- 3: 1, then 12, then 36, then the backspace drops the 6 -->
<echo value="MicrowaveButton('[*3]')->apply(12)" /> <!-- 36, because MultiplierEntry's apply multiplies -->
<echo value="MicrowaveButton('&lt;')->apply(36)" /> <!-- 3, because BackspaceEntry's apply drops the last digit -->
type MicrowaveButton with [string] {
  factory(label) => try each $label |> NumberEntry, MultiplierEntry, BackspaceEntry
  fn apply(total: int): int => $total
}

type NumberEntry with [MicrowaveButton] {
  pattern: /^[0-9]+$/
  fn apply(total: int): int => $total * 10 ** $value->count() + $value->to_int()
}

type MultiplierEntry with [MicrowaveButton] {
  pattern: /^\[\*([0-9]+)\]$/
  fn apply(total: int): int => $total * .group(1)->to_int()
}

type BackspaceEntry with [MicrowaveButton] {
  one_of: ['<']
  fn apply(total: int): int => $total ~/ 10
}

fn parse_buttons(input: string): MicrowaveButton[] =>
  $input->split(' ')->map(fn(label) => MicrowaveButton($label))

fn calculate(buttons: MicrowaveButton[]): int =>
  $buttons->reduce(fn(total, button) => $button->apply($total), 0)

$buttons = @parse_buttons('1 2 [*3] <')
echo @calculate($buttons)  // 3: 1, then 12, then 36, then the backspace drops the 6
echo MicrowaveButton('[*3]')->apply(12)  // 36, because MultiplierEntry's apply multiplies
echo MicrowaveButton('<')->apply(36)     // 3, because BackspaceEntry's apply drops the last digit

La lista tipizzata MicrowaveButton[] e il button in reduce mantengono il tipo di ogni elemento, quindi [*3] è ancora un MultiplierEntry dentro calculate, ed è il suo apply a essere eseguito.

Come viene creato un valore

Quando chiami MicrowaveButton($label), KScript:

  1. controlla una volta le regole proprie del padre (qui, nessuno spazio),
  2. esegue la factory con l'etichetta, e
  3. restituisce ciò che la factory ha creato, che deve essere un valore di MicrowaveButton o di un tipo derivato da esso.

Con try each, l'ordine in cui scrivi è l'ordine in cui si prova, quindi metti prima il tipo più specifico: una risposta ok corrisponde sia a ShortReply sia a AnyReply, e vince ShortReply perché viene prima. I tipi creati dalla factory non ricontrollano le regole del padre. Le regole validate di un tipo vengono eseguite dopo che le sue regole semplici (pattern, min, max, one_of, not) sono passate, quindi una regola può contare sul fatto che il pattern abbia già trovato corrispondenza.

Quando nulla corrisponde

Un'etichetta che non rispetta le regole del padre riceve quell'errore, e la factory non viene eseguita. Un'etichetta a cui non corrisponde nessun tipo del try each riceve un unico errore Shape che indica il padre, l'etichetta e ogni tipo provato:

<try>
  <let name="button" value="MicrowaveButton('[x]')" />
  <catch type="Shape" as="err">
    <echo value="$err.message" />
    <!-- The value doesn't fit MicrowaveButton: the string '[x]' fits none of NumberEntry, MultiplierEntry, BackspaceEntry. -->
  </catch>
</try>
try {
  $button = MicrowaveButton('[x]')
} catch Shape as err {
  echo $err.message
  // The value doesn't fit MicrowaveButton: the string '[x]' fits none of NumberEntry, MultiplierEntry, BackspaceEntry.
}

Per dirlo con parole tue, termina il try each con una riga _ => che lancia un errore:

<type name="Coin" with="string" factory="fn(side) => try each $side |>
    Heads,
    Tails,
    _ => throw Validation &quot;A coin lands on heads or tails, not {$side}&quot;" />

<type name="Heads" with="Coin" one_of="[heads]" />

<type name="Tails" with="Coin" one_of="[tails]" />

<echo value="Coin('heads')->is_a(Heads)" /> <!-- true -->
type Coin with [string] {
  factory(side) => try each $side |>
    Heads,
    Tails,
    _ => throw Validation "A coin lands on heads or tails, not {$side}"
}

type Heads with [Coin] {
  one_of: [heads]
}

type Tails with [Coin] {
  one_of: [tails]
}

echo Coin('heads')->is_a(Heads)  // true

Una regola che non passa significa solo “non questo tipo”, quindi si prova il successivo. Un errore lanciato da una regola, come una divisione per zero dentro validate, non è una mancata corrispondenza: risale fino al chiamante.

Creare un tipo direttamente

Puoi anche chiamare un tipo creato dalla factory. MultiplierEntry('[*3]') controlla le regole del padre e poi quelle di MultiplierEntry, e nient'altro: la factory non viene eseguita, quindi MultiplierEntry('12') è un errore Shape anche se 12 è un NumberEntry valido.

Tipi in file separati

Ogni tipo può stare in un file a sé. Metti il padre e i tipi derivati nella cartella natives/ del progetto: ogni script li vede senza import, quindi il padre può venire prima o dopo di loro. Il kscript check del progetto e l'editor controllano la factory allo stesso modo:

  • ogni tipo indicato nel try each deve derivare dal padre (with [MicrowaveButton]),
  • la factory non chiama mai il padre stesso, perché eseguirebbe di nuovo la factory, all'infinito,
  • factory(label) => ... accetta un solo valore, e
  • la factory va su un tipo derivato da un solo altro tipo, non su un tipo con campi.

Nell'editor, la riga factory viene proposta in un tipo derivato da un solo altro tipo, il |> e ogni virgola dopo di esso propongono i tipi derivati dal padre che la factory non prova ancora, e ogni nome porta al suo tipo. La lista variants: [...] usata prima di factory è un errore che indica cosa scrivere al suo posto.

Vicini: i valori accanto in una lista

Un valore letto da una sequenza a volte deve sapere cosa c'era prima o dopo. Un backspace annulla il pulsante premuto subito prima; una parentesi chiusa appartiene a quella aperta che la precede. Nei metodi del tipo stesso, .behind è il valore prima di questo nella sua lista e .ahead è il valore dopo:

<type name="Key" with="string" factory="fn(label) => try each $label |> Digit, Backspace">
  <fn name="label" description="What the key shows on its label." returns="string" value="$value" />
</type>

<type name="Digit" with="Key" pattern="/^[0-9]$/">
  <fn name="undone" description="True when the next key is a backspace, which takes this digit back." returns="bool" value=".ahead != null and .ahead->is_a(Backspace)" />
</type>

<type name="Backspace" with="Key" one_of="['&lt;']">
  <fn name="undoes" description="The key this backspace takes back: the one pressed just before it." returns="Key?" value=".behind" />
</type>

<let name="keys" value="'4 2 &lt;'->split(' ') as Key[]" />
<let name="back" value="$keys[2] as Backspace" />
<echo value="$back->undoes()" /> <!-- 2, because .behind is the key pressed before the backspace -->
<echo value="($keys[1] as Digit)->undone()" /> <!-- true, because the key after the 2 is a backspace -->
<echo value="($keys[0] as Digit)->undone()" /> <!-- false, because the key after the 4 is a 2 -->
type Key with [string] {
  factory(label) => try each $label |> Digit, Backspace

  /// What the key shows on its label.
  fn label(): string => $value
}

type Digit with [Key] {
  pattern: /^[0-9]$/

  /// True when the next key is a backspace, which takes this digit back.
  fn undone(): bool => .ahead != null and .ahead->is_a(Backspace)
}

type Backspace with [Key] {
  one_of: ['<']

  /// The key this backspace takes back: the one pressed just before it.
  fn undoes(): Key? => .behind
}

$keys = '4 2 <'->split(' ') as Key[]
$back = $keys[2] as Backspace
echo $back->undoes()                  // 2, because .behind is the key pressed before the backspace
echo ($keys[1] as Digit)->undone()    // true, because the key after the 2 is a backspace
echo ($keys[0] as Digit)->undone()    // false, because the key after the 4 is a 2

Un valore conosce la propria posizione quando la sua lista è tipizzata: as Key[] come sopra, una variabile, un parametro, un campo o un tipo di ritorno Key[]. Ogni valore mantiene la posizione che aveva in quella lista in quel momento, quindi un valore che filtri dalla lista, o che passi come Backspace, conosce ancora i tasti che aveva accanto:

<type name="Key" with="string" factory="fn(label) => try each $label |> Digit, Backspace">
  <fn name="label" returns="string" value="$value" />
</type>

<type name="Digit" with="Key" pattern="/^[0-9]$/" />

<type name="Backspace" with="Key" one_of="['&lt;']">
  <fn name="undoes" returns="Key?" value=".behind" />
</type>

<fn name="parse_keys" params="input: string" returns="Key[]" value="
  $input->split(' ')->map(fn(label) => Key($label))" />

<let name="keys" value="@parse_keys('7 3 &lt;')" />
<let name="backspaces" value="$keys->filter(fn(key) => $key->is_a(Backspace))" />
<echo value="($backspaces[0] as Backspace)->undoes()" /> <!-- 3, its neighbour in the list parse_keys returned -->
type Key with [string] {
  factory(label) => try each $label |> Digit, Backspace
  fn label(): string => $value
}

type Digit with [Key] {
  pattern: /^[0-9]$/
}

type Backspace with [Key] {
  one_of: ['<']
  fn undoes(): Key? => .behind
}

fn parse_keys(input: string): Key[] =>
  $input->split(' ')->map(fn(label) => Key($label))

$keys = @parse_keys('7 3 <')
$backspaces = $keys->filter(fn(key) => $key->is_a(Backspace))
echo ($backspaces[0] as Backspace)->undoes()  // 3, its neighbour in the list parse_keys returned

Le regole:

  • Tipizzati come il tipo in cima, o null. .ahead e .behind hanno come tipo quello in cima alla catena with con ? (qui Key?), perché il primo valore non ha nulla prima e l'ultimo non ha nulla dopo. Ogni vicino mantiene il proprio tipo, quindi ->is_a(Digit) ti dice di che variante si tratta. Chiamare un metodo su uno di essi senza ?. o un controllo != null genera un avviso nell'editor, come per qualsiasi valore che può essere null.
  • I vicini conoscono i loro vicini. .behind?.behind è due valori indietro.
  • Solo nei metodi del tipo stesso. È lì che un valore conosce sempre la sua lista. $keys[1].ahead fuori dal tipo, .ahead in un ciclo for, o $key.ahead nel metodo di un altro tipo è un errore, nell'editor e in esecuzione:
Testo
.ahead is read inside Key's own methods, such as fn next(): Key? => .ahead, where a value knows the list it was read into.
  • Un valore creato da solo non ha vicini. Backspace('<')->undoes() non ha una lista, quindi leggere .behind al suo interno è un errore Value. L'editor lo segnala sulla chiamata quando può vedere che il valore è stato creato da solo:
Testo
->undoes() reads .behind, but this Backspace was made on its own, not read into a typed list, so it has no neighbours. A value knows its neighbours when its list is typed, such as $labels as Key[], or a Key[] parameter, field or variable.
  • Paghi solo ciò che leggi. Una lista conserva le posizioni dei suoi valori solo quando uno dei metodi dei loro tipi legge .ahead o .behind. Un tipo che non li legge mai è veloce come prima e non si porta dietro nulla in più.

Nell'editor, . dentro un metodo propone ahead e behind (e di nuovo dopo .behind?.), con il tipo con cui vengono letti, e passandoci sopra con il mouse si vede cosa sono. Non vengono mai proposti dove sarebbero un errore.

Tipi nativi dai pacchetti

Un pacchetto aggiunge un tipo nativo con p.NativeType(new IsbnType()), dove IsbnType è una sottoclasse di NativeType (KScript.Core). La classe base fa sì che un tipo dichiari tutto ciò che il linguaggio fa con i suoi valori, quindi nulla può essere omesso: il suo nome, descrizione ed esempio, come il testo diventa un valore (Parse), come si scrive senza virgolette, cosa significa == (Equality), se < e l'ordinamento funzionano (Ordering), se un ciclo for può percorrerlo (Iteration), i suoi operatori (DeclareOperators), i suoi campi e metodi (DeclareMembers), i filtri e i metodi di una lista di esso (DeclareListMembers), i metodi stringa che mantiene e i valori che l'editor propone. "Nessuno" è una risposta valida a ciascuno, scritta come corpo vuoto o Ordering.None. DurationType è quello da copiare. Una volta importato il pacchetto, il tipo funziona come uno integrato: valori senza virgolette, controlli nell'editor, ->type() e schemi OpenAPI. I nomi dei tipi nativi sono in minuscolo, e un nome già preso non può essere riutilizzato.