정제 타입
하나의 내장 타입이나 다른 정제 타입을 바탕으로 만든 타입은 규칙을 더해요. 필드는 없어요. 값은 규칙을 통과한 기반 타입의 값들이에요.
<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
}규칙은 한 줄에 하나씩 쓰거나, 세미콜론으로 한 줄에 여러 규칙을 나눠 쓸 수 있어요. min: 8,처럼 규칙 값 뒤의 쉼표는 구문 오류예요. validate 규칙은 검사식과 메시지 사이에 쉼표를 쓸 수 있어요.
| 규칙 | 검사하는 대상 |
|---|---|
min, max |
숫자의 값, 또는 텍스트나 목록의 길이. |
pattern |
텍스트가 일치해야 해요. /^[a-z]+$/i와 같은 정규식 리터럴이나 따옴표로 묶은 텍스트예요. |
one_of |
값은 다음 중 하나여야 해요. |
not |
값은 다음 중 어느 것도 아니어야 해요. |
validate: test, 'message' |
어떤 식이든 가능하며, 값은 $value로 표현돼요. 여러 개를 줄 수 있고, 실패할 때마다 각자의 메시지가 추가돼요. |
normalize: expression |
기반 값을 $value에 담아 식을 평가해요. 식이 함수를 제공하면, KScript가 기반 값을 그 함수에 넘겨줘요. 규칙은 반환된 값을 검사해요. |
factory(value) => ... |
이 타입의 값이 무엇으로 만들어지는지 정해요. 그 타입에서 만든 타입의 값이 돼요. factory: ...은 값을 $value로 읽어요. 팩토리를 참고하세요. |
value: expression |
값이 쓰이는 모든 곳에서 나타내는 것으로, 모든 규칙을 통과한 뒤 마지막에 구합니다. $value는 검사를 마친 값이며, 결과는 다른 타입이어도 됩니다. 값이 나타내는 것을 참조하세요. |
값은 먼저 기반 타입으로 변환되고, 정규화된 다음, 규칙에 맞는지 검사되며, 마지막으로 value 규칙이 있으면 그 값이 나타내는 것을 구합니다. 실패한 값은 어긴 규칙을 모두 보고합니다. 필드의 규칙도 같은 방식으로 동작합니다: title: string(min: 1).
타입을 호출하면 그 타입의 값을 만들며, 같은 방식으로 검사해요: Age(42), Slug(' Hello-World '). 선언된 모든 타입이 이렇게 동작하고(Repo($data), Size('small')), 그 이름은 항상 $ 없이 그대로 써요.
패턴이 캡처한 내용 읽기
pattern가 있는 타입은 종종 자기 텍스트의 일부가 필요합니다. [/3]의 숫자, 12 cm의 단위 같은 것입니다. 텍스트를 잘라 내는 대신, 패턴에서 그 부분을 괄호로 묶고 타입의 메서드 안에서 .group()로 읽으세요. 그룹 1는 처음 열리는 그룹, 2는 그다음, 0는 일치 전체입니다:
<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(?<name>...)로 쓰는 이름 있는 그룹은 이름으로 읽습니다. 번호 매기기에도 여전히 포함되므로, 아래의 .group('amount')와 .group(1)는 같은 부분을 읽습니다:
<type name="Measure" with="string" pattern="/^(?<amount>[0-9]+) *(?<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()는 normalize가 실행된 뒤의 값을 읽습니다. 그것이 패턴이 검사한 텍스트이기 때문입니다. 대신 주어진 그대로의 텍스트를 읽으려면 raw를 더하세요. 일치에 참여하지 않은 그룹이나 패턴에 맞지 않는 raw 텍스트는 null를 줍니다:
<type name="Measure" with="string" pattern="/^(?<amount>[0-9]+) *(?<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()는 pattern와 메서드 또는 value 규칙이 있는 모든 타입에서 쓸 수 있어요. 그 타입의 validate와 value 규칙 안에서도, 밖에서 값에 대해서도($shelf->group(1)) 쓸 수 있어요. 다른 타입으로 만든 타입은 자기 패턴이 있으면 그것을, 없으면 가장 가까운 원래 타입의 패턴을 읽어요. 그래서 factory가 만드는 각 타입은 자기 패턴의 그룹을 읽어요. 패턴에 없는 그룹을 요청하면 있는 그룹을 나열하는 Value 오류가 나고, 편집기는 그것을 쓴 자리에 표시해요:
.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.편집기에서 .group(는 패턴에 있는 번호와 이름을 제안하고, 철자가 틀린 이름에는 가장 가까운 이름으로 바꾸는 빠른 수정이 있습니다.
값이 나타내는 것
타입이 검사하는 텍스트가 실제로 다루고 싶은 값이 아닐 때가 있습니다. x11로 적힌 전자레인지 버튼은 "11배"를 뜻합니다. 타입은 텍스트를 검사하고, 스크립트의 나머지 부분에서는 숫자를 쓰게 해야 합니다. value 규칙은 그 타입의 값이 쓰이는 모든 곳에서 무엇을 나타내는지 정합니다:
<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단계는 항상 같은 순서로 실행되며, 각 단계에는 저마다의 역할이 있습니다:
- 값이 기반 타입으로 변환됩니다. 여기서는 텍스트입니다.
normalize가 값을 정리하며, 결과는 여전히 기반 타입입니다:' X11 '는'x11'가 됩니다.- 규칙(
pattern,min,max,one_of,not,validate)이 그렇게 정리된 텍스트를 검사합니다. value는 값이 나타내는 것을 구합니다:11. 모든 규칙을 통과한 뒤에만 실행되므로 규칙을 믿고 쓸 수 있습니다.
value 규칙 안에서 $value는 검사를 마친 텍스트이고, .group()는 패턴이 잡아낸 부분을 읽습니다. 결과는 어떤 타입이어도 됩니다. 검사를 마친 텍스트를 받는 함수도 쓸 수 있습니다:
<type name="Shouted" with="string" min="1">
<value value="fn(text) => "{$text->upper()}!"" />
</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'타입의 메서드는 값이 나타내는 것으로 값을 봅니다. 메서드 안에서 $value는 value 규칙의 결과입니다. .group()는 여전히 검사를 마친 텍스트를 읽으므로, 메서드는 둘 다 쓸 수 있습니다:
<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=""times {.group(1)}"" />
</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값은 타입을 유지하므로, 그 타입의 매개변수에 넘겨도 숫자를 텍스트처럼 검사하지 않습니다. 매개변수는 텍스트 자체도 받으며, 같은 방식으로 값을 구합니다:
<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 6value 규칙이 있는 타입으로 만든 타입은 자체 value 규칙이 없는 한 같은 결과를 나타냅니다. 그 규칙들은 여전히 텍스트를 검사하므로 .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타입은 value 규칙을 최대 하나만 가질 수 있으며, 다른 타입 하나로 만든 타입만 가질 수 있습니다. 필드가 있는 타입은 이미 자신의 레코드를 나타냅니다. 이런 타입의 데이터베이스 열은 검사를 마친 텍스트를 저장하고, 행을 읽을 때 결과를 다시 구합니다.
편집기에서 그 타입의 값에 ->를 쓰면 타입 자체의 메서드와 함께 결과의 메서드(여기서는 숫자의 메서드)가 제안되며, 텍스트 메서드는 실행하면 실패하므로 보고됩니다.
as을 이용한 검사된 변환
식 안에서 타입이 지정된 값이 필요할 때 expression as Type을 사용하세요. KScript는 식을 한 번 평가한 뒤, 타입이 지정된 할당과 같은 변환, 정규화, 검증을 적용해요. 검사에 실패하면 변환 지점에서 오류가 발생해요.
<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=""passkey_{$kind}" 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정규식 리터럴에서는 여는 슬래시가 ^ 앵커보다 앞에 와요. 여기서 정규화기는 패턴이 실행되기 전에 문자열을 받아요. normalize: $value->trim()를 직접 쓸 수도 있어요.
as set과 as list는 목록과 집합 사이를 오가요. 집합은 각 항목을 한 번만 보관하므로, ['tea', 'milk', 'tea'] as set는 두 항목을 가지고, $set as list는 추가된 순서대로 목록으로 돌려줘요:
<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[]도우미 함수를 타입 자체에 둘 수 있어요. 정규화기는 @trim_key($value)로 호출하거나 함수를 normalize: @trim_key로 넘길 수 있어요. 두 형태 모두 입력 문자열을 사용해요. KScript는 블록 뒤쪽에 선언된 도우미, 상속된 메서드, 둘러싼 모듈에 선언된 함수를 찾아요. 타입의 메서드는 같은 이름의 모듈 함수보다 우선해요.
<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_LoginPasskeySessionKey은 string의 메서드와 자체 메서드를 지원해요. 정제 메서드 안에서 $value는 기반 값이고, $this는 정제된 수신 객체라서, $this->length()로 같은 타입의 다른 메서드를 호출할 수 있어요. 정제 타입은 기반 타입의 메서드를 상속하며, 같은 이름을 선언해 대체할 수도 있어요. 내장 기반 메서드를 호출하려면 $value를 쓰세요. key_length과 같은 타입 함수에 키를 넘길 수도 있어요. 레코드 메서드에서 $this.field는 레코드의 필드를 읽어요.
대상은 내장 타입($text as int), 로컬 규칙이 있는 타입($name as string(min: 2)), 또는 목록($rows as Repo[])일 수도 있어요. PasskeySessionKey?와 같은 선택적 대상은 null을 받아들이고, null이 아닌 모든 값을 검증해요. 산술 식의 결과를 변환하려면 ($a + $b) as int처럼 괄호로 묶으세요.
as int로 숫자 하나를 변환하거나, 타입이 지정된 변수($n: int = 3.9)나 int 매개변수를 변환하면 소수 부분이 버려지고 3가 돼요. 타입에 대해 검사되는 데이터는 더 엄격해요. int 필드, int[] 항목, 또는 int의 정제 타입은 정수가 아닌 숫자(needs a whole number, but got a number (12.9))를 잘라내는 대신 보고해요. 'NaN'나 'Infinity' 같은 텍스트는 숫자가 아니며, '1.5'처럼 평범한 숫자는 날짜가 아니에요.
나만의 네이티브 타입
kscript make native은 정제 타입을 natives/에 기록하여 내장 타입처럼 동작하게 해요. 프로젝트의 모든 스크립트가 extensions/ 폴더처럼 가져오기 없이 사용할 수 있어요. 이 타입이 텍스트를 나타내는 곳에서는 값을 따옴표 없이 쓰고, 타입이 사용되는 곳(할당, 인자, 타입 호출, 요청 본문)마다 검사하며, 편집기는 코드에 쓰인 값을 검사해요:
| 명령어 | 기능 |
|---|---|
kscript make native Sku --pattern '/^[A-Z]{3}-\d{4}$/' --normalize '$value->trim()->upper()' | 패턴에 맞는 텍스트, 먼저 다듬어짐. |
kscript make native Percent --base int --min 0 --max 100 | 0부터 100까지의 정수. |
kscript make native Username --base handle --max 16 --not @admin,@root | 이름으로 허용되지 않는 것이 있는 핸들. |
kscript make native CompanySite --base url --validate '$value.host->ends_with("example.com"), "Use a company site"' | 자체 규칙이 있는 URL. |
kscript make native Multiplier --pattern '/^x(\d+)$/' --value '.group(1)->to_int()' | 숫자 11을 나타내는 x11 같은 텍스트. |
첫 번째 것은 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.
}그다음, 프로젝트의 어떤 스크립트에서든:
<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은 기반 타입을 선택하며, 기본값은 string입니다. url, domain, country 같은 네이티브 타입이나 다른 정제 타입을 받습니다. 규칙은 --pattern, --min, --max, --one-of a,b, --not a,b, --normalize, --validate "test, 'message'", 그리고 값이 나타내는 것을 정하는 --value입니다(값이 나타내는 것 참조). 타입 본문에서 fn로 메서드를 선언하고 ->로 호출하세요.
블록에는 규칙과 fn 메서드만 들어가며, 문장은 들어가지 않아요. echo나 if 같은 코드는 메서드 안에 두어야 하며, 편집기는 블록의 다른 곳에 있으면 블록이 무엇을 담는지 알려 주며 오류로 보고해요:
<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
}모든 선언 블록도 같아요. 레코드 타입은 필드, 규칙, construct와 메서드를 담고, 모델은 필드, validate: 규칙과 메서드를 담으며, 작업은 필드와 handle, failed, middleware 함수를 담고, 오류는 필드를 담고, extend 블록은 메서드를 담고, 열거형은 값을 담아요. 블록 안의 자동 완성은 그 블록이 담을 수 있는 것만 제안해요. XML 프로젝트에서 이 파일은 natives/sku.ks.xml 안의 <type> 요소예요.
natives/ 아래(하위 폴더 포함)의 모든 파일에 있는 타입과 열거형이 프로젝트의 자체 네이티브 타입이에요. kscript.json의 "natives"는 다른 폴더나 글로브를 지정하며, kscript make native는 나열된 첫 번째 폴더에 기록해요:
{ "natives": ["src/types", "shared/**/*.kscript"] }스크립트가 직접 선언한 타입은 같은 이름의 프로젝트 타입보다 우선해요.
팩토리: 하나의 타입, 여러 종류
어떤 값 종류는 여러 모양으로 나타나며, 각 모양마다 고유한 규칙과 동작이 필요해요. 전자레인지 키패드에는 숫자 버튼(7), 배율 버튼([*2]), 백스페이스(<)가 있어요. 모두 버튼이지만 각각 다르게 읽히고, 눌렀을 때 하는 일도 달라요.
부모 타입에 factory을 지정하세요. 이것은 타입의 값이 무엇으로 만들어지는지 정하고, with [Parent]로 부모에서 만든 타입의 값을 돌려줘요. 각 타입은 자신의 규칙을 그대로 유지해요. 일반적인 팩토리는 각 타입을 차례로 시도하는 try each이에요:
<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="['<']">
<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
}부모를 호출하면 레이블을 읽고, 팩토리가 그것으로 만든 것을 돌려줘요. 각 값은 자신의 타입을 유지하고, 텍스트는 여전히 레이블이에요:
<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) // truefactory(label) => ...은 값에 이름을 붙여요. factory: ...는 값을 $value로 둔 같은 팩토리이고, validate:와 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팩토리를 쓰는 이유
각 값이 자신의 타입을 유지하므로, MicrowaveButton을 받는 코드는 어떤 종류인지 물어볼 필요가 없어요. 메서드를 호출하면 그 타입 자신의 버전이 실행되고, 타입이 선언하지 않았으면 부모의 버전이 실행돼요.
<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="['<']">
<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] <')" />
<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('<')->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타입이 지정된 리스트 MicrowaveButton[]과 reduce의 button는 각 항목의 타입을 유지해요. 그래서 calculate 안에서도 [*3]는 여전히 MultiplierEntry이고, 실행되는 것은 그 자신의 apply이에요.
값이 만들어지는 방식
MicrowaveButton($label)을 호출하면 KScript는:
- 상위 타입 자신의 규칙을 한 번 검사해요(여기서는 공백 없음),
- 레이블로 팩토리를 실행하고,
- 팩토리가 만든 것을 돌려줘요. 이것은
MicrowaveButton또는 그 타입에서 만든 타입의 값이어야 해요.
try each에서는 작성한 순서가 시도하는 순서이므로, 더 구체적인 타입을 먼저 두세요. ok라는 응답은 ShortReply와 AnyReply 모두에 맞고, 먼저 오는 ShortReply가 선택돼요. 팩토리가 만드는 타입은 부모의 규칙을 다시 검사하지 않아요. 타입의 validate 규칙은 일반 규칙(pattern, min, max, one_of, not)을 통과한 뒤에 실행되므로, 규칙은 패턴이 일치했다고 전제해도 돼요.
아무것도 맞지 않을 때
부모 자신의 규칙을 통과하지 못한 레이블은 그 오류가 발생하고, 팩토리는 실행되지 않아요. try each의 어떤 타입에도 맞지 않는 레이블은 부모, 레이블, 시도한 모든 타입을 알려 주는 Shape 오류 하나가 발생해요:
<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.
}직접 메시지를 작성하려면 try each의 끝에 오류를 던지는 _ => 줄을 두세요:
<type name="Coin" with="string" factory="fn(side) => try each $side |>
Heads,
Tails,
_ => throw Validation "A coin lands on heads or tails, not {$side}"" />
<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규칙이 실패하면 "이 타입이 아님"이라는 뜻일 뿐이므로 다음 타입을 시도해요. validate 안에서 0으로 나누는 것처럼 규칙이 던진 오류는 불일치가 아니에요. 호출한 쪽까지 올라가요.
타입을 직접 만들기
팩토리가 만드는 타입을 직접 호출할 수도 있어요. MultiplierEntry('[*3]')은 부모의 규칙과 MultiplierEntry의 규칙만 검사해요. 팩토리는 실행되지 않으므로, 12가 올바른 NumberEntry여도 MultiplierEntry('12')은 Shape 오류예요.
별도 파일에 있는 타입
각 타입은 자체 파일에 둘 수 있어요. 부모와 그 부모에서 만든 타입들을 프로젝트의 natives/ 폴더에 두세요. 모든 스크립트가 import 없이 이들을 볼 수 있으므로, 부모가 그들보다 앞에 있든 뒤에 있든 상관없어요. 프로젝트의 kscript check와 에디터는 팩토리를 같은 방식으로 검사해요:
try each이 지정하는 각 타입은 부모에서 만든 타입이어야 해요(with [MicrowaveButton]).- 팩토리는 부모 자신을 호출하지 않아요. 호출하면 팩토리가 다시 실행되어 끝없이 반복돼요.
factory(label) => ...은 값 하나를 받아요.- 팩토리는 필드가 있는 타입이 아니라, 다른 타입 하나에서 만든 타입에 둬요.
편집기에서는 다른 타입 하나로 만든 타입에서 factory 줄을 제안하고, |>와 그 뒤의 각 쉼표에서는 factory가 아직 시도하지 않은, 부모로 만든 타입을 제안하며, 각 이름은 해당 타입으로 이동해요. factory 이전에 쓰던 variants: [...] 목록은 대신 무엇을 써야 하는지 알려 주는 오류예요.
이웃: 리스트에서 옆에 있는 값
시퀀스에서 읽은 값은 앞이나 뒤에 무엇이 있었는지 알아야 할 때가 있어요. 백스페이스는 바로 앞에 누른 버튼을 취소하고, 닫는 괄호는 앞에 있는 여는 괄호와 짝을 이뤄요. 타입 자신의 메서드 안에서 .behind은 리스트에서 이 값 앞에 있는 값이고, .ahead는 뒤에 있는 값이에요:
<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="['<']">
<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 <'->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값은 리스트에 타입이 지정될 때 자신의 위치를 알게 돼요. 위의 as Key[]처럼, 또는 Key[] 변수, 매개변수, 필드, 반환 타입으로요. 각 값은 그때 리스트에서의 위치를 유지하므로, 리스트에서 걸러 낸 값이나 Backspace로 넘긴 값도 옆에 있던 키를 알고 있어요:
<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="['<']">
<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 <')" />
<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규칙:
- 최상위 타입 또는 null로 타입이 지정돼요.
.ahead과.behind는?가 있는with체인의 최상위 타입(여기서는Key?)으로 타입이 지정돼요. 첫 번째 값 앞에는 아무것도 없고 마지막 값 뒤에도 아무것도 없기 때문이에요. 각 이웃은 자신의 타입을 유지하므로,->is_a(Digit)로 어떤 종류인지 알 수 있어요.?.나!= null검사 없이 이웃의 메서드를 호출하면, null일 수 있는 다른 값과 마찬가지로 에디터에서 경고가 표시돼요. - 이웃도 자신의 이웃을 알아요.
.behind?.behind은 두 칸 앞의 값이에요. - 타입 자신의 메서드 안에서만 쓸 수 있어요. 그곳에서는 값이 항상 자신의 리스트를 알아요. 타입 밖의
$keys[1].ahead,for루프 안의.ahead, 다른 타입 메서드 안의$key.ahead는 에디터에서도 실행 중에도 오류예요:
.ahead is read inside Key's own methods, such as fn next(): Key? => .ahead, where a value knows the list it was read into.- 단독으로 만든 값에는 이웃이 없어요.
Backspace('<')->undoes()에는 리스트가 없으므로, 그 안에서.behind를 읽으면Value오류예요. 값이 단독으로 만들어졌다는 것을 알 수 있으면, 에디터는 호출 위치에서 이를 알려 줘요:
->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.- 읽는 만큼만 비용이 들어요. 리스트는 값들의 타입 중 하나의 메서드가
.ahead이나.behind를 읽을 때만 값의 위치를 보관해요. 이를 전혀 읽지 않는 타입은 이전만큼 빠르고 추가로 아무것도 갖지 않아요.
에디터에서는 메서드 안의 .에서 ahead와 behind가 읽히는 타입과 함께 제안되고(.behind?. 뒤에서도 마찬가지예요), 마우스를 올리면 무엇인지 알려 줘요. 오류가 되는 위치에서는 제안되지 않아요.
패키지의 네이티브 타입
패키지는 p.NativeType(new IsbnType())로 네이티브 타입을 추가해요. 여기서 IsbnType는 NativeType(KScript.Core)의 하위 클래스예요. 기반 클래스는 타입이 언어가 그 값에 대해 하는 모든 일을 설명하게 하므로 아무것도 빠질 수 없어요: 이름, 설명, 예제, 텍스트가 값이 되는 방법(Parse), 따옴표 없이 쓰는 방법, ==가 무엇을 뜻하는지(Equality), <와 정렬이 가능한지(Ordering), for 반복문이 순회할 수 있는지(Iteration), 연산자(DeclareOperators), 필드와 메서드(DeclareMembers), 이 타입 목록의 필터와 메서드(DeclareListMembers), 보관하는 문자열 메서드, 편집기가 제안하는 값. 어느 것에 대해서든 "없음"은 빈 본문이나 Ordering.None로 쓰는 올바른 답이에요. DurationType가 복사할 예시예요. 패키지를 가져오면 타입은 내장 타입처럼 동작해요: 따옴표 없는 값, 편집기 검사, ->type()와 OpenAPI 스키마. 네이티브 타입 이름은 소문자이며, 이미 쓰인 이름은 다시 쓸 수 없어요.