KScript 문서
KO

언어

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

언어

타입이 지정된 데이터

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 A built-in (string, int, float, number, bool, date, list, map, fn, any, email, password, handle, uuid, regex), an enum, another type, T[] for a list. Rules can follow in brackets: string(min: 1). Without it the field takes any value.
? 이름 뒤에 값은 없거나 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 등)의 값을 바탕으로 필드 값을 계산해요. 값을 직접 읽지 않아요.
/// 줄 위 마우스를 올리거나 자동 완성 목록에 표시됩니다.

The type itself takes options in brackets: type Repo(extra: error) { … }. extra says what happens to keys the type doesn't list: drop (the default), keep or error. path: "data/repo.json" takes the fields from a saved sample of the data: objects become nested types, and keys only some list items have become optional. Lines in the block replace the sampled fields they name. Types can refer to each other in any order and to themselves, and top-level types are exported to scripts that import the file. In a project, give each type its own file (types/repo.kscript, types/owner.kscript) and import the ones it uses: import "owner.kscript" at the top of types/repo.kscript (see One type per file).

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

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

데이터가 타입과 만나는 곳

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

Edit this page on GitHub