타입이 지정된 데이터
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이 아니라 비어 있으며, 모델의 필드는 데이터베이스에서 오므로 실행 시점에 맡겨져요.
strict 타입
strict로 시작하는 파일은 자신의 타입을 지켜야 합니다. 모든 값에는 검사기가 증명할 수 있는 타입이 있어야 하며, 타입 실수는 스크립트의 어떤 부분도 실행되기 전에 멈추게 하는 오류입니다:
<strict />
<fn name="area" params="width: number, height: number" value="$width * $height" />
<let name="total" value="0" /> <!-- a number: the value proves it -->
<let name="names" type="string[]" value="[]" /> <!-- an empty list says what it will hold -->
<for each="size" in="[2, 3]">
<set name="total" op="+=" value="@area($size, 2)" />
</for>
<echo value="$total" />strict
fn area(width: number, height: number) => $width * $height
$total = 0 // a number: the value proves it
$names: string[] = [] // an empty list says what it will hold
for size in [2, 3] {
$total += @area($size, 2)
}
echo $totalstrict 파일에서는:
- 타입 실수는 오류입니다. 잘못된 타입의 값(KS5005), 값에 없는 필드나 메서드(KS5010, KS5003), 타입에 맞지 않는 값(KS5012), null일 수 있는 값을 확인 없이 사용하는 것(KS5018)은 경고가 아니라 오류입니다.
kscript check가 이를 보고하며,kscript run,serve,test는 스크립트를 시작하지 않습니다. 어떤lint.rules설정으로도 끌 수 없습니다. - 매개변수는 타입을 밝히거나(KS6007), 기본값에서 가져옵니다:
fn greet(who = 'world'). lambda의 매개변수는[1, 2]->map(fn(n) => $n * 2)처럼 쓰이는 곳에서 타입을 가져오거나, 밝힙니다:fn(n: number) => $n * 2. - 나머지는 모두 검사기가 증명할 수 있는 타입이 필요합니다(KS5020). 변수는 값에서 타입을 가져오거나(
$n = 0,$repo = Repo(name: 'x')) 밝힙니다($n: int = $args[0]). 검사기는 다음의 타입을 쓰라고 요청합니다: 빈 리스트($names: string[] = []), 항목이 섞인 리스트,null($found: Repo? = null), 서로 다른 타입의 값이 주어지는 변수, JSON처럼 타입 없는 데이터에서 읽은 값, 알아낼 수 없는 함수 결과(fn first(items: list): string), 타입이나 기본값이 없는 필드. any는 값이 정말로 무엇이든 될 수 있을 때 쓸 수 있는 타입입니다:$data: any = $text->convert(from: json). 거기서 읽은 값에는 다시 타입이 필요합니다:$count: int = $data.count.
strict는 파일 맨 위, import를 제외한 모든 것보다 앞에 둡니다. XML에서는 <kscript>의 첫 번째 요소인 <strict />입니다. 프로젝트의 모든 스크립트를 strict로 만들려면 kscript.json에 "strict": true를 설정하세요. import한 strict 파일은 불러올 때 검사되므로, 그것을 import하는 스크립트도 시작되지 않습니다.
데이터가 타입과 만나는 곳
<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=""sorted by { $by }"" />
<fn name="retitle" params="title: Post.title" value=""renamed to { $title }"" />
<fn name="tag" params="tag: Post.tags.item" value=""tagged { $tag }"" />
<fn name="publish" params="post: Post, as: draft|live = 'live'" value=""{ $post.title } is { $as }"" />
<fn name="find" params="id: int|uuid" value=""found { $id }"" />
<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).