You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Как refract пишет код: примеры на пяти языках #605
Способ, которым refract пишет код, определяет, насколько сгенерированный код похож на написанный руками и насколько его легко поменять. Ты просил увидеть это на примерах, а не на словах.
Вопрос
Как refract пишет код:
А - модуль-писатель в стиле Forge: код собирается вызовами вроде w.line() и w.block();
Б - шаблоны Jinja;
В - построитель синтаксического дерева языка.
Что покажу
Одни и те же четыре операции в пяти языках (Python, TypeScript, Go, Java, Rust) по каждому способу:
операция
что в ней сложного
список задач Tracker со страницами
курсор, тип элемента в итераторе
создание страницы Wiki с телом
необязательные поля: Omit не отправляет поле, None отправляет null
загрузка файла в Forms
multipart
экспорт ответов Forms
долгое задание с ожиданием
Для каждой пары «способ × язык» - сгенерированный файл и строки самого генератора. Сравниваю, сколько стоит добавить новый язык и поменять одну деталь, например имя аргумента во всех языках.
Примеры появятся комментариями к этому тикету. Код - в <details>, сверху одна таблица сравнения.
Рекомендую заранее: А. Исследователь 14.10 выбрал его по выборке из 12 генераторов. Против: шаблон Jinja читается глазами как готовый файл, а у писателя в стиле Forge итоговый файл виден только после запуска.
Ответ одной строкой - после примеров: «А», «Б» или «В».
Примеры готовы. Генератор каждого способа работает, и все три пишут байт в байт одинаковый код.
Сравнение
Замерил на двух операциях: список задач Tracker с курсором и создание страницы Wiki, в TypeScript и Go, потом добавил Java. Размер - непустые строки генератора, правки - строки в git diff.
переименовать идентификатор, который генератор пишет сам, options → params в 3 языках
+11 / -11
+12 / -12
+11 / -11
отступ TypeScript 2 → 4, форматтер после генератора
0
0
0
то же, но генератор сам пишет итоговый отступ
0
+22 / -22
0
переносить комментарии на 80-й колонке в 3 языках
+24 / -25, 12 мест
+17 / -23, 16 мест
+8 / -11, 3 места
Общая часть одна на все три способа и в таблицу не входит: чтение каталога, имена и типы каждого языка, 208 строк, с Java 247. Для Java в нее добавилась 61 строка, для переноса комментариев - правило на 16 строк.
Что из этого следует:
вывод не зависит от способа: на всех ветках 0 differing files и до форматтера, и после. Значит, способ можно потом сменить для одного языка и сверить выход с прежним байт в байт
способ В дороже всех, потому что для Python нет готового синтаксического дерева для TypeScript, Go и Java. Узлы и печать пришлось писать на каждый язык, 116-159 строк еще до построения
Б короче всех и дешевле всех добавляет язык. Сгенерированный слой тонкий (метод, тип аргументов, таблица операции), и такой шаблон читается как готовый файл
форматтер после генератора снимает вопрос отступов: gofmt выравнивает Go у всех трех одинаково, Prettier сам переводит вывод шаблона на 4 пробела
правило поперек всего файла, как перенос комментариев, затрагивает столько мест, сколько раз комментарий написан руками. Способ В печатает комментарии в 3 функциях, шаблоны - в 16 местах, писатель - в 12, потому что в Go и Java я писал код писателя без общего doc(). Писатель с doc() с первого дня (у Forge перенос на 80-й колонке встроен) или шаблон с фильтром doc сразу свели бы это к одному месту
сверка байт в байт уже окупилась: при переименовании options я пропустил в А одно место, и разница с Б сразу его показала
Вывод каждого способа проверен: tsc 7.0.2 в строгом режиме без ошибок, go vet и тесты на Go 1.27.4, javac 25 с -Xlint:all -Werror. Демо шлют запросы в тестовый транспорт: курсор переходит на вторую страницу (?scrollId=s1), create({ slug, title }) отправляет только slug и title, а content: null отправляет "content":null.
Одна и та же правка в А, Б и В
Сначала один фрагмент до правки - тип аргументов операции на TypeScript в каждом генераторе.
А, gen/a_writer/ts.py:
def_options(writer: Writer, operation: Operation) ->None:
_doc(writer, f"The arguments of `{operation.operation_id}`: a member left out is not sent, `null` is sent as null.")
withwriter.block(f"export interface {ts.options_name(operation)} {{"):
forargumentinoperation.arguments:
formodelin [argument.type.model] ifargument.type.kind=="model"else []:
writer.use("./models.ts", model)
_doc(writer, argument.doc)
optional=""ifargument.requiredelse"?"writer.line(f"{ts.camel(argument.name)}{optional}: {ts.member_type(argument)};")
Б, gen/b_jinja/templates/ts/module.ts.j2:
/** The arguments of `{{ op.operation_id }}`: a member left out is not sent, `null` is sent as null. */
export interface {{ op | options_name }} {
{%forarginop.arguments%}
/** {{ arg.doc }} */
{{ arg.name | camel }}{{ "" if arg.required else "?" }}: {{ arg | member_type }};
{%endfor%}
}
В, gen/c_ast/ts_build.py строит узел, а gen/c_ast/ts_ast.py его печатает:
def_options(operation: Operation) ->t.Interface:
members=tuple(
t.Property(ts.camel(argument.name), ts.member_type(argument), notargument.required, t.Doc((argument.doc,)))
forargumentinoperation.arguments
)
doc=f"The arguments of `{operation.operation_id}`: a member left out is not sent, `null` is sent as null."returnt.Interface(ts.options_name(operation), t.Doc((doc,)), members)
# ts_ast.pycaseInterface(name, doc, members):
lines= [*_doc(doc, 0), f"export interface {name} {{"]
formemberinmembers:
lines+= [
*_doc(member.doc, 1),
f"{INDENT}{member.name}{'?'ifmember.optionalelse''}: {member.type};",
]
return [*lines, "}"]
Теперь правка: комментарий длиннее 80 колонок переносится по словам, а однострочный /** … */ при этом становится блоком. Ни gofmt, ни Prettier этого не делают, значит, это работа генератора. Правило comment() общее для всех трех, ниже только то, что поменялось в TypeScript.
А - каждое место, где пишется комментарий, вызывает новый метод писателя:
Б - в каждом месте шаблона текст заменяется вызовом фильтра, и отступ приходится передавать руками, потому что шаблон его не знает:
-/** The arguments of `{{ op.operation_id }}`: a member left out is not sent, `null` is sent as null. */+{{ ("The arguments of `" ~ op.operation_id ~ "`: a member left out is not sent, `null` is sent as null.") | comment("", "block") }}
export interface {{ op | options_name }} {
{% for arg in op.arguments %}
- /** {{ arg.doc }} */+{{ arg.doc | comment(" ", "block") }}
{{ arg.name | camel }}{{ "" if arg.required else "?" }}: {{ arg | member_type }};
...
- /**- * {{ op.summary }}- *- * @param options The named arguments.- */+{{ (op.summary ~ "\n\n@param options The named arguments.") | comment(" ", "block") }}
В - меняется одна функция печати, построение не трогается:
def _doc(doc: Doc, depth: int) -> list[str]:
- pad = INDENT * depth- if len(doc.lines) == 1:- return [f"{pad}/** {doc.lines[0]} */"]- return [f"{pad}/**", *(f"{pad} * {line}" if line else f"{pad} *" for line in doc.lines), f"{pad} */"]+ return comment(list(doc.lines), INDENT * depth, "block")
Сгенерированный код: 4 операции в 5 языках
Это то, что читает пользователь SDK. Код один и тот же при любом способе, поэтому каждый язык показан один раз. Источник указан над каждым блоком: kit14, порты 14.10 или этот бенчмарк. В портах 14.10 параметры прокрутки обязательные, потому что импорт kit14 пометил их required. В бенчмарке они необязательные, как в документации Tracker.
Список задач Tracker со страницами
tracker.issues.search_scroll: курсор приходит в заголовке X-Scroll-Id и уходит в scrollId, элементы итератора типизированы (Pager<Issue>, iter.Seq2[Issue, error], Paged<Issue>).
@overloaddefsearch_scroll(
self,
body: IssueSearch,
expand: str|None,
scroll_type: str|None,
per_scroll: int|None,
scroll_ttl_millis: int|None,
) ->Pager[Issue]: ...
@overloaddefsearch_scroll(
self,
*,
expand: str|None,
scroll_type: str|None,
per_scroll: int|None,
scroll_ttl_millis: int|None,
query: str|None= ...,
filter: dict[str, Any] |None= ...,
) ->Pager[Issue]: ...
defsearch_scroll(
self,
body: IssueSearch|Omit=OMIT,
expand: str|None=REQUIRED,
scroll_type: str|None=REQUIRED,
per_scroll: int|None=REQUIRED,
scroll_ttl_millis: int|None=REQUIRED,
**fields: Any,
) ->Pager[Issue]:
"""``POST /issues/_search`` in scroll mode: no 10 000 cap, each page named by the last reply. Args: body: Not documented in ycli under this name. expand: Not documented in ycli under this name. scroll_type: Not documented in ycli under this name. per_scroll: Not documented in ycli under this name. scroll_ttl_millis: Not documented in ycli under this name. """returnself._service.listing(
_ops(),
"tracker.issues.search_scroll",
{
"body": gather("tracker.issues.search_scroll", "body", body, IssueSearch, fields, required=True),
"expand": expand,
"scroll_type": scroll_type,
"per_scroll": per_scroll,
"scroll_ttl_millis": scroll_ttl_millis,
},
Issue,
)
// Generated by refract from tracker.openapi.json. Do not edit.importtype{Core,Operation,Pager}from"../core.ts";importtype{Issue}from"./models.ts";/** The arguments of `tracker.issues.search_scroll`: a member left out is not sent, `null` is sent as null. */exportinterfaceIssuesSearchScrollOptions{/** A query-language string. */query?: string|null;/** Field name to the value the issues must have. */filter?: {[key: string]: unknown}|null;/** The extra blocks to include: `transitions`, `attachments`, `comments`. */expand?: string;/** `sorted` keeps the request's order, `unsorted` drops it. */scrollType?: string;/** Issues per reply: 100 by default, at most 1000. */perScroll?: number;/** How long the scroll stays open, in milliseconds: 60000 by default. */scrollTtlMillis?: number;}constISSUES_SEARCH_SCROLL: Operation={name: "tracker.issues.search_scroll",method: "POST",path: "/issues/_search",query: ["expand","scrollType","perScroll","scrollTTLMillis"],body: ["query","filter"],paging: {cursor: "X-Scroll-Id",into: "scrollId",cap: 1000},};/** The `issues` operations of tracker. */exportclassIssues{readonly #core: Core;constructor(core: Core){this.#core =core;}/** * `POST /issues/_search` in scroll mode: no 10 000 cap, each page named by the last reply. * * @param options The named arguments. */searchScroll(options: IssuesSearchScrollOptions={}): Pager<Issue>{returnthis.#core.pager<Issue>(ISSUES_SEARCH_SCROLL,{query: options.query,filter: options.filter,expand: options.expand,scrollType: options.scrollType,perScroll: options.perScroll,scrollTTLMillis: options.scrollTtlMillis,});}}
// Code generated by refract from tracker.openapi.json. DO NOT EDIT.package tracker
import (
"context""iter""example.com/ycli/core"
)
// IssuesSearchScrollOptions are the arguments of IssuesService.SearchScroll: a zero core.Opt is not sent, core.Null sends null.typeIssuesSearchScrollOptionsstruct {
// A query-language string.Query core.Opt[string]
// Field name to the value the issues must have.Filter core.Opt[map[string]any]
// The extra blocks to include: `transitions`, `attachments`, `comments`.Expand core.Opt[string]
// `sorted` keeps the request's order, `unsorted` drops it.ScrollType core.Opt[string]
// Issues per reply: 100 by default, at most 1000.PerScroll core.Opt[int64]
// How long the scroll stays open, in milliseconds: 60000 by default.ScrollTTLMillis core.Opt[int64]
}
varopIssuesSearchScroll= core.Operation{
Name: "tracker.issues.search_scroll",
Method: "POST",
Path: "/issues/_search",
Query: []string{"expand", "scrollType", "perScroll", "scrollTTLMillis"},
Body: []string{"query", "filter"},
Paging: &core.Paging{Cursor: "X-Scroll-Id", Into: "scrollId", Cap: 1000},
}
// IssuesService holds the `issues` operations of tracker.typeIssuesServicestruct {
client*core.Client
}
// SearchScroll walks every item: `POST /issues/_search` in scroll mode: no 10 000 cap, each page named by the last reply.func (s*IssuesService) SearchScroll(ctx context.Context, optionsIssuesSearchScrollOptions) iter.Seq2[Issue, error] {
returncore.Items[Issue](ctx, s.client, &opIssuesSearchScroll, core.Args{
"query": options.Query,
"filter": options.Filter,
"expand": options.Expand,
"scrollType": options.ScrollType,
"perScroll": options.PerScroll,
"scrollTTLMillis": options.ScrollTTLMillis,
})
}
/** ``POST /issues/_search`` in scroll mode: no 10 000 cap, each page named by the last reply. The {@code IssueSearch} built by the lambda from its empty value (C-47). */publicycli.core.client.Page<Issue> searchScroll(java.util.function.UnaryOperator<IssueSearch> body, Stringexpand, StringscrollType, LongperScroll, LongscrollTtlMillis, Longlimit, Stringnext) {
returnsearchScroll(body.apply(IssueSearch.empty()), expand, scrollType, perScroll, scrollTtlMillis, limit, next);
}
/** ``POST /issues/_search`` in scroll mode: no 10 000 cap, each page named by the last reply. */publicycli.core.client.Page<Issue> searchScroll(IssueSearchbody, Stringexpand, StringscrollType, LongperScroll, LongscrollTtlMillis, Longlimit, Stringnext) {
java.util.Map<String, Object> args = newjava.util.LinkedHashMap<>();
args.put("body", Conv.request(body));
args.put("expand", Conv.request(expand));
args.put("scroll_type", Conv.request(scrollType));
args.put("per_scroll", Conv.request(perScroll));
args.put("scroll_ttl_millis", Conv.request(scrollTtlMillis));
booleandefaults = true; // read as a reply: a union member without its tag is a reply's (C-17)returncore.list("tracker.issues.search_scroll", args, limit, next).map(w -> Issue.read(w, defaults));
}
/// `POST /issues/_search` in scroll mode: no 10 000 cap, each page named by the last reply.////// `body`: Not documented in ycli under this name.////// `expand`: Not documented in ycli under this name.////// `scroll_type`: Not documented in ycli under this name.////// `per_scroll`: Not documented in ycli under this name.////// `scroll_ttl_millis`: Not documented in ycli under this name.////// Walks every item, a page at a time: an `Iterator` of `Result<Issue>`.pubfnsearch_scroll(&self,body:&IssueSearch,expand:&str,scroll_type:&str,per_scroll:i64,scroll_ttl_millis:i64,) -> Paged<'c,Issue>{letmut args = Map::new();
ykit::client::typed::put(&mut args,"body", body);
ykit::client::typed::put(&mut args,"expand", expand);
ykit::client::typed::put(&mut args,"scroll_type", scroll_type);
ykit::client::typed::put(&mut args,"per_scroll",&per_scroll);
ykit::client::typed::put(&mut args,"scroll_ttl_millis",&scroll_ttl_millis);Paged::new(self.core,"tracker.issues.search_scroll",&args)}
Создание страницы Wiki с телом
Пропущенный аргумент не отправляется, а None или null уходит как null: Python - OMIT и None, TypeScript - необязательное поле и null, Go - нулевой core.Opt и core.Null, Java - Opt.unset() и content(null), Rust - None и список null_fields.
classPageCreate(BaseModel):
"""Typed request body for ``POST /pages``: a new page at ``slug``. Examples: >>> PageCreate(slug="eng/new", title="New page", content="# New").slug 'eng/new'"""model_config=ConfigDict(validate_by_name=True, validate_by_alias=True, serialize_by_alias=True, extra="ignore")
slug: str=Field(..., description="Address of the page, e.g. ``data/x``.")
title: str=Field(..., description="Title of the page.")
content: str|None=Field(None, description="Body of the page in YFM markdown.")
access_policy: PageAccessPolicyUpdate|None=Field(None, description="Who may open the page.")
# ...@overloaddefcreate(
self, body: PageCreate, *, query_fields: str|None|Omit=OMIT, is_silent: bool|None|Omit=OMIT
) ->PageDetails: ...
@overloaddefcreate(
self,
*,
query_fields: str|None|Omit=OMIT,
is_silent: bool|None|Omit=OMIT,
slug: str,
title: str,
content: str|None= ...,
access_policy: PageAccessPolicyUpdate|None= ...,
) ->PageDetails: ...
defcreate(
self,
body: PageCreate|Omit=OMIT,
*,
query_fields: str|None|Omit=OMIT,
is_silent: bool|None|Omit=OMIT,
**fields: Any,
) ->PageDetails:
"""``POST /pages`` — create. ``body`` carries ``content``/``title``/``slug``. Args: body: The new page: ``content``, ``title`` and ``slug``. query_fields: The comma-separated blocks to include in the reply. is_silent: Do not notify the page's subscribers. """returnself._service.value(
_ops(),
"wiki.pages.create",
{
"body": gather("wiki.pages.create", "body", body, PageCreate, fields, required=True),
"query_fields": query_fields,
"is_silent": is_silent,
},
PageDetails,
)
TypeScript - бенчмарк
источник: examples/bench-output/ts/wiki/pages.ts
// Generated by refract from wiki.openapi.json. Do not edit.importtype{Core,Operation}from"../core.ts";importtype{PageAccessPolicyUpdate,PageDetails}from"./models.ts";/** The arguments of `wiki.pages.create`: a member left out is not sent, `null` is sent as null. */exportinterfacePagesCreateOptions{/** Address of the page, e.g. `data/x`. */slug: string;/** Title of the page. */title: string;/** Body of the page in YFM markdown. */content?: string|null;/** Who may open the page. */accessPolicy?: PageAccessPolicyUpdate|null;/** The comma-separated blocks to include in the reply. */queryFields?: string;/** Do not notify the page's subscribers. */isSilent?: boolean;}constPAGES_CREATE: Operation={name: "wiki.pages.create",method: "POST",path: "/pages",query: ["fields","is_silent"],body: ["slug","title","content","access_policy"],};/** The `pages` operations of wiki. */exportclassPages{readonly #core: Core;constructor(core: Core){this.#core =core;}/** * `POST /pages`: create a page at `slug`. * * @param options The named arguments. */create(options: PagesCreateOptions): Promise<PageDetails>{returnthis.#core.value<PageDetails>(PAGES_CREATE,{slug: options.slug,title: options.title,content: options.content,access_policy: options.accessPolicy,fields: options.queryFields,is_silent: options.isSilent,});}}
Go - бенчмарк
источник: examples/bench-output/go/wiki/pages.go
// Code generated by refract from wiki.openapi.json. DO NOT EDIT.package wiki
import (
"context""example.com/ycli/core"
)
// PagesCreateOptions are the arguments of PagesService.Create: a zero core.Opt is not sent, core.Null sends null.typePagesCreateOptionsstruct {
// Address of the page, e.g. `data/x`.Slugstring// Title of the page.Titlestring// Body of the page in YFM markdown.Content core.Opt[string]
// Who may open the page.AccessPolicy core.Opt[PageAccessPolicyUpdate]
// The comma-separated blocks to include in the reply.QueryFields core.Opt[string]
// Do not notify the page's subscribers.IsSilent core.Opt[bool]
}
varopPagesCreate= core.Operation{
Name: "wiki.pages.create",
Method: "POST",
Path: "/pages",
Query: []string{"fields", "is_silent"},
Body: []string{"slug", "title", "content", "access_policy"},
}
// PagesService holds the `pages` operations of wiki.typePagesServicestruct {
client*core.Client
}
// Create: `POST /pages`: create a page at `slug`.func (s*PagesService) Create(ctx context.Context, optionsPagesCreateOptions) (*PageDetails, error) {
returncore.Value[PageDetails](ctx, s.client, &opPagesCreate, core.Args{
"slug": options.Slug,
"title": options.Title,
"content": options.Content,
"access_policy": options.AccessPolicy,
"fields": options.QueryFields,
"is_silent": options.IsSilent,
})
}
// Generated by refract from wiki.openapi.json. Do not edit.packageycli.wiki;
importjava.util.function.UnaryOperator;
importycli.core.Args;
importycli.core.Core;
importycli.core.Operation;
importycli.core.Opt;
/** The {@code pages} operations of wiki. */publicfinalclassPages {
privatestaticfinalOperationPAGES_CREATE = Operation.of("wiki.pages.create", "POST", "/pages")
.query("fields", "is_silent")
.body("slug", "title", "content", "access_policy");
privatefinalCorecore;
publicPages(Corecore) {
this.core = core;
}
/** The arguments of {@code wiki.pages.create}: an unset member is not sent, {@code null} is sent as null. */publicrecordCreateOptions(
Stringslug,
Stringtitle,
Opt<String> content,
Opt<PageAccessPolicyUpdate> accessPolicy,
Opt<String> queryFields,
Opt<Boolean> isSilent) {
/** The required members; every other one is unset. */publicstaticCreateOptionsof(Stringslug, Stringtitle) {
returnnewCreateOptions(slug, title, Opt.unset(), Opt.unset(), Opt.unset(), Opt.unset());
}
/** Body of the page in YFM markdown. */publicCreateOptionscontent(Stringvalue) {
returnnewCreateOptions(slug, title, Opt.of(value), accessPolicy, queryFields, isSilent);
}
/** Who may open the page. */publicCreateOptionsaccessPolicy(PageAccessPolicyUpdatevalue) {
returnnewCreateOptions(slug, title, content, Opt.of(value), queryFields, isSilent);
}
/** The comma-separated blocks to include in the reply. */publicCreateOptionsqueryFields(Stringvalue) {
returnnewCreateOptions(slug, title, content, accessPolicy, Opt.of(value), isSilent);
}
/** Do not notify the page's subscribers. */publicCreateOptionsisSilent(Booleanvalue) {
returnnewCreateOptions(slug, title, content, accessPolicy, queryFields, Opt.of(value));
}
}
/** * `POST /pages`: create a page at `slug`. * * @param options The named arguments. */publicPageDetailscreate(CreateOptionsoptions) {
returncore.value(PageDetails.class, PAGES_CREATE, Args.of()
.put("slug", options.slug())
.put("title", options.title())
.put("content", options.content())
.put("access_policy", options.accessPolicy())
.put("fields", options.queryFields())
.put("is_silent", options.isSilent()));
}
/** {@link #create(CreateOptions)} with the unset members set by {@code options}. */publicPageDetailscreate(Stringslug, Stringtitle, UnaryOperator<CreateOptions> options) {
returncreate(options.apply(CreateOptions.of(slug, title)));
}
}
/// Typed request body for `POST /pages`: a new page at `slug`.#[derive(Clone,Debug,Default,PartialEq)]pubstructPageCreate{/// Address of the page, e.g. `data/x`.pubslug:String,/// Title of the page.pubtitle:String,/// Body of the page in YFM markdown.pubcontent:Option<String>,/// Who may open the page.pubaccess_policy:Option<PageAccessPolicyUpdate>,/// Members sent as null, which clears them (C-18 v1.3); a `None` field is left out of a request.pubnull_fields:Vec<String>,}// .../// The optional arguments of `wiki.pages.create`.#[derive(Clone,Debug,Default,PartialEq)]pubstructPagesCreateOptions{/// The comma-separated blocks to include in the reply.pubfields:Option<String>,/// Do not notify the page's subscribers.pubis_silent:Option<bool>,// .../// `POST /pages` — create. `body` carries `content`/`title`/`slug`.////// `body`: The new page: `content`, `title` and `slug`.////// # Errors////// The call's failure, its identity of C-12.pub fn create(&self,body:&PageCreate,options:PagesCreateOptions) -> Result<PageDetails>{letmut args = Map::new();
ykit::client::typed::put(&mut args,"body", body);
ykit::client::typed::put(&mut args,"fields",&options.fields);
ykit::client::typed::put(&mut args,"is_silent",&options.is_silent);
ykit::client::typed::value(self.core,"wiki.pages.create",&args)}
Загрузка файла в Forms
Multipart - факт каталога (multipart/form-data и x-ycli-part), а не работа генератора: метод везде один и тот же, upload(survey_id, filename, data), байты разбирает ядро.
/** The named arguments of `forms.files.upload`. */exportinterfaceFilesUploadOptions{/** The file's name. */filename: string;/** The file's raw bytes. */data: Uint8Array;}// .../** * Upload a file for form filling (multipart field `file`) → `FileOut`. * * @param surveyId The form's id. * @param options The named arguments. */asyncupload(surveyId: string,options: FilesUploadOptions): Promise<m.FileOut>{returnthis.#core.value<m.FileOut>("forms.files.upload",{survey_id: surveyId, ...options});}
/** Upload a file for form filling (multipart field ``file``) → :class:`FileOut`. */publicFileOutupload(StringsurveyId, Stringfilename, ycli.core.value.Bytesdata) {
java.util.Map<String, Object> args = newjava.util.LinkedHashMap<>();
args.put("survey_id", Conv.request(surveyId));
args.put("filename", Conv.request(filename));
args.put("data", Conv.request(data));
booleandefaults = true; // read as a reply: a union member without its tag is a reply's (C-17)returnFileOut.read(core.call("forms.files.upload", args), defaults);
}
/// Upload a file for form filling (multipart field `file`) → `FileOut`.////// `survey_id`: The form's id.////// `filename`: The file's name.////// `data`: The file's raw bytes.////// # Errors////// The call's failure, its identity of C-12.pubfnupload(&self,survey_id:&str,filename:&str,data:&[u8]) -> Result<FileOut>{letmut args = Map::new();
ykit::client::typed::put(&mut args,"survey_id", survey_id);
ykit::client::typed::put(&mut args,"filename", filename);
ykit::client::typed::put_bytes(&mut args,"data", data);
ykit::client::typed::value(self.core,"forms.files.upload",&args)}
Экспорт ответов Forms
Ожидание не генерируется ни в одном порту. Генерируются три вызова, а export_and_wait написан руками на поллере ядра по расписанию из таблицы (0,5 с, дальше ×2, потолок 60 с) - это решение C19. В Python kit14 такого сценария для Forms нет, поэтому там только три вызова.
/** * `POST /surveys/{id}/answers/export` — start an export → `202` with its operation. * * @param surveyId The form's id. * @param [options] The named arguments. */asyncexport(surveyId: string,options: AnswersExportOptions={}): Promise<m.OperationResult>{returnthis.#core.value<m.OperationResult>("forms.answers.export",{survey_id: surveyId, ...options});}// ...// The export flow of Forms in its typed calls: start, poll on the catalogue's schedule, download (C-14). The schedule,// the deadline and the flow's failures are the generic poller's (`src/polling.ts`); only the argument mapping is here.import{coreOf}from"../src/client.ts";import{typeAt,notExecutable}from"../src/failure.ts";import{waitFor}from"../src/polling.ts";importtype{FormsClient}from"../sdk/forms/client.ts";importtype*asmfrom"../sdk/forms/models.ts";constFLOW="forms.answers.export_wait";exportinterfaceExportWait{/** How long the export may take in all; unset has no deadline (C-06): the caller gives one. */maxWaitSeconds?: number;}/** How a waited export ended: the file when it succeeded, the operation alone when it did not. */exportinterfaceExportResult{operation: m.OperationResult;file: Uint8Array|null;}/** Start an export, ask for its state on the catalogue's schedule cut to the deadline, download the file once ready. * The flow's calls count against one `ceilingRequests` (rule 24). */exportasyncfunctionexportAndWait(client: FormsClient,surveyId: string,body: m.AnswerExport,wait: ExportWait={}): Promise<ExportResult>{constcore=coreOf(client);constpoll=core.tables.flows?.[FLOW]?.poll;if(poll===undefined)thrownotExecutable({operation: "forms.answers.export",method: null,url: null,status: null});constwhere=(step: "start"|"status",id: unknown): At=>{const[operation,args]=step==="start" ? [poll.start,{survey_id: surveyId, body }] : [poll.status,{survey_id: surveyId,task_id: id}];constplanned=core.plan(operation,args)as{requests?: {method?: string;url?: string}[]};constsent=planned.requests?.[0];return{operation: "forms.answers.export",method: sent?.method??null,url: sent?.url??null,status: null};};constended=awaitwaitFor({flow: FLOW, poll,clock: core.clock, ...(wait.maxWaitSeconds===undefined ? {} : {maxWaitSeconds: wait.maxWaitSeconds}), where,start: ()=>client.answers.export(surveyId,body),status: (id)=>client.answers.exportResultsGet(surveyId,{task_id: String(id)}),result: (id)=>client.answers.exportDownload(surveyId,{task_id: String(id)}),});return{operation: ended.state,file: ended.result};}
// Export: `POST /surveys/{id}/answers/export` — start an export → `202` with its operation.//// surveyID: The form's id.//// body: The `AnswerExport`: format, destination and filters.func (s*AnswersService) Export(ctx context.Context, surveyIDstring, body*AnswerExport) (*OperationResult, error) {
args:=value.NewObject()
client.Put(args, "survey_id", surveyID)
client.Put(args, "body", body)
returnclient.Value[*OperationResult](ctx, s.client, "forms.answers.export", args)
}
// ...// ExportWaitOptions bound the wait for an export. The zero value has no deadline (C-06): the caller gives one.typeExportWaitOptionsstruct {
MaxWait time.Duration// how long the export may take in all; 0 is no bound
}
// ExportResult is how a waited export ended: the file when it succeeded, the operation alone when it did not.typeExportResultstruct {
Operation*OperationResultFile []byte
}
constexportFlow="forms.answers.export_wait"// ExportAndWait starts an export, asks for its state on the table's schedule (`flows["forms.answers.export_wait"]// .poll`, C-14), and downloads the file once it is ready. Hand-written: the table has the three operations and the// flow's face; the poll loop is internal/polling's.func (s*AnswersService) ExportAndWait(ctx context.Context, surveyIDstring, body*AnswerExport, opts*ExportWaitOptions) (*ExportResult, error) {
flow:=s.client.Table.Flows[exportFlow]
ifflow==nil||flow.Poll==nil {
returnnil, failure.Document(failure.Where{Operation: "forms.answers.export"}, "flow")
}
ctx=client.WithBudget(ctx) // rule 24: the flow's requests count against one ceilingstarted, err:=s.Export(ctx, surveyID, body)
iferr!=nil {
returnnil, err
}
ifstarted==nil||started.ID==nil { // C-14: no reply decided, the flow judged a value the start acceptedreturnnil, failure.FlowNothingAt(s.where("forms.answers.export", surveyID, body, ""), exportFlow)
}
varmaxWait time.Durationifopts!=nil {
maxWait=opts.MaxWait
}
varstate*OperationResultpoll:=func(ctx context.Context) (string, error) {
ifstate, err=s.ExportResultsGet(ctx, surveyID, *started.ID); err!=nil {
return"", err
}
ifstate==nil||state.Status==nil { // D21: nothing at status_at, the flow cannot judge the pollreturn"", failure.FlowNothingAt(s.where("forms.answers.export_results_get", surveyID, nil, *started.ID), exportFlow)
}
return*state.Status, nil
}
on:=s.client.Clockifon==nil {
on= clock.Real{}
}
status, err:=polling.Until(ctx, on, flow.Poll, maxWait, poll)
switch {
caseerrors.Is(err, polling.ErrDeadline):
where:=s.where("forms.answers.export_results_get", surveyID, nil, *started.ID)
returnnil, failure.FlowWithin(where, exportFlow, maxWait.Seconds())
caseerrors.Is(err, polling.ErrInterrupted):
returnnil, failure.Interrupted(failure.Where{Operation: "forms.answers.export"})
caseerr!=nil:
returnnil, errcasestatus!=flow.Poll.Ready:
return&ExportResult{Operation: state}, nil
}
file, err:=s.ExportDownload(ctx, surveyID, *started.ID)
return&ExportResult{Operation: state, File: file}, err
}
/** ``POST /surveys/{id}/answers/export`` — start an export → ``202`` with its operation. The {@code AnswerExport} built by the lambda from its empty value (C-47). */publicOperationResultexport(StringsurveyId, java.util.function.UnaryOperator<AnswerExport> body) {
returnexport(surveyId, body.apply(AnswerExport.empty()));
}
/** ``POST /surveys/{id}/answers/export`` — start an export → ``202`` with its operation. */publicOperationResultexport(StringsurveyId, AnswerExportbody) {
java.util.Map<String, Object> args = newjava.util.LinkedHashMap<>();
args.put("survey_id", Conv.request(surveyId));
args.put("body", Conv.request(body));
booleandefaults = true; // read as a reply: a union member without its tag is a reply's (C-17)returnOperationResult.read(core.call("forms.answers.export", args), defaults);
}
// .../** * {@code forms answers export --wait}, written by hand over the generated client: start the export, poll its status * on the table's schedule ({@code flows["forms.answers.export_wait"].poll}, C-14), then download the file (the * {@code ready} status) or answer the status (another terminal one). A start or a poll without what the flow reads is * {@code reply-shape}, reason {@code nothing-at}; a poll past the deadline is {@code timed-out}, reason * {@code within}; both name the flow and have no status (C-12). Every request counts against one ceiling (rule 24). * * <p>{@code ExportFlow.run(forms, clock, 2.0, {"survey_id": "s", "body": {}})} -> the file's bytes, or the last status. */publicfinalclassExportFlow {
staticfinalStringFLOW = "forms.answers.export_wait";
privatestaticfinalStringSTART = "forms.answers.export";
privatestaticfinalStringSTATUS = "forms.answers.export_results_get";
privateExportFlow() {
}
publicstaticObjectrun(FormsClientforms, Clockclock, DoubledeadlineSeconds, Map<String, Object> arguments) {
returnClient.sharedBudget(() -> poll(forms, clock, deadlineSeconds, arguments));
}
privatestaticObjectpoll(FormsClientforms, Clockclock, DoubledeadlineSeconds, Map<String, Object> arguments) {
Flowflow = FormsClient.table().flows().get(FLOW);
if (flow == null || flow.poll() == null) throwFailure.document(START, "flow", "the table states no poll schedule (C-14)");
Pollschedule = flow.poll();
StringsurveyId = (String) arguments.get("survey_id");
Objectbody = arguments.getOrDefault("body", Map.of());
OperationResultstarted = forms.answers().export(surveyId, AnswerExport.of(body));
if (started.id() == null) {
Wherestart = where(forms, START, Map.of("survey_id", surveyId, "body", body), "the export started without an operation id");
throwFailure.flowNothingAt(start, FLOW);
}
Map<String, Object> polled = Map.of("survey_id", surveyId, "task_id", started.id());
Poller.Ended<OperationResult> ended;
try {
ended = Poller.poll(schedule, clock, deadlineSeconds, () -> forms.answers().exportResultsGet(surveyId, started.id()),
OperationResult::status);
} catch (InterruptedExceptione) {
Thread.currentThread().interrupt();
throwFailure.interrupted(where(forms, STATUS, polled, "interrupted")).because(e);
}
returnswitch (ended) {
casePoller.Ended.NoStatus<OperationResult> _ -> // D21: nothing at status_at: the flow cannot judge the pollthrowFailure.flowNothingAt(where(forms, STATUS, polled, "the poll reply has no status"), FLOW);
casePoller.Ended.PastDeadline<OperationResult> _ -> throwFailure.flowWithin(
where(forms, STATUS, polled, "the export is not ready after " + deadlineSeconds + " s"), FLOW, deadlineSeconds);
casePoller.Ended.Terminal<OperationResult> done -> schedule.ready().equals(done.reply().status())
? forms.answers().exportDownload(surveyId, started.id()) : done.reply().toJson();
/// `POST /surveys/{id}/answers/export` — start an export → `202` with its operation.////// `survey_id`: The form's id.////// `body`: The `AnswerExport`: format, destination and filters.////// # Errors////// The call's failure, its identity of C-12.pubfnexport(&self,survey_id:&str,body:&AnswerExport) -> Result<OperationResult>{letmut args = Map::new();
ykit::client::typed::put(&mut args,"survey_id", survey_id);
ykit::client::typed::put(&mut args,"body", body);
ykit::client::typed::value(self.core,"forms.answers.export",&args)}// ...//! `answers export --wait`, written by hand: the table has the three operations and the flow's face with its poll//! schedule (`flows["forms.answers.export_wait"].poll`, C-14); the poll loop and the flow's failures are the kit's//! poller (`ykit::polling`).use std::time::Duration;use ykit::client::model::Json;use ykit::polling::Job;use ykit::{Map,Result};usecrate::generated::AnswersApi;usecrate::models::{AnswerExport,OperationResult};/// The flow's name in the table.constFLOW:&str = "forms.answers.export_wait";/// Bounds of the wait for an export. `Default` has no deadline (C-06): the caller gives one.#[derive(Clone,Debug,Default)]pubstructExportWait{/// How long the export may take in all; `None` is no bound.pubmax_wait:Option<Duration>,}/// How a waited export ended: the file when it succeeded, the operation alone when it did not.#[derive(Clone,Debug,PartialEq)]pubenumExportEnd{/// The exported file.File(Vec<u8>),/// The export ended in a status other than ready.Failed(OperationResult),}implAnswersApi<'_>{/// Starts an export, asks for its state on the table's schedule, and downloads the file once it is ready: waits/// of `min(cap, first × factor^n)`, the last one cut to the deadline, one more poll at the deadline, then/// `timed-out`.////// # Errors////// A step's failure; `reply-shape` / `nothing-at` for a start without an id or a poll without a status (C-14,/// D21); `timed-out` / `within` past `wait.max_wait`.pubfnexport_and_wait(&self,survey_id:&str,body:&AnswerExport,wait:&ExportWait,) -> Result<ExportEnd>{let scoped = self.core.budgeted();// rule 24: the flow's requests count against one ceilinglet job = Job{client:&scoped,flow:FLOW,face:"forms.answers.export",};let schedule = job.schedule()?;let api = AnswersApi{core:&scoped };let started = api.export(survey_id, body)?;letSome(task_id) = started.idelse{let args = Map::new().with("survey_id", survey_id).with("body", body.to_request());returnErr(job.nothing_at("forms.answers.export",&args));};let poll_args = Map::new().with("survey_id", survey_id).with("task_id", task_id.as_str());letmut state = None;let status = job.until(&schedule,
wait.max_wait,("forms.answers.export_results_get",&poll_args),
|| {let got = api.export_results_get(survey_id,&task_id)?;let status = got.status.clone();
state = Some(got);Ok(status)},)?;if status != schedule.ready{returnOk(ExportEnd::Failed(state.unwrap_or_default()));}
api.export_download(survey_id,&task_id).map(ExportEnd::File)}}
Рекомендация
Б: шаблон Jinja держит скелет файла, а все, где есть логика (имена, типы, литералы таблиц, комментарии, импорты), - функции на Python, которые шаблон вызывает как фильтры. После генератора - форматтер языка, на выходе - сверка байт в байт с прошлой генерацией. Так уже был устроен прототип refract 15.10: 9 шаблонов по 9-27 строк, писатель литералов на 123 строки и заготовки методов на Python.
Это меняет мою рекомендацию из тикета, там был А по выборке 14.10. На этом бенчмарке А ни по одному замеру не лучше Б, а Б короче и дешевле добавляет язык. Довод из тикета в пользу Б подтвердился: шаблон выше читается как готовый файл, у писателя и дерева файл виден только после запуска.
Против: бенчмарк маленький - 2 операции из 465 и 3 языка, без объединений, вложенных моделей и импортов с конфликтами имен. Как раз там у шаблонов растет логика. Kiota отказался от шаблонов из-за дублирования между языками, логики внутри шаблонов и расхождения их поведения, а писатель решает импорты и конфликты имен один раз, как в Forge и protoc-gen-go. Уже здесь импорты в шаблоне перечислены руками (Pager - только если есть операция со страницами), а писатель собирает их сам. Если логика в шаблоне начнет расти, эта часть уходит в функцию на Python, а сверка байт в байт показывает, что выход не поменялся.
Ответ одной строкой: «А», «Б» или «В».
Не проверено
объединения с дискриминатором, вложенные модели, перечисления и генерация самих моделей: в бенчмарке модели - заглушки
как растет логика шаблонов на 465 операциях, скорость генерации
генераторы Python и Rust: их примеры взяты из kit14 и порта Rust
форматтер Java: вывод Java - раскладка самого генератора, проверен он только javac
core.Opt[T] в Go - мой выбор. Порт Go делал указатели и список NullFields, какой вариант тебе понятнее, не знаю
ядра в check/ - заглушки для бенчмарка, а не рукописные ядра языков
мне нравится больше всего вариант Б и мне кажется нужно именно в него и целить, потому что тут мы оперируем Сущностями и Шаблонами и Логикой (что происходит с Сущностями через Шаблон). но не хватает бенчмарка и замеров разных АПИшек, сложных и несложных операций, стандартного и нестандартного флоу, еще то что попадает в частные случаи Сущностей и Шаблонов и Логики а что нет
Activity
bim-ba commentedon Nov 18, 2026
Примеры готовы. Генератор каждого способа работает, и все три пишут байт в байт одинаковый код.
Сравнение
Замерил на двух операциях: список задач Tracker с курсором и создание страницы Wiki, в TypeScript и Go, потом добавил Java. Размер - непустые строки генератора, правки - строки в
git diff.query_fields→reply_fieldsoptions→paramsв 3 языкахОбщая часть одна на все три способа и в таблицу не входит: чтение каталога, имена и типы каждого языка, 208 строк, с Java 247. Для Java в нее добавилась 61 строка, для переноса комментариев - правило на 16 строк.
Что из этого следует:
0 differing filesи до форматтера, и после. Значит, способ можно потом сменить для одного языка и сверить выход с прежним байт в байтdoc(). Писатель сdoc()с первого дня (у Forge перенос на 80-й колонке встроен) или шаблон с фильтромdocсразу свели бы это к одному местуoptionsя пропустил в А одно место, и разница с Б сразу его показалаВывод каждого способа проверен:
tsc7.0.2 в строгом режиме без ошибок,go vetи тесты на Go 1.27.4,javac25 с-Xlint:all -Werror. Демо шлют запросы в тестовый транспорт: курсор переходит на вторую страницу (?scrollId=s1),create({ slug, title })отправляет толькоslugиtitle, аcontent: nullотправляет"content":null.Одна и та же правка в А, Б и В
Сначала один фрагмент до правки - тип аргументов операции на TypeScript в каждом генераторе.
А,
gen/a_writer/ts.py:Б,
gen/b_jinja/templates/ts/module.ts.j2:/** The arguments of `{{ op.operation_id }}`: a member left out is not sent, `null` is sent as null. */ export interface {{ op | options_name }} { {% for arg in op.arguments %} /** {{ arg.doc }} */ {{ arg.name | camel }}{{ "" if arg.required else "?" }}: {{ arg | member_type }}; {% endfor %} }В,
gen/c_ast/ts_build.pyстроит узел, аgen/c_ast/ts_ast.pyего печатает:Теперь правка: комментарий длиннее 80 колонок переносится по словам, а однострочный
/** … */при этом становится блоком. Ни gofmt, ни Prettier этого не делают, значит, это работа генератора. Правилоcomment()общее для всех трех, ниже только то, что поменялось в TypeScript.А - каждое место, где пишется комментарий, вызывает новый метод писателя:
Б - в каждом месте шаблона текст заменяется вызовом фильтра, и отступ приходится передавать руками, потому что шаблон его не знает:
В - меняется одна функция печати, построение не трогается:
Сгенерированный код: 4 операции в 5 языках
Это то, что читает пользователь SDK. Код один и тот же при любом способе, поэтому каждый язык показан один раз. Источник указан над каждым блоком: kit14, порты 14.10 или этот бенчмарк. В портах 14.10 параметры прокрутки обязательные, потому что импорт kit14 пометил их
required. В бенчмарке они необязательные, как в документации Tracker.Список задач Tracker со страницами
tracker.issues.search_scroll: курсор приходит в заголовкеX-Scroll-Idи уходит вscrollId, элементы итератора типизированы (Pager<Issue>,iter.Seq2[Issue, error],Paged<Issue>).Python - kit14
источник:
projection/kit14/_generated/tracker/issues.py:78-127TypeScript - бенчмарк
источник:
examples/bench-output/ts/tracker/issues.tsGo - бенчмарк
источник:
examples/bench-output/go/tracker/issues.goJava - порт 14.10
источник:
divergent/languages/java/other/tracker/src/ycli/tracker/Issues.java:75-90Rust - порт 14.10
источник:
divergent/languages/rust/tracker/src/generated/issues.rs:230-258Создание страницы Wiki с телом
Пропущенный аргумент не отправляется, а
Noneилиnullуходит какnull: Python -OMITиNone, TypeScript - необязательное поле иnull, Go - нулевойcore.Optиcore.Null, Java -Opt.unset()иcontent(null), Rust -Noneи списокnull_fields.Python - kit14
источник:
projection/kit14/_generated/wiki/models.py:1355-1366;projection/kit14/_generated/wiki/pages.py:161-200TypeScript - бенчмарк
источник:
examples/bench-output/ts/wiki/pages.tsGo - бенчмарк
источник:
examples/bench-output/go/wiki/pages.goJava - бенчмарк
источник:
examples/bench-output/java/wiki/Pages.javaRust - порт 14.10
источник:
divergent/languages/rust/wiki/src/generated/models.rs:3423-3436;divergent/languages/rust/wiki/src/generated/pages.rs:36-42;divergent/languages/rust/wiki/src/generated/pages.rs:205-218Загрузка файла в Forms
Multipart - факт каталога (
multipart/form-dataиx-ycli-part), а не работа генератора: метод везде один и тот же,upload(survey_id, filename, data), байты разбирает ядро.Python - kit14
источник:
projection/kit14/_generated/forms/files.py:21-31TypeScript - порт 14.10
источник:
divergent/languages/typescript/sdk/forms/client.ts:614-620;divergent/languages/typescript/sdk/forms/client.ts:654-662Go - порт 14.10
источник:
divergent/languages/go/forms/zz_files.go:51-64Java - порт 14.10
источник:
divergent/languages/java/forms/src/ycli/forms/Files.java:15-23Rust - порт 14.10
источник:
divergent/languages/rust/forms/src/generated/files.rs:58-75Экспорт ответов Forms
Ожидание не генерируется ни в одном порту. Генерируются три вызова, а
export_and_waitнаписан руками на поллере ядра по расписанию из таблицы (0,5 с, дальше ×2, потолок 60 с) - это решение C19. В Python kit14 такого сценария для Forms нет, поэтому там только три вызова.Python - kit14
источник:
projection/kit14/_generated/forms/answers.py:56-109TypeScript - порт 14.10
источник:
divergent/languages/typescript/sdk/forms/client.ts:189-198;divergent/languages/typescript/flows/export.tsGo - порт 14.10
источник:
divergent/languages/go/forms/zz_answers.go:55-65;divergent/languages/go/forms/flow_export.go:15-76Java - порт 14.10
источник:
divergent/languages/java/forms/src/ycli/forms/Answers.java:73-85;divergent/languages/java/forms/hand/ycli/forms/ExportFlow.java:15-62Rust - порт 14.10
источник:
divergent/languages/rust/forms/src/generated/answers.rs:96-110;divergent/languages/rust/forms/src/flow_export.rsРекомендация
Б: шаблон Jinja держит скелет файла, а все, где есть логика (имена, типы, литералы таблиц, комментарии, импорты), - функции на Python, которые шаблон вызывает как фильтры. После генератора - форматтер языка, на выходе - сверка байт в байт с прошлой генерацией. Так уже был устроен прототип refract 15.10: 9 шаблонов по 9-27 строк, писатель литералов на 123 строки и заготовки методов на Python.
Это меняет мою рекомендацию из тикета, там был А по выборке 14.10. На этом бенчмарке А ни по одному замеру не лучше Б, а Б короче и дешевле добавляет язык. Довод из тикета в пользу Б подтвердился: шаблон выше читается как готовый файл, у писателя и дерева файл виден только после запуска.
Против: бенчмарк маленький - 2 операции из 465 и 3 языка, без объединений, вложенных моделей и импортов с конфликтами имен. Как раз там у шаблонов растет логика. Kiota отказался от шаблонов из-за дублирования между языками, логики внутри шаблонов и расхождения их поведения, а писатель решает импорты и конфликты имен один раз, как в Forge и protoc-gen-go. Уже здесь импорты в шаблоне перечислены руками (
Pager- только если есть операция со страницами), а писатель собирает их сам. Если логика в шаблоне начнет расти, эта часть уходит в функцию на Python, а сверка байт в байт показывает, что выход не поменялся.Ответ одной строкой: «А», «Б» или «В».
Не проверено
javaccore.Opt[T]в Go - мой выбор. Порт Go делал указатели и списокNullFields, какой вариант тебе понятнее, не знаюcheck/- заглушки для бенчмарка, а не рукописные ядра языковbim-ba commentedon Nov 19, 2026
мне нравится больше всего вариант Б и мне кажется нужно именно в него и целить, потому что тут мы оперируем Сущностями и Шаблонами и Логикой (что происходит с Сущностями через Шаблон). но не хватает бенчмарка и замеров разных АПИшек, сложных и несложных операций, стандартного и нестандартного флоу, еще то что попадает в частные случаи Сущностей и Шаблонов и Логики а что нет