Skip to content

Как refract пишет код: примеры на пяти языках #605

Open

Description

@bim-ba

Способ, которым 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 итоговый файл виден только после запуска.

Ответ одной строкой - после примеров: «А», «Б» или «В».

Activity

  1. bim-ba commented on Nov 18, 2026

    @bim-ba
    OwnerAuthor

    Примеры готовы. Генератор каждого способа работает, и все три пишут байт в байт одинаковый код.

    Сравнение

    Замерил на двух операциях: список задач Tracker с курсором и создание страницы Wiki, в TypeScript и Go, потом добавил Java. Размер - непустые строки генератора, правки - строки в git diff.

    А - писатель в стиле Forge Б - шаблоны Jinja В - дерево языка
    строк генератора, TypeScript и Go 169 128 426
    строк генератора с Java 267 187 651
    вывод совпадает с другими способами да, 0 различающихся файлов да да
    добавить Java для одной операции +111 / -2 +72 / -2 +290 / -2
    переименовать аргумент API, query_fields → reply_fields 0, правится 1 строка каталога 0 0
    переименовать идентификатор, который генератор пишет сам, 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.")
        with writer.block(f"export interface {ts.options_name(operation)} {{"):
            for argument in operation.arguments:
                for model in [argument.type.model] if argument.type.kind == "model" else []:
                    writer.use("./models.ts", model)
                _doc(writer, argument.doc)
                optional = "" if argument.required else "?"
                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 }} {
    {% 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 его печатает:

    def _options(operation: Operation) -> t.Interface:
        members = tuple(
            t.Property(ts.camel(argument.name), ts.member_type(argument), not argument.required, t.Doc((argument.doc,)))
            for argument in operation.arguments
        )
        doc = f"The arguments of `{operation.operation_id}`: a member left out is not sent, `null` is sent as null."
        return t.Interface(ts.options_name(operation), t.Doc((doc,)), members)
    
    # ts_ast.py
            case Interface(name, doc, members):
                lines = [*_doc(doc, 0), f"export interface {name} {{"]
                for member in members:
                    lines += [
                        *_doc(member.doc, 1),
                        f"{INDENT}{member.name}{'?' if member.optional else ''}: {member.type};",
                    ]
                return [*lines, "}"]

    Теперь правка: комментарий длиннее 80 колонок переносится по словам, а однострочный /** … */ при этом становится блоком. Ни gofmt, ни Prettier этого не делают, значит, это работа генератора. Правило comment() общее для всех трех, ниже только то, что поменялось в TypeScript.

    А - каждое место, где пишется комментарий, вызывает новый метод писателя:

     def _doc(writer: Writer, text: str) -> None:
    -    writer.line(f"/** {text} */")
    +    writer.comment([text], "block")
    
     def _method(writer: Writer, operation: Operation) -> None:
    -    writer.line("/**")
    -    writer.line(f" * {operation.summary}")
    -    writer.line(" *")
    -    writer.line(" * @param options The named arguments.")
    -    writer.line(" */")
    +    writer.comment([operation.summary, "", "@param options The named arguments."], "block")
    
     # writer.py
    +    def comment(self, lines: list[str], style: Literal["block", "line"]) -> None:
    +        self.lines += comment(lines, self.indent * self.depth, style)

    Б - в каждом месте шаблона текст заменяется вызовом фильтра, и отступ приходится передавать руками, потому что шаблон его не знает:

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

    Python - kit14

    источник: projection/kit14/_generated/tracker/issues.py:78-127

        @overload
        def search_scroll(
            self,
            body: IssueSearch,
            expand: str | None,
            scroll_type: str | None,
            per_scroll: int | None,
            scroll_ttl_millis: int | None,
        ) -> Pager[Issue]: ...
        @overload
        def search_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]: ...
        def search_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.
            """
            return self._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,
            )
    TypeScript - бенчмарк

    источник: examples/bench-output/ts/tracker/issues.ts

    // Generated by refract from tracker.openapi.json. Do not edit.
    
    import type { Core, Operation, Pager } from "../core.ts";
    import type { Issue } from "./models.ts";
    
    /** The arguments of `tracker.issues.search_scroll`: a member left out is not sent, `null` is sent as null. */
    export interface IssuesSearchScrollOptions {
      /** 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;
    }
    
    const ISSUES_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. */
    export class Issues {
      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> {
        return this.#core.pager<Issue>(ISSUES_SEARCH_SCROLL, {
          query: options.query,
          filter: options.filter,
          expand: options.expand,
          scrollType: options.scrollType,
          perScroll: options.perScroll,
          scrollTTLMillis: options.scrollTtlMillis,
        });
      }
    }
    Go - бенчмарк

    источник: examples/bench-output/go/tracker/issues.go

    // 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.
    type IssuesSearchScrollOptions struct {
    	// 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]
    }
    
    var opIssuesSearchScroll = 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.
    type IssuesService struct {
    	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, options IssuesSearchScrollOptions) iter.Seq2[Issue, error] {
    	return core.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,
    	})
    }
    Java - порт 14.10

    источник: divergent/languages/java/other/tracker/src/ycli/tracker/Issues.java:75-90

        /** ``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). */
        public ycli.core.client.Page<Issue> searchScroll(java.util.function.UnaryOperator<IssueSearch> body, String expand, String scrollType, Long perScroll, Long scrollTtlMillis, Long limit, String next) {
            return searchScroll(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. */
        public ycli.core.client.Page<Issue> searchScroll(IssueSearch body, String expand, String scrollType, Long perScroll, Long scrollTtlMillis, Long limit, String next) {
            java.util.Map<String, Object> args = new java.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));
            boolean defaults = true; // read as a reply: a union member without its tag is a reply's (C-17)
            return core.list("tracker.issues.search_scroll", args, limit, next).map(w -> Issue.read(w, defaults));
        }
    Rust - порт 14.10

    источник: divergent/languages/rust/tracker/src/generated/issues.rs:230-258

        /// `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>`.
        pub fn search_scroll(
            &self,
            body: &IssueSearch,
            expand: &str,
            scroll_type: &str,
            per_scroll: i64,
            scroll_ttl_millis: i64,
        ) -> Paged<'c, Issue> {
            let mut 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.

    Python - kit14

    источник: projection/kit14/_generated/wiki/models.py:1355-1366; projection/kit14/_generated/wiki/pages.py:161-200

    class PageCreate(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.")
    
    # ...
    
        @overload
        def create(
            self, body: PageCreate, *, query_fields: str | None | Omit = OMIT, is_silent: bool | None | Omit = OMIT
        ) -> PageDetails: ...
        @overload
        def create(
            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: ...
        def create(
            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.
            """
            return self._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.
    
    import type { Core, Operation } from "../core.ts";
    import type { PageAccessPolicyUpdate, PageDetails } from "./models.ts";
    
    /** The arguments of `wiki.pages.create`: a member left out is not sent, `null` is sent as null. */
    export interface PagesCreateOptions {
      /** 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;
    }
    
    const PAGES_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. */
    export class Pages {
      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> {
        return this.#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.
    type PagesCreateOptions struct {
    	// Address of the page, e.g. `data/x`.
    	Slug string
    	// Title of the page.
    	Title string
    	// 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]
    }
    
    var opPagesCreate = 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.
    type PagesService struct {
    	client *core.Client
    }
    
    // Create: `POST /pages`: create a page at `slug`.
    func (s *PagesService) Create(ctx context.Context, options PagesCreateOptions) (*PageDetails, error) {
    	return core.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,
    	})
    }
    Java - бенчмарк

    источник: examples/bench-output/java/wiki/Pages.java

    // Generated by refract from wiki.openapi.json. Do not edit.
    
    package ycli.wiki;
    
    import java.util.function.UnaryOperator;
    import ycli.core.Args;
    import ycli.core.Core;
    import ycli.core.Operation;
    import ycli.core.Opt;
    
    /** The {@code pages} operations of wiki. */
    public final class Pages {
        private static final Operation PAGES_CREATE = Operation.of("wiki.pages.create", "POST", "/pages")
                .query("fields", "is_silent")
                .body("slug", "title", "content", "access_policy");
    
        private final Core core;
    
        public Pages(Core core) {
            this.core = core;
        }
    
        /** The arguments of {@code wiki.pages.create}: an unset member is not sent, {@code null} is sent as null. */
        public record CreateOptions(
                String slug,
                String title,
                Opt<String> content,
                Opt<PageAccessPolicyUpdate> accessPolicy,
                Opt<String> queryFields,
                Opt<Boolean> isSilent) {
            /** The required members; every other one is unset. */
            public static CreateOptions of(String slug, String title) {
                return new CreateOptions(slug, title, Opt.unset(), Opt.unset(), Opt.unset(), Opt.unset());
            }
    
            /** Body of the page in YFM markdown. */
            public CreateOptions content(String value) {
                return new CreateOptions(slug, title, Opt.of(value), accessPolicy, queryFields, isSilent);
            }
    
            /** Who may open the page. */
            public CreateOptions accessPolicy(PageAccessPolicyUpdate value) {
                return new CreateOptions(slug, title, content, Opt.of(value), queryFields, isSilent);
            }
    
            /** The comma-separated blocks to include in the reply. */
            public CreateOptions queryFields(String value) {
                return new CreateOptions(slug, title, content, accessPolicy, Opt.of(value), isSilent);
            }
    
            /** Do not notify the page's subscribers. */
            public CreateOptions isSilent(Boolean value) {
                return new CreateOptions(slug, title, content, accessPolicy, queryFields, Opt.of(value));
            }
        }
    
        /**
         * `POST /pages`: create a page at `slug`.
         *
         * @param options The named arguments.
         */
        public PageDetails create(CreateOptions options) {
            return core.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}. */
        public PageDetails create(String slug, String title, UnaryOperator<CreateOptions> options) {
            return create(options.apply(CreateOptions.of(slug, title)));
        }
    }
    Rust - порт 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

    /// Typed request body for `POST /pages`: a new page at `slug`.
    #[derive(Clone, Debug, Default, PartialEq)]
    pub struct PageCreate {
        /// Address of the page, e.g. `data/x`.
        pub slug: String,
        /// Title of the page.
        pub title: String,
        /// Body of the page in YFM markdown.
        pub content: Option<String>,
        /// Who may open the page.
        pub access_policy: Option<PageAccessPolicyUpdate>,
        /// Members sent as null, which clears them (C-18 v1.3); a `None` field is left out of a request.
        pub null_fields: Vec<String>,
    }
    
    // ...
    
    /// The optional arguments of `wiki.pages.create`.
    #[derive(Clone, Debug, Default, PartialEq)]
    pub struct PagesCreateOptions {
        /// The comma-separated blocks to include in the reply.
        pub fields: Option<String>,
        /// Do not notify the page's subscribers.
        pub is_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> {
            let mut 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), байты разбирает ядро.

    Python - kit14

    источник: projection/kit14/_generated/forms/files.py:21-31

        def upload(self, survey_id: str, filename: str, data: bytes) -> FileOut:
            """Upload a file for form filling (multipart field ``file``) → :class:`FileOut`.
    
            Args:
                survey_id: The form's id.
                filename: The file's name.
                data: The file's raw bytes.
            """
            return self._service.value(
                _ops(), "forms.files.upload", {"survey_id": survey_id, "filename": filename, "data": data}, FileOut
            )
    TypeScript - порт 14.10

    источник: divergent/languages/typescript/sdk/forms/client.ts:614-620; divergent/languages/typescript/sdk/forms/client.ts:654-662

    /** The named arguments of `forms.files.upload`. */
    export interface FilesUploadOptions {
      /** 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.
       */
      async upload(surveyId: string, options: FilesUploadOptions): Promise<m.FileOut> {
        return this.#core.value<m.FileOut>("forms.files.upload", { survey_id: surveyId, ...options });
      }
    Go - порт 14.10

    источник: divergent/languages/go/forms/zz_files.go:51-64

    // Upload: Upload a file for form filling (multipart field `file`) → FileOut.
    //
    // surveyID: The form's id.
    //
    // filename: The file's name.
    //
    // data: The file's raw bytes.
    func (s *FilesService) Upload(ctx context.Context, surveyID string, filename string, data []byte) (*FileOut, error) {
    	args := value.NewObject()
    	client.Put(args, "survey_id", surveyID)
    	client.Put(args, "filename", filename)
    	client.Put(args, "data", data)
    	return client.Value[*FileOut](ctx, s.client, "forms.files.upload", args)
    }
    Java - порт 14.10

    источник: divergent/languages/java/forms/src/ycli/forms/Files.java:15-23

        /** Upload a file for form filling (multipart field ``file``) → :class:`FileOut`. */
        public FileOut upload(String surveyId, String filename, ycli.core.value.Bytes data) {
            java.util.Map<String, Object> args = new java.util.LinkedHashMap<>();
            args.put("survey_id", Conv.request(surveyId));
            args.put("filename", Conv.request(filename));
            args.put("data", Conv.request(data));
            boolean defaults = true; // read as a reply: a union member without its tag is a reply's (C-17)
            return FileOut.read(core.call("forms.files.upload", args), defaults);
        }
    Rust - порт 14.10

    источник: divergent/languages/rust/forms/src/generated/files.rs:58-75

        /// 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.
        pub fn upload(&self, survey_id: &str, filename: &str, data: &[u8]) -> Result<FileOut> {
            let mut 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 нет, поэтому там только три вызова.

    Python - kit14

    источник: projection/kit14/_generated/forms/answers.py:56-109

        @overload
        def export(self, survey_id: str, body: AnswerExport) -> OperationResult: ...
        @overload
        def export(
            self,
            survey_id: str,
            *,
            format: Literal["csv", "xlsx", "json"] | str | None = ...,
            upload: Literal["default", "disk"] | str | None = ...,
            started_at: str | None = ...,
            finished_at: str | None = ...,
            pks: builtins.list[int] | None = ...,
            columns: builtins.list[str] | None = ...,
            limit: int | None = ...,
            upload_files: bool | None = ...,
        ) -> OperationResult: ...
        def export(self, survey_id: str, body: AnswerExport | Omit = OMIT, **fields: Any) -> OperationResult:
            """``POST /surveys/{id}/answers/export`` — start an export → ``202`` with its operation.
    
            Args:
                survey_id: The form's id.
                body: The ``AnswerExport``: format, destination and filters.
            """
            return self._service.value(
                _ops(),
                "forms.answers.export",
                {
                    "survey_id": survey_id,
                    "body": gather("forms.answers.export", "body", body, AnswerExport, fields, required=True),
                },
                OperationResult,
            )
    
        def export_results_get(self, survey_id: str, task_id: str) -> OperationResult:
            """``GET /surveys/{id}/answers/export-results?task_id=`` → the export's status.
    
            Args:
                survey_id: The form's id.
                task_id: The export operation's ``id``.
            """
            return self._service.value(
                _ops(), "forms.answers.export_results_get", {"survey_id": survey_id, "task_id": task_id}, OperationResult
            )
    
        def export_download(self, survey_id: str, task_id: str) -> bytes:
            """The exported file's raw bytes, once :meth:`export_results_get` reports it ready.
    
            Args:
                survey_id: The form's id.
                task_id: The export operation's ``id``.
            """
            return self._service.value(
                _ops(), "forms.answers.export_download", {"survey_id": survey_id, "task_id": task_id}, None
            )
    TypeScript - порт 14.10

    источник: divergent/languages/typescript/sdk/forms/client.ts:189-198; divergent/languages/typescript/flows/export.ts

      /**
       * `POST /surveys/{id}/answers/export` — start an export → `202` with its operation.
       *
       * @param surveyId The form's id.
       * @param [options] The named arguments.
       */
      async export(surveyId: string, options: AnswersExportOptions = {}): Promise<m.OperationResult> {
        return this.#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 { type At, notExecutable } from "../src/failure.ts";
    import { waitFor } from "../src/polling.ts";
    import type { FormsClient } from "../sdk/forms/client.ts";
    import type * as m from "../sdk/forms/models.ts";
    
    const FLOW = "forms.answers.export_wait";
    
    export interface ExportWait {
      /** 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. */
    export interface ExportResult {
      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). */
    export async function exportAndWait(client: FormsClient, surveyId: string, body: m.AnswerExport, wait: ExportWait = {}): Promise<ExportResult> {
      const core = coreOf(client);
      const poll = core.tables.flows?.[FLOW]?.poll;
      if (poll === undefined) throw notExecutable({ operation: "forms.answers.export", method: null, url: null, status: null });
      const where = (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 }];
        const planned = core.plan(operation, args) as { requests?: { method?: string; url?: string }[] };
        const sent = planned.requests?.[0];
        return { operation: "forms.answers.export", method: sent?.method ?? null, url: sent?.url ?? null, status: null };
      };
      const ended = await waitFor({
        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 };
    }
    Go - порт 14.10

    источник: divergent/languages/go/forms/zz_answers.go:55-65; divergent/languages/go/forms/flow_export.go:15-76

    // 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, surveyID string, body *AnswerExport) (*OperationResult, error) {
    	args := value.NewObject()
    	client.Put(args, "survey_id", surveyID)
    	client.Put(args, "body", body)
    	return client.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.
    type ExportWaitOptions struct {
    	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.
    type ExportResult struct {
    	Operation *OperationResult
    	File      []byte
    }
    
    const exportFlow = "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, surveyID string, body *AnswerExport, opts *ExportWaitOptions) (*ExportResult, error) {
    	flow := s.client.Table.Flows[exportFlow]
    	if flow == nil || flow.Poll == nil {
    		return nil, failure.Document(failure.Where{Operation: "forms.answers.export"}, "flow")
    	}
    	ctx = client.WithBudget(ctx) // rule 24: the flow's requests count against one ceiling
    	started, err := s.Export(ctx, surveyID, body)
    	if err != nil {
    		return nil, err
    	}
    	if started == nil || started.ID == nil { // C-14: no reply decided, the flow judged a value the start accepted
    		return nil, failure.FlowNothingAt(s.where("forms.answers.export", surveyID, body, ""), exportFlow)
    	}
    	var maxWait time.Duration
    	if opts != nil {
    		maxWait = opts.MaxWait
    	}
    	var state *OperationResult
    	poll := func(ctx context.Context) (string, error) {
    		if state, err = s.ExportResultsGet(ctx, surveyID, *started.ID); err != nil {
    			return "", err
    		}
    		if state == nil || state.Status == nil { // D21: nothing at status_at, the flow cannot judge the poll
    			return "", failure.FlowNothingAt(s.where("forms.answers.export_results_get", surveyID, nil, *started.ID), exportFlow)
    		}
    		return *state.Status, nil
    	}
    	on := s.client.Clock
    	if on == nil {
    		on = clock.Real{}
    	}
    	status, err := polling.Until(ctx, on, flow.Poll, maxWait, poll)
    	switch {
    	case errors.Is(err, polling.ErrDeadline):
    		where := s.where("forms.answers.export_results_get", surveyID, nil, *started.ID)
    		return nil, failure.FlowWithin(where, exportFlow, maxWait.Seconds())
    	case errors.Is(err, polling.ErrInterrupted):
    		return nil, failure.Interrupted(failure.Where{Operation: "forms.answers.export"})
    	case err != nil:
    		return nil, err
    	case status != flow.Poll.Ready:
    		return &ExportResult{Operation: state}, nil
    	}
    	file, err := s.ExportDownload(ctx, surveyID, *started.ID)
    	return &ExportResult{Operation: state, File: file}, err
    }
    Java - порт 14.10

    источник: divergent/languages/java/forms/src/ycli/forms/Answers.java:73-85; divergent/languages/java/forms/hand/ycli/forms/ExportFlow.java:15-62

        /** ``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). */
        public OperationResult export(String surveyId, java.util.function.UnaryOperator<AnswerExport> body) {
            return export(surveyId, body.apply(AnswerExport.empty()));
        }
    
        /** ``POST /surveys/{id}/answers/export`` — start an export → ``202`` with its operation. */
        public OperationResult export(String surveyId, AnswerExport body) {
            java.util.Map<String, Object> args = new java.util.LinkedHashMap<>();
            args.put("survey_id", Conv.request(surveyId));
            args.put("body", Conv.request(body));
            boolean defaults = true; // read as a reply: a union member without its tag is a reply's (C-17)
            return OperationResult.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.
     */
    public final class ExportFlow {
        static final String FLOW = "forms.answers.export_wait";
        private static final String START = "forms.answers.export";
        private static final String STATUS = "forms.answers.export_results_get";
    
        private ExportFlow() {
        }
    
        public static Object run(FormsClient forms, Clock clock, Double deadlineSeconds, Map<String, Object> arguments) {
            return Client.sharedBudget(() -> poll(forms, clock, deadlineSeconds, arguments));
        }
    
        private static Object poll(FormsClient forms, Clock clock, Double deadlineSeconds, Map<String, Object> arguments) {
            Flow flow = FormsClient.table().flows().get(FLOW);
            if (flow == null || flow.poll() == null) throw Failure.document(START, "flow", "the table states no poll schedule (C-14)");
            Poll schedule = flow.poll();
            String surveyId = (String) arguments.get("survey_id");
            Object body = arguments.getOrDefault("body", Map.of());
            OperationResult started = forms.answers().export(surveyId, AnswerExport.of(body));
            if (started.id() == null) {
                Where start = where(forms, START, Map.of("survey_id", surveyId, "body", body), "the export started without an operation id");
                throw Failure.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 (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw Failure.interrupted(where(forms, STATUS, polled, "interrupted")).because(e);
            }
            return switch (ended) {
                case Poller.Ended.NoStatus<OperationResult> _ -> // D21: nothing at status_at: the flow cannot judge the poll
                        throw Failure.flowNothingAt(where(forms, STATUS, polled, "the poll reply has no status"), FLOW);
                case Poller.Ended.PastDeadline<OperationResult> _ -> throw Failure.flowWithin(
                        where(forms, STATUS, polled, "the export is not ready after " + deadlineSeconds + " s"), FLOW, deadlineSeconds);
                case Poller.Ended.Terminal<OperationResult> done -> schedule.ready().equals(done.reply().status())
                        ? forms.answers().exportDownload(surveyId, started.id()) : done.reply().toJson();
    Rust - порт 14.10

    источник: divergent/languages/rust/forms/src/generated/answers.rs:96-110; divergent/languages/rust/forms/src/flow_export.rs

        /// `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.
        pub fn export(&self, survey_id: &str, body: &AnswerExport) -> Result<OperationResult> {
            let mut 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};
    
    use crate::generated::AnswersApi;
    use crate::models::{AnswerExport, OperationResult};
    
    /// The flow's name in the table.
    const FLOW: &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)]
    pub struct ExportWait {
        /// How long the export may take in all; `None` is no bound.
        pub max_wait: Option<Duration>,
    }
    
    /// How a waited export ended: the file when it succeeded, the operation alone when it did not.
    #[derive(Clone, Debug, PartialEq)]
    pub enum ExportEnd {
        /// The exported file.
        File(Vec<u8>),
        /// The export ended in a status other than ready.
        Failed(OperationResult),
    }
    
    impl AnswersApi<'_> {
        /// 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`.
        pub fn export_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 ceiling
            let 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)?;
            let Some(task_id) = started.id else {
                let args = Map::new()
                    .with("survey_id", survey_id)
                    .with("body", body.to_request());
                return Err(job.nothing_at("forms.answers.export", &args));
            };
            let poll_args = Map::new()
                .with("survey_id", survey_id)
                .with("task_id", task_id.as_str());
            let mut 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 {
                return Ok(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/ - заглушки для бенчмарка, а не рукописные ядра языков
  2. bim-ba commented on Nov 19, 2026

    @bim-ba
    OwnerAuthor

    мне нравится больше всего вариант Б и мне кажется нужно именно в него и целить, потому что тут мы оперируем Сущностями и Шаблонами и Логикой (что происходит с Сущностями через Шаблон). но не хватает бенчмарка и замеров разных АПИшек, сложных и несложных операций, стандартного и нестандартного флоу, еще то что попадает в частные случаи Сущностей и Шаблонов и Логики а что нет

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions