KScript 문서
KO

언어

영어에서 자동 번역되었습니다. 원문은 영어입니다.

KScript 언어

소개

이 문서는 KScript 2 스크립트의 참조 문서입니다. 모든 스크립트와 페이지에 쓰이는 핵심 언어, 나머지 기능을 위해 가져오는 패키지, 그리고 모든 OS에서 실행되는 스크립트를 위한 몇 가지 팁을 다룹니다. KScript가 처음이시라면 시작하기를 먼저 읽어보시는 것이 좋습니다.

변수와 출력

<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

echo에 맵 또는 맵 목록만 단독으로 넘기면 들여쓰기된 JSON으로 출력되며, 색이 입혀져요(NO_COLOR가 설정되지 않은 경우). 텍스트 안에서는 한 줄로 유지돼요. echo(format: json)는 JSON 텍스트를 다시 포맷하고, ->convert(to: json)는 압축된 JSON을 만들어요.

변수는 선언된 블록에 속해요. {{와 }}는 리터럴 중괄호예요.

타입을 붙여 선언한 변수는 그 타입을 유지해요. 이후의 각 대입은 처음 값이 변환된 것과 같은 방식으로 그 타입으로 변환되며, 변환할 수 없으면 스크립트가 거기서 멈춰요:

<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

그다음 $count = 'many'는 편집기에서 오류이고, 실행하면 $count must be an int, but got the string 'many'에서 멈춰요.

"Double quotes"에서는 할당, 반환 값, 호출 인자에서 { } 뒤의 echo 안에 있는 식을 보간합니다. .kscript에서 KS6019는 중괄호 없이 쓴 참조를 잡아내고, 중괄호로 감싸자고 제안합니다. 'Single quotes' 안의 텍스트는 적힌 그대로 유지되므로, 채울 내용이 없는 텍스트는 그 안에 넣으세요(KS6020이 수정을 제안합니다). echo 뒤의 따옴표 텍스트도 공백까지 포함해 그대로 출력됩니다. 예를 들어 echo " - { $item }"는 공백 두 칸을 출력합니다. XML에서는 <echo>와 </echo> 사이의 텍스트에서 앞뒤 공백이 제거되고 줄들이 공유하는 들여쓰기가 사라집니다. 다만 채워 넣는 값은 그대로 두며, 빈 값은 불필요한 공백을 남기지 않고, 텍스트는 줄바꿈으로 끝나지 않습니다.

<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

큰따옴표 안의 { }은 어떤 것으로 시작하든 항상 식을 담습니다. 변수, 명령, 타입({ Order->count() }), 숫자, 괄호로 묶은 합계 모두 가능합니다. 자체 중괄호가 있는 텍스트, 예를 들어 경로('/users/{id}'), 패턴('\d{3}'), CSS나 번역 텍스트('Hello {name}')는 작은따옴표에 넣거나 중괄호를 두 번 써서 "/users/{{id}}"처럼 작성합니다. 다만 @sql에 주는 텍스트는 예외입니다. 그 안의 { }는 매개변수로 전달되며, 그대로 붙여 넣지 않습니다(데이터 참조).

식

+ - * / % **, == !=(느슨한 비교: '3' == 3), === !==(엄격한 비교), < <= > >=, and or not, ??, ?., a ? b : c, in, 리스트 [1, 2]과 맵 { name: 'Joan' } 리터럴(as set을 쓰면 리스트가 집합이 됩니다), $p.name, $list[0](음수 인덱스는 끝에서부터 셉니다), 범위 0..10과 0..100 step 5(끝 값 제외, 0.1처럼 단계를 줄 수도 있음), 1..=10(끝 값 포함), match $x { 1 => 'one', _ => 'other' }, ->method(), |>, fn(x) => …을 사용할 수 있습니다. 조건을 결합하려면 and와 or를 씁니다. 전위 !는 not와 우선순위와 참/거짓 판정이 같으므로, !$ready, ! $ready, not $ready은 모두 동일합니다. 필드(!$user.active), 조건 전체(if !($ready and $open) { … }), 보간("{ ! null->is_null() }")에 사용할 수 있습니다. null->!is_null() 표기는 체인에서 다음 연결 전에 메서드 결과를 부정합니다. XML에도 비교 연산자마다 단어형 표기(lt le gt ge eq ne)가 있어, 원시 <를 쓸 수 없는 따옴표 속성 안에서 사용할 수 있습니다. 축약 시작 태그에서는 <와 >를 그대로 쓸 수 있습니다. .kscript 파일에서는 단어형 표기가 보고되며(KS6012), kscript check --fix는 기호 표기로 바꿔 씁니다.

<, <=, >, >=로 숫자와 문자열을 비교할 때, 문자열을 숫자로 해석할 수 있으면 KScript는 수치로 비교합니다. 해석에 실패하면 비교는 false를 반환합니다. 비교는 수학에서처럼 연결됩니다. 수학 절에서 보여 줍니다. 두 날짜는 ==로 비교할 때 초까지 포함해 같은 순간일 때만 같습니다.

수학

일상적인 수학에는 고유한 기호가 있으며, 각각 스크립트, 템플릿, 데이터베이스 쿼리에서 같은 방식으로 작동합니다. +은 더하고, -는 빼고, *는 곱하고, /는 나누며 소수를 유지합니다. ~/는 정수로 나누고 내림합니다. %는 나머지를 주는데, 왼쪽 수의 부호를 따릅니다. %%은 시계처럼 한 바퀴 돌아 감쌉니다. **는 거듭제곱입니다:

<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

연산자는 다음 순서로 묶이므로, 가장 강하게 묶이는 것부터 적용됩니다. 따라서 2 + 3 * 4은 *가 +보다 먼저 묶이기 때문에 14입니다:

우선순위 연산자 묶음 방향
1 . -> ?. ( ) [ ] 왼쪽에서 오른쪽으로
2 ** 오른쪽에서 왼쪽으로: 2 ** 3 ** 2은 2 ** 9, 512
3 -x +x -2 ** 2의 결과는 -4입니다. **가 먼저 결합하기 때문입니다. 따라서 -(2 ** 2)나 (-2) ** 2로 써야 합니다(KS6023).
4 * / ~/ % %% 왼쪽에서 오른쪽으로
5 + - 왼쪽에서 오른쪽으로
6 .. ..= step 식마다 범위는 하나
7 |> 왼쪽에서 오른쪽으로
8 < <= > >= in 한 방향의 체인: 0 <= $n < 10
9 == != === !== 비교마다 하나. 더 연결하려면 and을 사용하세요.
10 not, and, or, ??, a ? b : c

%과 %%는 음수 부호가 있을 때만 다릅니다. 나머지는 왼쪽 피연산자의 부호를 따르며, C#과 JavaScript와 같습니다. 모듈로는 오른쪽 피연산자의 부호를 따르므로 한 바퀴 돌아 감쌉니다. 자정 한 시간 전은 -1이 아니라 23입니다. 끝에서 감싸는 시계, 요일, 목록의 위치에는 %%을 쓰세요:

<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

~/은 0 쪽이 아니라 아래로 내림하므로 %%와 짝을 이룹니다. ($a ~/ $b) * $b + $a %% $b은 항상 $a입니다. 기간과 금액에도 작동하며, 일반 숫자를 돌려줍니다:

<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

//는 주석을 시작하므로 정수 나눗셈이 될 수 없습니다. $hours = $minutes // $per_hour는 $minutes를 그대로 두며, KS6022가 이를 지적하고 ~/로 고치는 수정을 제안합니다.

같은 방향을 가리키는 비교는 수학에서처럼 이어서 쓸 수 있으므로, 범위 검사를 말하는 그대로 읽을 수 있습니다. 가운데 값은 각각 한 번만 계산되며, 거짓이 되는 첫 비교에서 체인이 멈춥니다:

<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

체인은 한 방향으로만 이어집니다. 1 < $n > 0은 1과 0의 비교에 대해 아무 정보도 주지 않으므로 오류이며, 1 < $n and $n > 0로 작성해야 합니다. ==와 !=는 이어지지 않습니다. $a == $b == $c는 $c와 비교한 참/거짓 값을 내기 때문에 $a == $b and $b == $c로 작성해야 합니다. 괄호는 체인을 끊으므로 (1 < $n) == true은 그 결과를 비교합니다. 체인은 데이터베이스 쿼리에서도 동작합니다. Person->where(fn(person) => 18 <= $person.age < 65)는 age >= 18 AND age < 65을 요청합니다. ->between()은 더 이상 쓸 수 없으며, 오류 메시지가 대신 써야 할 체인을 알려줍니다.

..은 끝 값 앞에서 멈추는 범위를 만들며, 0부터 세는 경우와 목록의 위치에 어울립니다. ..=는 끝 값을 포함하며, 1부터 세는 경우에 어울립니다. 두 가지 중 어느 것에 마우스를 올려도 범위가 어디서 시작하고 끝나는지 보여줍니다:

<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

..와 마찬가지로, 끝 값이 시작 값보다 작으면 범위는 거꾸로 셉니다. 따라서 3..=1는 [3, 2, 1]이고 1..=0는 [1, 0]입니다. 값이 0일 수도 있는 상한까지 세려면 1..($count + 1)처럼 ..을 사용하세요. $count이 0이면 값이 하나도 나오지 않습니다.

KScript에서 ^은 거듭제곱이 아닙니다(C#과 JavaScript에서는 비트 연산자입니다). 따라서 2 ^ 10는 오류이며, 고치기 기능은 2 ** 10로 작성합니다.

비트 연산은 기호 대신 메서드 ->bits()로 수행합니다. &와 |는 and와 or와 쉽게 혼동되기 때문입니다. 정수에 대해 한 번에 한 단계씩 적용합니다:

<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

&, 단독 |, 두 값 사이의 <<와 >>는 작성해야 할 ->bits() 호출을 알려주는 오류입니다. &와 |은 and 또는 or로 고치는 방법을 제시하며, 보통 의도했던 코드가 그것입니다.

($hour + 24) % 24는 숫자를 반올림하던 예전 방식입니다. KS6021은 $hour %% 24를 제안하며, 이는 -24보다 작은 숫자에도 동작합니다.

+=, -=, *=, /=, ~/=, %=, %%=, **=, ??=는 변수를 그 자리에서 바꿉니다. 예를 들어 $total += 5은 $total = $total + 5와 같습니다. 연산자 주변의 공백은 자유지만, 연산자 안의 공백은 연산자를 둘로 나눕니다. 2 * * 10는 **을 가리키는 오류이며, 빠른 수정 기능은 공백을 제거합니다.

편집기는 연산자와 공백 뒤에 변수 목록을 보여주며, 왼쪽 값의 타입과 일치하는 변수가 먼저 나옵니다. 연산자에 마우스를 올리면 그 동작을 보여줍니다.

검사하는 변환에는 expression as Type을 사용합니다. 예를 들어 $text as int처럼 씁니다. 대상은 선언된 레코드, 열거형, 정제 타입일 수도 있습니다. 검사하는 변환

제어 흐름

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

match의 각 분기는 pattern => result입니다. 패턴은 하나의 값이거나 여러 값(2, 3 =>)이며, 모든 값을 뜻하는 _를 쓸 수도 있습니다. 그 뒤에는 when 검사를 붙일 수 있습니다(_ when $it > 9 =>). 결과는 같은 줄의 문장 하나이거나, { }으로 묶은 여러 문장의 블록입니다. 값으로 쓰는 match도 같은 방식으로 분기를 씁니다. 각 결과는 값이며 예는 다음과 같습니다: $label = match $choice { 1 => 'one', 2, 3 => 'a few', _ => 'many' }. 분기는 줄바꿈이나 쉼표로 구분하고, 처음으로 맞는 분기가 실행됩니다. XML에서 분기는 <case is="2, 3">, <case when="…">, <default>입니다.

한 줄 if

if가 한 가지 일만 할 때는 한 줄에 씁니다. 조건, =>, 그리고 문장 순서입니다. 이는 match의 분기와 fn(name) => ...와 비슷하게 읽히며, 가드 검사와 조기 종료를 각각 한 줄로 유지합니다.

<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와 else도 같은 형태를 따르며, 분기마다 한 줄씩 씁니다:

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

=> 뒤의 문장은 한 줄에 들어가는 것이면 무엇이든 될 수 있습니다: 호출(if $continue => @method_call()), 할당(if $count > 2 => $label = 'many'), echo, return, break, continue, throw 또는 exit. 문장은 줄이 끝나는 곳에서 끝나므로 if $ready => echo 1; echo 2는 어느 쪽이든 2를 출력합니다. 문장이 여러 개이거나 반복문, match 또는 다른 if이 필요하면 { } 블록을 씁니다. 괄호 밖에서 처음 나오는 =>가 조건을 끝내므로, 호출 안의 fn(fruit) => ...와 @load() catch => false는 그 호출의 일부로 남습니다. if $ready => { }는 오류입니다. 블록은 화살표 없이 조건 뒤에 올 수 없기 때문입니다. XML에는 한 줄 형태가 없으므로 kscript convert는 문장을 안에 넣은 <if>로 씁니다.

XML에서 <if>, <elif>, <while>, <match>는 시작 태그에 바로 식을 씁니다. <if $user.is_logged_in>는 <if test="$user.is_logged_in">의 줄임 표기이고, <match $choice>는 <match value="$choice">의 줄임 표기입니다. 두 형태 모두 스크립트와 페이지에서 동작하며, 태그에 다른 속성이 있을 때는 긴 형태를 쓰세요. 태그 안에서는 <, >, 따옴표를 이스케이프할 필요가 없어서 <if $n > 3>와 <if $name == "Joan">가 그대로 동작합니다. >는 양쪽에 공백이 있고 뒤에 조건이 더 이어지는 경우가 아니면 태그를 끝내므로, $n>3가 아니라 $n > 3로 써야 합니다. kscript convert와 편집기의 <if> 스니펫은 짧은 형태를 사용합니다.

짧은 태그 때문에 .ks.xml 파일은 엄격한 XML이 아니라 KScript 마크업이 됩니다. KScript 자체의 파서, 포매터, 편집기 지원은 이를 읽을 수 있지만, xmllint 같은 범용 XML 도구는 거부합니다. 파일이 유효한 XML이어야 한다면 test="…"를 쓰세요.

else 대신 조기 반환

함수나 반복문 안에서는 else를 쓰는 대신 분기를 일찍 끝내세요. 함수에서는 return, 반복문에서는 continue나 break를 씁니다(이것들은 같은 함수의 반복문에 작용하며, 자신을 호출한 반복문에는 작용하지 않습니다). 그러면 주요 흐름은 왼쪽 가장자리에 머물고, 각 예외 상황을 먼저 처리합니다.

<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와 편집기는 else와 elif에 대해 KS6001 경고를 표시합니다. 앞의 모든 분기가 이미 return, break, continue, throw, exit 중 하나로 끝나는 경우 스크립트 최상단에서도 경고합니다. 빠른 수정은 else를 제거하거나(또는 elif을 별도의 if로 바꿉니다), 체인이 함수나 루프의 마지막 문장이면 return 또는 continue를 자동으로 추가합니다. 페이지, <live> 블록, 빈 리스트를 위한 for…else는 반환할 대상이 없으므로 표시되지 않습니다. KS6001은 기본 표준인 kscript:recommended에서 가져옵니다. 프로젝트에서 끄려면 kscript.json(또는 프로젝트들이 공유하는 표준)에서 "lint": { "rules": { "KS6001": "off" } }를 설정하세요.

사용되지 않는 코드

kscript check와 편집기는 아무 일도 하지 않는 코드도 알려줘요. 편집기에서는 흐리게 표시되며, 삭제하거나 앞에 _를 붙여 이름을 바꾸는 빠른 수정이 제공돼요. 이름 앞의 그 표시는 의도적으로 사용하지 않는다는 뜻이에요(_ 이름은 보고되지 않아요).

코드 표시하는 항목
KS6002 아무도 호출하지 않는 함수예요. 스크립트의 main 함수는 자동으로 실행되므로 보고되지 않아요. 프로젝트의 다른 파일에서 하는 호출도 인정돼요. 예를 들어 다른 스크립트가 import해서 호출하는 라이브러리 함수, 라우트 파일이 이름을 지정한 컨트롤러(to="people.show", 또는 index, store, show, update, destroy용 <Resource to="people">), kscript.json에 이름이 적힌 미들웨어가 해당해요. 자기 자신만 호출하는 함수는 여전히 사용되지 않는 것이에요.
KS6003 값이 한 번도 읽히지 않는 변수, 상수 또는 반복 변수. 값이 설정되기만 하는 경우도 포함합니다. 스크립트의 최상위 상수는 함수와 마찬가지로 내보내지므로, 가져오는 파일이 사용하면 사용된 것으로 계산합니다. 페이지에서는 레이아웃이나 컴포넌트가 나머지를 읽을 수 있으므로 함수 자체의 변수만 검사합니다.
KS6004 본문이 읽지 않는 함수 매개변수. 람다의 경우, 마지막으로 읽는 매개변수 뒤에 오는 매개변수만 해당합니다. 호출하는 쪽이 무엇을 전달할지 정하기 때문입니다. 위치를 유지하려면 fn(_y) => ...라고 쓰세요.
KS6005 아무도 사용하지 않는 가져오기: as 별칭, names="..."의 이름, 스크립트 전체, 또는 그 요소, 명령, 메서드, 변수가 하나도 나타나지 않는 패키지.
KS6006 사용되지 않는 코드는 아니지만 스타일 힌트입니다. .kscript 파일에서 이름 목록을 하나의 문자열로 쓴 경우(Middleware(use: "log, cors"))입니다. 배열로 쓰세요: use: [log, cors]. 빠른 수정이 이를 대신 해줍니다. XML 속성은 텍스트이므로 거기서는 use="log, cors"도 괜찮습니다.
KS6008 이것도 사용되지 않는 코드는 아닙니다. 프로젝트에서 두 번째 타입, 모델, 열거형 또는 오류 타입을 선언한 스크립트입니다. 각 타입은 자신의 이름을 딴 파일에 두고, 쓰는 곳에서 가져와야 합니다. 경고는 옮길 위치를 알려줍니다(types/order-status.kscript). 파일 이름과 같은 타입은 그대로 둡니다. 프로젝트 밖의 스크립트는 검사하지 않습니다.

프로젝트는 가장 가까운 kscript.json가 있는 폴더와 그 아래의 모든 것입니다(숨김 폴더, bin, obj, node_modules는 건너뜁니다). 프로젝트 밖의 스크립트는 같은 폴더의 다른 파일을 기준으로 검사합니다. 프로젝트 밖에서 사용하는 API의 일부인 함수는 문서 주석에 @public를 넣어 이를 알릴 수 있습니다:

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

KS6001과 마찬가지로, 이 항목들은 기본 표준인 kscript:recommended에서 가져오며 경고로 표시됩니다(kscript:strict로 설정하면 오류가 됩니다). 프로젝트는 kscript.json에서 각 항목을 변경하거나 끌 수 있습니다. 예: "lint": { "rules": { "KS6004": "off" } }.

함수

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

함수는 선언 전에 호출할 수 있고, 재귀하며, 값으로 전달할 수 있습니다. @square는 함수 자체입니다. 람다도 값이며, 매개변수를 같은 방식으로 선언합니다: $by_age = fn(a, b) => $a.age - $b.age.

짧은 함수는 각 항목의 필드를 읽거나 메서드를 호출합니다. 항목을 나타내는 . 또는 ->로 시작하며, 함수가 쓰이는 곳이라면 어디서든 동작합니다:

<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는 fn(order) => $order.priority이고, ->trim()는 fn(line) => $line->trim()입니다. 짧은 함수는 필드와 메서드 호출을 하나로 이은 체인입니다. $order.price > 10처럼 더 복잡한 경우에는 fn(order) => …로 작성하세요.

main 함수

스크립트는 작업을 main이라는 함수에 담을 수 있어요. 이 스크립트가 실행되는 대상이라면, 최상위 코드가 실행된 뒤 main가 자동으로 실행되므로, 최상위 코드에서 설정을 하고 main가 실제 작업을 수행해요:

<!-- 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!
  }
}
  • 매개변수는 선택 사항이에요. fn main()도 같은 방식으로 실행돼요. fn main(args: list)는 스크립트의 인자를 받으며, $args와 같은 목록이에요. 두 번째 매개변수에는 다른 값이 전달되지 않으므로 기본값이 필요해요. fn main(first, second)는 오류예요(KS5004).
  • 반환값은 종료 코드예요. 정수 main을 반환하면 exit처럼 그 코드로 스크립트가 끝나므로, 셸이나 CI 작업이 결과를 알 수 있어요. 그 밖의 값이나 아무것도 반환하지 않으면 종료 코드는 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
}
  • 실행 중인 스크립트만. main은 여러분이 실행하는 스크립트에 속해요. kscript run, kscript greet.kscript, 컴파일된 프로그램, 디버거, 편집기의 실행 명령이 모두 이를 호출해요. import된 스크립트는 최상위 코드를 실행하지만 main는 실행하지 않으므로, 라이브러리는 단독으로 시험해 볼 수 있도록 main를 둘 수 있어요.
  • 최상위 수준에서만. 다른 함수, 타입, 테스트 파일 안의 fn main는 일반 함수예요.
  • 사용되지 않는 것으로 보고되지 않아요. main을 호출하는 곳이 없어도 kscript check와 편집기는 이를 사용되지 않는 것으로 보고하지 않아요(KS6002). 다만 최상위 코드도 이를 호출하면 두 번 실행되므로 경고해요(KS5019). 빠른 수정이 하는 것처럼 그 호출을 제거하세요.

kscript.json의 app.main_function는 프로젝트의 모든 스크립트에 대해 다른 이름을 줘요:

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

블록 함수

함수에 식 하나 이상이 필요하면 => 대신 블록을 사용하세요. 블록에는 fn name() { }의 본문처럼 문장들이 들어가며, return가 함수의 결과를 돌려줍니다:

<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

fn(price) => …에서처럼 매개변수의 타입은 호출로부터 정해집니다. 예를 들어 $price는 $prices가 숫자 목록이므로 숫자입니다. 따라서 편집기는 $price-> 뒤에 숫자 메서드를 제안하고 with_tax: number[]를 보여줍니다.

블록은 if로 분기하고 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]

->reduce(fn(total, item), initial?)처럼 매개변수를 두 개 받는 함수도 같은 방식으로 블록을 받습니다:

<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

return이 없이 끝나는 블록은 null를 돌려주며, 이는 ->each()처럼 블록이 하는 일만 중요한 경우에 어울립니다. 그 밖의 경우에는 호출이 블록이 돌려주는 값을 사용하므로, 비어 있거나 값을 전혀 돌려주지 않는 블록은 편집기, kscript check, 실행 시 모두에서 오류가 됩니다:

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

블록은 주변의 변수를 읽고 바꿀 수 있으며, 블록 안에서 만든 변수는 블록 안에만 머뭅니다:

<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

블록 함수도 다른 함수와 같은 값이므로 변수에 담아 호출할 수 있습니다: $greet = fn(name) { … }, 그다음 $greet('Ada'). 블록 함수는 .kscript 파일에서도 동작합니다. XML 속성에는 문장을 담을 수 없으므로, 그곳에서는 fn(n) => value로 쓰거나 <fn>를 선언해 @name로 넘기세요. 데이터베이스 쿼리의 조건(->where(fn(u) => $u.age >= 18))은 SQL로 바뀌므로 반드시 하나의 식이어야 합니다.

any로 선언한 매개변수는 어떤 값이든 받습니다. 그 위에서 호출하는 메서드는 값의 실제 타입을 사용합니다. 예를 들어 $key->trim()는 문자열의 공백을 제거하고, 숫자에 대해서는 오류를 내며, 해당 타입의 trim()가 있으면 그것을 호출합니다. 문자열 정규화 함수를 원한다면 fn trim_key(key: string) => $key->trim()로 작성하세요. 그러면 편집기가 문자열 반환 타입을 추론할 수 있습니다.

이름 있는 인자

모든 호출은 인자에 이름을 붙일 수 있으며, 순서는 자유입니다. 내장 명령, 메서드, 직접 만든 fn 함수와 람다 모두 해당합니다.

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

위치 인자는 순서대로 매개변수를 채우고, 각 name: value는 같은 이름의 매개변수를 채우므로 중간의 선택 매개변수는 건너뛸 수 있습니다. 이름 있는 인자 뒤에 쓴 위치 인자는 아직 비어 있는 첫 번째 매개변수를 채우며, @join_path(base: $folder, [...])가 그렇게 읽힙니다. 존재하지 않는 매개변수 이름을 쓰거나 같은 것을 두 번 주면 "혹시 이것을 뜻하셨나요" 힌트가 붙은 오류가 됩니다. 편집기는 (나 , 뒤에 매개변수 이름을 자동 완성합니다.

그룹 중 하나

어떤 매개변수들은 서로 대안입니다. 호출은 그중 정확히 하나만 넘겨야 합니다. 이름들을 |로 이어 쓰세요:

<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)는 오류이며("@file()은 add: 또는 remove:를 받으며, 둘 다 받지 않습니다"), @file(4)도 오류입니다("add: 또는 remove:가 필요합니다"). kscript check는 코드가 실행되기 전에 둘 다 알려줍니다. 그룹의 구성원은 항상 이름을 붙여 써야 하며, 호출이 넘기지 않은 구성원은 본문에서 null입니다. 하나에 대해 null(또는 false)를 넘기는 것은 넘기지 않은 것으로 칩니다.

표기 의미
add|remove: file add와 remove 중 정확히 하나, 두 파일 모두.
at|after?: date 최대 하나: 마지막 이름 뒤의 ? 때문에 호출이 아무것도 넘기지 않아도 됩니다.
text: string | template: Template 정확히 하나이며, 각각 고유한 타입을 가집니다.
(text: string | template: Template)? 같은 내용을 괄호로 묶으며, 최대 하나는 ?로 나타냅니다.

구성원들의 타입이 서로 다른 그룹은 그 옆에 다른 매개변수가 있을 때 괄호가 필요합니다. 그래야 그룹이 어디서 끝나는지 분명해집니다: fn send(to: email, (text: string | template: Template), at|after?: date). 어떤 그룹이든 괄호로 감쌀 수 있습니다. 구성원은 자신만의 기본값을 가질 수 없습니다.

내장 명령도 그룹을 사용합니다. @api()는 post:, put:, patch:, delete: 중 하나를 받으며, 작업의 ->dispatch()는 delay: 또는 at: 중 하나를 받고 둘 다 받지는 않습니다. 시그니처 도움말은 그룹을 한 자리로 보여주고, 하나가 작성되면 자동 완성은 나머지 구성원을 제안하지 않으며, 편집기는 그룹의 이름들에 같은 색을 입힙니다.

플래그

참/거짓 매개변수는 단독 단어로 쓸 수 있습니다. recursive는 참으로, not recursive는 거짓으로 설정하므로 호출이 문장처럼 읽힙니다.

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

overwrite: true 또는 recursive: false로 써도 동작하지만, 편집기는 대신 플래그를 제안합니다(KS6024). 이 수정은 이를 overwrite 또는 not recursive로 다시 씁니다.

인자 타입

각 인자는 그 매개변수가 받는 값이어야 합니다. 이를 결정하는 규칙은 하나이며, 편집기, kscript check, 실행 모두 이 규칙을 적용하므로 실행 전에 같은 실수를 같은 말로 알려줍니다:

<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.
매개변수가 받는 값 추가로 받는 값 절대 받지 않는 값
텍스트(string) 텍스트로 쓴 숫자 또는 참/거짓 목록, 맵 또는 함수
숫자(number, int, float) '3'처럼 숫자로 읽히는 텍스트 그 밖의 텍스트, 참/거짓, 목록, 맵 또는 함수
참 또는 거짓(bool) 'yes'처럼 참/거짓으로 읽히는 텍스트 숫자, 목록, 맵 또는 함수
목록, 맵 또는 함수 그 밖의 모든 것

직접 선언한 함수는 텍스트에 더 엄격합니다. string로 선언한 매개변수나 결과는 텍스트만 받습니다. 숫자나 참/거짓은 편집기, kscript check, 실행 시에 오류가 되므로, 잘못된 값을 넘긴 호출이 조용히 텍스트로 바뀌지 않습니다. 호출에 쓴 값은 따옴표로 감싸거나, 숫자는 ->to_string()로 텍스트로 바꾸세요. 편집기는 두 방법을 모두 빠른 수정으로 제안합니다.

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

선언된 타입 하나의 레코드는 매개변수, 결과, 타입이 지정된 변수가 선언한 타입과 대조해 확인해요. 그 타입의 필수 필드 중 하나가 빠진 레코드는 실행 시점과 마찬가지로 스크립트가 실행되기 전에 오류가 나요:

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

{ }는 인수 이름 뒤에 두 줄에 걸쳐 쓰더라도 항상 맵입니다. 따라서 다음 줄의 least: {와 }는 블록이 아니라 맵입니다. 편집기는 least: { }를 least로 바꾸도록 제안합니다.

타입 매개변수

어떤 타입에서든 같은 방식으로 동작하는 함수는 이름 뒤 꺾쇠괄호에 타입을 적고, 매개변수와 결과에서 그 타입을 사용해요. 호출하면 전달된 값으로 타입이 채워져요:

<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

호출 한 번에 타입 매개변수마다 타입 하나가 지정돼요. @same(1, 'x')은 편집기, kscript check, 실행 시점 모두에서 오류예요. a이 T를 숫자로 만들고 b는 텍스트이기 때문이에요. 호출이 T로 만든 타입이 아닌 결과도 오류예요. 함수 안에서 T는 어떤 타입이든 될 수 있으므로 $items[0]에는 검사가 필요 없어요. 여러 타입 매개변수는 쉼표로 써요: fn pair<K, V>(key: K, value: V). XML에서는 generics 속성에 넣어요: <fn name="first" generics="T" params="items: T[]" returns="T">.

후행 쉼표

항목 사이에는 쉼표를 넣습니다. 마지막 항목 뒤의 쉼표는 목록을 항목마다 한 줄씩 작성한 경우에만 허용되며, 이렇게 하면 항목을 추가해도 한 줄만 바뀝니다. 같은 줄에서 닫는 괄호 앞에 쉼표를 두면 모든 종류의 목록에서 오류입니다:

<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은(는) 이름이 붙은 값들의 집합을 선언하고, const은(는) 변경할 수 없는 값을 선언해요.

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

긴 열거형은 타입이 필드를 한 줄에 하나씩 담는 것처럼, 쉼표 없이 값을 한 줄에 하나씩 담을 수 있어요. kscript fmt는 줄 너비 안에 들어가는 열거형을 한 줄에 두고, 더 긴 열거형은 값을 한 줄에 하나씩 둬요:

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

타입을 알 수 있는 경우 열거형(enum) 값은 앞에 점(.)을 붙여 씁니다: .large은 Size.large이며, 이는 size이 Size이기 때문입니다 (아래 앞 점을 참조하세요). 타입을 알려주는 것이 없으면 전체 이름으로 씁니다: Size.medium. 열거형의 목록은 그 값들의 배열로 표현합니다: fn pack_all(sizes: Size[])와 함께 쓸 때는 @pack_all([.large, .small])로 씁니다. 내장 명령어에도 단어 매개변수가 있으며, 이 단어들은 점 없이 그대로 씁니다: @known_folder(downloads)는 home, desktop, documents, downloads, music, pictures, videos, appdata 또는 temp를 받습니다. Size 자체는 각 이름을 그 자신에 대응시키는 맵이므로, 'large' in Size는 값을 검사하는 데 사용합니다. 최상위 수준의 <const> 및 <enum> 선언은 해당 파일을 가져오는 스크립트에 내보내집니다.

선행 점: .name

점(.)으로 시작하는 이름은 그 자리에서 요구하는 타입의 멤버를 가리킵니다. 주변 코드에서 이미 타입이 드러나 있다면, 타입 이름을 다시 적지 않아도 되므로 편리합니다:

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

점이 의미하는 바는 다음 순서로 읽습니다:

  1. 타입이 지정된 슬롯입니다. 인수, 필드의 기본값, 비교, 매치 암, 리스트 항목, 또는 열거형을 받는 타입 지정 fn의 반환값입니다. 이때 .pink는 그 열거형의 값입니다. ->map(.name)처럼 함수를 받는 슬롯은 각 항목의 해당 필드를 읽습니다.
  2. 루프 for 안의 항목입니다. for account in $accounts { ... }에서 .id은(는) $account.id이고, .name = 'Ann'은(는) 항목의 필드를 설정합니다. 중첩된 루프에서는 이름이 같은 가장 안쪽 항목이 우선하므로, 안쪽 루프의 .label과 바깥 루프의 .id을 나란히 사용할 수 있습니다. while 루프에는 항목이 없으므로 아무것도 추가하지 않습니다.
  3. 레코드 자체의 메서드 안에서. type, model, extend 또는 컴포넌트 메서드 안에서 .text는 레코드 자신의 필드이고 .save()는 자신의 메서드를 호출해요. .count += 1와 .color = .red는 필드 값을 설정해요.
  4. 해당하는 항목이 없어요. $c = .red은(는) 오류이고, .red needs a type here, 빠른 수정은 이를 전체 형태로 씁니다: NoteColor.red.

슬롯이 먼저 시도됩니다. 메서드 안에서 @paint(color: .red)은 레코드에 red라는 필드가 있더라도 NoteColor.red입니다. 열거형에 없는 이름은 레코드 자체의 것이므로 fn current(): NoteColor => .color는 레코드의 color를 반환합니다. 둘 다 없는 이름은 오류입니다.

루프의 항목은 레코드보다 앞에 옵니다. 행을 순회하는 메서드에서 title가 있는 행의 .title는 행의 것이며, 레코드 자체의 항목은 $this.title로 씁니다. 검사기가 이를 알려 주고 해당 수정안을 제안합니다.

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

값이 들어갈 자리에 .을(를) 입력하면 들어갈 수 있는 항목이 정확히 제안됩니다. 타입이 지정된 자리에서는 열거형의 값이, 반복문 안에서는 반복 항목의 필드(그다음 바깥 반복문과 레코드의 필드)가, 메서드 안에서는 레코드의 필드와 메서드가 제안됩니다. 값 위에 마우스를 올리면 그 값이 무엇을 나타내는지 보여 줍니다. 예를 들어 NoteColor.pink처럼요.

타입이 지정된 데이터

type는 API 응답처럼 일부 데이터의 형태를 선언합니다. 이를 통과하는 데이터는 검사되어 레코드로 변환됩니다. 레코드는 자신의 타입을 아는 맵이므로, 편집기가 필드를 자동완성하고 $repo.stras와 같은 오타를 잡아냅니다. 필드는 email, password, handle, uuid, regex일 수도 있으며, 타입은 다른 타입에 규칙을 추가하거나 타입끼리 결합할 수 있습니다. 타입과 검증을 참조하세요.

타입은 한 줄에 필드 하나씩 들어가는 블록이며, 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는 다른 이름의 키에서 필드를 읽고, owner: User는 다른 타입이므로 중첩된 데이터도 검사한 뒤 User 레코드로 변환해요. Repo(data)는 맵, 맵의 리스트 또는 JSON 텍스트를 매핑해요.

현재 스코프에서 값을 찾으려면 $.name을(를) 사용하세요. $name와(과) 같은 이름을 해석하며, 함수 매개변수, 지역 변수, 컴포넌트 필드를 포함합니다.

메서드 시그니처

타입은 본문을 적지 않고 메서드를 선언할 수 있습니다. fn 줄의 끝에 => 또는 { }가 들어갈 자리 대신 ;를 씁니다. 이 줄은 메서드 시그니처이며, 이 타입을 extends 다른 타입은 그 메서드를 반드시 구현해야 합니다. fn details?(): string;처럼 메서드 이름 뒤에 ?를 붙이면 그 메서드는 선택 사항이 됩니다. 편집기와 이 문서는 시그니처 줄을 기울임꼴로 표시하므로, 본문이 있는 메서드와 한눈에 구별할 수 있습니다. 검사기는 누락된 필수 메서드나 매개변수 이름, 매개변수 타입, 반환 타입의 불일치를 모두 보고합니다.

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

필드 라인

필드 줄은 name[?][: type] [from path] [= default | => value] 형식입니다. 이름을 제외한 각 부분은 선택 사항입니다. 값이 있고 타입이 없는 필드는 콜론 바로 뒤에 값을 쓸 수 있으며, 이때 layout: ```text ... ``` 또는 symbols: { '#': '#' }처럼 쓰고, 타입은 값에서 결정됩니다:

<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)'
}
부분 기능
: type 내장 타입(string, int, float, number, bool, date, list, set, map, fn, any, email, password, handle, uuid, regex) 중 하나, enum, 다른 type, 리스트용 T[], T의 집합용 set(of: T). 규칙은 대괄호 안에 이어서 쓸 수 있습니다: string(min: 1). 이를 생략하면 필드는 어떤 값이든 받습니다.
? 이름 뒤에 값은 없거나 null일 수 있어요. 이것이 선택적 필드를 표시하는 유일한 방법이에요. type, model, error, job에 사용할 수 있어요: license?: string, license: string? 대신 (KS6014, 빠른 수정 제공). T?은 필드 고유의 타입이 아닌 타입에 사용해요. 예를 들어 null일 수 있는 매개변수에는 fn show(repo: Repo?)을 사용해요.
from path 값을 필드 이름과 다른 곳에서 읽어야 할 때 사용하세요: stargazers_count, owner.login, items[0].name. 중첩된 데이터는 평평하게 출력됩니다. 공백이 있는 경로는 따옴표로 감싸세요.
= default 데이터에 값이 없을 때 사용되는 값입니다. 이 필드는 선택 사항입니다.
=> value 다른 필드($name, $stars 등)의 값을 바탕으로 필드 값을 계산해요. 값을 직접 읽지 않아요.
/// 줄 위 마우스를 올리거나 자동 완성 목록에 표시됩니다.

타입 자체는 대괄호 안에 옵션을 받습니다: type Repo(extra: error) { … }. extra는 타입에 나열되지 않은 키를 어떻게 처리할지 정합니다: drop(기본값), keep, error. path: 'data/repo.json'는 저장된 데이터 샘플에서 필드를 가져옵니다. 객체는 중첩 타입이 되고, 일부 리스트 항목에만 있는 키는 선택 항목이 됩니다. 블록 안의 줄은 이름이 같은 샘플 필드를 대체합니다. 타입은 어떤 순서로든 서로를, 그리고 자기 자신을 참조할 수 있으며, 최상위 타입은 해당 파일을 가져오는 스크립트에 내보내집니다. 프로젝트에서는 타입마다 자기 파일(types/repo.kscript, types/owner.kscript)을 두고, 사용하는 타입을 가져오세요. 가져오기는 types/repo.kscript 상단에서 import "owner.kscript"로 합니다(파일당 타입 하나 참조).

작은 타입은 한 줄에도 쓸 수 있어요. 필드는 fn 매개변수처럼 작성해요: type Point(fields: [x: int, y: int]). kscript convert는 이것을 블록으로 작성해요.

XML에서 타입은 줄마다 <field name="stars" type="int" from="stargazers_count" /> 요소가 있는 <type name="Repo"> 형태이며, 한 줄 형식에서는 fields="..." 속성을 사용합니다. 예제를 XML로 바꾸면 확인할 수 있어요.

타입이 지정된 목록은 항목 타입을 유지해요

항목 타입과 함께 선언된 목록 $scores: int[] = [90, 72]은 그 타입을 유지해요. $scores[0] = '85'는 숫자 85를 저장하고, $scores[1] = 'high'는 "$scores의 항목은 int여야 해요"라며 멈춰요. kscript check와 편집기는 그 타입이 될 수 없는 값이 그 자리에 작성되면 보고해요(KS5012).

null일 수 있는 값

?로 작성된 타입은 값이 null일 수 있음을 뜻해요. fn find(slug: string): Post?로 선언된 함수, post: Post?인 매개변수, $post: Post? = ...인 변수, 또는 기본값 없이 license?: string인 필드가 해당해요. null의 필드를 읽거나 null에 메서드를 호출하면 스크립트가 멈추므로, 그런 값을 검사하기 전에 사용하면 kscript check와 편집기가 경고해요(KS5018):

<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

다음 중 어느 것이든 검사로 쳐요. 사용 주위의 if, elif, while(if $post != null, if $post, if $post is Post), if $post == null 뒤의 else, 그 위의 if $post == null { return }(또는 throw, break, continue, exit), 그리고 한 표현식 안의 $post and $post.title, $post == null or $post.title == '', $post ? $post.title : ''이 있어요. 위에서 방금 만든 레코드에 필드가 주어졌다면($p = Post(title: 'x', summary: 'y')) 그것도 검사예요. 선택적 목록, 집합, 맵은 null이 아니라 비어 있으며, 모델의 필드는 데이터베이스에서 오므로 실행 시점에 맡겨져요.

데이터가 타입과 만나는 곳

<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:는 타입을 받으며, as: Repo, as: int, 또는 as: Repo[]로 쓸 수 있고, 리스트는 선언에서 쓰는 방식대로 목록 형태로 씁니다. $repo->type()는 'Repo'입니다. 레코드는 맵이 쓰이는 모든 곳에서 여전히 동작하지만, 타입에 없는 필드를 읽거나 설정하면 오류가 발생하며, 필드를 설정하면 값이 해당 필드의 타입으로 변환됩니다.

->type()는 리스트의 요소 타입을 알려줍니다. [1, 2]->type()는 'number[]'를 반환하고, Repo 레코드들의 리스트는 'Repo[]'를 반환합니다. 여러 타입이 섞인 리스트와 타입이 없는 빈 리스트는 'any[]'를 반환합니다. 값이 어떤 종류의 리스트인지 확인하려면 ->is_a(list)를 사용하세요.

데이터가 맞지 않으면 매핑은 모든 문제를 JSON 경로와 함께 나열하는 하나의 Shape 오류로 실패합니다:

텍스트
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'.

catch에서 $err.problems는 { path, field, message } 맵들의 리스트입니다. Repo->check($data)는 예외를 던지지 않고 그 리스트를 반환하며(데이터가 맞으면 빈 리스트 아님), Repo.fields는 필드들을 나열하고, Repo->schema()는 타입을 JSON Schema로 설명합니다.

타입으로부터 만드는 타입

타입은 다른 타입으로부터 만들 수 있으므로, 매개변수나 필드는 반복해서 적는 대신 자신이 가리키는 타입을 따릅니다. 타입이 바뀌면 그로부터 만들어진 모든 것도 함께 바뀌며, 편집기는 이름을 자동 완성하고 연결하며 검사합니다.

형식 개요
Post.fields Post의 필드 이름 중 하나를 따옴표 없이 씁니다: title. 모델 자체의 필드(id, 그 키들)와 관계도 포함됩니다.
Post.fields(except: [body]) 더 적은 이름: except:은 일부를 제외하고, only:는 일부만 유지하며, relations: false는 관계를 제외하고, relations: only는 관계만 남깁니다.
Post.title Post의 title 필드의 타입과 그 규칙입니다. Post.title(max: 80)는 그 위에 규칙을 추가합니다.
Order.address.postcode 필드의 필드입니다. Order.lines.item은 리스트 필드 lines의 한 항목입니다.
Self.fields, Self.title type 또는 model 안에서는 선언 중인 타입을 가리킵니다.
draft|live 다음 단어 중 하나를 따옴표 없이 씁니다.
int|uuid 둘 중 어느 타입의 값이든 가능합니다. 타입의 이름이 되는 단어는 그 타입을 뜻하며, 단어 자체를 뜻하려면 따옴표로 감싸세요: card|'email'.
(draft|live)[] 괄호는 유니온을 묶으며, 여기서는 그것의 리스트를 만들기 위해 사용합니다.
<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 }"

맞지 않는 값은 모든 타입 인수와 같은 방식으로 보고되며, 가능한 모든 이름을 나열합니다:

텍스트
'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'.

내장 옵션도 같은 방식으로 타입이 지정되며, 호버, 시그니처 도움말, 참조 문서는 각 옵션의 타입을 보여 줍니다:

  • 모델의 hidden:와 guarded:는 Self.fields[]를 받고, key:는 Self.fields를 받습니다. unique:와 index:는 (Self.fields|Self.fields[])[]를 받는데, 이는 이름 하나 또는 이름들의 그룹입니다.
  • 작업의 unique_by:는 Self.fields[]를 받습니다.
  • ModelUpdate의 fields:는 model.fields[]를 받는데, 이는 model:가 가리키는 모델의 필드들입니다.
  • 마이그레이션의 Index(columns:)는 해당 테이블의 필드들을 받습니다.
  • 메서드는 수신자의 필드를 같은 방식으로 지정합니다: $post->is_dirty(title)는 Self.fields를 받고, 레코드의 ->pick([title, views])와 ->omit([body])는 Self.fields[]를 받으며, 레코드 리스트의 $posts->pluck(title) 또는 ->pluck([title, views])는 Self.fields|Self.fields[]를 받습니다. 수신자가 가지고 있지 않은 이름은 제안과 함께 오류가 됩니다.
  • 고정된 몇 개의 단어를 가진 옵션은 단어 유니온입니다: Document(template: plain|paper|report|letter|invoice), ->sort(by:, order?: asc|desc), 그리고 Resource(only:)는 (index|store|show|update|destroy)[]를 받습니다. 타입의 이름과 같은 단어는 echo의 format: text|'json'|'markdown'처럼 타입 안에서 따옴표로 감싸지만, 여전히 format: json처럼 따옴표 없이 씁니다.

status: draft|live로 쓰인 모델 필드는 데이터베이스 enum 열로 저장됩니다.

하나 중 선택하는 그룹에서 콜론 앞의 |은 이름들을 구분하고, 콜론 뒤의 |는 유니온입니다: id|slug: int|uuid는 id: 또는 slug:를 받으며, 즉 int 또는 uuid입니다. 구성원의 타입이 서로 다른 그룹에서는 | 다음에 name:가 오면 다음 구성원이 시작됩니다: (as: draft|live | template: Template).

값과 메서드

값은 문자열, 숫자, 불리언, 리스트, 맵, 날짜, 함수, null, 그리고 패키지가 추가하는 값(파일, HTTP 응답)입니다. 모든 값에는 메서드가 있으며, ->로 호출하고 연결할 수 있습니다:

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

pluck(key)를 사용하면 각 항목에서 순서대로 필드를 읽을 수 있습니다. pluck에 키 목록을 주면 항목마다 새 맵을 하나씩 만듭니다. 키는 따옴표 없는 이름, 따옴표로 감싼 문자열, 또는 변수일 수 있습니다.

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

맵에 없는 키는 null을 줍니다. 타입이 있는 레코드는 평소의 필드 검사를 유지합니다. 빈 입력 리스트는 []를 주고, pluck([])는 입력 항목마다 빈 맵을 하나씩 줍니다. 반복된 키는 요청한 순서대로 한 번만 나타납니다.

리스트에서 contains(value), index_of(value), remove(value), count_of(value)는 ==로 비교합니다. 예를 들어 [1, '1']->count_of(1)는 2을 줍니다. unique()는 엄격한 동등성(===)을 사용하므로 [1, '1']->unique()는 두 항목을 모두 유지합니다.

is_empty()은 문자열에서는 문자 0개, 리스트에서는 항목 0개, 맵에서는 키 0개를 뜻합니다. 공백만 있는 입력도 허용하려고 $text->is_empty()를 사용했다면, 그 동작을 유지하려면 $text->is_blank()를 사용하세요.

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

숫자는 항상 지수 표기 없이 일반 숫자로 씁니다: echo 10 ** 20는 100000000000000000000를 출력하고, echo 0.1 ** 20는 0.00000000000000000001를 출력합니다. 정수는 크기에 상관없이 정확합니다: 123456789 * 987654321는 121932631112635269, 2 ** 100는 1267650600228229401496703205376이며, 텍스트나 JSON에서 읽은 20자리 id도 모든 자릿수를 유지합니다. +, -, *, %, **, /(나누어떨어질 때), ->sum(), ->product(), @gcd, @lcm, @factorial는 모두 정확하게 유지됩니다. 소수, @sqrt 등은 일반 부동소수점으로 동작합니다. 소수는 유효숫자 15자리까지 보여 주므로 0.1 + 0.2는 0.3를 출력합니다. 정수는 약 30,000자리까지 커질 수 있으며, 그 이상이면 Limit 오류로 멈춥니다.

텍스트에서 ->count()과 위치(->slice(), ->index_of(), $text[0]에서 쓰는)는 대부분의 문자를 한 자리로, 이모지 같은 문자는 두 자리로 셉니다. 어떤 메서드도 그런 문자를 반으로 자르지 않습니다: ->chars(), ->first(), ->last(), ->reverse()는 독자가 보는 대로 온전한 문자 단위로 동작하며, ->slice()와 ->truncate()는 그 안에 떨어질 자르기 지점을 그 앞으로 옮깁니다.

값에 관한 단순한 사실은 필드이며, 맵의 키와 같은 방식으로 점을 쓰고 괄호 없이 읽습니다:

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

따라서 $response.status, $file.size, $url.host, $e.status는 필드이고, 인수를 받거나 작업을 수행하는 것은 메서드입니다: $response->convert(from: json), $file->read_text(), $day->format('yyyy'). 참 또는 거짓을 답하는 이름은 is_ 또는 has_로 시작합니다: $response.is_ok, $ip.is_private, $list->is_empty(), $map->has(key).

시간의 길이는 기간입니다. 숫자와 따옴표 없는 단위로 쓰며, 예를 들어 500ms, 30s, 10m, 2h, 1d, 1w이고, 여러 단위를 이어 붙일 수도 있습니다(1h30m). 시간 길이를 받는 것은 모두 기간을 받습니다: wait(500ms), @api($url, options: { timeout: 30s }), $cache->set(key, value, ttl: 10m). 단순한 숫자는 항상 초입니다.

년과 월은 y과 mo이며(m는 분입니다): 1y, 6mo, 5y10mo. 월이나 년은 고정된 길이가 없으므로, 이들은 달력 기준으로 날짜를 옮기며($date + 1mo는 가능한 경우 일자를 유지합니다), wait(1mo)나 1mo.hours처럼 고정 길이가 필요한 곳에서는 거부됩니다.

편집기는 각 타입의 필드와 메서드를 자동 완성하고 그 기능을 보여 줍니다. 값의 형식을 바꾸려면, 예를 들어 JSON 텍스트를 읽거나 행을 CSV로 쓰려면 ->convert()를 사용하세요: 형식 간 변환을 보세요.

날짜

날짜의 달력 정보는 필드입니다: .year, .month, .day, .weekday, .quarter, .day_of_year, .week(ISO 주차 번호), .days_in_month. .is_past, .is_future, .is_today, .is_weekend는 날짜를 현재와 비교하므로 템플릿에 적합합니다:

<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)와 ->end_of(unit)는 날짜가 속한 day, week, month, quarter, 또는 year의 첫 순간과 마지막 순간을 줍니다. 이는 '이번 달 주문'이라는 보고서에 필요한 것입니다. 주는 로캘의 첫 요일로 시작합니다(en-GB에서는 월요일, en-US에서는 일요일), 또는 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

달력 연산은 온전한 단위를 셉니다. $date + 1y6mo는 날짜를 년과 월만큼 옮기며, ->add()도 그렇게 하는데, 이것은 years:, months:, weeks:, days:의 어떤 조합도 받습니다(->subtract()는 뒤로 옮깁니다). 월은 가능한 경우 일자를 유지하므로, 1월 31일에 한 달을 더하면 2월의 마지막 날이 됩니다. 시간과 분은 기간을 더하거나 빼서 다룹니다:

<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

날짜는 기간으로만 옮길 수 있습니다. $date + 1는 오류인데, 다른 곳에서는 단순한 숫자가 항상 초를 뜻하기 때문이며, 불리언, 리스트, 또 다른 날짜를 더하는 것도 마찬가지입니다. 단위를 쓰세요($date + 3d). 숫자가 날짜를 뜻하는 유일한 곳은 1970년 이후의 초 단위인 Unix 타임스탬프이며, ->to_date()는 이를 읽고 ->timestamp()는 이를 돌려줍니다:

<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

한 날짜에서 다른 날짜를 빼면 그 사이의 정확한 시간이 기간으로 나옵니다. ->since(other, in: unit)는 대신 생일처럼 온전한 일, 주, 월, 년 수를 셉니다. ->is_same(other, unit)는 두 날짜가 같은 날(기본값), 주, 월, 분기, 년에 속하는지 묻습니다:

<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는 컴퓨터의 시계에서 가져오므로, 테스트에서는 @with_clock(date, fn)이 @now(), @today(), 위의 필드들, 그리고 @format_relative()에 대해 그 시각을 고정합니다.

텍스트 다루기

텍스트에는 자주 반복되는 작업을 위한 도우미가 있습니다. 이름의 대소문자를 바꾸기, 구분자에서 자르기, 공백 정리하기, 페이로드에 서명하기입니다.

<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()와 ->after()는 첫 번째 구분자에서 자르며, last를 주면 마지막 구분자에서 자르고, 구분자가 없으면 전체 텍스트를 돌려줍니다. ->wrap(width: 60)는 텍스트를 단어 사이에서 나누어 @terminal_width() 같은 너비에 맞춥니다. ->is_numeric()는 '42'나 '-3.5' 같은 텍스트에 대해 참입니다.

->contains(), ->starts_with(), ->ends_with(), ->index_of() (마지막 일치는 last와 함께) 및 ->replace()은 대소문자를 정확히 구분해서 일치시킵니다. 대소문자를 구분하지 않고 일치시키려면 ignore_case을 전달하세요:

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

웹훅을 확인하려면 ->hmac(key)로 서명을 계산해요(기본값은 SHA-256이며, sha1 또는 sha512도 사용할 수 있어요). 그런 다음 두 값이 얼마나 일치하든 항상 같은 시간이 걸리는 @secure_equals()로 비교해요:

<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() 및 ->sha512()는 해시를 16진수로 반환합니다. @escape_regex(text)는 사용자가 입력한 내용을 이스케이프 처리하므로, 그 값으로 만든 패턴은 해당 텍스트와만 일치합니다.

리스트와 맵

목록은 ->difference(other), ->intersect(other), ->union(other)로 집합처럼 비교합니다. 각 함수는 첫 번째 목록의 순서를 유지하고, 모든 항목을 한 번씩만 반환하며, ==로 항목을 일치시키거나 by:가 각 항목에 대해 반환하는 값으로 일치시킵니다:

<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)는 각 키의 항목 수를 셉니다. ->take_while(fn)와 ->skip_while(fn)는 조건에 맞지 않는 첫 항목에서 멈춥니다. ->window(size, step?)는 겹치는 구간을 반환하고, ->replace_at(index, item)는 한 항목만 바뀐 복사본을 반환합니다:

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

가장 많이 나오는 것과 가장 적게 나오는 것: common

->common(count?, least, by?)는 각 항목이 몇 번 나오는지 세고, 그 순서대로 항목을 한 번씩만 반환합니다. least를 쓰지 않으면 가장 많이 나온 항목이 먼저 오고, least를 쓰면 가장 적게 나온 항목이 먼저 옵니다. count는 앞에서부터 그 개수만큼만 남기며, 생략하면 서로 다른 모든 항목을 얻습니다. 같은 횟수로 나온 항목은 목록에서 처음 등장한 순서를 유지하고, 각 항목은 원래 모습 그대로 반환되므로 숫자는 숫자로 남습니다:

<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:는 무엇을 같은 항목으로 볼지 결정합니다. 여기서 'Tea'와 'tea'는 둘 다 'tea'로 변환되므로 함께 세어지며, 먼저 나온 쪽이 반환됩니다:

<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

가장 많이 나온 숫자 세 개를 곱하려면 ->common(3)로 그 숫자들을 가져오고 ->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

맵에도 목록과 같은 콜백이 있으며, 콜백은 값을 먼저, 키를 나중에 받습니다: ->filter(), ->reject(), ->any(), ->all(), ->find()({ key, value }를 반환), ->reduce(), ->sort(by:) 및 ->map(). ->map_keys(fn)는 각 키의 이름을 바꾸며, 키를 먼저, 값을 나중에 받습니다:

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

집합(Set)

집합은 각 항목이 한 번씩만 나타나는 항목들의 묶음입니다. 이미 있는 항목을 추가하면 아무 일도 일어나지 않고, 항목이 집합에 있는지 확인하는 것은 집합이 아무리 커져도 빠르게 처리됩니다. 집합은 목록처럼 작성한 뒤 as set로 집합으로 만들거나, 변수나 필드를 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

집합은 이미 본 것을 기억할 때 가장 유용합니다. $seen: set = []은 빈 집합을 만들고, +=는 항목을 추가하며, in는 항목이 있는지 확인합니다. 두 작업 모두 집합이 커져도 빠르게 동작합니다:

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

+는 두 집합을 합치고, -는 항목을 제거하며, ->intersect()는 두 집합에 모두 있는 항목만 남깁니다. 오른쪽 피연산자는 일반 목록일 수도 있습니다. set(of: string)는 한 가지 타입의 집합이며, 타입이 지정된 목록과 마찬가지로 항목이 들어올 때마다 해당 타입으로 변환됩니다. $set as list는 항목들을 목록으로 반환합니다. 집합의 모든 메서드와 예시는 Sets에서 확인할 수 있습니다.

<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

형식 간 변환: convert

데이터는 형식 사이를 끊임없이 오갑니다. API는 JSON으로 응답하고, 설정 파일은 YAML이며, 스프레드시트는 CSV로 저장됩니다. 모든 값은 이 작업을 위한 메서드 하나, ->convert()를 가지며, 이는 문장처럼 읽힙니다: from 이 형식에서, to 저 형식으로 변환하라.

from:는 특정 형식으로 작성된 텍스트를 읽어 그 안의 값을 반환합니다. to:는 값을 특정 형식으로 씁니다. 두 가지를 함께 전달하면 한 형식을 곧바로 다른 형식으로 바꿀 수 있습니다.

형식 from:로 읽기 to:로 쓰기
json 맵, 목록, 텍스트, 숫자 json 텍스트
yaml 맵, 목록, 텍스트, 숫자 yaml 텍스트
csv 행의 목록 csv 텍스트
markdown, latex 문서 KScript.Document 사용
html KScript.Markdown을 사용한 Markdown에서, KScript.Document를 사용한 문서에서

텍스트 읽기: from

from:는 텍스트를 받습니다. 텍스트 블록(예: ```yaml 또는 ```csv 블록), json 또는 csv 값, 또는 HTTP 응답(그 본문)도 받을 수 있습니다:

<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

CSV는 기본적으로 헤더 줄을 가지며, 이 줄이 각 행의 키 이름을 정합니다. 모든 줄이 데이터일 때는 not header를 쓰세요. 그러면 각 행은 셀들의 목록이 됩니다:

<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

타입으로 검사하기: as

as:는 읽은 값을 타입과 대조해 레코드로 변환합니다. 그래서 필드가 없거나 잘못되어도 나중에 뜻밖의 오류가 나는 대신, 그 값을 읽은 줄에서 바로 오류가 발생합니다. 레코드의 목록은 선언이 그렇게 쓰이듯 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

형식으로 쓰기: to

to:는 모든 값을 씁니다. 맵과 목록은 JSON이나 YAML로, 행의 목록은 CSV로 씁니다. indented는 JSON을 여러 줄에 걸쳐 펼치고, headers:는 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

한 번에 둘 다

from:과 to:를 함께 주면, 중간에 값을 직접 다루지 않고도 한 형식을 다른 형식으로 바꿀 수 있습니다:

<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

축약형: from과 to

읽기만 하거나 쓰기만 할 때는 ->from(type: json)와 ->to(type: csv)로 같은 일을 더 짧게 표현할 수 있습니다. 두 메서드는 ->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()이 형식을 바꾸는 유일한 방법이므로, 형식마다 하나씩 있던 예전 방식의 표기(->json(), ->yaml(), ->csv(), ->markdown(), ->to_json(), ->to_yaml(), ->to_csv(), 그리고 문서의 ->html(), ->latex(), ->markdown())는 오류가 되며, 대신 작성해야 할 ->convert()를 보여 주고 편집기에서 수정 방법을 제시합니다.

구조화된 텍스트 읽기

데이터는 종종 텍스트로 들어옵니다. 한 줄에 레코드 하나씩이거나, 빈 줄로 구분된 줄 묶음이거나, 문자로 그린 그림일 수도 있습니다. 이 메서드들은 그런 텍스트를 다루기 쉬운 목록으로 바꿔 줍니다.

줄과 블록

->lines()는 한 줄당 텍스트 하나를 반환합니다. ->blocks()는 대신 빈 줄을 기준으로 텍스트를 나누므로, 각 블록은 줄들의 묶음이 됩니다. 한 번의 줄바꿈은 블록 안에 남고, 빈 줄만 새 블록을 시작합니다:

<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()는 fn(block) => $block->lines()를 줄여 쓴 것입니다. 즉 각 항목에 대해 메서드를 호출하며, 이는 .name가 각 항목의 필드를 읽는 것과 같습니다. ->filter(.is_empty())나 ->sort(by: .age)처럼 함수가 들어가는 어느 곳에서든 동작합니다:

목록 나누기: split

이미 목록이 있을 때 ->split(separator)는 구분 항목이 나타나는 곳마다 목록을 잘라 여러 목록으로 만들며, 구분 항목은 버립니다. 일치시킬 값을 ==로 주거나, 구분 항목에 대해 참인 검사 함수를 줄 수 있습니다:

<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()는 텍스트를 자르고, 목록에 쓰면 ->split()는 목록을 자릅니다.

텍스트 속 숫자: numbers

->numbers()는 텍스트에 적힌 모든 숫자를 순서대로 반환하므로 그것을 위한 패턴을 따로 만들 필요가 없습니다. 마이너스 기호는 바로 앞에 아무것도 붙어 있지 않은 숫자 바로 앞에 있을 때 부호로 취급됩니다(예: x=-3). 두 숫자 사이에 있는 경우(예: 1-3)에는 대시로 취급되어 1와 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]

문자로 그린 그림: grid

->grid()는 문자 줄들을 한 글자짜리 문자들의 행으로 바꾸므로, $grid[row][column]는 문자 하나입니다. 0번 행은 맨 위 줄이고 0번 열은 첫 글자입니다:

<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

행과 열 따라가기: cells

->cells()는 표를 읽듯이 그리드를 읽습니다. 단독으로 쓰거나 rows와 함께 쓰면 모든 행을 반환하고, columns와 함께 쓰면 위에서 아래로 모든 열을 반환합니다. 이렇게 두 방향 모두로 그리드를 순회할 수 있습니다:

<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:는 한 행을, column:는 한 열을 고르며, 둘 다 0부터 셉니다. -1는 마지막 항목입니다. 둘을 함께 주면 두 위치가 만나는 셀 하나를 얻습니다:

<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

울퉁불퉁한 맵처럼 줄의 길이가 서로 다를 수 있습니다. 그러면 열은 그 열에 닿지 못할 만큼 짧은 행을 건너뛰며, 빈 칸을 채우기 위해 값을 만들어 넣지 않습니다:

<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()는 그리드만이 아니라 모든 목록의 목록에서 동작합니다. [[1, 2], [3, 4]]->cells(columns)는 [[1, 3], [2, 4]]이며, 이는 행을 열로 바꿉니다.

그리드에서 항목 찾기: positions_of

->positions_of(item)는 그리드에서 항목이 있는 모든 위치를 .row와 .column를 가진 점들로 반환하며, 행 순서대로, 왼쪽에서 오른쪽으로 나열합니다. 함수를 주면, 셀에 대해 그 함수가 참인 위치들을 반환합니다:

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

점은 ->combinations(2)와 함께 잘 동작합니다. 이는 모든 쌍을 한 번씩, 앞쪽 점이 먼저 오도록 반환합니다. 매개변수가 두 개인 함수는 쌍의 두 점을 하나씩 받습니다. 이 예시는 네 모서리가 모두 나무인 정사각형의 개수를 셉니다. 모서리 사이에 다른 나무가 있어도 상관없습니다:

<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

도형 찾기: shapes

->shapes()는 텍스트, 목록, 격자 또는 3D 목록에서 도형을 찾습니다. 내장 도형인 정사각형, 직사각형, 선, 원과, 직접 그린 도형인 마스크를 찾을 수 있습니다. 텍스트는 ->grid()가 읽는 방식대로, 한 행이 한 줄이고 한 셀이 한 글자입니다. 따라서 먼저 ->grid()를 호출할 필요가 없습니다. 격자의 셀에는 무엇이든 들어갈 수 있으므로, 내장 도형의 경우 of:는 어떤 셀이 도형을 이루는지 지정합니다. 예를 들어 '#' 같은 값이나 /[#@]/ 같은 정규식으로 지정합니다. 각 일치는 한 번만 { kind, points }로 반환되며, 각 점은 하나의 셀 { row, column, value }입니다. 도형의 점 사이에는 다른 셀이 있을 수 있습니다:

<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

rotated를 쓰지 않으면 도형은 수평을 유지합니다. 정사각형과 직사각형의 변은 수평이고, 선은 가로 또는 세로로 뻗습니다. rotated를 쓰면 도형이 기울어질 수 있어, 정사각형이 마름모가 되거나 선이 대각선으로 뻗을 수 있습니다:

<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

여러 도형을 지정하면 모두 찾습니다. 한 셀이 둘 이상의 도형에 맞아도 일치는 한 번만 반환됩니다. 예를 들어 정사각형은 직사각형이기도 하므로 정사각형으로 반환되며, .kind가 그 도형이 무엇인지 알려 줍니다:

<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

선에는 점이 몇 개인지 알려 주는 size:가 필요합니다. 원에는 radius:가 필요하고, distance:는 얼마나 떨어져 있어야 먼 것인지 정합니다. straight(직선 거리, 기본값), steps(가로와 세로만 계산하여 마름모를 그림) 또는 moves(대각선도 한 칸으로 계산하여 정사각형 고리를 그림):

<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()는 ->positions_of()가 주는 것처럼 점의 목록에도 작동합니다. 또는 csv에서 읽은 행에도 작동합니다. 이 경우 모든 점이 포함되므로 of:가 필요 없습니다: $trees->shapes(square, rotated).

직접 만드는 도형: 마스크

마스크는 직접 그리는 도형입니다. 내장 도형은 점이 어디 있는지만 알지만, 마스크는 간격을 포함하여 모든 셀이 정확히 무엇을 담아야 하는지 말해 줍니다. extends Mask하는 타입으로 선언하고, layout에서 그립니다. 이는 도형을 그림으로 보여 주는 텍스트 블록으로, 한 글자가 한 셀입니다. (길이가 정해지지 않은 행 도형에는 정규식을 쓸 수도 있습니다: 정규식 레이아웃). 각 글자는 같은 글자를 담은 셀과 일치합니다. 모든 줄이 공유하는 들여쓰기는 그림의 일부가 아니므로, 주변 코드와 함께 들여쓰면 됩니다.

#로 이루어진 속이 꽉 찬 2x2 블록을 찾으려면, 그것을 그리고 이름으로 마스크를 ->shapes()에 넘깁니다:

<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는 자기 자신이 아닌 다른 의미를 가진 글자에만 씁니다. 글자를 그것이 일치하는 대상에 대응시킵니다. 값(t: 'taken')은 그 값을 담은 셀과 일치하고, 정규식(/[#@]/)은 텍스트가 맞는 셀과, fn(cell)는 참을 돌려주는 셀과 일치합니다. same는 모두 같은 값을 담아야 하는 셀(아래)에, any는 도형의 일부가 아닌 셀에 대응합니다. any 셀에는 무엇이든 들어갈 수 있고, 입력의 가장자리 밖으로 넘어갈 수도 있으며, 일치의 점에서는 제외됩니다. 3x3 정사각형의 네 모서리에 나무가 있고 그 사이에는 무엇이든 있어도 되는 나무 네 그루를 찾으려면:

<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는 셀이 한 글자가 아닐 때 제 역할을 합니다. 좌석 한 줄은 단어의 목록이고, 값의 목록은 한 행이므로, 레이아웃에는 단어마다 글자 하나가 필요합니다:

<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()는 마스크 하나 또는 그 목록을 받고, rotated는 입력이 허용하는 모든 방향으로 각각을 돌립니다. 행을 따라 앞뒤로 뒤집고, 격자에서는 4분의 1, 2분의 1, 4분의 3만큼 회전하며, 3D에서는 24가지 방향 모두를 사용합니다. 여러 마스크의 일치는 함께 반환되며 각각은 .kind로 이름이 붙습니다. 마스크와 내장 도형을 한 번의 호출에서 함께 찾을 수 있습니다:

<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

마스크의 기호는 사용하는 곳에서 바꿀 수 있으며, 다른 필드와 마찬가지입니다. Fork(symbols: { t: fn(cell) => $cell != '.', '~': any })는 .를 제외한 모든 것과 같은 V입니다.

레이아웃에서 빈 줄은 다음 층을 시작하며, 마스크가 훑는 텍스트에서 빈 줄이 하는 것과 같습니다. 맨 위 층이 먼저입니다. 모든 층은 행 수가 같아야 하며, 3D에서 일치의 각 점에도 layer가 있습니다. 3D 목록($cube[layer][row][column])도 같은 방식으로 읽습니다:

<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

층이나 행이 입력보다 적은 마스크는 입력 전체를 미끄러지듯 훑습니다. 한 줄짜리 마스크는 격자의 모든 행에서 시도되고, 평면 마스크는 3D 텍스트나 3D 목록의 모든 층에서 시도됩니다. 입력보다 많은 층이나 행이 있는 마스크는 오류이며, 예를 들어 "Step has 2 layers, and this is one grid." 같이 그 사실을 알려 줍니다.

Mask는 매개변수나 필드에 쓸 수 있는 타입입니다. Mask를 확장하는 모든 타입을 받으며, 타입 자체(Block)나 그것으로 만든 타입(Block(symbols: ...))을 받습니다. Mask[]는 그것들의 목록을 받습니다:

<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

서로 같아야 하는 셀: same

지금까지의 모든 기호는 셀을 고정된 무언가와 비교합니다. same는 셀끼리 비교합니다. 그 글자로 그려진 모든 셀은 값이 무엇이든 하나의 값을 담아야 하며, 서로 다른 same 글자는 서로 다른 값을 담아야 합니다. same(...)는 그 값이 무엇일 수 있는지 좁히며, 값, 정규식 또는 fn(cell)로 지정합니다. 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

어떤 길이든 되는 도형: 정규식 레이아웃

그림은 크기가 고정되어 있습니다. 대신 레이아웃을 정규식으로 쓸 수 있는데, 이는 각 행을 따라 셀을 하나씩 차례로 읽고, 필요한 만큼 일치시킵니다. 각 셀은 그 텍스트로 읽히며, 일치는 셀 사이에서 시작하고 끝나야 합니다. 정규식 레이아웃에는 symbols가 없습니다. 부분에 (?<name>...)로 이름을 붙이면, 각 점의 symbol는 그 점이 속한 부분의 이름이 됩니다:

<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

rotated를 쓰면 정규식 레이아웃은 각 행을 뒤에서 앞으로도 읽고, 격자에서는 각 열을 위아래로도 읽습니다. 단어의 목록은 셀마다 단어 하나씩 읽히므로, /\d+/를 ['ab', '12', '34']에 적용하면 ['12', '34']를 찾습니다.

반복해서 찍기: repeated

repeated를 쓰면 마스크는 쿠키 틀과 같습니다. 왼쪽 위에서 시작해 입력 전체를 덮을 때까지 계속 찍히며, 오른쪽과 아래 가장자리의 복사본은 잘립니다. 모든 복사본이 첫 번째 복사본과 셀마다 같은 내용을 담으면 맞는 것입니다(any 셀은 자유롭습니다). 일치는 첫 번째 복사본이며, copies는 몇 번 찍혔는지 알려 줍니다:

<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

정규식 레이아웃은 고정된 크기가 없으므로 repeated를 쓰면 가장 짧은 틀부터 시도하여 맞는 가장 짧은 것을 줍니다. 행을 따라 찍힌 처음 size 셀이 행을 이루어야 하며, 정규식은 그 셀 전체와 맞아야 합니다. 행 하나만 읽으므로 한 번에 한 줄씩 주세요:

<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

어떤 것과도 맞는 셀: blank

입력이 손상되었거나 알 수 없을 때가 있습니다. blank:는 어떤 것과도 맞는 셀을 지정하며, 값('?'), 정규식 또는 fn(cell)로 지정합니다. 빈 셀은 모든 기호와 맞고, same나 repeated에서는 비교되지 않으므로, 복사본들이 서로의 빈칸을 채웁니다. 점의 value는 다른 복사본이 값을 알고 있을 때 채워진 값입니다. blank:는 마스크가 아니라 호출에 씁니다. 모양이 아니라 입력을 설명하기 때문입니다:

<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

내장 도형도 blank:를 받으며, of:는 값이나 정규식뿐 아니라 fn(cell)도 받아서 세 가지 모두 셀을 같은 방식으로 읽습니다. $field->shapes(square, of: '#', blank: '?')는 ?를 #로 셉니다.

바코드의 행 목록에서 도형을 찾으려면, 줄마다 적용합니다:

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

마스크에는 layout, symbols, 그리고 :로 작성하는 고유 메서드가 들어 있습니다. 편집기와 kscript check는 잘못 작성된 마스크를 보고하며, 대부분 수정 방법도 함께 제시합니다. 보고 대상은 다음과 같습니다. 레이아웃이 없거나 비어 있는 경우, 레이아웃이 전부 any인 경우, 그림에 탭이 있는 경우, 레이어 높이가 서로 다른 경우, 기호가 한 글자를 넘거나 중복 나열된 경우, any 대신 null를 쓴 경우, 따옴표 안의 'same'를 same로 써야 하는 경우, 정규식 레이아웃 옆의 symbols, layout: 대신 쓴 layout =, 내장 도형에 쓴 repeated, ->find_all()나 ->matches()(정규식을 받음)에 마스크를 넘긴 경우, 그리고 더 이상 받지 않는 ->shapes()에 쓴 like:입니다. 레이아웃이 사용하지 않는 기호는 경고(KS6026)가 되며, 글자를 자기 자신으로 대응시키는 기호도 경고(KS6025)가 됩니다. 모든 글자는 이미 자기 자신과 일치하기 때문입니다:

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

편집기에서 마스크는 언어의 일부입니다. extends ‸는 Mask를 제안하며, Mask 타입 안에서 layout를 입력하면 텍스트 블록이 써집니다. 일단 블록이 있으면 symbols는 레이아웃의 글자와 any로 완성되어 나타납니다. symbols: { } 안에서는 아직 나열되지 않은 레이아웃의 글자를 완성 목록으로 제안하고, 키 뒤의 콜론 다음에는 any, same, same(/…/), 값, 정규식과 fn(cell)를 제안합니다. layout: 뒤에는 텍스트 블록과 정규식을 제안합니다. 서명 도우미는 마스크를 쓰는 동안 ->shapes(mask, rotated?, repeated?, blank?)를 보여 줍니다. 레이아웃의 글자에 마우스를 올리면 그것이 무엇과 맞는지, 그리고 레이아웃이 그것을 몇 번 쓰는지 알려 주며, 각 글자는 맞는 대상에 따라 색이 칠해집니다. 자기 자신이나 텍스트 같은 값은 한 색으로, 정규식은 정규식의 색으로, fn는 함수의 색으로, any는 주석처럼 흐리게 표시됩니다.

순서 다루기

곱하기: product

->product(fn?)는 항목들을 곱합니다. ->sum()가 항목들을 더하는 것과 같습니다. 함수가 주어지면 각 항목에 대해 함수가 준 값을 곱합니다. 정수는 크기와 관계없이 정확하게 유지됩니다:

<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

누적 합계: scan

->scan(fn(total, item), initial?)는 ->reduce()와 같이 작동하지만 중간의 모든 합계를 유지하므로, 결과가 어떻게 쌓이는지 볼 수 있습니다. initial가 없으면 첫 번째 항목이 첫 번째 합계가 됩니다:

<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

모든 선택: combinations

->combinations(size)는 순서가 중요하지 않을 때 목록에서 size개 항목을 고르는 모든 방법을 제공해요. 각 조합은 목록 순서를 유지하며, 같은 조합에 같은 항목을 두 번 고르지 않아요.

목록 ['tea', 'milk', 'juice']에서 2개를 고르면 다음과 같아요. tea부터 시작해 그 뒤의 각 항목(milk, 그다음 juice)과 짝을 짓고, 그다음 milk부터 시작해 그 뒤의 각 항목(juice)과 짝을 지어요. juice 뒤에는 항목이 없으므로 더 없어요. ['milk', 'tea']는 ['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']]

흔한 용도는 모든 짝을 확인하는 거예요. 예를 들어 합이 특정 금액이 되는 두 가격을 찾을 때 써요:

<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

고른 항목 수만큼 매개변수가 있는 함수는 항목을 하나씩 받으므로 $two[0]과 $two[1]를 직접 읽지 않고 이름으로 쓸 수 있어요. 어떤 크기에서도 동작해요. 3개를 고르면 fn(first, second, third)를 채워요. 매개변수가 하나뿐인 함수는 조합 전체를 받아요:

<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

고른 항목이 매개변수를 채우기 때문에 이런 함수는 인덱스를 함께 받지 않아요. 짝을 고르면 fn(first, second)은 그 짝의 두 항목이에요.

모든 순서: 순열

->permutations(size?)는 순서가 중요할 때 모든 배열을 제공하므로 ['tea', 'milk']와 ['milk', 'tea']가 모두 포함돼요. size가 없으면 각 배열은 모든 항목을 사용해요:

<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

조합과 순열은 빠르게 늘어나요(항목 10개면 3,628,800가지 순서가 나와요). 그래서 목록이 100만 개를 넘으면 메모리가 부족해지기 전에 Limit 오류로 멈춰요.

방향 바꾸기: rotate

->rotate(by)는 모든 항목을 by칸씩 앞쪽으로 옮기고, 앞에서 밀려난 항목은 뒤에 붙여요. 음수 by는 반대 방향으로 돌려요:

<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

타입에 메서드 추가하기: extend

extend는 내장 타입이든 직접 만든 타입이든 거기에 나만의 메서드를 추가해요. 블록 안에서 각 fn가 메서드이고, $this는 메서드가 호출된 값이에요:

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

string, number(또는 int와 float), bool, list, set, map, fn, date, email, password, handle, uuid, regex를 확장할 수 있고, file나 response 같은 패키지 값도 확장할 수 있어요. 직접 만든 type에도 쓸 수 있는데, 그 메서드에서는 $this(레코드)와 그 필드를 $this.name로 볼 수 있어요. 메서드도 모든 fn처럼 매개변수, 기본값, 이름 있는 인자를 받을 수 있어요.

타입이 이미 가진 이름과 같은 메서드는 추가할 수 없으므로 오타나 이름 충돌이 내장 메서드 동작을 바꾸지 않아요. 일부러 교체하려면 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')
}

XML에서 extend은 <fn> 요소를 담은 <extend type="date">이고, override fn는 <fn override="true">예요.

확장이 적용되는 범위. 파일 안의 extend 블록은 그 파일과, 그 파일을 가져오는 모든 파일에 적용돼요. 프로젝트(kscript.json가 있는 폴더)에서는 extensions/ 폴더의 모든 파일이 가져오기 없이 프로젝트의 모든 스크립트, 테스트, 페이지에 적용돼요. 예를 들어 타입마다 파일을 하나씩 두는 식으로 자유롭게 나눌 수 있어요:

텍스트
extensions/
  date.kscript        extend date { … }
  list.kscript        extend list { … }
  text/
    slug.kscript      extend string { … }

kscript make extension date --methods api_date,is_payday는 시작점으로 extensions/date.kscript를 작성해요. 다른 위치에 두려면 kscript.json에 폴더나 글로브를 나열하세요. 이렇게 하면 기본 폴더 "extensions": ["extensions", "shared/**/*.kscript"]는 대체돼요. 같은 타입의 같은 메서드를 추가하는 확장 파일 두 개는 오류이며, 오류 메시지에 두 파일 모두 표시돼요. 스크립트 자체의 extend(또는 가져오기)가 프로젝트의 것보다 우선해요.

편집기는 확장 메서드를 적용되는 곳에서만 자동 완성하고 검사해요. 파일이 선언하거나 가져오지 않고, 프로젝트를 통해서도 받지 않았다면 날짜에 대한 ->api_date()는 여전히 알 수 없는 메서드예요. 마우스를 올리면 메서드의 /// 문서와 어떤 파일이 추가했는지 보이고, 정의로 이동하면 그 파일이 열려요. @today()->api_date()

오류

guard condition else { ... }를 쓰면 전제 조건이 성립할 때만 계속 진행합니다. 실패 블록은 return, throw, break, continue 또는 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

후위 catch는 평가가 성공하면 왼쪽의 값을 그대로 유지합니다. 오류가 던져지면 KScript는 그 오류를 $err에 바인딩하고 대체 값을 평가합니다. 특정 오류 타입 하나만 복구하려면 catch Validation => $err.message를 쓰고, 바인딩 이름을 지정하려면 catch Validation as problem => $problem.message를 씁니다. null 대체 값은 원래 오류를 그대로 전파합니다.

@a() + @b() catch => 0에서 처리기는 호출과 덧셈 모두를 포함합니다. @a() + (@b() catch => 0)에서는 @b()만 포함합니다.

조건이 성립할 때만 오류를 발생시키려면 throw if를 씁니다. 블록 안에는 한 줄에 필드 하나씩 씁니다. KScript는 조건을 한 번 평가하고, 조건이 참일 때만 필드를 평가하므로 성공 응답에서는 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는 처리하는 오류 타입을 |로 이어서 받고, as는 오류의 이름을 지정합니다: catch FileNotFound | Permission as e. 소문자 이름만 있는 catch(catch err)는 모든 오류를 처리합니다. when는 검사를 추가합니다: catch Network as e when $e.status == 503. catch는 순서대로 시도되며, 처음으로 맞는 것이 실행됩니다. 오류 타입 이름은 대문자로 시작하며, 이것으로 catch는 변수 이름과 구별합니다.

알 수 없는 요소, 속성, 구문 오류는 스크립트를 시작하기 전에 보고되므로, 끝부분의 오타 때문에 작업이 반쯤 끝난 채로 남지 않습니다.

어떤 catch에도 잡히지 않은 오류는 발생 위치와 타입을 포함한 KScript 오류로 출력되며, 스크립트는 코드 3으로 종료합니다:

텍스트
   ERROR  app.kscript:2:11: Name: Unknown command @nope().

kscript는 스크립트, kscript serve 오류 페이지 및 그 밖의 모든 명령에서 모든 실패를 이런 방식으로 보여주며, .NET 예외를 그대로 노출하지 않습니다. 스크립트가 아니라 컴퓨터에서 발생한 실패에는 적합한 오류 타입이 주어집니다(FileNotFound, Access, IO, Network 등). kscript가 예상하지 못한 실패는 Internal 오류이며, 이는 보고할 가치가 있는 버그입니다. 오류 뒤의 .NET 예외와 스택 추적을 보려면 --stack-trace로 실행하거나(스크립트 경로 앞에: kscript --stack-trace app.kscript), KSCRIPT_STACK_TRACE=1를 설정하세요. 이 방법은 kscript serve와 컴파일된 프로그램에서도 동작합니다.

함수와 타입의 처리기

모든 호출자의 오류를 처리하려면 함수나 메서드에 catch를 붙이세요. 타입의 메서드들이 처리기를 공유하도록 하려면 타입에 붙이세요.

가장 가까운 일치하는 처리기가 먼저 실행됩니다. 복구하려면 null이 아닌 값을 반환하세요. false, 0, '' 같은 값은 모두 동작합니다. 그냥 throw만 쓰거나, null를 반환하거나, 처리기 끝에 도달하면 원래 오류가 다음으로 가까운 바깥 처리기에 전달됩니다.

<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

throw if condition의 조건이 참이면 핸들러 안에서 현재 오류를 다시 던집니다. 페이로드 블록을 추가하면 새 오류를 발생시킬 수 있습니다. 오류를 기록만 하는 핸들러는 오류를 그대로 전파합니다. 실행 가능한 catch 테스트에서 메서드 핸들러가 오류를 해당 타입의 핸들러에 전달하는 모습과, 기록된 뒤 호출자가 오류를 잡는 모습을 확인할 수 있습니다.

호출자에게 전달될 수 있는 오류를 기록하려면 /// @throws Network를 사용하세요. 마우스 오버와 시그니처 도움말에 알려진 오류가 표시됩니다. 스크립트 최상위에서 알려진 오류가 빠져나갈 수 있으면 kscript check와 편집기가 경고합니다(KS5016).

단일 호출의 결과는 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 }")
}

값과 원인을 함께 던지기

throw Error(message: ..., value: ..., cause: ...)을 사용하면 추가 데이터를 담은 일반 오류를 발생시킬 수 있습니다. 괄호 앞의 이름이 오류 타입을 정합니다. 일반 오류에는 Error를, Validation 같은 내장 타입에는 해당 이름을, 직접 선언한 타입에는 그 타입을 사용하세요. 이름 있는 인수는 필드가 됩니다. message:는 설명을 설정하고, 이전 오류를 감쌀 때는 cause:가 그 오류를 보관합니다.

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

첫 오류를 발생시킬 때는 cause:을 생략하세요. 내장 오류에 직접 추가한 필드에는 $err['value'] 같은 대괄호 조회를 사용하세요. 호출자가 찾고 타입을 검사할 수 있어야 하는 필드에는 오류 타입을 선언하고 그 타입을 잡으세요. 선언된 필드는 $err.value처럼 점 표기법으로 읽을 수 있습니다.

이미 type, message 등의 필드가 있는 맵이 있다면 throw $payload로 맵을 직접 던지세요. 맵을 Error($payload)의 첫 번째 인수로 전달하면 메시지 텍스트로 변환됩니다. 오류 생성자는 편집기 자동 완성에서 이름 있는 인수를 제공합니다.

XML에서 같은 throw는 <throw value="Error(message: 'Could not save profile', value: $age, cause: $original)" />입니다. 바깥 XML value 속성에는 전체 오류 식이 들어갑니다. 안쪽 value: 인수는 그 오류의 추가 필드입니다. 타입과 메시지만 있을 때는 <throw type="Validation" message="Invalid age" />가 throw Validation "Invalid age"에 해당합니다.

다시 시도하기

일부 실패는 저절로 사라집니다. 바쁜 데이터베이스, 일시적인 네트워크 끊김, 요청 빈도를 제한하는 API가 그런 예입니다. @retry(times, work)은 work를 호출하고, 던질 때마다 다시 호출하며, 총 times번까지 시도합니다. 성공하면 work가 반환하는 값을 돌려주고, 모두 실패하면 마지막 오류를 던집니다. work는 시도 번호를 받으며, 첫 번째 시도는 1입니다:

<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은 호출 사이에 대기합니다. when는 오류를 받아 다시 시도할지 여부를 정합니다. 그래서 결코 성공할 수 없는 실수는 즉시 실패합니다: @retry(5, @charge, when: fn(err) => $err.type == 'Timeout').

오류 타입

error로 자체 오류 타입을 선언합니다. 필드는 type에서와 같이 동작하며, 메시지에서 사용할 수 있습니다. extends는 오류의 종류를 지정합니다:

<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 })"
}
  • 던지기. throw PersonNotFound(id: 42)은 오류를 만들고 던집니다. 그 인수는 이름으로 지정한 필드이며, 추가로 message:(타입의 기본 메시지 대신)와 cause:(이 오류의 원인이 된 오류)를 받을 수 있습니다. 기본값이 없는 필드는 반드시 값을 주어야 하며, 편집기는 누락되거나 알 수 없는 필드를 표시합니다. 필드가 없는 타입에는 여전히 throw Validation "Too short"가 작동하고, 내장 타입에 필드를 추가하려면 throw Validation(field: 'name', message: 'Too short')를 씁니다.
  • 캐칭. catch NotFound은(는) PersonNotFound도 캐치합니다. NotFound을(를) 확장하기 때문입니다. 캐치에서 $e.id은(는) 필드를 읽고, 편집기는 캐치가 지정한 타입의 필드를 완성합니다. 모든 오류에는 type, message, line, column, file, status, cause이(가) 있습니다. $e->is(NotFound)은(는) 코드에서 타입을 확인하고, $e->chain()은(는) 이를 나열합니다: ['PersonNotFound', 'NotFound', 'Error'].
  • 다시 던지기와 감싸기. catch 안의 단독 throw은 처리 중인 오류를 변경 없이 다시 던집니다. throw $e는 저장된 오류로 같은 일을 합니다. 맥락을 추가하려면 감싸세요: throw ConfigBroken(path: $path, cause: $e), 그러면 $err.cause.message로 원래 오류를 읽을 수 있습니다.
  • 던지지 않고 만들기. OutOfStock(item: 'tea')은 나중에 반환하거나 던질 수 있는 값으로 오류를 만듭니다.
  • 상태. status는 아무도 오류를 잡지 않을 때 KScript.Http 라우트가 응답하는 HTTP 상태 코드입니다. 타입은 자신이 확장하는 타입으로부터 이 상태와 필드, 메시지를 상속합니다.
  • 내보내기. 최상위 오류 타입은 함수와 타입처럼 내보내지므로 import "errors/payment-failed.kscript"으로 가져올 수 있습니다. kscript make error PaymentFailed --status 402 --extends Validation --fields "order: int"는 하나를 errors/에 씁니다.

KScript 자체가 발생시키는 내장 오류 타입들은 catch이 따라가는 트리를 이룹니다:

타입 확장 발생 원인
Error 모든 오류. catch Error은 전부를 잡습니다.
Syntax, Name, Null, Argument, Value, Const, Math Error 스크립트의 실수: 잘못된 문법, 알 수 없는 이름, 값이 필요한 자리의 null, 잘못된 인수, 잘못된 값, const 변경, 0으로 나누기. Index은 목록 밖의 위치를 뜻하는 Value를 확장합니다.
Type Error 잘못된 타입의 값. Shape은 이를 확장하며, type에 맞지 않는 데이터에 쓰입니다($e.problems이 각 문제를 나열합니다).
Format Error 잘못된 형식의 텍스트. Json과 Yaml가 이를 확장합니다.
IO Error 파일. FileNotFound, Permission, Access이 이를 확장합니다.
Network Error 요청. Timeout이 이를 확장하며, $e.status는 응답의 상태입니다.
Import, Config, Input, Limit, Context, Platform, Cancelled, Retired, Http, AI, UI, Reference, Assertion, Internal Error 가져오기, 설정, 입력, 재귀 같은 한도, 잘못된 위치, OS, 중단된 스크립트, 폐기된 기능, KScript.Http 앱, 언어 모델, 데스크톱 창, 문서의 참조, 실패한 테스트 검사, KScript 자체의 결함.
Validation (422), BadRequest (400), Unauthorized (401), Forbidden (403), NotFound (404), Conflict (409), TooManyRequests (429) Error 사용자 코드가 던지거나 확장하기 위한 것. 숫자는 HTTP 상태입니다.
Query, Connection (503) Error KScript.Data: 데이터베이스가 거부한 쿼리, 열 수 없는 데이터베이스. Migration: 읽거나 실행할 수 없는 마이그레이션, 또는 진행할 수 없는 kscript db 명령. ModelNotFound는 NotFound를 확장합니다. UniqueViolation와 ForeignKeyViolation는 Conflict을 확장합니다. (->sole()에서 온) MultipleRecordsFound는 Query을 확장합니다.
JobFailed Error KScript.Queue: 재시도 횟수를 모두 소진한 작업. JobTimeout는 Timeout를 확장합니다.

어떤 타입 이름도 Error로 끝나지 않습니다. 모두 오류입니다. (QueryError와 ConnectionError은 이제 Query와 Connection이며, catch QueryError이 이를 알려 줍니다.)

catch이나 throw에 선언되지도 내장되지도 않은 이름이 있으면 여전히 작동하지만(Error의 한 종류로), 보통 오타이므로 편집기가 경고합니다(KS5011).

설정: $config

$config에는 앱 고유의 설정이 있어요. 예를 들어 앱 이름, 데이터베이스, 캐시가 여기 속해요. 모든 스크립트, 페이지, 라우트, 테스트는 import 없이 이 값을 읽을 수 있어요. 설정은 한 곳에 있어요: kscript.json의 config 섹션이에요.

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

없는 설정은 null이므로 $config.port ?? 8080가 동작해요. 이름은 대소문자를 구분하지 않아서 $config.app.name와 $config.APP.NAME는 같은 설정이에요. 편집기에서 $config.app.name 위에 마우스를 올리면 타입이 보이고, 정의로 이동하면 이 키를 제공하는 파일을 열어요. 보간 문자열 안에서도 동작해요.

패키지는 $config의 자기 부분을 읽습니다. KScript.Data는 database를, KScript.Cache는 cache를, KScript.Mail은 mail를, $log는 logging를, 번역은 i18n를, 금액 계산은 money.exchange_rates를 읽습니다(금액 참조).

환경. 같은 앱이라도 다른 곳에서는 다른 설정이 필요할 수 있어요. 예를 들어 테스트에는 메모리 데이터베이스가, 운영에는 실제 서버가 필요해요. 그런 설정은 kscript.json 옆의 kscript.<env>.json에 두세요. 그 파일의 config 섹션이 kscript.json의 것 위에 겹쳐지고, 맵은 필드 단위로 병합되므로 바뀌는 설정만 있으면 돼요:

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

kscript --env staging script.kscript 또는 KSCRIPT_ENV=staging로 환경을 선택합니다. kscript test는 kscript.json의 test.env를 사용합니다(테스트 참조). $config->environment()는 현재 환경을 반환하며, 선택된 환경이 없으면 null을 반환합니다. 환경 파일에는 config 섹션만 들어가며, 그 밖의 모든 내용은 kscript.json에 속합니다.

코드가 필요한 설정: config.kscript. JSON으로는 환경 변수를 읽거나 값을 계산할 수 없어요. 그런 설정은 kscript.json 옆에 config.kscript를 추가하세요(XML 프로젝트에서는 config.ks.xml). 이 파일은 configure(environment)를 정의하는데, 환경(고른 환경이 없으면 development)을 받아 맵을 돌려줘요. 그 맵은 JSON 설정 위에 겹쳐지므로 코드가 필요한 설정만 있으면 돼요:

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

값은 KScript 타입을 유지해요. 그래서 8s는 여전히 duration이에요. 스크립트에서는 @env(), $env, 가져온 파일, KScript.IO 같은 패키지를 쓸 수 있고, 경로는 스크립트 자신의 폴더부터 시작해요. 스크립트는 $config를 처음 읽을 때 한 번 실행되고, $config는 직접 읽을 수 없어요. kscript make config base는 시작용 config.kscript를 만들고, kscript make config staging는 kscript.staging.json를 만들어요.

설정은 여러 층으로 쌓이고, 뒤의 층이 우선해요. 순서는 kscript.json의 config 섹션, 그다음 kscript.<env>.json, 그다음 config.kscript예요. 프로젝트 밖의 스크립트는 자기 폴더의 config.kscript를 읽어요.

.env 파일은 비밀 정보를 프로젝트 파일 밖에 둡니다. .env(환경별로는 .env.<env>)는 kscript.json와 나란히 두며, NAME=value 줄로 구성됩니다. # 주석을 쓸 수 있고, 원하면 export를 앞에 붙일 수 있습니다. 'single quotes'은 적힌 그대로 읽힙니다. "double quotes"를 사용하면 \n을 쓸 수 있고 여러 줄에 걸칠 수 있습니다. ${NAME}와 ${NAME:-default}는 다른 변수를 참조합니다. 값은 보통 config.kscript에서 @env('NAME')로 읽으며, 이미 설정되지 않은 경우 환경 변수로도 등록되므로 KScript.AI는 .env에서 ANTHROPIC_API_KEY를 찾습니다. .env 파일은 git에 올리지 마세요.

사용자 자신의 설정. 데스크톱 앱은 프로젝트를 건드리지 않고도 사용자가 설정을 바꿀 수 있게 할 수 있습니다. kscript.json의 "app": { "user_config": true }와 함께 쓰면, 앱 설정 폴더의 config.json이 다른 모든 설정 위에 덮어씌워집니다(앱 폴더 참조).

config은 다른 옵션으로 설정을 다시 읽거나, 다른 설정 세트를 변수에 읽어 들여요. into가 없으면 $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 프로젝트의 파일 대신 읽을 다른 파일을 나열합니다. 설정 JSON 파일, 구성 스크립트, 그리고 .env 파일을 순서대로 지정하며, 각 파일 뒤에는 환경별 버전(settings.staging.json)이 붙습니다. 확장자가 없는 이름은 .json 파일을 의미하며, ?로 끝나는 이름은 없을 수도 있습니다. prefix를 사용하면 환경 변수가 파일의 값을 덮어쓰고, __은 중첩됩니다. 예를 들어 SHOP_DATABASE__HOST=db.internal은 database.host를 설정하며, true, false, 8080 같은 값은 각각 불리언과 숫자로 변환됩니다. root은 파일이 들어 있는 폴더입니다. defaults는 어떤 파일에서도 설정하지 않은 항목을 채우고, require는 반드시 설정해야 하는 항목을 나열합니다. user: true은 사용자 개인 설정도 함께 읽습니다.

$config->sources()는 읽은 파일의 목록을 보여주고, $config->all()는 모든 설정을 맵으로 제공하며, $config->reload()는 파일을 다시 읽어요. @parse_env(text)는 .env 텍스트를 파싱하고, KScript.IO는 @read_env(path)를 추가해요.

kscript serve는 kscript.json, kscript.<env>.json, 스크립트, .env 파일, config.* JSON 파일을 제공하지 않아요. 페이지는 프로젝트의 설정을 읽고 .env 파일의 값에 @env()를 사용할 수 있지만, 프로세스 환경은 건드리지 않아요.

로깅: $log

모든 스크립트에는 로거가 있습니다. info 이상 수준의 항목은 다른 위치를 설정하기 전까지 터미널(stderr)로 출력됩니다:

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

레벨은 trace, debug, info, warn, error, fatal입니다. 제공자가 항목을 어디에 보낼지 결정하며, 보통 설정 파일에서 지정합니다:

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(…)는 스크립트에서 같은 옵션으로 하나를 추가합니다(replace는 이미 설정된 항목을 제거하며, 기본 콘솔 항목도 포함됩니다). memory 공급자는 $log->entries()용 항목을 보관하므로 테스트할 때 유용합니다. http 배치처럼 공급자가 보류한 항목은 스크립트가 끝나거나 $log->flush()를 호출할 때 전송됩니다. 실패한 공급자는 stderr에 한 번 보고되며, 나머지 공급자는 계속 동작합니다.

패키지는 p.LogProvider("type", description, create)로 공급자 타입을 추가하며, KScript를 실행하는 프로그램은 host.Logs.AddProvider(provider, level)로 자체 공급자 타입을 추가할 수 있습니다. 공급자는 ILogProvider를 구현합니다.

번역: @t()

스크립트 옆(또는 사이트 폴더)의 locales 폴더에 번역을 둡니다: locales/en.json, locales/fr.yaml, 또는 locales/de/shop.json와 같이 로캘마다 폴더를 두며, 그 키는 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
  • 복수형. count와 함께 쓰면 @t()는 언어 고유의 규칙에 따라 zero, one, two, few, many 또는 other을 선택해요. 여기에는 영어, 프랑스어, 포르투갈어, 러시아어, 우크라이나어, 폴란드어, 체코어, 아랍어, 히브리어, 아일랜드어, 웨일스어, 일본어, 중국어, 한국어 등의 CLDR 규칙이 포함돼요. =0처럼 정확한 형태를 지정하면 그 형태가 우선해요.
  • 대체 값. 번역이 없으면 fr-CA에서 찾은 다음 fr에서 찾고, 그다음 기본 로케일(설정하지 않았다면 en)에서 찾아요. 어디에도 없으면 키 자체를 반환하고, i18n 카테고리 아래에 경고를 한 번 기록해요.
  • 로케일은 locale(set: fr)에서, locale(from: …)(목록이나 Accept-Language 헤더와 가장 잘 맞는 것)에서, $config.i18n.locale에서, KSCRIPT_LOCALE에서, 또는 컴퓨터의 언어에서 가져와요. @locale()가 이를 설정하고, @locales()는 파일이 있는 로케일을 나열해요. 로케일을 설정하는 라우트나 미들웨어는 응답할 때 쓰는 @view()에 이를 담으며, 요청이 원하는 언어보다 앞서요. 그래서 사이트는 자체 쿠키가 브라우저 설정보다 우선하도록 할 수 있어요.
  • 페이지는 다음 순서로 언어를 선택해요: 경로 접두사(프랑스어 번역이 있으면 /fr/about이 about.html를 제공해요), ?lang=fr, lang 쿠키, 그다음 브라우저의 Accept-Language 순이에요. @locale_path($request.path, 'de')는 같은 페이지의 독일어 링크를 제공해요. 기본 로케일에는 접두사가 없어요.
  • 서식. 이 함수들은 로케일을 따르거나, 마지막 인자로 전달한 로케일을 따릅니다:
    • @format_number(1234.5)는 1,234.5 또는 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?)은 지금부터 측정하여 3시간 전, 2일 후 또는 방금 전을 나타냅니다. 단, from:가 주어진 경우에는 그 기준으로 측정합니다;
    • @format_duration(1h30m)은 1시간 30분을 나타냅니다;
    • @format_list(['tea', 'coffee', 'milk'])은 차, 커피, 우유를 제공하며, style: 'or'가 있으면 차, 커피 또는 우유를 제공해요;
    • @format_ordinal(23)은 23rd를, 프랑스어에서는 23e를 반환해요;
    • @format_bytes($file.size)는 1.4 MB를 출력하며, binary: true를 사용하면 1.3 MiB를 출력합니다.
  • 설정: 구성 파일의 i18n: { folder: lang, default: en-GB, locale: fr } 또는 translations(folder: lang, default: en-GB). @has_t(key)은 키에 번역이 있는지 확인하고, @plural(count)는 복수형 범주를 반환해요.

상대 시간, 시간 길이, 목록, 서수를 나타내는 단어는 영어, 프랑스어, 독일어, 스페인어, 이탈리아어, 포르투갈어, 네덜란드어에 기본으로 내장되어 있습니다. 다른 언어를 추가하거나 이 단어를 바꾸려면 번역 파일에 다음 키를 추가하세요: time.second부터 time.year까지 복수형과 함께, 그리고 {count}, time.ago, time.in는 {time}, time.now, list.and, list.or, ordinal은 {count}와 함께:

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

패키지

KScript.Core(위의 모든 내용)는 항상 포함됩니다. 그 밖의 기능은 모두 패키지에서 가져오며, 패키지는 스크립트 맨 위에서 import합니다. 따라서 스크립트는 실제로 사용하는 것만 불러옵니다. 예를 들어 터미널 스크립트는 웹 서버를 불러오지 않습니다.

<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"
// …

.kscript 및 .ks.xml 파일만 가져올 수 있어요. 스크립트 안에서 직접 선언한 함수는 같은 이름의 가져온 함수보다 우선하며, 가져온 const은 상수로 유지돼요.

패키지 추가되는 기능
KScript.Terminal input(into, type, default, secret) (type은 email, handle, uuid 또는 password일 수 있어요), picker (파일 또는 폴더 경로), menu(options, multiple), progress(into, total)과 함께 ->advance(), confirm, pause, clear, @color(text, color: 'green'), @bold, @dim, @underline, @terminal_width(), @is_terminal() (출력이 파이프로 전달되면 없음), echo(format: markdown), 그리고 kscript 명령줄 자체의 모양: info, success, warn, alert(type: error), heading, detail(name), bullets(items), task(name) { }, table(rows, columns, header, align) (터미널 출력 참고)
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). 파일 값에는 .name .extension .mime .size .modified… 필드가 있고, ->read_text() ->read_bytes() ->read_json(as:) ->sha256() ->write_text(text) ->copy_to(path) ->move_to(path) ->delete() 메서드가 있어요.
KScript.Net @api(url, options: { method, headers, body, timeout })로 HTTP 요청을 보내며, 간편 메서드 post:, put:, patch:, delete:, bearer:, timeout:, retries:, as:, encoding:(json, form 또는 multipart)와 query:도 제공합니다. 응답에는 .status, .is_ok, .text, ->convert(from: json), ->check()이 있습니다. @download(url, to)와 @query_string도 제공합니다. '/api/notes'와 같은 경로는 프로젝트 자체의 라우트를 호출합니다. 자신의 API 호출하기를 참조하세요.
KScript.Markdown @markdown(text)과 @read_markdown(path)(front matter의 html, title, meta), ->convert(from: markdown, to: html)
KScript.Web 페이지에서 레이아웃, 컴포넌트, kscript serve용 라이브 블록으로 화면을 렌더링해요. 페이지에서는 KScript.IO, KScript.Markdown, KScript.Web을 가져오지 않고도 사용할 수 있어요.
KScript.AI @llm(prompt, system, schema, tools, model, max_tokens), llm(into, system, schema, tools, model, max_tokens), @chat(system)(->ask() .history ->reset() 포함), 테스트용 @fake_llm(replies). Claude는 ANTHROPIC_API_KEY의 키를 사용합니다(언어 모델 참조).
KScript.Style 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)(스타일시트 참조).
KScript.Http kscript serve용 라우트, 컨트롤러, 미들웨어. Routes { } 파일에는 Get Post Put Patch Delete Any Route Resource Group Middleware가 들어 있습니다. 컨트롤러는 @view, @response, @redirect, @abort, @route을 사용합니다. 라우트, 컨트롤러, 미들웨어를 참조하세요.
KScript.Storage 앱 고유의 폴더로, 각 플랫폼에서 올바른 위치에 있습니다: @storage(config) (data, cache, state, logs도 가능)에 ->read ->read_json ->write ->write_json ->read_bytes ->write_bytes ->file ->move ->copy ->append ->list ->delete ->folder ->path_of, 그리고 @app_name()와 @app_folders(). 앱 폴더를 참고하세요.
KScript.Cache $cache (메모리 내)와 @cache(file)가 ->get ->set ->remember(key, fn, ttl: 10m) ->has ->remove ->increment ->ttl ->keys ->clear와 함께 제공됩니다. 캐싱을 참고하세요.
KScript.Data model로 레코드를 저장하고, 쿼리 빌더로 조회하며, Migration와 kscript db migrate로 스키마 변경을 관리합니다. 데이터베이스를 참고하세요.
KScript.Queue job로 백그라운드 작업을 선언하고, ->dispatch()로 대기열에 넣고, kscript worker로 실행합니다. Schedule는 정해진 시간에 작업을 실행합니다. 큐와 작업과 작업 예약을 참고하세요.
KScript.Mail @send_mail(to:, subject:, html:|text:|view:)로 SMTP를 통해 이메일을 보내거나, 로그 또는 가짜 전송 대상으로 보냅니다. 지금 보내거나, kscript worker에서 queue로 예약할 수도 있습니다. @fake_mail()는 테스트를 위해 메일을 보관합니다. 메일을 참고하세요.
KScript.Auth kscript serve 앱의 로그인 기능: @register, @attempt, @login, @logout, @user(), @is_signed_in(), $session (->get ->set ->flash …), @users(), @csrf_field(), @reset_token, @reset_password, @api_token, 그리고 auth와 guest 미들웨어. 로그인을 참고하세요.
KScript.Document Document(template: paper, to: 'paper.pdf') { }와 함께 Section, Paragraph, List, Table, Figure, Math, Bibliography 등을 사용할 수 있으며, Letter와 Invoice도 있습니다. ->save ->pages ->words ->markdown ->latex ->html도 지원합니다. 문서를 참고하세요.
KScript.UI 데스크톱 창: Window { } 블록으로 창을 엽니다. Column Row Grid Text Button TextBox CheckBox Select Slider Box Spacer Timer, @close_window(). 데스크톱 앱을 참고하세요.
KScript.Test test, describe, before_each, after_each, expect, expect_error, capture, @assert, @fail, @run_script, @check_script. 테스트 파일은 이것을 직접 가져옵니다 (스크립트 테스트를 참고하세요).

가져오지 않은 패키지의 기능을 사용하면 input is part of KScript.Terminal. Add import KScript.Terminal at the top of the script.와 함께 실행이 멈추고, 편집기가 import 추가를 제안해요. 패키지는 import에서만 지정해요. 문장에는 절대 KScript. 접두사를 쓰지 않아요(input처럼 쓰고 KScript.input처럼 쓰지 않아요). job와 dispatch를 포함해 어떤 것도 자동으로 import되지 않아요(import KScript.Queue). 프로젝트에서는 kscript.json(아래 참고)에 있는 모든 스크립트에 대해 패키지를 import할 수 있어요.

암호학적으로 안전한 무작위 바이트

@random_bytes(count, format: hex)는 운영체제에서 엔트로피를 읽어요. 1부터 65536 사이의 바이트 수를 정수로 주세요. 소문자 16진수는 바이트당 두 글자를 사용해요. base64url 형식은 URL에 안전한 문자를 쓰고 패딩을 생략해요. 두 형식 모두 @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

시드로 만드는 난수

@random_generator(seed)는 같은 시드에 대해 모든 머신과 모든 KScript 버전에서 같은 숫자를 주는 생성기를 만들어요. 그래서 이로 만든 결과를 나중에 다시 만들 수 있어요. 한 사람을 위해 만든 퍼즐이나 테스트 데이터가 그 예예요. 시드는 최소 16바이트의 16진수 텍스트이므로 해시가 좋은 시드가 돼요. ->hmac($secret)는 비밀을 모르는 사람이 이를 알아내지 못하게 해요. 부분 사이의 @char_of(0)는 'ab' + 'c'와 '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()는 0부터 4294967295까지의 정수를, ->float()는 1보다 작은 소수를 줘요. 생성기는 sfc32이며, 처음 16바이트를 빅엔디언 32비트 워드 네 개로 시드하고 먼저 15번 돌려요. 그래서 같은 방식으로 시드된 JavaScript sfc32는 같은 숫자를 내요. 빠르고 고르게 분포하지만, 숫자를 충분히 보는 사람은 나머지를 알아낼 수 있으므로 비밀에는 @random_bytes()를 사용하세요.

문장과 인자의 이름

문장과 인자는 모든 패키지에서 같은 규칙을 따르며, kscript check와 테스트 스위트가 내장 기능을 이 규칙에 맞춰 검사해요:

규칙 예제
무언가를 실행하거나 선언하는 문장은 소문자 snake_case 단어예요. input, table, before_each, expect_error, log_provider
KScript.UI, KScript.Http, KScript.Document에서 창, 라우트 표, 문서를 설명하는 문장은 PascalCase를 사용해요. KScript.Data에서는 Migration와 그 스키마 단계도 PascalCase를 사용해요. Button, Routes, Get, Section, Migration, CreateTable
인자는 snake_case예요. 어떤 이름에도 하이픈이 없어요. max_tokens, must_exist, on_click, new_page
into:는 결과를 받는 변수예요. input(into: name), llm(into: reply), capture(into: out)
to:는 무언가가 가는 곳이에요: 파일, URL, 컨트롤러 등이요. 변수 이름을 지정하지 않아요. Get(path: /, to: @home), Post(path: /notes, to: @notes.add)
path:는 문장이 읽거나 작업하는 파일이에요. import(path: 'lib.kscript'), <include path="_nav.html">, <layout path="_layout.html">
at는 위치예요. 예를 들어 for item at i in $list처럼 쓰여요. menu(into: choice, at: i)
함수는 식에서처럼 @name로 이름을 붙여요. spawn(fn: @job), llm(tools: [@order_status]), Get(to: @people.show)

함수가 아닌 이름 세 종류는 그대로 둬요. 컨트롤러(Resource(to: people)는 스크립트를 가져올 때 쓰는 이름이에요), 미들웨어 목록의 이름([log, throttle:30, my_check], 내장 기능, 그룹, 함수가 하나의 목록을 공유해요), 선언 중인 변수나 타입이 여기에 해당해요. XML에서는 같은 인자가 같은 이름의 속성이 되고, 함수는 @ 없이 써요(<spawn fn="job" />). kscript convert는 이를 추가하거나 제거해요.

페이지에서 on-click 등의 핸들러는 HTML 태그(<button on-click="$count += 1">)에 붙으므로 HTML의 하이픈을 그대로 써요. Button 같은 KScript 자체 요소에서는 인자가 on_click예요.

이 규칙 이전의 이름은 새 이름('to' is now into.)을 알려 주는 오류가 나요. kscript check --fix로 이름을 바꿀 수 있어요. 문장에 값을 대입하는 것($name = input "Name? ")은 아직 언어에 포함되지 않았어요.

터미널 출력

KScript.Terminal은 kscript 명령과 같은 방식으로 출력해서, 스크립트의 출력이 도구의 나머지 부분과 같아 보여요. 색은 터미널에서만 써요. 파이프로 보내거나 파일에 쓰거나 테스트에서는 색 없이 같은 텍스트가 나오고, NO_COLOR, FORCE_COLOR, --ansi, --no-ansi는 kscript 자체와 같이 동작해요.

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

[bracketed] 부분은 굵게 표시돼요. alert(type: error)는 stderr에 써요. 표의 숫자는 오른쪽 정렬돼요. align: ['left', 'right']는 각 열을 설정해요.

단계로 나뉜 작업에는 진행 막대가 붙어요. progress(into: bar, total: n)는 라벨로 텍스트를 붙여 막대를 보여 주고, $bar->advance()는 한 단계씩(또는 ->advance(5)로 다섯 단계씩) 진행시켜요. 터미널에서는 같은 자리에서 다시 그려지고, 파이프나 테스트에서는 작업이 전체에 도달했을 때 한 줄만 출력돼요:

<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)는 응답이 1, 3 같은 여러 선택지를 고를 수 있게 해요. 선택한 항목은 메뉴 순서대로 목록으로 저장돼요(at:는 위치의 목록을 저장해요).

언어 모델: KScript.AI

KScript.AI를 사용하면 스크립트가 Claude에 요청할 수 있어요. API 키는 스크립트에서 가져오지 않고 ANTHROPIC_API_KEY 환경 변수에서 가져와요(또는 ANTHROPIC_AUTH_TOKEN의 토큰이나, ant 명령이 설치된 경우 ant auth login에 저장된 프로필에서 가져와요). ANTHROPIC_BASE_URL는 요청을 프록시 같은 다른 호스트로 보내요. 스크립트는 다른 모델을 요청하거나 KSCRIPT_AI_MODEL에서 모델을 지정하지 않는 한 claude-opus-5-5을 사용해요.

<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 와 @llm(prompt, ...)는 같은 옵션으로 같은 질문을 합니다: system, schema, tools([@order_status] 같은 목록), model 그리고 max_tokens(기본값은 16,000). 한 가지 차이점은 프롬프트가 어디서 오고 답이 어디로 가는지입니다: llm 문은 프롬프트를 텍스트로 받고 답을 to:에 저장하며, @llm()는 프롬프트를 값으로 받아 답을 반환하므로 식 안에 넣을 수 있습니다. @llm()는 옵션을 이름으로 받습니다: @llm($prompt, system: 'Be brief.', max_tokens: 500).
  • 스키마: 각 필드는 필수입니다. 'string', 'number', 'int', 'bool', 'date'는 타입을 지정하고, 'int 1-5'는 범위를 나타내며, 'a|b|c'는 선택지를 나열합니다. 맵은 중첩된 객체이고, ['string']는 목록입니다. 그 밖의 텍스트는 문자열 필드를 설명합니다.
  • 도구는 fn 함수입니다. 도구의 params(id: int와 같은 타입 포함)과 description는 모델에게 도구를 호출하는 방법을 알려줍니다. 도구가 실패하면 모델에게 오류가 전달되고, 모델은 작업을 계속할 수 있습니다.
  • 테스트에서는 Claude 대신 @fake_llm(replies)을 사용합니다. 언어 모델 가짜 처리를 참고하세요.
  • 오류는 AI 타입을 가지므로, try와 catch e를 함께 사용하면 $e.type를 확인하고 누락된 키, 거부, 또는 max_tokens로 인해 잘린 응답을 처리할 수 있어요. Claude의 안전 검사가 요청을 거부하면 API는 먼저 대체 모델로 요청을 다시 시도해요.

스크립트 실행 방식

kscript는 블록의 문장을 처음 실행할 때 각각 컴파일하므로, 반복문이나 여러 번 호출되는 함수는 매번 다시 읽히지 않고 .NET 코드로 실행돼요. 함수 본문이나 반복문 본문 안에서 블록이 선언한 변수는 스코프 대신 번호가 매겨진 슬롯에 보관돼요. 이것이 숫자가 많은 코드(배낭 문제, 격자 탐색, 시뮬레이션)를 몇 배 빠르게 만들어요. 반복문이 있는 본문이나 64번 실행된 본문은 하나의 .NET 메서드로 다시 컴파일되므로, 숫자를 다루는 빡빡한 반복문이 약 두 배 더 빨라져요. 그 메서드 안의 반복문이 숫자와 목록을 다루면(산술, 비교, 목록 항목의 읽기와 설정, 범위에 대한 if, while, for) 변수가 정확히 그런 값이라고 가정하는 두 번째 복사본도 생기며, 이는 여러 배 더 빨라요. 값이 다른 것으로 판명되는 순간, 같은 문장부터 일반 복사본에서 반복문이 이어져요. fn(x) => ...를 ->map()와 같은 메서드에 넘기는 함수도, 콜백이 읽는 각 변수가 콜백을 호출하기 전에 한 번 설정되기만 하면 슬롯을 유지해요. 0..1000000와 같은 범위에 대한 반복문은 목록을 만들지 않고 범위를 세요. 스크립트의 동작은 전혀 바뀌지 않아요. 같은 값, 같은 줄과 열의 같은 오류가 나며, 디버거도 모든 문장을 단계별로 실행해요. 디버그 중인 스크립트는 항상 인터프리터로 실행되기 때문이에요.

이 값들을 비교하기 위한 환경 변수가 몇 가지 있어요. 예를 들어 한 가지에서만 나타나는 버그를 보고할 때 써요. KSCRIPT_INTERPRET=1은 컴파일을 꺼요. KSCRIPT_NO_REGIONS=1는 컴파일하되 모든 변수를 스코프에 둬요. KSCRIPT_NO_TREES=1는 슬롯을 유지하지만 단일 .NET 메서드는 만들지 않아요. KSCRIPT_NO_LOOPS=1는 반복문의 두 번째 복사본 없이 메서드를 만들어요.

이식 가능한 스크립트 작성하기

  • @join_path(base: $dir, ['reports', 'file.txt'])(KScript.IO)로 경로를 만드세요. \나 /를 직접 쓰지 마세요.
  • @known_folder(downloads)(KScript.IO)로 사용자의 폴더를 찾을 수 있어요: home, desktop, documents, downloads, music, pictures, videos, appdata, temp. 각 시스템의 설정을 따르며, 예를 들어 Windows의 다운로드 위치와 Linux의 user-dirs.dirs를 따라요.
  • $os.name는 windows, linux, macos이고, $os.home, $os.temp, $os.separator도 있어요. $env.HOME는 환경 변수를 읽어요.
  • 숫자는 기기의 언어와 상관없이 항상 .을 소수점 구분자로 사용해 해석하고 출력해요.