#!/usr/bin/env python3"""Generate catalogue storage from Rust serde struct declarations, never definition JSON.The core owns validation and union semantics. BINDINGS names the app's drawingtype for each Rust named type a model holds, and the storage is written intoCottonUI as plain structs over those types (the look's half into CottonPaper, thecard kinds a face reads into CottonValues). Only native presentationdefaults/name projections and bindings live here; field membership, wire keys,containers and optionality come from Rust. Unsupported syntax and an unboundnamed type fail."""import argparseimport hashlibimport jsonimport refrom pathlib importPathROOT = Path(__file__).resolve().parents[1]OUTPUT = ROOT / 'apps/cotton/Sources/CottonUI/Definitions/GeneratedDefinitionTypes.swift'# What the LOOK reads, written into `CottonPaper` rather than beside the# definitions (architect, 20 Oct 2026: the look names no definition): the# theme row it draws from, and the card stock — a photographed paper — the# row says each class of act is printed on (`ThemeLook.swift`). Everything# else is CottonUI's, and that file imports this one's module.LOOK_OUTPUT = ROOT / 'apps/loom/Sources/CottonPaper/Theme/GeneratedThemeTypes.swift'LOOK_ENUMS = {'CardStock': 'mod.rs'}# What a FACE reads, written into `CottonValues` (Loom, 27 Oct 2026): the face# id a card names, the slots a card fills and its art — plain values a face is# drawn by, in the module that imports Foundation alone, so a face builds with# no core. CottonUI's file names them from there.VALUES_OUTPUT = ROOT / 'apps/loom/Sources/CottonValues/Generated/GeneratedCardTypes.swift'VALUES_ENUMS = {'CardSlot': 'card.rs', 'CardArt': 'card.rs'}# A face's open id (`card::FaceId`, Loom step 5): any well-formed id reads, so# a face newer than this build is drawn plain; the faces this build knows are# its named values, from the ids `pnpm gen:faces` writes for the core. The# Swift name stays the card kind's, which the deck's callers name.FACE_ID = ('FaceId', 'DefinitionCardKind')FACE_IDS = ROOT / 'crates/cotton-core/src/definitions/face_ids.json'# The theme row's storage: what `ThemeRow.swift` reads a theme from. The JSON# value and the coding key every model decodes through go with it, because# the look is the module both sides see.LOOK_MODELS = {'ThemeDefinition', 'ThemePalettes', 'ThemeTexture', 'ThemeCap', 'ThemeScale'}# Root storage used by the catalogue. A named nested type is drawn by the app# type BINDINGS names for it (a generated model by its own storage); no second# wire field list is needed to bind it.# A file outside cotton-core's definitions names its crate.STORE_TABLES = 'cotton-store/src/schema/package_tables.rs'RECORD_PAGE = 'cotton-core/src/records/page.rs'MODELS = {'TableDefinition': 'mod.rs', 'TableProducer': 'mod.rs', 'Column': 'mod.rs', 'PlaceColumns': 'mod.rs','ShippedView': 'mod.rs', 'RecordCommand': 'commands.rs','BoardDefinition': 'board.rs', 'BoardPart': 'board.rs', 'BoardVariant': 'board.rs','ThemeDefinition': 'theme.rs', 'ThemePalettes': 'theme.rs','ThemeTexture': 'theme.rs', 'ThemeCap': 'theme.rs', 'ThemeScale': 'theme.rs',# Lists.'ListSort': 'mod.rs', 'ListGrid': 'mod.rs', 'ListPaste': 'mod.rs','ListMonths': 'mod.rs', 'ListSelect': 'mod.rs', 'MenuLine': 'mod.rs', 'LinkTiles': 'mod.rs','PolaroidLayout': 'mod.rs', 'ListClear': 'mod.rs', 'DeletionWords': 'mod.rs','ListGrouping': 'mod.rs', 'ListGroup': 'mod.rs', 'GroupDue': 'mod.rs', 'ColumnUnits': 'mod.rs', 'EmptyWords': 'mod.rs','NoMatchWords': 'mod.rs', 'RecentLayout': 'mod.rs', 'KeptBy': 'mod.rs', 'RecordExport': 'mod.rs','ListCreate': 'mod.rs', 'CreateAct': 'mod.rs', 'CreateDoor': 'mod.rs', 'CreateFiles': 'mod.rs', 'CreatePick': 'mod.rs', 'CreateDraft': 'mod.rs', 'CountWords': 'mod.rs', 'LiveReading': 'mod.rs', 'ListFilter': 'mod.rs','ListLink': 'mod.rs', 'ListUpcoming': 'mod.rs', 'ChipRow': 'mod.rs', 'ProjectsRead': 'mod.rs','BinnedRows': 'mod.rs', 'LinkedWhen': 'mod.rs', 'CoverLayout': 'mod.rs','TableViewer': 'mod.rs', 'ViewerWords': 'mod.rs', 'VoiceWords': 'mod.rs','TableWords': 'mod.rs', 'CouldNotReadWords': 'mod.rs',# Sections, page acts and what a record hands on.'SectionWhen': 'mod.rs', 'SectionAction': 'mod.rs', 'PageAction': 'mod.rs', 'RecordOpens': 'mod.rs','ListCapture': 'mod.rs', 'RecordHandOver': 'mod.rs', 'AttachmentsLayout': 'mod.rs','RelatedRecords': 'mod.rs',# Column details.'AmountSigns': 'mod.rs', 'ColumnProvenance': 'mod.rs', 'ValueMatch': 'mod.rs', 'SecretReveal': 'mod.rs','StoriesLayout': 'mod.rs', 'SlipStockBy': 'mod.rs',# Page sections.'PageSection': 'mod.rs', 'SectionList': 'mod.rs', 'SectionEmptyWords': 'mod.rs', 'SectionLink': 'mod.rs','LinkedSection': 'mod.rs', 'RecordAnswers': 'mod.rs',# Slips.'SlipBy': 'mod.rs', 'SlipVariant': 'mod.rs', 'SlipCaption': 'mod.rs', 'SlipBadge': 'mod.rs','SlipReply': 'mod.rs', 'SlipByline': 'mod.rs', 'SlipLayout': 'mod.rs', 'SlipLines': 'mod.rs',# Tiles.'TileLayout': 'mod.rs', 'TileCurrent': 'mod.rs', 'TileSummary': 'mod.rs', 'ChartFace': 'mod.rs','Sparkline': 'mod.rs',# Conversations.'ConversationLayout': 'mod.rs', 'ConversationQueue': 'mod.rs', 'ConversationStarted': 'mod.rs','ConversationSource': 'mod.rs',# A table's groups.'Groups': 'mod.rs', 'GroupsKeptIn': 'mod.rs',# What a command asks before it runs.'CommandList': 'commands.rs', 'CommandSpoken': 'spoken.rs', 'SpokenCounted': 'spoken.rs', 'CommandReveal': 'commands.rs', 'CommandPick': 'commands.rs',# How a column's contact points are reached.'ReachDetail': 'mod.rs',# The tool a home table heads.'ToolHome': 'mod.rs', 'ToolFigure': 'mod.rs', 'ToolView': 'tool_views.rs',# A record drawn alone as a card (`card`).'CardFace': 'card.rs', 'CardField': 'card.rs', 'CornerFact': 'card.rs', 'PaceInputs': 'card.rs','CardOpens': 'card.rs', 'FaceByValue': 'card.rs',# A tool and its picture.'Reservation': 'reserve.rs','ToolDefinition': 'mod.rs', 'ToolContribution': 'mod.rs', 'ToolAct': 'mod.rs', 'ToolServer': 'mod.rs', 'ToolLists': 'mod.rs', 'ToolAuthor': 'mod.rs', 'ToolPhoto': 'mod.rs', 'LinkPicture': 'mod.rs',# A computed column's shapes.'Lookup': 'computed.rs', 'Rollup': 'computed.rs', 'Formula': 'computed.rs', 'Running': 'computed.rs', 'Previous': 'computed.rs', 'Activity': 'computed.rs', 'RunningRollup': 'computed.rs', 'RunningAggregate': 'computed.rs',# The physical tables a package owns, in cotton-store.'PackageTable': STORE_TABLES, 'PackageColumn': STORE_TABLES, 'LegacyConstraint': STORE_TABLES,'PackageIndexDeclared': STORE_TABLES, 'PackageFullTextDeclared': STORE_TABLES,# A record page's parts.'PageParts': 'parts.rs', 'PartsHead': 'parts.rs', 'PartsList': 'parts.rs', 'PartsMatch': 'parts.rs','PartsRead': 'parts.rs', 'ReadLine': 'parts.rs', 'PartsCard': 'parts.rs', 'PartsActs': 'parts.rs','SlipsLayout': 'parts.rs',# What a record page opens on, its fact slips and its views (`parts`).'GroupColumns': 'record_page.rs', 'GroupReads': 'record_page.rs', 'GroupReach': 'record_page.rs','PageViewRef': 'record_page.rs',# The record page the core resolves (`records.page`), which the app draws.'RecordPage': RECORD_PAGE, 'PageHead': RECORD_PAGE, 'PageState': RECORD_PAGE, 'PageLink': RECORD_PAGE,'PageBody': RECORD_PAGE, 'PageList': RECORD_PAGE, 'PageRow': RECORD_PAGE, 'PageActs': RECORD_PAGE,'PageAct': RECORD_PAGE, 'PageListAllTable': RECORD_PAGE, 'PageListAllRead': RECORD_PAGE,# Each table's page as the catalogue hands it over.'Page': 'cotton-ffi/src/phone/catalogue.rs',}# A struct variant of an untagged enum, stored as its own model: its fields# are the variant's, named by the enum and the variant.VARIANT_STRUCTS = {'PackageIndexDeclared': ('PackageIndex', 'Declared'),'PackageFullTextDeclared': ('PackageFullText', 'Declared'),'PageListAllTable': ('PageListAll', 'Table'), 'PageListAllRead': ('PageListAll', 'Read')}# serde(untagged) enums of newtype variants: decoded as the first variant# whose payload reads, in Rust's declaration order, exactly as serde does.UNTAGGED = {'RunningOpening': 'computed.rs', 'SlipSubtitle': 'mod.rs', 'SectionEmpty': 'mod.rs', 'PageHand': 'mod.rs', 'SlipOpens': 'mod.rs', 'MessageColumns': 'mod.rs', 'CanSend': 'mod.rs', 'ColumnReach': 'mod.rs', 'ToolPicture': 'mod.rs','PackageIndex': STORE_TABLES, 'PackageFullText': STORE_TABLES, 'PageListAll': RECORD_PAGE,'PageGroup': 'record_page.rs'}# Externally tagged enums of newtype variants (serde's default): an object of# exactly one key, the variant's wire name, holding its payload.TAGGED = {'Computed': 'computed.rs'}# The app's names for a variant, where they read better than Rust's.VARIANTS = {('SlipOpens', 'column'): 'address', ('CanSend', 'always'): 'allowed',# The app reads a reach's kind across both forms; the bare form is its word. ('ColumnReach', 'kind'): 'word'}ENUMS = {'ColumnType': 'mod.rs', 'PickSource': 'mod.rs', 'DeviceReads': 'mod.rs', 'PictureKind': 'mod.rs', 'CommandKind': 'commands.rs', 'CommandDoes': 'commands.rs', 'ViewFace': 'mod.rs','ListLayout': 'mod.rs', 'SelectVerb': 'mod.rs', 'TableRole': 'mod.rs','TableScope': 'mod.rs', 'ActionScheme': 'mod.rs', 'AttachmentSource': 'mod.rs', 'SlipStock': 'mod.rs', 'SearchFace': 'mod.rs','SectionRole': 'mod.rs', 'SectionFace': 'mod.rs', 'Ink': 'mod.rs', 'SlipEdge': 'mod.rs', 'TileFace': 'mod.rs', 'SummaryOp': 'mod.rs','ChartKind': 'mod.rs', 'ChartPeriod': 'mod.rs', 'ChartSign': 'mod.rs', 'ConversationFace': 'mod.rs', 'StackFace': 'mod.rs', 'PickKind': 'commands.rs', 'ReachKind': 'mod.rs', 'LinkObject': 'mod.rs', 'ColumnFormat': 'mod.rs', 'RollupOp': 'cotton-rules/src/computed.rs', 'FormulaOp': 'cotton-rules/src/computed.rs', 'ActivityOp': 'computed.rs', 'ListHead': 'mod.rs', 'PagePart': 'parts.rs','PageShape': 'parts.rs', 'ListFace': 'parts.rs', 'ReadFormat': 'parts.rs', 'SlipWidth': 'parts.rs','ToggleStyle': 'mod.rs', 'PageOpens': 'record_page.rs', 'Form': 'mod.rs'}RENAMES = { ('TableDefinition', 'delete'): 'deletes', ('Column', 'default'): 'defaultValue', ('CommandPick', 'default'): 'defaultValue', ('RecordCommand', 'does'): 'doesWord',# Whether a table shipped is provenance only: no generic surface reads the# wire word, so the storage names it as the shipped rename does. ('TableDefinition', 'builtin'): 'shipped',# A list's empty words are a sentence or a title with one; the app reads both. ('SectionList', 'empty'): 'emptyWords',# The app reads a slip's subtitles as a list; the stored spelling is the core's. ('SlipLayout', 'subtitle'): 'subtitleKeys',# A tile's narrowing reads as a filter, as the app's list filters do.# The app reads the send fact through canSend; the stored fact is the gate. ('ConversationLayout', 'can_send'): 'sendGate', ('TileSummary', 'where'): 'filter', ('ChartFace', 'where'): 'filter', ('CommandPick', 'where'): 'filter', ('PackageColumn', 'default'): 'defaultValue', ('PageListAllTable', 'where'): 'filter', ('PartsList', 'match'): 'matching',}# The app's drawing type for each Rust named type a model holds. Plain types,# never generic parameters: a struct generic over its fields' types makes the# Swift runtime build its metadata at first use, checking every parameter's# Codable and Hashable conformances by scanning the binary's conformance# records — TableDefinition's 57 parameters cost 90-130 ms of every cold start# before one byte was decoded (pagespeed, 15 Oct 2026, iOS 26.5 simulator).BINDINGS = {'ListGroup': {'GroupDue': 'DefinitionGroupDue'},'ListCreate': {'CreateAct': 'DefinitionCreateAct', 'CreateDoor': 'DefinitionCreateDoor'},'CreateDoor': {'CreateAct': 'DefinitionCreateAct', 'CreateFiles': 'DefinitionCreateFiles', 'CreatePick': 'DefinitionCreatePick', 'CreateDraft': 'DefinitionCreateDraft', 'DeviceReads': 'DefinitionDeviceReads'},'CreateDraft': {'OrderedMap<serde_json::Value>': '[String: RecordValue]'},'CreatePick': {'PickSource': 'DefinitionPickSource', 'PictureKind': 'DefinitionPictureKind'},'TableDefinition': {'AttachmentsLayout': 'AttachmentsLayout', 'BinnedRows': 'BinnedRows', 'ChipRow': 'ChipRow','Column': 'ColumnDefinition', 'ConversationLayout': 'ConversationLayout', 'CountWords': 'CountWords','TableViewer': 'TableViewer', 'VoiceWords': 'VoiceWords', 'TableWords': 'DefinitionTableWords','CoverLayout': 'CoverLayout', 'DeletionWords': 'DeletionWords', 'EmptyWords': 'EmptyWords','Groups': 'TableGroups', 'KeptBy': 'KeptBy', 'LinkTiles': 'LinkTiles', 'LinkedWhen': 'LinkedWhen','ListCapture': 'ListCapture', 'ListClear': 'ListClear', 'ListCreate': 'ListCreate', 'ListFilter': 'ListFilter','ListGrid': 'ListGrid', 'ListGrouping': 'ListGrouping', 'ListLink': 'ListLink','ListMonths': 'ListMonthsLayout', 'ListPaste': 'ListPaste', 'ListSelect': 'ListSelect', 'ListSort': 'ListSort','ListUpcoming': 'ListUpcoming', 'LiveRead': 'LiveRecordRead', 'LiveReading': 'LiveReading', 'MenuLine': 'MenuLine','OrderedMap<serde_json::Value>': '[String: RecordValue]', 'PageAction': 'PageAction','PageSection': 'PageSection', 'PolaroidLayout': 'PolaroidLayout','ProjectsRead': 'ProjectsRead', 'RecentLayout': 'RecentLayout', 'RecordCommand': 'RecordCommand','RecordExport': 'RecordExport', 'RecordHandOver': 'RecordHandOver', 'RecordOpens': 'RecordOpens','RelatedRecords': 'RelatedRecords', 'RetiredColumn': 'DefinitionJSONValue', 'SectionWhen': 'SectionWhen','SlipBy': 'SlipBy', 'SlipLayout': 'SlipLayout', 'SlipsLayout': 'DefinitionSlipsLayout','StoriesLayout': 'StoriesLayout', 'TableRole': 'TableRole', 'TableScope': 'TableScope', 'TileLayout': 'TileLayout','TokenPrices': 'DefinitionJSONValue', 'ToolHome': 'TableTool','TableProducer': 'DefinitionTableProducer','ValueMatch': 'ValueMatch',# A view's rows are its source's, kept by the core (every read and# write of a view is answered there); the app carries it and reads none.'ViewSource': 'DefinitionJSONValue',# How a sealed table's rows are sealed is the core's: the phone seals# and opens them through cotton-ffi; the app carries it and reads none.'SealSpec': 'DefinitionJSONValue',# What a send of a record carries is the core's: the phone offers and# sends through cotton-ffi send.*; the app carries it and reads none.'cotton_rules::send::SendSpec': 'DefinitionJSONValue', },'Column': {'AmountSigns': 'AmountSigns', 'ColumnLinkBy': 'DefinitionJSONValue','ColumnPresentation': 'String', 'ColumnProvenance': 'ColumnProvenance','ColumnUnits': 'ColumnUnits', 'OrderedMap<Stamp>': '[String: String]', 'OrderedMap<StampTone>': 'DefinitionJSONValue','OrderedMap<String>': '[String: String]', 'OrderedMap<Vec<String>>': '[String: [String]]','RecordOpens': 'RecordOpens', 'SecretReveal': 'ColumnReveal', 'ValueMatch': 'ShownWhen','contributors::Contributes': 'DefinitionJSONValue','serde_json::Value': 'RecordValue', },# Where a view or link stands is the core's to settle (it leaves the other# kind's out of what it resolves); the app carries the word and reads none.'ShippedView': {'ChartFace': 'DefinitionJSONValue', 'DatabaseWhen': 'DefinitionJSONValue'},'RecordCommand': {'CommandList': 'RecordCommandList', 'CommandPick': 'RecordCommandPick', 'CommandReveal': 'RecordCommandReveal',# Where an act's made record lands is the core's to read: the app# stands on the `open` its outcome names and carries this as data.'CommandLands': 'DefinitionJSONValue','OrderedMap<String>': '[String: String]', 'OrderedMap<serde_json::Value>': '[String: RecordValue]', },# A figure the core works out arrives as its line in Home's counts; the# app carries how it is worked out and reads none of it.'ToolFigure': {'FigureSummary': 'DefinitionJSONValue', 'FigureFormula': 'DefinitionJSONValue'},# A view's head arrives as its line in `shell.fan`; the app carries how# it is counted and reads none of it.# A sealed view's opened read (`OpenedRead`) narrows and orders the opened# rows in the core; the app carries it and reads none.'ToolView': {'ViewHead': 'DefinitionJSONValue', 'OpenedRead': 'DefinitionJSONValue', 'CurrentOf': 'DefinitionJSONValue'},# A tool's fan tile is the core's to read: shell.fan answers it, no Swift reads it here.'ToolDefinition': {'fan_tile::FanTile': 'DefinitionJSONValue'},# A contributed column is installed by the core onto the shared table's own# definition; the app reads it there (Column is internal storage), never here.'ToolContribution': {'Column': 'DefinitionJSONValue'},'BoardDefinition': {'BoardPart': 'BoardPart', 'BoardVariant': 'BoardVariant'},'BoardVariant': {'BoardPart': 'BoardPart'},# A page list's whole-list query reads as record values, as list filters do.'PageListAllTable': {'Map<String,Value>': '[String: RecordValue]'},'PageListAllRead': {'Map<String,Value>': '[String: RecordValue]'},'SlipsLayout': {'OrderedMap<SlipWidth>': '[String: DefinitionSlipWidth]', 'OrderedMap<Vec<String>>': '[String: [String]]','OrderedMap<String>': '[String: String]'},} | {# A map of JSON values a record carries is drawn as the app's record values. model: {'OrderedMap<serde_json::Value>': '[String: RecordValue]'} | ({'DatabaseWhen': 'DefinitionJSONValue'} if model == 'ListLink'else {})for model in ['ListLink', 'ChipRow', 'SectionAction', 'RelatedRecords', 'SectionList', 'TileSummary', 'ChartFace','ConversationLayout', 'CommandPick']}# Storage the app holds only behind an internal type (TableDefinition.Stored,# ColumnDefinition.Storage) is internal, because it is bound to internal types.INTERNAL = {'TableDefinition', 'Column'}# These are drawing defaults, not a mirror of the field list. Optional arrays# that existing native surfaces iterate are read as empty; column flags as false.# Projected fields written even at their default, so a definition that names# one explicitly (a section's empty `columns`) keeps it through a round trip.WRITTEN = {('PageSection', key) for key in ['columns', 'above', 'actions', 'commands']} | { ('ConversationLayout', key) for key in ['can_send', 'header', 'sends', 'header_columns', 'also', 'folds']} | {('ConversationStarted', 'words')} | {# The core writes a package column's absent default as null. ('PackageColumn', 'default')}DEFAULTS = { ('TableDefinition', key): '[]'for key in ['lists','exports','search','links','menu']} | {('TableDefinition', 'delete'): 'true', ('TableDefinition', 'layout'): '.list'} | { ('Column', key): 'false'for key in ['required','indexed','readonly','multiple','week','month','zone','yearly']} | { ('ToolView', 'visibility'): '"owner"',# Absent in a definition reads as these; each is the core's own reading. ('ListSort', 'descending'): 'false', ('ListSelect', 'verb'): '.delete', ('ListGrouping', 'sections'): '[]', ('ListGroup', 'closed'): 'false', ('ListClear', 'message'): '""', ('ListClear', 'confirm'): '"Delete"', ('DeletionWords', 'undo'): 'true', ('DeletionWords', 'confirm'): '"Delete"', ('DeletionWords', 'asks'): 'true', ('DeletionWords', 'bin'): 'false', ('RecentLayout', 'count'): '2', ('RecentLayout', 'over'): '3', ('ListFilter', 'tabs'): 'true', ('ListFilter', 'all'): '"all"', ('ListFilter', 'words'): '[:]', ('ListFilter', 'empty'): '[:]', ('ListLink', 'where'): '[:]', ('ListUpcoming', 'dates'): '[]', ('ListUpcoming', 'horizon'): '7', ('ChipRow', 'sends'): '[:]', ('CoverLayout', 'footer'): '[]', ('CoverLayout', 'bound'): 'false', ('AttachmentsLayout', 'editable'): 'true', ('AttachmentsLayout', 'sources'): '[.library, .camera]', ('PageSection', 'columns'): '[]', ('PageSection', 'above'): 'false', ('PageSection', 'actions'): '[]', ('PageSection', 'commands'): '[]', ('SectionList', 'face'): '.slip', ('SectionList', 'archived'): 'false', ('SectionList', 'with'): '[]', ('SectionList', 'where'): '[:]', ('LinkedSection', 'except'): '[]', ('ConversationLayout', 'can_send'): '.allowed(true)', ('ConversationLayout', 'header'): '[]', ('ConversationLayout', 'sends'): '[:]', ('ConversationLayout', 'header_columns'): '[]', ('ConversationLayout', 'also'): '[]', ('ConversationLayout', 'folds'): 'false', ('ConversationStarted', 'words'): '[]', ('ConversationSource', 'face'): '.note', ('SlipLayout', 'toggle_style'): '.check', ('SlipLayout', 'ordinal'): 'false', ('SlipCaption', 'columns'): '[]', ('SlipCaption', 'dates'): '[]', ('RecordAnswers', 'when'): '[]', ('RecordAnswers', 'leaves'): 'true', ('SectionAction', 'sets'): '[:]', ('SectionAction', 'delete'): 'false', ('ListCapture', 'page_only'): 'false',} | {('ListLink', key): 'false'for key in ['lead', 'above', 'review', 'hides_empty']} | {# A serde default function's value (`default = "yes"`), always written. ('PackageColumn', 'nullable'): 'true'}# A pre-existing native view keeps kind optional; the core's resolved answer# always supplies it. Theme drawing also accepts a partial family overlay.OPTIONAL = {('RecordCommand','kind'), ('ThemeDefinition','id')}def balanced(text, start, opening='{', closing='}'): depth, quoted, escaped = 0, False, Falsefor pos in range(start, len(text)): char = text[pos]if quoted:if escaped: escaped = Falseelif char == '\\': escaped = Trueelif char == '"': quoted = Falsecontinueif char == '"': quoted = Trueelif char == opening: depth += 1elif char == closing: depth -= 1if depth == 0: return posraiseValueError('unclosed Rust declaration')def split_types(text): out, start, depth = [], 0, 0for pos, char in enumerate(text):if char in'<{(': depth += 1elif char in'>})': depth -= 1elif char == ','and depth == 0: out.append(text[start:pos].strip()); start = pos + 1 out.append(text[start:].strip())return outdef rust_file(root, file):return root / 'crates' / file if'/'in file else root / 'crates/cotton-core/src/definitions' / filedef rust_module(file):if'/'notin file: return'cotton_core::definitions' crate, path = file.split('/src/')return crate.replace('-', '_') + '::' + path[:-3].replace('/', '::')def rust_name(model):return'::'.join(VARIANT_STRUCTS.get(model, (model,)))def fields(source, model):# Documentation carries no shape. Removing it first prevents examples in# comments from being mistaken for a declaration or attribute. source = re.sub(r'//[^\n]*', '', source)if model in VARIANT_STRUCTS: owner, variant = VARIANT_STRUCTS[model] match = re.search(r'\bpub enum ' + owner + r'\s*\{', source)ifnot match: raiseValueError(f'no Rust enum {owner}') start = source.index('{', match.start()) match = re.compile(r'\b' + variant + r'\s*\{').search(source, start, balanced(source, start))ifnot match: raiseValueError(f'no struct variant {owner}::{variant}')else: match = re.search(r'\bpub struct ' + model + r'\s*\{', source)ifnot match: raiseValueError(f'no named Rust struct {model}') start = source.index('{', match.start()) body = source[start+1:balanced(source, start)] result, pos = [], 0while pos < len(body):while pos < len(body) and body[pos].isspace(): pos += 1if pos == len(body): break attrs = []while body[pos:pos+2] == '#[': end = balanced(body, pos+1, '[', ']') attrs.append(body[pos:end+1]); pos = end+1while pos < len(body) and body[pos].isspace(): pos += 1# A struct variant's fields carry no visibility. field = re.match(r'(?:pub\s+)?(?:r#)?(\w+)\s*:\s*', body[pos:])ifnot field: raiseValueError(f'unsupported field in {model}: {body[pos:pos+100]}') name = field[1]; pos += field.end(); start = pos; depth = 0while pos < len(body): char = body[pos]if char == '<': depth += 1elif char == '>': depth -= 1elif char == ','and depth == 0: break pos += 1 rust = re.sub(r'\s+', '', body[start:pos]); pos += 1 attr = ' '.join(attrs) rename = re.search(r'\brename\s*=\s*"([^"]+)"', attr) key = rename[1] if rename else nameif re.search(r'\b(skip|skip_serializing|serialize_with|with)\s*(?:=|[,\)])', attr):raiseValueError(f'unsupported serde serialization for {model}.{name}: {attr}') result.append({'rust': rust, 'key': key, 'name': name, 'attr': attr})return resultdef camel(word):return re.sub(r'_([a-z])', lambda m: m[1].upper(), word)def identifier(word):# Swift keywords are legal field names when escaped.return'`' + word + '`'if word in {'type','default','where','when','extension','repeat','class','new','operator','case','init','switch'} else worddef swift_type(rust, model): match = re.fullmatch(r'(.+?)<(.*)>', rust) base = (match[1] if match else rust).split('::')[-1] args = split_types(match[2]) if match else []if base == 'Option': return swift_type(args[0], model) + '?'if base == 'Vec': return'[' + swift_type(args[0], model) + ']'if base in {'Map','BTreeMap','HashMap'}:if rust in BINDINGS.get(model, {}): return BINDINGS[model][rust]if args[0] != 'String': raiseValueError(f'non-string map key: {rust}')return'[String: ' + swift_type(args[1], model) + ']'if base in {'Value','Unknown'}:return'DefinitionJSONValue'if base == 'Value'else'[String: DefinitionJSONValue]'# A static string the core writes (`&'static str`) reads as any string.if base in {'String', "&'staticstr"}: return'String'if base == 'bool': return'Bool'if base == 'RunningNumber': return'Decimal'if base in {'f32','f64','Number'}: return'Double'if base in {'usize','u8','u16','u32','u64','i8','i16','i32','i64'}: return'Int'if base == FACE_ID[0]: return FACE_ID[1]if base in ENUMS or base in LOOK_ENUMS or base in VALUES_ENUMS or base in UNTAGGED or base in TAGGED or base == 'PlaceColumns': return'Definition' + base# OrderedMap's native drawing type must preserve authored argument order,# so a binding is named by the whole Rust spelling. bound = BINDINGS.get(model, {}).get(rust)if bound: return bound# An ordered map no binding names reads as a dictionary, as every native# reader takes it.if base == 'OrderedMap'and args[0].split('::')[-1] != 'Value':return'[String: ' + swift_type(args[0], model) + ']'if base in MODELS: return'Definition' + baseraiseValueError(f'{model} holds {rust}, which BINDINGS does not name')def model_info(root=ROOT): result = {}for model, file in MODELS.items(): declared = fields(rust_file(root, file).read_text(), model)for field in declared: field['swift'] = swift_type(field['rust'], model)if model == 'RecordCommand'and field['key'] == 'does': field['swift'] = 'String?'if model == 'Column'and field['key'] == 'default':# A column's default is drawn as a record value, not opaque JSON. field['swift'] = BINDINGS['Column']['serde_json::Value'] + '?' field['property'] = RENAMES.get((model, field['key']), camel(field['key'])) default = DEFAULTS.get((model,field['key']))if default andnot field['swift'].endswith('?'):# The value of a serde default function, which Rust always writes.ifnot re.search(r'default\s*=', field['attr']):raiseValueError(f'projection expects optional {model}.{field["key"]}') field['custom'] = Trueelif default: field['swift'] = field['swift'][:-1]elif (model,field['key']) in OPTIONAL andnot field['swift'].endswith('?'): field['swift'] += '?' field['default'] = default result[model] = declaredreturn resultJSON_VALUE = '''/// A serde_json::Value at the catalogue boundary, including unknown keys.public indirect enum DefinitionJSONValue: Codable, Hashable, Sendable { case null, bool(Bool), integer(Int64), unsigned(UInt64), number(Double), string(String) case array([DefinitionJSONValue]), object([String: DefinitionJSONValue]) public init(from decoder: Decoder) throws { let c = try decoder.singleValueContainer() if c.decodeNil() { self = .null } else if let value = try? c.decode(Bool.self) { self = .bool(value) } else if let value = try? c.decode(Int64.self) { self = .integer(value) } else if let value = try? c.decode(UInt64.self) { self = .unsigned(value) } else if let value = try? c.decode(Double.self) { self = .number(value) } else if let value = try? c.decode(String.self) { self = .string(value) } else if let value = try? c.decode([DefinitionJSONValue].self) { self = .array(value) } else { self = .object(try c.decode([String: DefinitionJSONValue].self)) } } // JSON numbers have one value regardless of whether a writer spelled an // integral value with a decimal point. Canonicalize equality/hash without // rounding a 64-bit integer through Double. private enum Numeric: Hashable { case signed(Int64), unsigned(UInt64), decimal(Double) } private var numeric: Numeric? { switch self { case .integer(let value): return .signed(value) case .unsigned(let value): return Int64(exactly: value).map(Numeric.signed) ?? .unsigned(value) case .number(let value): if let exact = Int64(exactly: value) { return .signed(exact) } if let exact = UInt64(exactly: value) { return .unsigned(exact) } return .decimal(value) default: return nil } } public static func == (lhs: Self, rhs: Self) -> Bool { if let a = lhs.numeric, let b = rhs.numeric { return a == b } switch (lhs, rhs) { case (.null, .null): return true case (.bool(let a), .bool(let b)): return a == b case (.string(let a), .string(let b)): return a == b case (.array(let a), .array(let b)): return a == b case (.object(let a), .object(let b)): return a == b default: return false } } public func hash(into hasher: inout Hasher) { if let numeric { hasher.combine(2); hasher.combine(numeric); return } switch self { case .null: hasher.combine(0) case .bool(let value): hasher.combine(1); hasher.combine(value) case .string(let value): hasher.combine(3); hasher.combine(value) case .array(let value): hasher.combine(4); hasher.combine(value) case .object(let value): hasher.combine(5); hasher.combine(value) case .integer, .unsigned, .number: break } } public func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer() switch self { case .null: try c.encodeNil() case .bool(let value): try c.encode(value) case .integer(let value): try c.encode(value) case .unsigned(let value): try c.encode(value) case .number(let value): try c.encode(value) case .string(let value): try c.encode(value) case .array(let value): try c.encode(value) case .object(let value): try c.encode(value) } }}public struct DefinitionCodingKey: CodingKey { public let stringValue: String public var intValue: Int? { nil } public init(_ value: String) { stringValue = value } public init?(stringValue: String) { self.stringValue = stringValue } public init?(intValue: Int) { return nil }}'''def enum_source(source, model): source = re.sub(r'//[^\n]*', '', source) match = re.search(r'\bpub enum ' + model + r'\s*\{',source)ifnot match: raiseValueError(f'no Rust enum {model}') start = source.index('{',match.start()) rule = rename_rule(source, match.start()) out = []for entry in source[start+1:balanced(source,start)].split(','): entry = entry.strip()ifnot entry: continue field = re.fullmatch(r'((?:#\[[^]]+\]\s*)*)([A-Za-z_][A-Za-z_0-9]*)',entry)ifnot field: raiseValueError(f'unsupported non-unit enum {model}: {entry}') attribute, name = field.groups() out.append((name[0].lower()+name[1:], wire_name(name, attribute, rule)))return outdef rename_rule(source, start):# Serde's rule is attached to this enum, after the preceding declaration. prefix = source[:start] attrs = prefix[max(prefix.rfind('}'), prefix.rfind(';'))+1:] rename = re.search(r'rename_all\s*=\s*"([^"]+)"', attrs)return rename[1] if rename elseNonedef wire_name(name, attribute, rule): explicit = re.search(r'rename\s*=\s*"([^"]+)"', attribute) words = re.findall(r'[A-Z]+(?=[A-Z][a-z]|$)|[A-Z]?[a-z]+|[0-9]+', name)if explicit: return explicit[1]if rule == 'lowercase': return name.lower()if rule == 'snake_case': return'_'.join(w.lower() for w in words)if rule == 'kebab-case': return'-'.join(w.lower() for w in words)if rule == 'camelCase': return words[0].lower() + ''.join(w.title() for w in words[1:])if rule isNone: return nameraiseValueError(f'unsupported serde enum casing: {rule}')def tagged_swift(root, model, file): source = re.sub(r'//[^\n]*', '', rust_file(root, file).read_text()) match = re.search(r'\bpub enum ' + model + r'\s*\{', source)ifnot match: raiseValueError(f'no Rust enum {model}')if re.search(r'\b(tag|content|untagged)\b', source[max(source[:match.start()].rfind('}'), 0):match.start()]):raiseValueError(f'{model} is not externally tagged') rule, start = rename_rule(source, match.start()), source.index('{', match.start()) variants = []for entry in split_types(source[start+1:balanced(source, start)]): entry = entry.strip()ifnot entry: continue variant = re.fullmatch(r'((?:#\[[^]]+\]\s*)*)([A-Za-z_]\w*)\s*\((.+)\)', entry, re.S)ifnot variant: raiseValueError(f'unsupported tagged variant {model}: {entry}') attribute, name, payload = variant.groups() variants.append((name[0].lower() + name[1:], wire_name(name, attribute, rule), swift_type(re.sub(r'\s+', '', payload), model))) out = [f'\n/// Storage of {rust_module(file)}::{model} (tagged: one key, the variant, holding its payload).', f'public enum Definition{model}: Codable, Hashable, Sendable {{'] out += [f' case {identifier(name)}({typ})'for name, _, typ in variants] out.append(' public enum CodingKeys: String, CodingKey, CaseIterable {') out += [f' case {identifier(name)} = "{wire}"'for name, wire, _ in variants] out.append(' }\n public init(from decoder: Decoder) throws {\n let c = try decoder.container(keyedBy: CodingKeys.self)') out.append(' guard c.allKeys.count == 1, let key = c.allKeys.first else {') out.append(f' throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "{model} is exactly one of ' + ', '.join(wire for _, wire, _ in variants) + '"))\n }\n switch key {') out += [f' case .{identifier(name)}: self = .{identifier(name)}(try c.decode({typ}.self, forKey: .{identifier(name)}))'for name, _, typ in variants] out.append(' }\n }\n public func encode(to encoder: Encoder) throws {\n var c = encoder.container(keyedBy: CodingKeys.self)\n switch self {') out += [f' case .{identifier(name)}(let value): try c.encode(value, forKey: .{identifier(name)})'for name, _, _ in variants] out.append(' }\n }\n}')return outdef untagged_source(source, model): source = re.sub(r'//[^\n]*', '', source) match = re.search(r'#\[serde\(untagged(?:,\s*deny_unknown_fields)?\)\]\s*pub enum ' + model + r'\s*\{', source)ifnot match: raiseValueError(f'no untagged Rust enum {model}') start = source.index('{', match.start()) out = []for entry in split_types(source[start+1:balanced(source, start)]):ifnot entry: continue variant = re.fullmatch(r'([A-Za-z_]\w*)\((.+)\)', re.sub(r'\s+', '', entry)) struct = re.fullmatch(r'([A-Za-z_]\w*)\s*\{.*\}', entry.strip(), re.S)if struct and model + struct[1] in VARIANT_STRUCTS: name = struct[1][0].lower() + struct[1][1:] out.append((VARIANTS.get((model, name), name), 'Definition' + model + struct[1]))continueifnot variant: raiseValueError(f'unsupported untagged variant {model}: {entry}') name = variant[1][0].lower() + variant[1][1:] out.append((VARIANTS.get((model, name), name), swift_type(variant[2], model)))return outdef untagged_swift(root, model, file): variants = untagged_source(rust_file(root, file).read_text(), model) out = [f'\n/// Storage of {rust_module(file)}::{model} (untagged: the first variant that reads).', f'public enum Definition{model}: Codable, Hashable, Sendable {{'] out += [f' case {identifier(name)}({typ})'for name, typ in variants] out.append(' public init(from decoder: Decoder) throws {\n let c = try decoder.singleValueContainer()')for name, typ in variants[:-1]: out.append(f' if let value = try? c.decode({typ}.self) {{ self = .{identifier(name)}(value); return }}') name, typ = variants[-1] out.append(f' self = .{identifier(name)}(try c.decode({typ}.self))\n }}') out.append(' public func encode(to encoder: Encoder) throws {\n var c = encoder.singleValueContainer()\n switch self {') out += [f' case .{identifier(name)}(let value): try c.encode(value)'for name, _ in variants] out.append(' }\n }\n}')return outdef enum_swift(root, model, file): variants = enum_source(rust_file(root, file).read_text(),model)return [f'\npublic enum Definition{model}: String, Codable, Hashable, CaseIterable, Sendable {{', *(f' case {identifier(name)} = "{wire}"'for name,wire in variants), '}']def face_id_swift(root): ids = json.loads((root / FACE_IDS.relative_to(ROOT)).read_text()) name = FACE_ID[1]return [f'''/// A face's open id (`card::FaceId`): the name a kit gives the face that/// draws a card. Any well-formed id reads — lowercase words of letters, digits/// and `_`, each a letter first, joined by `.` — so a face newer than this/// build is drawn plain; the faces this build knows are named below/// (apps/loom/faces.json and faces-pending.json).public struct {name}: RawRepresentable, Codable, Hashable, Sendable {{ public let rawValue: String /// `rawValue` as a face id, or nil when it is not one. public init?(rawValue: String) {{ let words = rawValue.split(separator: ".", omittingEmptySubsequences: false) let word: (Substring) -> Bool = {{ word in guard let first = word.unicodeScalars.first, ("a"..."z").contains(first) else {{ return false }} return word.unicodeScalars.allSatisfy {{ ("a"..."z").contains($0) || ("0"..."9").contains($0) || $0 == "_" }} }} guard words.allSatisfy(word) else {{ return nil }} self.rawValue = rawValue }} private init(_ known: String) {{ rawValue = known }} public init(from decoder: Decoder) throws {{ let c = try decoder.singleValueContainer() let raw = try c.decode(String.self) guard let id = {name}(rawValue: raw) else {{ throw DecodingError.dataCorruptedError(in: c, debugDescription: "\\(raw) is no face id") }} self = id }} public func encode(to encoder: Encoder) throws {{ var c = encoder.singleValueContainer() try c.encode(rawValue) }}''', *(f' public static let {identifier(camel(face.replace(".", "_")))} = {name}("{face}")'for face in ids), '}']def generate(root=ROOT, look=False, values=False):"""CottonUI's file, with `look` the look's (`LOOK_OUTPUT`), with `values` the plain values' (`VALUES_OUTPUT`).""" declarations = []# The definitions' types, and the computed ops they take from cotton-rules.for path in [*sorted((root / 'crates/cotton-core/src/definitions').glob('*.rs')), root / 'crates/cotton-rules/src/computed.rs']: source = re.sub(r'//[^\n]*', '', path.read_text())for match in re.finditer(r'(?:#\[[^]]*\]\s*)*\bpub (?:struct|enum) \w+[^;{]*\{',source): start = source.index('{', match.start()) declaration = source[match.start():balanced(source,start)+1] declarations.append(re.sub(r'\s+', '', declaration)) fingerprint = hashlib.sha256('\n'.join(declarations).encode()).hexdigest() head = ('// GENERATED by pnpm gen:swift-definitions. Never hand-edit.\n''// Inputs: Rust serde types under cotton-core/src/definitions and cotton-rules/src/computed.rs; no product data.\n' f'// Rust definition type fingerprint: {fingerprint}\n')if values:# Enums alone: no model, so neither the JSON value nor a bound type. out = [head + "// The plain values' half (`VALUES_ENUMS`): what a face is drawn by.\n""// CottonValues imports Foundation alone (guard loom-imports).\n"'import Foundation'] out.extend(face_id_swift(root))for model, file in VALUES_ENUMS.items(): out.extend(enum_swift(root, model, file))return'\n'.join(out) + '\n'if look: out = [head + "// The look's half (`LOOK_ENUMS`, `LOOK_MODELS`); CottonUI's\n""// `GeneratedDefinitionTypes.swift` holds every other definition type.\n"'import Foundation\n\n' + JSON_VALUE]for model, file in LOOK_ENUMS.items(): out.extend(enum_swift(root, model, file))else: out = [head + 'import CottonPaper\nimport CottonValues\nimport Foundation']for model, file in UNTAGGED.items(): out.extend(untagged_swift(root, model, file))for model, file in TAGGED.items(): out.extend(tagged_swift(root, model, file))for model, file in ENUMS.items(): out.extend(enum_swift(root, model, file))for model, declared in model_info(root).items():if (model in LOOK_MODELS) != look: continue access = ''if model in INTERNAL else'public ' out.append(f'\n/// Storage of {rust_module(MODELS[model])}::{rust_name(model)}.\n{access}struct Definition{model}: Codable, Hashable, Sendable {{') required = []for field in declared: prop, typ = identifier(field['property']), field['swift'] default = field['default']ifnot default:if typ.endswith('?'): default = 'nil'# A key Rust never reads (skip_deserializing) reads as its# default too: a row only carries it on the way out (fallbacks).elif'flatten'in field['attr'] or'default'in field['attr'] or'skip_deserializing'in field['attr']:if typ.startswith('['): default = '[:]'if': 'in typ else'[]'elif typ == 'Bool': default = 'false'elif typ == 'String': default = '""'elif typ in {'Int','Double'}:# Numeric custom defaults belong to the core; a resolved# catalogue supplies their value rather than omitting it.if re.search(r'default\s*=',field['attr']): default = Noneelse: default = '0'ifnot default: required.append(field) field['initial'] = default out.append(f' {access}var {prop}: {typ}' + (f' = {default}'if default else''))# Explicit native constructor permits helpers in another module to# delegate before applying presentation choices. args = ', '.join(f'{identifier(f["property"])}: {f["swift"]}'for f in required) out.append(f' {access}init(_generated: Void{", " if args else ""}{args}) {{')for field in required: prop = identifier(field['property']); out.append(f' self.{prop} = {prop}') out.append(' }') known = [f for f in declared if'flatten'notin f['attr']] out.append(f' {access}enum CodingKeys: String, CodingKey, CaseIterable {{')for field in known: out.append(f' case {identifier(field["property"])} = "{field["key"]}"') out.append(f' }}\n {access}init(from decoder: Decoder) throws {{\n let c = try decoder.container(keyedBy: CodingKeys.self)')for field in known: prop, typ = identifier(field['property']), field['swift'] optional = typ.endswith('?') decode = 'decodeIfPresent'if optional or field['initial'] else'decode' read_type = typ[:-1] if optional else typ default = f' ?? {field["initial"]}'if field['initial'] andnot optional else''if model.startswith('Theme') and optional: out.append(f' {prop} = try? c.{decode}({read_type}.self, forKey: .{prop})')elif model == 'Column'and field['key'] in {'computed', 'reach', 'format'}: out.append(f' {prop} = try? c.{decode}({read_type}.self, forKey: .{prop})')else: out.append(f' {prop} = try c.{decode}({read_type}.self, forKey: .{prop}){default}') flat = [f for f in declared if'flatten'in f['attr']]if flat:if len(flat) != 1: raiseValueError(f'multiple flattened maps: {model}') prop = identifier(flat[0]['property']) out.append(' let all = try decoder.container(keyedBy: DefinitionCodingKey.self)') out.append(' let known = Set(CodingKeys.allCases.map(\\.rawValue))') out.append(f' for key in all.allKeys where !known.contains(key.stringValue) {{\n {prop}[key.stringValue] = try all.decode(DefinitionJSONValue.self, forKey: key)\n }}') out.append(f' }}\n {access}func encode(to encoder: Encoder) throws {{\n var c = encoder.container(keyedBy: CodingKeys.self)')for field in known: prop, typ, attr = identifier(field['property']), field['swift'], field['attr']# A written optional writes its absence as null, as serde does. method = 'encodeIfPresent'if typ.endswith('?') and (model, field['key']) notin WRITTEN else'encode' line = f'try c.{method}({prop}, forKey: .{prop})'if (model, field['key']) in WRITTEN or field.get('custom'):passelif field['default'] and field['default'] in {'[]','[:]'}: line = f'if !{prop}.isEmpty {{ {line} }}'elif field['default']:# Rust omits the absent value this default reads it as. line = f'if {prop} != {field["default"]} {{ {line} }}'elif'Vec::is_empty'in attr andnot typ.endswith('?'): line = f'if !{prop}.isEmpty {{ {line} }}'elif'Not::not'in attr: line = f'if {prop} {{ {line} }}' out.append(' ' + line)if flat: prop = identifier(flat[0]['property']) out.append(' var all = encoder.container(keyedBy: DefinitionCodingKey.self)') out.append(' let known = Set(CodingKeys.allCases.map(\\.rawValue))') out.append(f' for (key, value) in {prop} where !known.contains(key) {{\n try all.encode(value, forKey: DefinitionCodingKey(key))\n }}') out.append(' }\n}')return'\n'.join(out) + '\n'def swift_code(source):"""Mask comments and Swift strings, keeping declaration positions/newlines.""" out, pos = [], 0while pos < len(source): start = posif source.startswith('//', pos): end = source.find('\n', pos) pos = len(source) if end < 0else endelif source.startswith('/*',pos): pos += 2; depth = 1while depth and pos < len(source):if source.startswith('/*',pos): depth += 1; pos += 2elif source.startswith('*/',pos): depth -= 1; pos += 2else: pos += 1else: match = re.match(r'(#{0,})("""|")',source[pos:])ifnot match: out.append(source[pos]); pos += 1; continue hashes, quotes = match.groups() pos += match.end(); close = quotes + hasheswhile pos < len(source):if source.startswith(close,pos): pos += len(close); breakifnot hashes and source[pos] == '\\': pos += 2else: pos += 1 out.append(''.join('\n'if c == '\n'else' 'for c in source[start:pos]))return''.join(out)# A Swift struct whose fields happen to be a model's, read from a different# wire type: named here with that type, so the scan stays exact for the rest.UNRELATED = { ('Colours', 'ThemePalettes'): "look's answer (LookAnswer.Colours: the app's colour tokens by appearance, as the core's `look` says them), not a theme definition's palettes", ('Line', 'BoardPart'): "story.lines' answer (StoryCore's Lines.Line: one line's screenplay kind), not a board part", ('Option', 'PageAct'): "a create question's answer (the store's question), not a page act", ('Act', 'PageAct'): "Cinemas' own acts (CinemasShapes' Act: an act's id and the core's label), not a page act", ('Said', 'TableViewer'): "count.words' answer (one resolved `words` string), not a table's viewer", ('Face', 'PageAct'): "shell.player's face choices (PlayerAnswer.Face: a face id and its label), not a page act", ('Mark', 'PageAct'): "shell.stream's mark on a chat (StreamAnswer.Mark: a mark id and its label), not a page act", ('ReaderSeekSaid', 'TableViewer'): "reader.seek.say's answer (the slip's resolved `words` string for a dragged place), not a table's viewer", ('Kind', 'BoardPart'): "PlayerAnswer's peek at what is playing (`now.kind`, song or not) before it decodes the rest, not a board part", ('Bringing', 'TableViewer'): "HomeAnswer's arriving line (the core's resolved `words` while a signed-in phone's rows are still coming, d33d191f2), not a table's viewer", ('Made', 'TableViewer'): "Days' invented seed row (days-dev-seed.json's `made`: words, a day offset, a time, a mark), not a table's viewer", ('Icon', 'PageAct'): "Notes' icon choices (notes.icons: an icon id and its label), not a page act",}def scan(root=ROOT):# Compare stored property sets as well as names: renaming a second wire# declaration does not evade the guard. Computed view wrappers are allowed. shapes = []for model, declared in model_info(root).items(): shapes.append((model, {f['property'] for f in declared})) shapes.append((model, {f['key'] for f in declared})) shapes.append((model, {f['property'] for f in declared if'flatten'notin f['attr']})) shapes.append((model, {f['key'] for f in declared if'flatten'notin f['attr']})) violations = []for path in (root / 'apps/cotton/Sources').rglob('*.swift'):if path in {root / out.relative_to(ROOT) for out in (OUTPUT, LOOK_OUTPUT, VALUES_OUTPUT)}: continue source = swift_code(path.read_text())for match in re.finditer(r'\bstruct\s+(\w+)[^{]*\{', source): name = match[1]ifnot re.search(r'\b(?:Codable|Decodable)\b', match[0]) and name notin {'Stored', 'ThemeRowForm'}:continue start = source.index('{', match.start()) body = source[start+1:balanced(source, start)]# Keep only the declaration's own depth, excluding nested helpers,# computed properties, initializer locals and nested types. direct, depth, quoted, escaped = [], 0, False, Falsefor char in body:if quoted:if escaped: escaped = Falseelif char == '\\': escaped = Trueelif char == '"': quoted = Falseelif char == '"': quoted = Trueelif char == '{': depth += 1elif char == '}': depth -= 1if depth == 0: direct.append(char)elif char == '\n': direct.append('\n') fields = set(re.findall(r'^\s*(?:(?:public|private|internal|fileprivate|package)\s+)?(?:var|let)\s+`?(\w+)`?\s*:[^\n{]+(?:\n|$)', ''.join(direct), re.M))# Any computed accessor has its opening brace removed above; its# declaration line is excluded by checking the original line. computed = set(re.findall(r'^\s*(?:(?:public|private|internal|fileprivate|package)\s+)?var\s+`?(\w+)`?\s*:[^\n{]+\{',body,re.M)) fields -= computedif name in {'Stored','ThemeRowForm','RecordCommand'} or name.startswith('Definition') and name[10:] in MODELS: violations.append(f'{path}: {name} is handwritten wire storage')for model, expected in shapes:if fields == expected and (name, model) notin UNRELATED: violations.append(f'{path}: {name} repeats {model}')if violations: raiseValueError('Handwritten definition storage twins: ' + ', '.join(sorted(set(violations))))def stored(source):"""Each generated type's stored properties, by Rust name: {model: {property: line}}.""" out, model = {}, Nonefor line in source.splitlines(): head = re.match(r'(?:public )?(?:struct|enum) Definition(\w+)', line)if head: model = head[1]; out[model] = {}; continueif model and line == '}': model = None; continue prop = re.match(r' (?:(?:public )?var (`?\w+`?): .*|case (`?\w+`?)(?: = |\().*)$', line)if model and prop: out[model][prop[1] or prop[2]] = line.strip()return outdef drift(held, fresh):"""Name what moved, so a Rust field added without regenerating says which.""" before, after, said = stored(held), stored(fresh), []for model in sorted(set(before) | set(after)):if model notin before: said.append(f'new Rust type {model}'); continueif model notin after: said.append(f'Rust type {model} is gone'); continue old, new = before[model], after[model] said += [f'{model}.{p} added in Rust'for p in new if p notin old] said += [f'{model}.{p} removed in Rust'for p in old if p notin new] said += [f'{model}.{p} changed in Rust ({new[p]})'for p in new if p in old and old[p] != new[p]]return': ' + '; '.join(said) if said else' (coders or header only)'def main(): parser = argparse.ArgumentParser() parser.add_argument('--check',action='store_true') parser.add_argument('--scan',action='store_true') args = parser.parse_args()if args.scan: scan(); returnfor output, fresh in ((OUTPUT, generate()), (LOOK_OUTPUT, generate(look=True)), (VALUES_OUTPUT, generate(values=True))):if args.check: held = output.read_text() if output.exists() else''if held != fresh:raiseValueError('Generated Swift definitions drifted' + drift(held, fresh) + '. Run: pnpm gen:swift-definitions')continueifnot output.exists() or output.read_text() != fresh: output.parent.mkdir(parents=True, exist_ok=True) output.write_text(fresh)if __name__ == '__main__': main()