// Version 4.1.1 // // Part of the Dialect project: // https://github.com/OGStudio/dialect // // GENERATED by util/package-generator-script - do not edit. // Reusable "none" constant public let DIALECT_CONTEXT_RECENT_FIELD_NONE = "none" // Base protocol for each component's state public protocol DialectContext { var recentField: String { get set } func field(_ name: String) -> T func fieldAny(_ name: String) -> Any mutating func setField(_ name: String, _ value: Any) } // Default implementation of `fieldAny` method for the protocol public extension DialectContext { func fieldAny(_ name: String) -> Any { return field(name) } } // The engine of the dialect components public class DialectController { var callbacks = [(DialectContext) -> Void]() var context: DialectContext var functions = [(DialectContext) -> DialectContext]() var isProcessingQueue = false var queue = [DialectContext]() public init(_ context: DialectContext) { self.context = context } func executeFunctions() { let c = queue.removeFirst() // Keep SSOT: Only allow single field change per should-function context.recentField = c.recentField context.setField(c.recentField, c.fieldAny(c.recentField)) for f in functions { let ctx = f(context) if ctx.recentField != DIALECT_CONTEXT_RECENT_FIELD_NONE { queue.append(ctx) } } reportContext() } func processQueue() { // Prevent recursion. if isProcessingQueue { return } isProcessingQueue = true while (queue.count > 0) { executeFunctions() } isProcessingQueue = false } public func registerCallback(_ cb: @escaping (DialectContext) -> Void) { callbacks.append(cb) } public func registerFieldCallback( _ fieldName: String, _ cb: @escaping (DialectContext) -> Void ) { callbacks.append({ c in if c.recentField == fieldName { cb(c) } }) } public func registerFunction(_ f: @escaping (DialectContext) -> DialectContext) { functions.append(f) } func reportContext() { for cb in callbacks { cb(context) } } public func set( _ fieldName: String, _ value: Any ) { var c = context c.setField(fieldName, value) c.recentField = fieldName queue.append(c) processQueue() } } // Register several oneliner callbacks to a controller func registerOneliners( _ ctrl: DialectController, _ items: [Any] ) -> T? { let halfCount = items.count / 2 for i in 0.. Void ctrl.registerFieldCallback(field) { cc in let c = cc as! T callback(c) } } // A hack for generics to operate return nil } // Context field names for static type check public struct F { public static let about = "about" public static let arguments = "arguments" public static let body = "body" public static let chunks = "chunks" public static let cliDidConsoleOutput = "cliDidConsoleOutput" public static let condition = "condition" public static let consoleOutput = "consoleOutput" public static let contents = "contents" public static let didLaunch = "didLaunch" public static let didSetup = "didSetup" public static let didWriteFile = "didWriteFile" public static let dstQueue = "dstQueue" public static let entities = "entities" public static let entityFieldTypes = "entityFieldTypes" public static let entityFields = "entityFields" public static let entityOneliners = "entityOneliners" public static let entityShouldBranches = "entityShouldBranches" public static let entityShoulds = "entityShoulds" public static let entityTypes = "entityTypes" public static let field = "field" public static let filesCount = "filesCount" public static let headers = "headers" public static let inputAbsoluteDir = "inputAbsoluteDir" public static let inputContents = "inputContents" public static let inputError = "inputError" public static let inputFileName = "inputFileName" public static let inputLines = "inputLines" public static let isConvertingOneliners = "isConvertingOneliners" public static let isConvertingShoulds = "isConvertingShoulds" public static let llmError = "llmError" public static let method = "method" public static let out = "out" public static let outContexts = "outContexts" public static let outFields = "outFields" public static let outKotlin = "outKotlin" public static let outRegisterEffects = "outRegisterEffects" public static let outRegisterShoulds = "outRegisterShoulds" public static let outSets = "outSets" public static let outShoulds = "outShoulds" public static let outStructs = "outStructs" public static let outSwift = "outSwift" public static let outputPaths = "outputPaths" public static let parseInput = "parseInput" public static let path = "path" public static let prompt = "prompt" public static let reaction = "reaction" public static let readFile = "readFile" public static let reply = "reply" public static let req = "req" public static let request = "request" public static let response = "response" public static let responseError = "responseError" public static let srcId = "srcId" public static let srcQueue = "srcQueue" public static let transpiledOneliners = "transpiledOneliners" public static let transpiledShouldBranches = "transpiledShouldBranches" public static let type = "type" public static let url = "url" public static let version = "version" public static let willGenerate = "willGenerate" public static let willShutdown = "willShutdown" } public struct NetRequest { public var body = String() public var headers = [String: String]() public var method = String() public var url = String() } public struct NetResponse { public var contents = String() public var req = NetRequest() } public struct Oneliner { public var field = String() public var reaction = String() } public struct OutputPath { public var path = String() public var type = String() } public struct ShouldBranch { public var about = String() public var condition = [String]() public var reaction = [String]() } public struct CLIContext: DialectContext { public var arguments = [String]() public var consoleOutput = String() public var didLaunch = Bool() public var didSetup = Bool() public var inputAbsoluteDir = String() public var inputContents = String() public var inputError = String() public var inputFileName = String() public var readFile = Bool() public var recentField = "" public func field(_ name: String) -> T { if (name == "arguments") { return arguments as! T } else if (name == "consoleOutput") { return consoleOutput as! T } else if (name == "didLaunch") { return didLaunch as! T } else if (name == "didSetup") { return didSetup as! T } else if (name == "inputAbsoluteDir") { return inputAbsoluteDir as! T } else if (name == "inputContents") { return inputContents as! T } else if (name == "inputError") { return inputError as! T } else if (name == "inputFileName") { return inputFileName as! T } else if (name == "readFile") { return readFile as! T } return "unknown-field-name" as! T } public mutating func setField( _ name: String, _ value: Any ) { if (name == "arguments") { arguments = value as! [String] } else if (name == "consoleOutput") { consoleOutput = value as! String } else if (name == "didLaunch") { didLaunch = value as! Bool } else if (name == "didSetup") { didSetup = value as! Bool } else if (name == "inputAbsoluteDir") { inputAbsoluteDir = value as! String } else if (name == "inputContents") { inputContents = value as! String } else if (name == "inputError") { inputError = value as! String } else if (name == "inputFileName") { inputFileName = value as! String } else if (name == "readFile") { readFile = value as! Bool } } } public struct ConvContext: DialectContext { public var didLaunch = Bool() public var didSetup = Bool() public var dstQueue = [String]() public var entityOneliners = [Int: [Oneliner]]() public var entityShouldBranches = [Int: [Int: [ShouldBranch]]]() public var isConvertingOneliners = Bool() public var isConvertingShoulds = Bool() public var prompt = String() public var reply = String() public var srcId = Int() public var srcQueue = [String]() public var transpiledOneliners = [Int: [Oneliner]]() public var transpiledShouldBranches = [Int: [Int: [ShouldBranch]]]() public var willGenerate = Bool() public var recentField = "" public func field(_ name: String) -> T { if (name == "didLaunch") { return didLaunch as! T } else if (name == "didSetup") { return didSetup as! T } else if (name == "dstQueue") { return dstQueue as! T } else if (name == "entityOneliners") { return entityOneliners as! T } else if (name == "entityShouldBranches") { return entityShouldBranches as! T } else if (name == "isConvertingOneliners") { return isConvertingOneliners as! T } else if (name == "isConvertingShoulds") { return isConvertingShoulds as! T } else if (name == "prompt") { return prompt as! T } else if (name == "reply") { return reply as! T } else if (name == "srcId") { return srcId as! T } else if (name == "srcQueue") { return srcQueue as! T } else if (name == "transpiledOneliners") { return transpiledOneliners as! T } else if (name == "transpiledShouldBranches") { return transpiledShouldBranches as! T } else if (name == "willGenerate") { return willGenerate as! T } return "unknown-field-name" as! T } public mutating func setField( _ name: String, _ value: Any ) { if (name == "didLaunch") { didLaunch = value as! Bool } else if (name == "didSetup") { didSetup = value as! Bool } else if (name == "dstQueue") { dstQueue = value as! [String] } else if (name == "entityOneliners") { entityOneliners = value as! [Int: [Oneliner]] } else if (name == "entityShouldBranches") { entityShouldBranches = value as! [Int: [Int: [ShouldBranch]]] } else if (name == "isConvertingOneliners") { isConvertingOneliners = value as! Bool } else if (name == "isConvertingShoulds") { isConvertingShoulds = value as! Bool } else if (name == "prompt") { prompt = value as! String } else if (name == "reply") { reply = value as! String } else if (name == "srcId") { srcId = value as! Int } else if (name == "srcQueue") { srcQueue = value as! [String] } else if (name == "transpiledOneliners") { transpiledOneliners = value as! [Int: [Oneliner]] } else if (name == "transpiledShouldBranches") { transpiledShouldBranches = value as! [Int: [Int: [ShouldBranch]]] } else if (name == "willGenerate") { willGenerate = value as! Bool } } } public struct GeneratorContext: DialectContext { public var cliDidConsoleOutput = Bool() public var consoleOutput = String() public var didWriteFile = Bool() public var filesCount = Int() public var inputAbsoluteDir = String() public var llmError = String() public var out = String() public var outputPaths = [OutputPath]() public var outKotlin = String() public var outSwift = String() public var path = String() public var willShutdown = Bool() public var recentField = "" public func field(_ name: String) -> T { if (name == "cliDidConsoleOutput") { return cliDidConsoleOutput as! T } else if (name == "consoleOutput") { return consoleOutput as! T } else if (name == "didWriteFile") { return didWriteFile as! T } else if (name == "filesCount") { return filesCount as! T } else if (name == "inputAbsoluteDir") { return inputAbsoluteDir as! T } else if (name == "llmError") { return llmError as! T } else if (name == "out") { return out as! T } else if (name == "outputPaths") { return outputPaths as! T } else if (name == "outKotlin") { return outKotlin as! T } else if (name == "outSwift") { return outSwift as! T } else if (name == "path") { return path as! T } else if (name == "willShutdown") { return willShutdown as! T } return "unknown-field-name" as! T } public mutating func setField( _ name: String, _ value: Any ) { if (name == "cliDidConsoleOutput") { cliDidConsoleOutput = value as! Bool } else if (name == "consoleOutput") { consoleOutput = value as! String } else if (name == "didWriteFile") { didWriteFile = value as! Bool } else if (name == "filesCount") { filesCount = value as! Int } else if (name == "inputAbsoluteDir") { inputAbsoluteDir = value as! String } else if (name == "llmError") { llmError = value as! String } else if (name == "out") { out = value as! String } else if (name == "outputPaths") { outputPaths = value as! [OutputPath] } else if (name == "outKotlin") { outKotlin = value as! String } else if (name == "outSwift") { outSwift = value as! String } else if (name == "path") { path = value as! String } else if (name == "willShutdown") { willShutdown = value as! Bool } } } public struct KotlinContext: DialectContext { public var didLaunch = Bool() public var didSetup = Bool() public var entities = [String]() public var entityFields = [Int: [String]]() public var entityFieldTypes = [Int: [Int: String]]() public var entityOneliners = [Int: [Oneliner]]() public var entityShouldBranches = [Int: [Int: [ShouldBranch]]]() public var entityShoulds = [Int: [String]]() public var entityTypes = [Int: String]() public var out = String() public var outContexts = String() public var outFields = String() public var outputPaths = [OutputPath]() public var outRegisterEffects = String() public var outRegisterShoulds = String() public var outSets = String() public var outShoulds = String() public var outStructs = String() public var transpiledOneliners = [Int: [Oneliner]]() public var transpiledShouldBranches = [Int: [Int: [ShouldBranch]]]() public var willGenerate = Bool() public var recentField = "" public func field(_ name: String) -> T { if (name == "didLaunch") { return didLaunch as! T } else if (name == "didSetup") { return didSetup as! T } else if (name == "entities") { return entities as! T } else if (name == "entityFields") { return entityFields as! T } else if (name == "entityFieldTypes") { return entityFieldTypes as! T } else if (name == "entityOneliners") { return entityOneliners as! T } else if (name == "entityShouldBranches") { return entityShouldBranches as! T } else if (name == "entityShoulds") { return entityShoulds as! T } else if (name == "entityTypes") { return entityTypes as! T } else if (name == "out") { return out as! T } else if (name == "outContexts") { return outContexts as! T } else if (name == "outFields") { return outFields as! T } else if (name == "outputPaths") { return outputPaths as! T } else if (name == "outRegisterEffects") { return outRegisterEffects as! T } else if (name == "outRegisterShoulds") { return outRegisterShoulds as! T } else if (name == "outSets") { return outSets as! T } else if (name == "outShoulds") { return outShoulds as! T } else if (name == "outStructs") { return outStructs as! T } else if (name == "transpiledOneliners") { return transpiledOneliners as! T } else if (name == "transpiledShouldBranches") { return transpiledShouldBranches as! T } else if (name == "willGenerate") { return willGenerate as! T } return "unknown-field-name" as! T } public mutating func setField( _ name: String, _ value: Any ) { if (name == "didLaunch") { didLaunch = value as! Bool } else if (name == "didSetup") { didSetup = value as! Bool } else if (name == "entities") { entities = value as! [String] } else if (name == "entityFields") { entityFields = value as! [Int: [String]] } else if (name == "entityFieldTypes") { entityFieldTypes = value as! [Int: [Int: String]] } else if (name == "entityOneliners") { entityOneliners = value as! [Int: [Oneliner]] } else if (name == "entityShouldBranches") { entityShouldBranches = value as! [Int: [Int: [ShouldBranch]]] } else if (name == "entityShoulds") { entityShoulds = value as! [Int: [String]] } else if (name == "entityTypes") { entityTypes = value as! [Int: String] } else if (name == "out") { out = value as! String } else if (name == "outContexts") { outContexts = value as! String } else if (name == "outFields") { outFields = value as! String } else if (name == "outputPaths") { outputPaths = value as! [OutputPath] } else if (name == "outRegisterEffects") { outRegisterEffects = value as! String } else if (name == "outRegisterShoulds") { outRegisterShoulds = value as! String } else if (name == "outSets") { outSets = value as! String } else if (name == "outShoulds") { outShoulds = value as! String } else if (name == "outStructs") { outStructs = value as! String } else if (name == "transpiledOneliners") { transpiledOneliners = value as! [Int: [Oneliner]] } else if (name == "transpiledShouldBranches") { transpiledShouldBranches = value as! [Int: [Int: [ShouldBranch]]] } else if (name == "willGenerate") { willGenerate = value as! Bool } } } public struct LLMContext: DialectContext { public var didLaunch = Bool() public var didSetup = Bool() public var prompt = String() public var reply = String() public var request = NetRequest() public var response = NetResponse() public var responseError = NetResponse() public var recentField = "" public func field(_ name: String) -> T { if (name == "didLaunch") { return didLaunch as! T } else if (name == "didSetup") { return didSetup as! T } else if (name == "prompt") { return prompt as! T } else if (name == "reply") { return reply as! T } else if (name == "request") { return request as! T } else if (name == "response") { return response as! T } else if (name == "responseError") { return responseError as! T } return "unknown-field-name" as! T } public mutating func setField( _ name: String, _ value: Any ) { if (name == "didLaunch") { didLaunch = value as! Bool } else if (name == "didSetup") { didSetup = value as! Bool } else if (name == "prompt") { prompt = value as! String } else if (name == "reply") { reply = value as! String } else if (name == "request") { request = value as! NetRequest } else if (name == "response") { response = value as! NetResponse } else if (name == "responseError") { responseError = value as! NetResponse } } } public struct SwiftContext: DialectContext { public var didLaunch = Bool() public var didSetup = Bool() public var entities = [String]() public var entityFields = [Int: [String]]() public var entityFieldTypes = [Int: [Int: String]]() public var entityOneliners = [Int: [Oneliner]]() public var entityShouldBranches = [Int: [Int: [ShouldBranch]]]() public var entityShoulds = [Int: [String]]() public var entityTypes = [Int: String]() public var out = String() public var outContexts = String() public var outFields = String() public var outRegisterEffects = String() public var outRegisterShoulds = String() public var outSets = String() public var outShoulds = String() public var outStructs = String() public var recentField = "" public func field(_ name: String) -> T { if (name == "didLaunch") { return didLaunch as! T } else if (name == "didSetup") { return didSetup as! T } else if (name == "entities") { return entities as! T } else if (name == "entityFields") { return entityFields as! T } else if (name == "entityFieldTypes") { return entityFieldTypes as! T } else if (name == "entityOneliners") { return entityOneliners as! T } else if (name == "entityShouldBranches") { return entityShouldBranches as! T } else if (name == "entityShoulds") { return entityShoulds as! T } else if (name == "entityTypes") { return entityTypes as! T } else if (name == "out") { return out as! T } else if (name == "outContexts") { return outContexts as! T } else if (name == "outFields") { return outFields as! T } else if (name == "outRegisterEffects") { return outRegisterEffects as! T } else if (name == "outRegisterShoulds") { return outRegisterShoulds as! T } else if (name == "outSets") { return outSets as! T } else if (name == "outShoulds") { return outShoulds as! T } else if (name == "outStructs") { return outStructs as! T } return "unknown-field-name" as! T } public mutating func setField( _ name: String, _ value: Any ) { if (name == "didLaunch") { didLaunch = value as! Bool } else if (name == "didSetup") { didSetup = value as! Bool } else if (name == "entities") { entities = value as! [String] } else if (name == "entityFields") { entityFields = value as! [Int: [String]] } else if (name == "entityFieldTypes") { entityFieldTypes = value as! [Int: [Int: String]] } else if (name == "entityOneliners") { entityOneliners = value as! [Int: [Oneliner]] } else if (name == "entityShouldBranches") { entityShouldBranches = value as! [Int: [Int: [ShouldBranch]]] } else if (name == "entityShoulds") { entityShoulds = value as! [Int: [String]] } else if (name == "entityTypes") { entityTypes = value as! [Int: String] } else if (name == "out") { out = value as! String } else if (name == "outContexts") { outContexts = value as! String } else if (name == "outFields") { outFields = value as! String } else if (name == "outRegisterEffects") { outRegisterEffects = value as! String } else if (name == "outRegisterShoulds") { outRegisterShoulds = value as! String } else if (name == "outSets") { outSets = value as! String } else if (name == "outShoulds") { outShoulds = value as! String } else if (name == "outStructs") { outStructs = value as! String } } } public struct YMLContext: DialectContext { public var chunks = [String: [String]]() public var didLaunch = Bool() public var didSetup = Bool() public var entities = [String]() public var entityFields = [Int: [String]]() public var entityFieldTypes = [Int: [Int: String]]() public var entityOneliners = [Int: [Oneliner]]() public var entityShouldBranches = [Int: [Int: [ShouldBranch]]]() public var entityShoulds = [Int: [String]]() public var entityTypes = [Int: String]() public var inputContents = String() public var inputLines = [String]() public var outputPaths = [OutputPath]() public var parseInput = Bool() public var version = Int() public var recentField = "" public func field(_ name: String) -> T { if (name == "chunks") { return chunks as! T } else if (name == "didLaunch") { return didLaunch as! T } else if (name == "didSetup") { return didSetup as! T } else if (name == "entities") { return entities as! T } else if (name == "entityFields") { return entityFields as! T } else if (name == "entityFieldTypes") { return entityFieldTypes as! T } else if (name == "entityOneliners") { return entityOneliners as! T } else if (name == "entityShouldBranches") { return entityShouldBranches as! T } else if (name == "entityShoulds") { return entityShoulds as! T } else if (name == "entityTypes") { return entityTypes as! T } else if (name == "inputContents") { return inputContents as! T } else if (name == "inputLines") { return inputLines as! T } else if (name == "outputPaths") { return outputPaths as! T } else if (name == "parseInput") { return parseInput as! T } else if (name == "version") { return version as! T } return "unknown-field-name" as! T } public mutating func setField( _ name: String, _ value: Any ) { if (name == "chunks") { chunks = value as! [String: [String]] } else if (name == "didLaunch") { didLaunch = value as! Bool } else if (name == "didSetup") { didSetup = value as! Bool } else if (name == "entities") { entities = value as! [String] } else if (name == "entityFields") { entityFields = value as! [Int: [String]] } else if (name == "entityFieldTypes") { entityFieldTypes = value as! [Int: [Int: String]] } else if (name == "entityOneliners") { entityOneliners = value as! [Int: [Oneliner]] } else if (name == "entityShouldBranches") { entityShouldBranches = value as! [Int: [Int: [ShouldBranch]]] } else if (name == "entityShoulds") { entityShoulds = value as! [Int: [String]] } else if (name == "entityTypes") { entityTypes = value as! [Int: String] } else if (name == "inputContents") { inputContents = value as! String } else if (name == "inputLines") { inputLines = value as! [String] } else if (name == "outputPaths") { outputPaths = value as! [OutputPath] } else if (name == "parseInput") { parseInput = value as! Bool } else if (name == "version") { version = value as! Int } } } public func cliSet( _ key: String, _ value: Any ) { CLIComponent.singleton!.ctrl.set(key, value) } public func convSet( _ key: String, _ value: Any ) { ConvComponent.singleton!.ctrl.set(key, value) } public func generatorSet( _ key: String, _ value: Any ) { GeneratorComponent.singleton!.ctrl.set(key, value) } public func kotlinSet( _ key: String, _ value: Any ) { KotlinComponent.singleton!.ctrl.set(key, value) } public func llmSet( _ key: String, _ value: Any ) { LLMComponent.singleton!.ctrl.set(key, value) } public func swiftSet( _ key: String, _ value: Any ) { SwiftComponent.singleton!.ctrl.set(key, value) } public func ymlSet( _ key: String, _ value: Any ) { YMLComponent.singleton!.ctrl.set(key, value) } func cliShouldResetConsoleOutput(_ c: CLIContext) -> CLIContext { var c = c /* 1. File argument was not found */ if c.recentField == F.didLaunch && cliArgumentValue(c.arguments, CLI_ARG_FILE).isEmpty { c.consoleOutput = CLI_CONSOLE_USAGE c.recentField = F.consoleOutput return c } /* 2. Could not open input file */ if c.recentField == F.inputError { c.consoleOutput = CLI_CONSOLE_INPUT_FILE_ERROR c.recentField = F.consoleOutput return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func cliShouldResetDidLaunch(_ c: CLIContext) -> CLIContext { var c = c /* 1. Only once during the first setup */ if c.recentField == F.didSetup && c.didLaunch == false { c.didLaunch = true c.recentField = F.didLaunch return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func cliShouldResetInputFileName(_ c: CLIContext) -> CLIContext { var c = c /* 1. Get file name by parsing aguments */ if c.recentField == F.arguments && cliArgumentValue(c.arguments, CLI_ARG_FILE) != "" { c.inputFileName = cliArgumentValue(c.arguments, CLI_ARG_FILE) c.recentField = F.inputFileName return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func cliShouldResetReadFile(_ c: CLIContext) -> CLIContext { var c = c /* 1. File name has been specified */ if c.recentField == F.didLaunch && !c.inputFileName.isEmpty { c.readFile = true c.recentField = F.readFile return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func convShouldResetDidLaunch(_ c: ConvContext) -> ConvContext { var c = c /* 1. Only once during the first setup */ if c.recentField == F.didSetup && c.didLaunch == false { c.didLaunch = true c.recentField = F.didLaunch return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func convShouldResetDstQueue(_ c: ConvContext) -> ConvContext { var c = c /* 1. Upon new queue to transpile */ if c.recentField == F.srcQueue { c.dstQueue = [] c.recentField = F.dstQueue return c } /* 2. Upon LLM reply */ if c.recentField == F.reply { c.dstQueue.append(c.reply) c.recentField = F.dstQueue return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func convShouldResetIsConvertingOneliners(_ c: ConvContext) -> ConvContext { var c = c /* 1. Upon transpiled shoulds */ if c.recentField == F.transpiledShouldBranches { c.isConvertingOneliners = true c.recentField = F.isConvertingOneliners return c } /* 2. Upon oneliners' transpilation completion */ if c.recentField == F.dstQueue && c.isConvertingOneliners && c.dstQueue.count == c.srcQueue.count { c.isConvertingOneliners = false c.recentField = F.isConvertingOneliners return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func convShouldResetIsConvertingShoulds(_ c: ConvContext) -> ConvContext { var c = c /* 1. If going to generate */ if c.recentField == F.willGenerate && c.willGenerate { c.isConvertingShoulds = true c.recentField = F.isConvertingShoulds return c } /* 2. Upon shoulds' transpilation completion */ if c.recentField == F.dstQueue && c.isConvertingShoulds && c.dstQueue.count == c.srcQueue.count { c.isConvertingShoulds = false c.recentField = F.isConvertingShoulds return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func convShouldResetPrompt(_ c: ConvContext) -> ConvContext { var c = c /* 1. Upon getting new source to transpile */ if c.recentField == F.srcId { c.prompt = convQueuePrompt(c.srcQueue, c.srcId) c.recentField = F.prompt return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func convShouldResetSrcId(_ c: ConvContext) -> ConvContext { var c = c /* 1. Upon new queue to transpile */ if c.recentField == F.srcQueue { c.srcId = 0 c.recentField = F.srcId return c } /* 2. Upon transpiled reply */ if c.recentField == F.reply && c.srcId + 1 < c.srcQueue.count { c.srcId += 1 c.recentField = F.srcId return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func convShouldResetSrcQueue(_ c: ConvContext) -> ConvContext { var c = c /* 1. Started transpilation of shoulds */ if c.recentField == F.isConvertingShoulds && c.isConvertingShoulds { c.srcQueue = convSrcQueueShoulds(c.entityShouldBranches) c.recentField = F.srcQueue return c } /* 2. Started transpilation of oneliners */ if c.recentField == F.isConvertingOneliners && c.isConvertingOneliners { c.srcQueue = convSrcQueueOneliners(c.entityOneliners) c.recentField = F.srcQueue return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func convShouldResetTranspiledOneliners(_ c: ConvContext) -> ConvContext { var c = c /* 1. Finished transpilation of oneliners */ if c.recentField == F.isConvertingOneliners && !c.isConvertingOneliners { c.transpiledOneliners = convTranspiledOneliners(c.entityOneliners, c.dstQueue) c.recentField = F.transpiledOneliners return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func convShouldResetTranspiledShouldBranches(_ c: ConvContext) -> ConvContext { var c = c /* 1. Finished transpilation of shoulds */ if c.recentField == F.isConvertingShoulds && !c.isConvertingShoulds { c.transpiledShouldBranches = convTranspiledShouldBranches(c.entityShouldBranches, c.dstQueue) c.recentField = F.transpiledShouldBranches return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func generatorShouldResetConsoleOutput(_ c: GeneratorContext) -> GeneratorContext { var c = c /* 1. Upon LLM error */ if c.recentField == F.llmError { c.consoleOutput = GENERATOR_LLM_ERROR_T .replacingOccurrences(of: "%ERROR%", with: c.llmError) c.recentField = F.consoleOutput return c } /* 2. Upon writing a file */ if c.recentField == F.didWriteFile { c.consoleOutput = GENERATOR_DID_WRITE_FILE_T .replacingOccurrences(of: "%PATH%", with: c.path) .replacingOccurrences(of: "%SIZE%", with: String(c.out.count)) c.recentField = F.consoleOutput return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func generatorShouldResetFilesCount(_ c: GeneratorContext) -> GeneratorContext { var c = c /* 1. Upon writing a file */ if c.recentField == F.didWriteFile { c.filesCount += 1 c.recentField = F.filesCount return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func generatorShouldResetOut(_ c: GeneratorContext) -> GeneratorContext { var c = c /* 1. Upon Swift path */ if c.recentField == F.path && c.outputPaths.first(where: { c.path.hasSuffix($0.path) })!.type == GENERATOR_SWIFT { c.out = c.outSwift c.recentField = F.out return c } /* 2. Upon Kotlin path */ if c.recentField == F.path && c.outputPaths.first(where: { c.path.hasSuffix($0.path) })!.type == GENERATOR_KOTLIN { c.out = c.outKotlin c.recentField = F.out return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func generatorShouldResetPath(_ c: GeneratorContext) -> GeneratorContext { var c = c /* 1. Upon Swift output */ if c.recentField == F.outSwift { let last = c.outputPaths.first(where: { $0.type == GENERATOR_SWIFT })!.path c.path = c.inputAbsoluteDir + "/" + last c.recentField = F.path return c } /* 2. Upon Kotlin output */ if c.recentField == F.outKotlin { let last = c.outputPaths.first(where: { $0.type == GENERATOR_KOTLIN })!.path c.path = c.inputAbsoluteDir + "/" + last c.recentField = F.path return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func generatorShouldResetWillShutdown(_ c: GeneratorContext) -> GeneratorContext { var c = c /* 1. Upon CLI console output */ if c.recentField == F.cliDidConsoleOutput { c.willShutdown = true c.recentField = F.willShutdown return c } /* 2. After writing all expected files */ if c.recentField == F.filesCount && c.filesCount == c.outputPaths.count { c.willShutdown = true c.recentField = F.willShutdown return c } /* 3. Upon LLM error */ if c.recentField == F.llmError { c.willShutdown = true c.recentField = F.willShutdown return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func kotlinShouldResetDidLaunch(_ c: KotlinContext) -> KotlinContext { var c = c /* 1. Only once during the first setup */ if c.recentField == F.didSetup && c.didLaunch == false { c.didLaunch = true c.recentField = F.didLaunch return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func kotlinShouldResetOut(_ c: KotlinContext) -> KotlinContext { var c = c /* 1. When transpiled oneliners are ready */ if c.recentField == F.outRegisterEffects { c.out = KOTLIN_OGS_PKG + "\n" + otherBase64ToString(KOTLIN_EMB64_CORE) .replacingOccurrences(of: KOTLIN_OGS_PKG, with: "") + c.outFields + c.outStructs + c.outContexts + c.outSets + c.outShoulds + c.outRegisterShoulds + c.outRegisterEffects c.recentField = F.out return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func kotlinShouldResetOutContexts(_ c: KotlinContext) -> KotlinContext { var c = c /* 1. When entity field types are available */ if c.recentField == F.entityFieldTypes { c.outContexts = kotlinContexts(c.entities, c.entityTypes, c.entityFields, c.entityFieldTypes) c.recentField = F.outContexts return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func kotlinShouldResetOutFields(_ c: KotlinContext) -> KotlinContext { var c = c /* 1. When entity fields are available */ if c.recentField == F.entityFields { c.outFields = kotlinFields(c.entityFields) c.recentField = F.outFields return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func kotlinShouldResetOutSets(_ c: KotlinContext) -> KotlinContext { var c = c /* 1. When entities are ready */ if c.recentField == F.entities { c.outSets = kotlinSets(c.entities) c.recentField = F.outSets return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func kotlinShouldResetOutStructs(_ c: KotlinContext) -> KotlinContext { var c = c /* 1. When entity field types are available */ if c.recentField == F.entityFieldTypes { c.outStructs = kotlinStructs(c.entities, c.entityTypes, c.entityFields, c.entityFieldTypes) c.recentField = F.outStructs return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func kotlinShouldResetOutRegisterEffects(_ c: KotlinContext) -> KotlinContext { var c = c /* 1. When transpiled oneliners are ready */ if c.recentField == F.transpiledOneliners { c.outRegisterEffects = kotlinRegisterEffects(c.entities, c.transpiledOneliners) c.recentField = F.outRegisterEffects return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func kotlinShouldResetOutRegisterShoulds(_ c: KotlinContext) -> KotlinContext { var c = c /* 1. When shoulds are ready */ if c.recentField == F.entityShoulds { c.outRegisterShoulds = kotlinRegisterShoulds(c.entities, c.entityShoulds) c.recentField = F.outRegisterShoulds return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func kotlinShouldResetOutShoulds(_ c: KotlinContext) -> KotlinContext { var c = c /* 1. When transpiled shoulds are available */ if c.recentField == F.transpiledShouldBranches { c.outShoulds = kotlinShoulds(c.entities, c.entityShoulds, c.transpiledShouldBranches) c.recentField = F.outShoulds return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func kotlinShouldResetWillGenerate(_ c: KotlinContext) -> KotlinContext { var c = c /* 1. Upon did launch */ if c.recentField == F.didLaunch { let will = c.outputPaths.contains(where: { $0.type == KOTLIN_TYPE }) c.willGenerate = will c.recentField = F.willGenerate return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func llmShouldResetDidLaunch(_ c: LLMContext) -> LLMContext { var c = c /* 1. Only once during the first setup */ if c.recentField == F.didSetup && c.didLaunch == false { c.didLaunch = true c.recentField = F.didLaunch return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func llmShouldResetReply(_ c: LLMContext) -> LLMContext { var c = c /* 1. Upon successful response */ if c.recentField == F.response { c.reply = llmExtractReply(c.response.contents) c.recentField = F.reply return c } /* 2. Upon error response */ if c.recentField == F.responseError { c.reply = c.responseError.contents c.recentField = F.reply return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func llmShouldResetRequest(_ c: LLMContext) -> LLMContext { var c = c /* 1. See if server is available upon receiving promp */ if c.recentField == F.prompt { c.request = llmReqPrompt(LLM_DEFAULT_HOST, LLM_DEFAULT_PORT, c.prompt) c.recentField = F.request return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func swiftShouldResetDidLaunch(_ c: SwiftContext) -> SwiftContext { var c = c /* 1. Only once during the first setup */ if c.recentField == F.didSetup && c.didLaunch == false { c.didLaunch = true c.recentField = F.didLaunch return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func swiftShouldResetOut(_ c: SwiftContext) -> SwiftContext { var c = c /* 1. Upon launch */ if c.recentField == F.didLaunch { c.out = otherBase64ToString(SWIFT_EMB64_CORE) + c.outFields + c.outStructs + c.outContexts + c.outSets + c.outShoulds + c.outRegisterShoulds + c.outRegisterEffects c.recentField = F.out return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func swiftShouldResetOutContexts(_ c: SwiftContext) -> SwiftContext { var c = c /* 1. When entity field types are available */ if c.recentField == F.entityFieldTypes { c.outContexts = swiftContexts(c.entities, c.entityTypes, c.entityFields, c.entityFieldTypes) c.recentField = F.outContexts return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func swiftShouldResetOutFields(_ c: SwiftContext) -> SwiftContext { var c = c /* 1. When entity fields are available */ if c.recentField == F.entityFields { c.outFields = swiftFields(c.entityFields) c.recentField = F.outFields return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func swiftShouldResetOutRegisterEffects(_ c: SwiftContext) -> SwiftContext { var c = c /* 1. When oneliners are ready */ if c.recentField == F.entityOneliners { c.outRegisterEffects = swiftRegisterEffects(c.entities, c.entityOneliners) c.recentField = F.outRegisterEffects return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func swiftShouldResetOutRegisterShoulds(_ c: SwiftContext) -> SwiftContext { var c = c /* 1. When shoulds are ready */ if c.recentField == F.entityShoulds { c.outRegisterShoulds = swiftRegisterShoulds(c.entities, c.entityShoulds) c.recentField = F.outRegisterShoulds return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func swiftShouldResetOutSets(_ c: SwiftContext) -> SwiftContext { var c = c /* 1. When entities are ready */ if c.recentField == F.entities { c.outSets = swiftSets(c.entities) c.recentField = F.outSets return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func swiftShouldResetOutShoulds(_ c: SwiftContext) -> SwiftContext { var c = c /* 1. When entity should branches are available */ if c.recentField == F.entityShouldBranches { c.outShoulds = swiftShoulds(c.entities, c.entityShoulds, c.entityShouldBranches) c.recentField = F.outShoulds return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func swiftShouldResetOutStructs(_ c: SwiftContext) -> SwiftContext { var c = c /* 1. When entity field types are available */ if c.recentField == F.entityFieldTypes { c.outStructs = swiftStructs(c.entities, c.entityTypes, c.entityFields, c.entityFieldTypes) c.recentField = F.outStructs return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func ymlShouldResetChunks(_ c: YMLContext) -> YMLContext { var c = c /* 1. Split input lines into chunks */ if c.recentField == F.inputLines { c.chunks = ymlParseChunks(c.inputLines) c.recentField = F.chunks return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func ymlShouldResetDidLaunch(_ c: YMLContext) -> YMLContext { var c = c /* 1. Only once during the first setup */ if c.recentField == F.didSetup && c.didLaunch == false { c.didLaunch = true c.recentField = F.didLaunch return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func ymlShouldResetEntities(_ c: YMLContext) -> YMLContext { var c = c /* 1. When chunks are ready */ if c.recentField == F.chunks { c.entities = ymlParseEntities(c.chunks) c.recentField = F.entities return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func ymlShouldResetEntityFields(_ c: YMLContext) -> YMLContext { var c = c /* 1. Upon entities */ if c.recentField == F.entities { c.entityFields = ymlParseEntityFields(c.chunks, c.entities) c.recentField = F.entityFields return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func ymlShouldResetEntityFieldTypes(_ c: YMLContext) -> YMLContext { var c = c /* 1. Upon entity fields */ if c.recentField == F.entityFields { c.entityFieldTypes = ymlParseEntityFieldTypes(c.chunks, c.entities, c.entityFields) c.recentField = F.entityFieldTypes return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func ymlShouldResetEntityOneliners(_ c: YMLContext) -> YMLContext { var c = c /* 1. Upon entities */ if c.recentField == F.entities { c.entityOneliners = ymlParseEntityOneliners(c.chunks, c.entities) c.recentField = F.entityOneliners return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func ymlShouldResetEntityShouldBranches(_ c: YMLContext) -> YMLContext { var c = c /* 1. Upon entity shoulds */ if c.recentField == F.entityShoulds { c.entityShouldBranches = ymlParseEntityShouldBranches(c.chunks, c.entities, c.entityShoulds) c.recentField = F.entityShouldBranches return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func ymlShouldResetEntityShoulds(_ c: YMLContext) -> YMLContext { var c = c /* 1. Upon entities */ if c.recentField == F.entities { c.entityShoulds = ymlParseEntityShoulds(c.chunks, c.entities) c.recentField = F.entityShoulds return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func ymlShouldResetEntityTypes(_ c: YMLContext) -> YMLContext { var c = c /* 1. Upon entities */ if c.recentField == F.entities { c.entityTypes = ymlParseEntityTypes(c.chunks, c.entities) c.recentField = F.entityTypes return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func ymlShouldResetOutputPaths(_ c: YMLContext) -> YMLContext { var c = c /* 1. When chunks are ready */ if c.recentField == F.chunks { c.outputPaths = ymlParseOutputPaths(c.chunks) c.recentField = F.outputPaths return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func ymlShouldResetParseInput(_ c: YMLContext) -> YMLContext { var c = c /* 1. Upon launching */ if c.recentField == F.didLaunch && !c.inputContents.isEmpty { c.parseInput = true c.recentField = F.parseInput return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func ymlShouldResetVersion(_ c: YMLContext) -> YMLContext { var c = c /* 1. When chunks are ready */ if c.recentField == F.chunks { c.version = ymlParseVersion(c.chunks) c.recentField = F.version return c } c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } func cliRegisterShoulds(_ ctrl: DialectController) { [ cliShouldResetConsoleOutput, cliShouldResetDidLaunch, cliShouldResetInputFileName, cliShouldResetReadFile, ].forEach { f in ctrl.registerFunction { c in f(c as! CLIContext) } } } func convRegisterShoulds(_ ctrl: DialectController) { [ convShouldResetDidLaunch, convShouldResetDstQueue, convShouldResetIsConvertingOneliners, convShouldResetIsConvertingShoulds, convShouldResetPrompt, convShouldResetSrcId, convShouldResetSrcQueue, convShouldResetTranspiledOneliners, convShouldResetTranspiledShouldBranches, ].forEach { f in ctrl.registerFunction { c in f(c as! ConvContext) } } } func generatorRegisterShoulds(_ ctrl: DialectController) { [ generatorShouldResetConsoleOutput, generatorShouldResetFilesCount, generatorShouldResetOut, generatorShouldResetPath, generatorShouldResetWillShutdown, ].forEach { f in ctrl.registerFunction { c in f(c as! GeneratorContext) } } } func kotlinRegisterShoulds(_ ctrl: DialectController) { [ kotlinShouldResetDidLaunch, kotlinShouldResetOut, kotlinShouldResetOutContexts, kotlinShouldResetOutFields, kotlinShouldResetOutSets, kotlinShouldResetOutStructs, kotlinShouldResetOutRegisterEffects, kotlinShouldResetOutRegisterShoulds, kotlinShouldResetOutShoulds, kotlinShouldResetWillGenerate, ].forEach { f in ctrl.registerFunction { c in f(c as! KotlinContext) } } } func llmRegisterShoulds(_ ctrl: DialectController) { [ llmShouldResetDidLaunch, llmShouldResetReply, llmShouldResetRequest, ].forEach { f in ctrl.registerFunction { c in f(c as! LLMContext) } } } func swiftRegisterShoulds(_ ctrl: DialectController) { [ swiftShouldResetDidLaunch, swiftShouldResetOut, swiftShouldResetOutContexts, swiftShouldResetOutFields, swiftShouldResetOutRegisterEffects, swiftShouldResetOutRegisterShoulds, swiftShouldResetOutSets, swiftShouldResetOutShoulds, swiftShouldResetOutStructs, ].forEach { f in ctrl.registerFunction { c in f(c as! SwiftContext) } } } func ymlRegisterShoulds(_ ctrl: DialectController) { [ ymlShouldResetChunks, ymlShouldResetDidLaunch, ymlShouldResetEntities, ymlShouldResetEntityFields, ymlShouldResetEntityFieldTypes, ymlShouldResetEntityOneliners, ymlShouldResetEntityShouldBranches, ymlShouldResetEntityShoulds, ymlShouldResetEntityTypes, ymlShouldResetOutputPaths, ymlShouldResetParseInput, ymlShouldResetVersion, ].forEach { f in ctrl.registerFunction { c in f(c as! YMLContext) } } } func cliRegisterEffects(_ ctrl: DialectController) { let _: CLIContext? = registerOneliners(ctrl, [ F.consoleOutput, { (c: CLIContext) in print(c.consoleOutput) }, F.consoleOutput, { (c: CLIContext) in generatorSet(F.cliDidConsoleOutput, true) }, F.inputAbsoluteDir, { (c: CLIContext) in generatorSet(F.inputAbsoluteDir, c.inputAbsoluteDir) }, F.inputContents, { (c: CLIContext) in ymlSet(F.inputContents, c.inputContents) }, F.inputFileName, { (c: CLIContext) in cliResolveAbsoluteDir(c.inputFileName, F.inputAbsoluteDir) }, F.readFile, { (c: CLIContext) in cliReadInputFile(c.inputFileName, F.inputContents, F.inputError) }, ]) } func convRegisterEffects(_ ctrl: DialectController) { let _: ConvContext? = registerOneliners(ctrl, [ F.prompt, { (c: ConvContext) in llmSet(F.prompt, c.prompt) }, F.transpiledOneliners, { (c: ConvContext) in kotlinSet(F.transpiledOneliners, c.transpiledOneliners) }, F.transpiledShouldBranches, { (c: ConvContext) in kotlinSet(F.transpiledShouldBranches, c.transpiledShouldBranches) }, ]) } func generatorRegisterEffects(_ ctrl: DialectController) { let _: GeneratorContext? = registerOneliners(ctrl, [ F.consoleOutput, { (c: GeneratorContext) in print(c.consoleOutput) }, F.out, { (c: GeneratorContext) in generatorWriteFile(c.path, c.out, F.didWriteFile) }, F.willShutdown, { (c: GeneratorContext) in otherShutdown() }, ]) } func kotlinRegisterEffects(_ ctrl: DialectController) { let _: KotlinContext? = registerOneliners(ctrl, [ F.out, { (c: KotlinContext) in generatorSet(F.outKotlin, c.out) }, F.willGenerate, { (c: KotlinContext) in convSet(F.willGenerate, c.willGenerate) }, ]) } func llmRegisterEffects(_ ctrl: DialectController) { let _: LLMContext? = registerOneliners(ctrl, [ F.request, { (c: LLMContext) in llmLoad(c.request, F.response, F.responseError) }, F.responseError, { (c: LLMContext) in generatorSet(F.llmError, c.responseError.contents) }, F.reply, { (c: LLMContext) in convSet(F.reply, c.reply) }, ]) } func swiftRegisterEffects(_ ctrl: DialectController) { let _: SwiftContext? = registerOneliners(ctrl, [ F.out, { (c: SwiftContext) in generatorSet(F.outSwift, c.out) }, ]) } func ymlRegisterEffects(_ ctrl: DialectController) { let _: YMLContext? = registerOneliners(ctrl, [ F.entities, { (c: YMLContext) in kotlinSet(F.entities, c.entities) }, F.entities, { (c: YMLContext) in swiftSet(F.entities, c.entities) }, F.entityFields, { (c: YMLContext) in kotlinSet(F.entityFields, c.entityFields) }, F.entityFields, { (c: YMLContext) in swiftSet(F.entityFields, c.entityFields) }, F.entityFieldTypes, { (c: YMLContext) in kotlinSet(F.entityFieldTypes, c.entityFieldTypes) }, F.entityFieldTypes, { (c: YMLContext) in swiftSet(F.entityFieldTypes, c.entityFieldTypes) }, F.entityOneliners, { (c: YMLContext) in convSet(F.entityOneliners, c.entityOneliners) }, F.entityOneliners, { (c: YMLContext) in kotlinSet(F.entityOneliners, c.entityOneliners) }, F.entityOneliners, { (c: YMLContext) in swiftSet(F.entityOneliners, c.entityOneliners) }, F.entityShouldBranches, { (c: YMLContext) in convSet(F.entityShouldBranches, c.entityShouldBranches) }, F.entityShouldBranches, { (c: YMLContext) in kotlinSet(F.entityShouldBranches, c.entityShouldBranches) }, F.entityShouldBranches, { (c: YMLContext) in swiftSet(F.entityShouldBranches, c.entityShouldBranches) }, F.entityShoulds, { (c: YMLContext) in kotlinSet(F.entityShoulds, c.entityShoulds) }, F.entityShoulds, { (c: YMLContext) in swiftSet(F.entityShoulds, c.entityShoulds) }, F.entityTypes, { (c: YMLContext) in kotlinSet(F.entityTypes, c.entityTypes) }, F.entityTypes, { (c: YMLContext) in swiftSet(F.entityTypes, c.entityTypes) }, F.outputPaths, { (c: YMLContext) in generatorSet(F.outputPaths, c.outputPaths) }, F.outputPaths, { (c: YMLContext) in kotlinSet(F.outputPaths, c.outputPaths) }, F.parseInput, { (c: YMLContext) in ymlReadLines(c.inputContents) }, ]) } class CLIComponent { let ctrl = DialectController(CLIContext()) static private(set) weak var singleton: CLIComponent? init() { Self.singleton = self cliRegisterEffects(ctrl); cliRegisterShoulds(ctrl) } func setup() { cliSet(F.arguments, CommandLine.arguments) cliSet(F.didSetup, true) } } enum CLIError: Error { case invalidString } let CLI_ARG_FILE = "--file" let CLI_ARG_PROMPT = "--prompt" let CLI_CONSOLE_INPUT_FILE_ERROR = "ERROR Could not read file" let CLI_CONSOLE_USAGE = """ Usage: generator --file=/path/to/dialect.yml """ let CLI_CONSOLE_USAGE_AGENT = """ Usage: agent --prompt="text" """ let CLI_CONSOLE_USAGE_TRANSPILER = """ Usage: transpiler --file=/path/to/file.swift """ import Foundation /// Read an input file and push its contents into the context func cliReadInputFile( _ fileName: String, _ keyContents: String, _ keyError: String ) { let url = URL(fileURLWithPath: fileName) do { let data = try Data(contentsOf: url) guard let str = String(data: data, encoding: .utf8) else { throw CLIError.invalidString } cliSet(keyContents, str) } catch { cliSet(keyError, "\(error)") } } /// Resolve the absolute directory of an input file and push it into the context func cliResolveAbsoluteDir( _ fileName: String, _ keyAbsDir: String ) { let cwd = FileManager.default.currentDirectoryPath let fullPath = fileName.hasPrefix("/") ? fileName : cwd + "/" + fileName let dir = URL(fileURLWithPath: fullPath).deletingLastPathComponent() cliSet(keyAbsDir, dir.standardizedFileURL.path) } func cliArgumentValue( _ args: [String], _ argument: String ) -> String { for item in args { if item.hasPrefix(argument) { let prefix = argument + "=" return String(item.dropFirst(prefix.count)) } } return "" } class ConvComponent { let ctrl = DialectController(ConvContext()) static private(set) weak var singleton: ConvComponent? init() { Self.singleton = self convRegisterEffects(ctrl) convRegisterShoulds(ctrl) } func setup() { convSet(F.didSetup, true) } } let CONV_EXAMPLE_KOTLIN_DST = """ KOTLIN-1 c.singleton!!.countText = c.countText KOTLIN-2 val vm = RootVM.shared as RootVM KOTLIN-3 RootVM.shared!!.countText = c.countText KOTLIN-4 proxy.base!!.count = 0 KOTLIN-5 val copy = engine.stage as Stage KOTLIN-6 c.words = listOf(c.head, "z") KOTLIN-7 c.countText = "Count: '${c.count}'" KOTLIN-8 c.recentField == F.didThis && c.didThis == false KOTLIN-9 c.items = listOf(c.name, "x") KOTLIN-10 c.label = "name: '${c.name}'" KOTLIN-11 c.items.forEach { item -> c.count += 1 } KOTLIN-12 c.countText = if (c.count > 0) "yes" else "no" KOTLIN-13 c.recentField == F.didClickIncrement && c.count == 9 KOTLIN-14 c.count += 10 KOTLIN-15 c.recentField == F.didClickIncrement KOTLIN-16 print(c.countText) KOTLIN-17 c.recentField == F.didRename && c.name != "new" """ let CONV_EXAMPLE_SWIFT_SRC = """ SWIFT-1 c.singleton!.countText = c.countText SWIFT-2 let vm = RootVM.shared as! RootVM SWIFT-3 RootVM.shared!.countText = c.countText SWIFT-4 proxy.base!.count = 0 SWIFT-5 let copy = engine.stage as! Stage SWIFT-6 c.words = [c.head, "z"] SWIFT-7 c.countText = "Count: '\\(c.count)'" SWIFT-8 c.recentField == F.didThis && c.didThis == false SWIFT-9 c.items = [c.name, "x"] SWIFT-10 c.label = "name: '\\(c.name)'" SWIFT-11 c.items.forEach { item in c.count += 1 } SWIFT-12 c.countText = c.count > 0 ? "yes" : "no" SWIFT-13 c.recentField == F.didClickIncrement && c.count == 9 SWIFT-14 c.count += 10 SWIFT-15 c.recentField == F.didClickIncrement SWIFT-16 print(c.countText) SWIFT-17 c.recentField == F.didRename && c.name != "new" """ let CONV_PREFIX_KOTLIN = "KOTLIN-" let CONV_PREFIX_SWIFT = "SWIFT-" let CONV_PROMPT_PREFIX = """ You are a transpiler that converts Swift source code into idiomatic Kotlin source code. Rules you must always follow: - Output ONLY the transpiled Kotlin code as numbered KOTLIN-n blocks matching the format of the example below. Never repeat, quote, or echo the input Swift code. - Never add leading titles, bullet points, explanations, or prose before the KOTLIN-0 block. Never add trailing notes, greetings, or text after the last KOTLIN-n block. - Never wrap the output in markdown code fences or backticks. - Never add blank lines anywhere: neither between blocks nor inside a block. - Preserve the exact shape of every fragment. A block with N lines in the input MUST have exactly N lines in the output, in the same order: never merge two lines into one, never split one line into two - Preserve indentation for each source code line - Emit only the fragment itself with the token conversions below applied. Never add an enclosing statement, braces, or any surrounding syntax that was not in the input. - Convert Swift 'x.isEmpty' (Bool property, no parentheses) into the Kotlin function call 'x.isEmpty()'. The Swift '!c.countText.isEmpty' MUST become '!c.countText.isEmpty()' with parentheses, because Kotlin requires the call. - Convert Swift string interpolation '\\(expr)' to Kotlin '${expr}'. - Convert a Swift force unwrap 'x!' to the Kotlin non-null assertion 'x!!'. For example 'c.singleton!.countText' must become 'c.singleton!!.countText' — add the second '!'. - Convert a Swift force cast 'x as! T' to Kotlin 'x as T'. For example 'RootVM.shared as! RootVM' must become 'RootVM.shared as RootVM' — remove the '!'. - Convert Swift array literals '[a, b]' to Kotlin 'listOf(a, b)'. - Convert Swift trailing closures '{ x in ... }' to Kotlin lambdas '{ x -> ... }'. - Convert a Swift ternary 'a ? b : c' to Kotlin 'if (a) b else c'. - Convert a Swift force cast 'x as! T' to Kotlin 'x as T'. Study this example of a correct Swift-to-Kotlin transpilation and match its format exactly: SWIFT INPUT === \(CONV_EXAMPLE_SWIFT_SRC) KOTLIN OUTPUT === \(CONV_EXAMPLE_KOTLIN_DST) Transpile the following Swift input: """ let CONV_PROMPT_SUFFIX = """ Kotlin output: """ func convQueuePrompt( _ queue: [String], _ id: Int ) -> String { let src = CONV_PREFIX_SWIFT + String(id) + "\n" + queue[id] return CONV_PROMPT_PREFIX + src + CONV_PROMPT_SUFFIX } // Build a flat queue of oneliner reactions to transpile func convSrcQueueOneliners( _ entityOneliners: [Int: [Oneliner]] ) -> [String] { var items = [String]() for entityId in entityOneliners.keys.sorted() { let oneliners = entityOneliners[entityId] ?? [] for oneliner in oneliners { items.append(oneliner.reaction) } } return items } // Build a flat queue of shoulds to transpile func convSrcQueueShoulds( _ entityShouldBranches: [Int: [Int: [ShouldBranch]]] ) -> [String] { var items = [String]() for entityId in entityShouldBranches.keys.sorted() { let shoulds = entityShouldBranches[entityId] ?? [:] for shouldId in shoulds.keys.sorted() { let branches = shoulds[shouldId] ?? [] for branch in branches { items.append(branch.condition.joined(separator: "\n")) items.append(branch.reaction.joined(separator: "\n")) } } } return items } // Construct single transpiled oneliner func convTranspiledOneliner( _ orig: Oneliner, _ reac: String ) -> Oneliner { var o = orig var linesReaction = reac.split(separator: "\n") if let first = linesReaction.first, first.hasPrefix(CONV_PREFIX_KOTLIN) { linesReaction = Array(linesReaction.dropFirst()) o.reaction = linesReaction.joined(separator: "\n") } return o } // Construct several transpiled oneliners func convTranspiledOneliners( _ entityOneliners: [Int: [Oneliner]], _ dstQueue: [String] ) -> [Int: [Oneliner]] { var items = [Int: [Oneliner]]() var id = 0 for entityId in entityOneliners.keys.sorted() { let oneliners = entityOneliners[entityId] ?? [] for oneliner in oneliners { // Get transpiled snippet let reaction = dstQueue[id] id += 1 // Format the snippet let item = convTranspiledOneliner(oneliner, reaction) items[entityId, default: []].append(item) } } return items } // Construct single transpiled branch func convTranspiledShouldBranch( _ orig: ShouldBranch, _ cond: String, _ reac: String ) -> ShouldBranch { var b = orig var linesCondition = cond.split(separator: "\n") if let first = linesCondition.first, first.hasPrefix(CONV_PREFIX_KOTLIN) { linesCondition = Array(linesCondition.dropFirst()) b.condition = linesCondition.map(String.init) } var linesReaction = reac.split(separator: "\n") if let first = linesReaction.first, first.hasPrefix(CONV_PREFIX_KOTLIN) { linesReaction = Array(linesReaction.dropFirst()) b.reaction = linesReaction.map(String.init) } return b } // Construct serveral transpiled branches func convTranspiledShouldBranches( _ entityShouldBranches: [Int: [Int: [ShouldBranch]]], _ dstQueue: [String] ) -> [Int: [Int: [ShouldBranch]]] { var items = [Int: [Int: [ShouldBranch]]]() var id = 0 for entityId in entityShouldBranches.keys.sorted() { let shoulds = entityShouldBranches[entityId] ?? [:] for shouldId in shoulds.keys.sorted() { let branches = shoulds[shouldId] ?? [] for branch in branches { // Get transpiled snippets let condition = dstQueue[id] id += 1 let reaction = dstQueue[id] id += 1 // Format the snippets let item = convTranspiledShouldBranch(branch, condition, reaction) items[entityId, default: [:]][shouldId, default: []].append(item) } } } return items } class GeneratorComponent { let ctrl = DialectController(GeneratorContext()) static private(set) weak var singleton: GeneratorComponent? init() { Self.singleton = self generatorRegisterEffects(ctrl) generatorRegisterShoulds(ctrl) } } let GENERATOR_DID_WRITE_FILE_T = "Generated (%SIZE%): %PATH%" let GENERATOR_KOTLIN = "kotlin" let GENERATOR_LLM_ERROR_T = "LLM error: '%ERROR%'" let GENERATOR_SWIFT = "swift" func generatorWriteFile( _ path: String, _ contents: String, _ keyDone: String ) { otherWriteFile(path, contents) generatorSet(keyDone, true) } class KotlinComponent { let ctrl = DialectController(KotlinContext()) static private(set) weak var singleton: KotlinComponent? init() { Self.singleton = self kotlinRegisterEffects(ctrl) kotlinRegisterShoulds(ctrl) } func setup() { kotlinSet(F.didSetup, true) } } let KOTLIN_CONTEXT_FIELD_T = " var %NAME%: %TYPE% = %DEFAULT%,\n" let KOTLIN_CONTEXT_GETTER_T = """ %ELSE%if (name == \"%NAME%\") { return %NAME% as T } """ let KOTLIN_CONTEXT_SETTER_T = """ %ELSE%if (name == \"%NAME%\") { %NAME% = value as %TYPE% } """ let KOTLIN_CONTEXT_T = """ @Suppress("UNCHECKED_CAST") data class %NAME%( %FIELDS% override var recentField: String = "" ) : DialectContext { override fun field(name: String): T { %GETTERS% return \"\" as T } override fun selfCopy(): DialectContext { return this.copy() } override fun setField( name: String, value: Any? ) { %SETTERS% } } """ let KOTLIN_DEFAULT_BOOL = "false" let KOTLIN_DEFAULT_INT = "0" let KOTLIN_DEFAULT_LIST = "arrayOf()" let KOTLIN_DEFAULT_MAP = "mapOf()" let KOTLIN_DEFAULT_NAMED_T = "%TYPE%()" let KOTLIN_DEFAULT_STRING = "\"\"" let KOTLIN_FIELD_T = " const val %NAME% = \"%NAME%\"\n" let KOTLIN_FIELDS_T = """ // Context field names for static type check object F { %ITEMS% } """ let KOTLIN_LIST_T = "Array<%TYPE%>" let KOTLIN_MAPPED_BOOL = "Boolean" let KOTLIN_MAPPED_INT = "Int" let KOTLIN_MAPPED_STRING = "String" let KOTLIN_MAP_T = "Map<%KEY%, %VALUE%>" let KOTLIN_OGS_PKG = "package org.opengamestudio" let KOTLIN_REGISTER_EFFECTS_SUFFIX = "RegisterEffects" let KOTLIN_REGISTER_EFFECTS_T = """ fun %FUNC%(ctrl: DialectController) { registerOneliners(ctrl, arrayOf( %ITEMS% )) } """ let KOTLIN_REGISTER_EFFECT_ITEM_T = """ F.%FIELD%, { c: %CONTEXT% -> %REACTION% }, """ let KOTLIN_REGISTER_SHOULDS_SUFFIX = "RegisterShoulds" let KOTLIN_REGISTER_SHOULDS_T = """ fun %FUNC%(ctrl: DialectController) { listOf( %ITEMS% ).forEach { f -> ctrl.registerFunction { c -> f(c as %CONTEXT%) } } } """ let KOTLIN_REGISTER_SHOULDS_ITEM_T = " ::%SHOULD%,\n" let KOTLIN_SET_SUFFIX = "Set" let KOTLIN_SET_T = """ fun %FUNC%( key: String, value: Any ) { %COMPONENT%.ctrl.set(key, value) } """ let KOTLIN_SHOULD_BRANCH_T = """ // %ABOUT% if ( %CONDITION% ) { %REACTION% c.recentField = F.%FIELD% return c } """ let KOTLIN_SHOULD_INDENTATION = " " let KOTLIN_SHOULD_RESET = "ShouldReset" let KOTLIN_SHOULD_T = """ fun %FUNC%(c: %CONTEXT%): %CONTEXT% { val c = c %BRANCHES% c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } """ let KOTLIN_STRUCT_FIELD_T = " var %NAME%: %TYPE% = %DEFAULT%,\n" let KOTLIN_STRUCT_T = """ data class %NAME%( %FIELDS% ) """ let KOTLIN_SUFFIX_COMPONENT = "Component" let KOTLIN_SUFFIX_CONTEXT = "Context" let KOTLIN_TYPE = "kotlin" let KOTLIN_TYPE_BOOL = "Bool" let KOTLIN_TYPE_COMPONENT = "component" let KOTLIN_TYPE_CONTEXT = "context" let KOTLIN_TYPE_INT = "Int" let KOTLIN_TYPE_STRING = "String" let KOTLIN_TYPE_STRUCT = "struct" let KOTLIN_EMB64_CORE="cGFja2FnZSBvcmcub3BlbmdhbWVzdHVkaW8KCnZhbCBESUFMRUNUX0NPTlRFWFRfUkVDRU5UX0ZJRUxEX05PTkUgPSAibm9uZSIKCmludGVyZmFjZSBEaWFsZWN0Q29udGV4dCB7CiAgICAvKioKICAgICAqIE5hbWUgb2YgdGhlIGZpZWxkIHRoYXQgaGFzIGp1c3QgYmVlbiBjaGFuZ2VkCiAgICAgKgogICAgICogQWxsb3dzIHNob3VsZC1mdW5jdGlvbnMgKHJlZHVjZXJzKSB0byByZWFjdCBvbmx5IHRvCiAgICAgKiByZWxldmFudCBjaGFuZ2VzIGFuZCBpZ25vcmUgb3RoZXIgY2hhbmdlcyBvZiBEaWFsZWN0Q29udGV4dAogICAgICovCiAgICB2YXIgcmVjZW50RmllbGQ6IFN0cmluZwoKICAgIC8qKgogICAgICogR2V0IGZpZWxkJ3MgdmFsdWUgYnkgaXRzIG5hbWUKICAgICAqLwogICAgZnVuIDxUPiBmaWVsZChuYW1lOiBTdHJpbmcpOiBUCiAgICAvKioKICAgICAqIEVyYXNlIHR5cGUKICAgICAqCiAgICAgKiBVc2VkIGJ5IERpYWxlY3RDb250cm9sbGVyIHRvIGFzc2lnbiByZWNlbnQgZmllbGQncyB2YWx1ZQogICAgICovCiAgICBmdW4gZmllbGRBbnkobmFtZTogU3RyaW5nKTogQW55IHsKICAgICAgICByZXR1cm4gZmllbGQobmFtZSkKICAgIH0KICAgIC8qKgogICAgICogQ3JlYXRlIGEgY29weSBvZiB0aGUgRGlhbGVjdENvbnRleHQgZGVyaXZhdGl2ZQogICAgICoKICAgICAqIFVzZWQgYnkgRGlhbGVjdENvbnRyb2xsZXIgdG8gdHJlYXQgYWxsIGRlcml2ZWQgY29udGV4dHMgYXMgRGlhbGVjdENvbnRleHQKICAgICAqLwogICAgZnVuIHNlbGZDb3B5KCk6IERpYWxlY3RDb250ZXh0CiAgICAvKioKICAgICAqIFNldCBmaWVsZCdzIHZhbHVlIGJ5IGl0cyBuYW1lCiAgICAgKi8KICAgIGZ1biBzZXRGaWVsZChuYW1lOiBTdHJpbmcsIHZhbHVlOiBBbnk/KQp9CnBhY2thZ2Ugb3JnLm9wZW5nYW1lc3R1ZGlvCgpjbGFzcyBEaWFsZWN0Q29udHJvbGxlcigKICAgIHZhciBjb250ZXh0OiBEaWFsZWN0Q29udGV4dAopIHsKICAgIGludGVybmFsIHZhciBjYWxsYmFja3MgPSBtdXRhYmxlTGlzdE9mPChjOiBEaWFsZWN0Q29udGV4dCkgLT4gVW5pdD4oKQogICAgaW50ZXJuYWwgdmFyIGZ1bmN0aW9ucyA9IG11dGFibGVMaXN0T2Y8KGM6IERpYWxlY3RDb250ZXh0KSAtPiBEaWFsZWN0Q29udGV4dD4oKQogICAgdmFyIGlzUHJvY2Vzc2luZ1F1ZXVlID0gZmFsc2UKICAgIGludGVybmFsIHZhciBxdWV1ZSA9IG11dGFibGVMaXN0T2Y8RGlhbGVjdENvbnRleHQ+KCkKIAogICAgZnVuIGV4ZWN1dGVGdW5jdGlvbnMoKSB7CiAgICAgICAgdmFsIGMgPSBxdWV1ZS5yZW1vdmVBdCgwKQogICAgICAgIC8vIEtlZXAgU1NPVDogT25seSBhbGxvdyBzaW5nbGUgZmllbGQgY2hhbmdlIHBlciBzaG91bGQtZnVuY3Rpb24KICAgICAgICBjb250ZXh0LnJlY2VudEZpZWxkID0gYy5yZWNlbnRGaWVsZAogICAgICAgIGNvbnRleHQuc2V0RmllbGQoYy5yZWNlbnRGaWVsZCwgYy5maWVsZEFueShjLnJlY2VudEZpZWxkKSkKICAgICAgIAogICAgICAgIGZvciAoZiBpbiBmdW5jdGlvbnMpIHsKICAgICAgICAgICAgdmFsIGN0eCA9IGYoY29udGV4dC5zZWxmQ29weSgpKQogICAgICAgICAgICBpZiAoY3R4LnJlY2VudEZpZWxkICE9IERJQUxFQ1RfQ09OVEVYVF9SRUNFTlRfRklFTERfTk9ORSkgewogICAgICAgICAgICAgICAgcXVldWUuYWRkKGN0eCkKICAgICAgICAgICAgfQogICAgICAgIH0KICAgICAgIAogICAgICAgIHJlcG9ydENvbnRleHQoKQogICAgfQogCiAgICBmdW4gcHJvY2Vzc1F1ZXVlKCkgewogICAgICAgIC8vIFByZXZlbnQgcmVjdXJzaW9uLgogICAgICAgIGlmIChpc1Byb2Nlc3NpbmdRdWV1ZSkgewogICAgICAgICAgICByZXR1cm4KICAgICAgICB9CiAgICAgICAKICAgICAgICBpc1Byb2Nlc3NpbmdRdWV1ZSA9IHRydWUKICAgICAgIAogICAgICAgIHdoaWxlIChxdWV1ZS5zaXplID4gMCkgewogICAgICAgICAgICBleGVjdXRlRnVuY3Rpb25zKCkKICAgICAgICB9CiAgICAgICAKICAgICAgICBpc1Byb2Nlc3NpbmdRdWV1ZSA9IGZhbHNlCiAgICB9CiAKICAgIGZ1biByZWdpc3RlckNhbGxiYWNrKGNiOiAoYzogRGlhbGVjdENvbnRleHQpIC0+IFVuaXQpIHsKICAgICAgICBjYWxsYmFja3MuYWRkKGNiKQogICAgfQogCiAgICBmdW4gcmVnaXN0ZXJGaWVsZENhbGxiYWNrKAogICAgICAgIGZpZWxkTmFtZTogU3RyaW5nLAogICAgICAgIGNiOiAoRGlhbGVjdENvbnRleHQpIC0+IFVuaXQKICAgICkgewogICAgICAgIGNhbGxiYWNrcy5hZGQoeyBjIC0+CiAgICAgICAgICAgIGlmIChjLnJlY2VudEZpZWxkID09IGZpZWxkTmFtZSkgewogICAgICAgICAgICAgICAgY2IoYykKICAgICAgICAgICAgfQogICAgICAgIH0pCiAgICB9CiAKICAgIGZ1biByZWdpc3RlckZ1bmN0aW9uKGY6IChEaWFsZWN0Q29udGV4dCkgLT4gRGlhbGVjdENvbnRleHQpIHsKICAgICAgICBmdW5jdGlvbnMuYWRkKGYpCiAgICB9CiAKICAgIGZ1biByZXBvcnRDb250ZXh0KCkgewogICAgICAgIGZvciAoY2IgaW4gY2FsbGJhY2tzKSB7CiAgICAgICAgICAgIGNiKGNvbnRleHQpCiAgICAgICAgfQogICAgfQogCiAgICBmdW4gc2V0KGZpZWxkTmFtZTogU3RyaW5nLCB2YWx1ZTogQW55KSB7CiAgICAgICAgdmFyIGMgPSBjb250ZXh0LnNlbGZDb3B5KCkKICAgICAgICBjLnNldEZpZWxkKGZpZWxkTmFtZSwgdmFsdWUpCiAgICAgICAgYy5yZWNlbnRGaWVsZCA9IGZpZWxkTmFtZQogICAgICAgIHF1ZXVlLmFkZChjKQogICAgICAgIHByb2Nlc3NRdWV1ZSgpCiAgICB9Cn0KcGFja2FnZSBvcmcub3BlbmdhbWVzdHVkaW8KCi8vIFJlZ2lzdGVyIHNldmVyYWwgb25lbGluZXIgY2FsbGJhY2tzIHRvIGEgY29udHJvbGxlcgpAU3VwcHJlc3MoIlVOQ0hFQ0tFRF9DQVNUIikKZnVuIHJlZ2lzdGVyT25lbGluZXJzKAogICAgY3RybDogRGlhbGVjdENvbnRyb2xsZXIsCiAgICBpdGVtczogQXJyYXk8QW55PgopIHsKICAgIHZhbCBoYWxmQ291bnQgPSBpdGVtcy5zaXplIC8gMgogICAgZm9yIChpIGluIDAuLjxoYWxmQ291bnQpIHsKICAgICAgICB2YWwgZmllbGQgPSBpdGVtc1tpICogMl0gYXMgU3RyaW5nCiAgICAgICAgdmFsIGNhbGxiYWNrID0gaXRlbXNbaSAqIDIgKyAxXSBhcyAoYzogRGlhbGVjdENvbnRleHQpIC0+IFVuaXQKICAgICAgICBjdHJsLnJlZ2lzdGVyRmllbGRDYWxsYmFjayhmaWVsZCwgY2FsbGJhY2spCiAgICB9Cn0K" import Foundation /// Generate single entity `context` declaration func kotlinContext( _ name: String, _ fields: [String], _ fieldTypes: [Int: String] ) -> String { var outFields = "" var outGetters = "" var outSetters = "" var fieldId = 0 for field in fields { let els = (fieldId == 0) ? "" : "else " let type = fieldTypes[fieldId]! let defaultValue = kotlinTypeDefaultValue(type) outFields += KOTLIN_CONTEXT_FIELD_T .replacingOccurrences(of: "%NAME%", with: field) .replacingOccurrences(of: "%TYPE%", with: kotlinType(type)) .replacingOccurrences(of: "%DEFAULT%", with: defaultValue) outGetters += KOTLIN_CONTEXT_GETTER_T .replacingOccurrences(of: "%ELSE%", with: els) .replacingOccurrences(of: "%NAME%", with: field) outSetters += KOTLIN_CONTEXT_SETTER_T .replacingOccurrences(of: "%ELSE%", with: els) .replacingOccurrences(of: "%NAME%", with: field) .replacingOccurrences(of: "%TYPE%", with: kotlinType(type)) fieldId += 1 } return KOTLIN_CONTEXT_T .replacingOccurrences(of: "%NAME%", with: name) .replacingOccurrences(of: "%FIELDS%", with: outFields) .replacingOccurrences(of: "%GETTERS%", with: outGetters) .replacingOccurrences(of: "%SETTERS%", with: outSetters) } /// Generate the context name for a component func kotlinContextName(_ entity: String) -> String { return entity.replacingOccurrences(of: KOTLIN_SUFFIX_COMPONENT, with: KOTLIN_SUFFIX_CONTEXT) } /// Generate entities of `context` type func kotlinContexts( _ entities: [String], _ entityTypes: [Int: String], _ entityFields: [Int: [String]], _ entityFieldTypes: [Int: [Int: String]] ) -> String { var out = "" // Locate contexts var entityId = 0 var contextIds = [Int]() for _ in entities { let type = entityTypes[entityId] if type == KOTLIN_TYPE_CONTEXT { contextIds.append(entityId) } entityId += 1 } // Generate each context for id in contextIds { out += kotlinContext( entities[id], entityFields[id]!, entityFieldTypes[id]! ) } return out } /// Generate `object F` holding one string constant per field name func kotlinFields(_ entityFields: [Int: [String]]) -> String { var names = Set() // Collect field names for fields in entityFields.values { for field in fields { names.insert(field) } } // Construct the body of the object var sitems = "" for name in names.sorted() { sitems += KOTLIN_FIELD_T.replacingOccurrences(of: "%NAME%", with: name) } // Construct the whole object return KOTLIN_FIELDS_T.replacingOccurrences(of: "%ITEMS%", with: sitems) } /// Join code lines func kotlinFormatCode(_ lines: [String]) -> String { return lines.joined(separator: "\n") } /// Generate single component `RegisterEffects` function func kotlinRegisterEffect( _ contextName: String, _ oneliners: [Oneliner] ) -> String { let prefix = String(contextName.dropLast(KOTLIN_SUFFIX_CONTEXT.count)).lowercased() let funcName = prefix + KOTLIN_REGISTER_EFFECTS_SUFFIX var outItems = "" for oneliner in oneliners { outItems += KOTLIN_REGISTER_EFFECT_ITEM_T .replacingOccurrences(of: "%CONTEXT%", with: contextName) .replacingOccurrences(of: "%FIELD%", with: oneliner.field) .replacingOccurrences(of: "%REACTION%", with: kotlinFormatCode([oneliner.reaction])) } return KOTLIN_REGISTER_EFFECTS_T .replacingOccurrences(of: "%FUNC%", with: funcName) .replacingOccurrences(of: "%ITEMS%", with: outItems) } /// Generate `RegisterEffects` functions for all components func kotlinRegisterEffects( _ entities: [String], _ entityOneliners: [Int: [Oneliner]] ) -> String { var out = "" // Collect entity ids with oneliners var entityIds = [Int]() for entityId in entityOneliners.keys.sorted() { let oneliners = entityOneliners[entityId]! if !oneliners.isEmpty { entityIds.append(entityId) } } // Generate register-effects function for each component for entityId in entityIds { let contextName = kotlinContextName(entities[entityId]) let oneliners = entityOneliners[entityId] ?? [] if !oneliners.isEmpty { out += kotlinRegisterEffect(contextName, oneliners) } } return out } /// Generate single component `RegisterShoulds` function func kotlinRegisterShould( _ contextName: String, _ shoulds: [String] ) -> String { let prefix = String(contextName.dropLast(KOTLIN_SUFFIX_CONTEXT.count)).lowercased() let funcName = prefix + KOTLIN_REGISTER_SHOULDS_SUFFIX var outItems = "" for should in shoulds { let shouldFuncName = prefix + KOTLIN_SHOULD_RESET + otherCapitalize(should) outItems += KOTLIN_REGISTER_SHOULDS_ITEM_T .replacingOccurrences(of: "%SHOULD%", with: shouldFuncName) } return KOTLIN_REGISTER_SHOULDS_T .replacingOccurrences(of: "%FUNC%", with: funcName) .replacingOccurrences(of: "%CONTEXT%", with: contextName) .replacingOccurrences(of: "%ITEMS%", with: outItems) } /// Generate `RegisterShoulds` functions for all components func kotlinRegisterShoulds( _ entities: [String], _ entityShoulds: [Int: [String]] ) -> String { var out = "" // Collect entity ids with shoulds var entityIds = [Int]() for entityId in entityShoulds.keys.sorted() { let shoulds = entityShoulds[entityId]! if !shoulds.isEmpty { entityIds.append(entityId) } } // Generate register-shoulds function for each component for entityId in entityIds { let contextName = kotlinContextName(entities[entityId]) let shoulds = entityShoulds[entityId] ?? [] if !shoulds.isEmpty { out += kotlinRegisterShould(contextName, shoulds) } } return out } /// Generate single component `Set` function func kotlinSet(_ entity: String) -> String { let contextName = kotlinContextName(entity) let prefix = String(contextName.dropLast(KOTLIN_SUFFIX_CONTEXT.count)).lowercased() let funcName = prefix + KOTLIN_SET_SUFFIX return KOTLIN_SET_T .replacingOccurrences(of: "%FUNC%", with: funcName) .replacingOccurrences(of: "%COMPONENT%", with: entity) } /// Generate `Set` functions for all components func kotlinSets(_ entities: [String]) -> String { var out = "" // Generate each component's `Set` function for entity in entities { if entity.hasSuffix(KOTLIN_SUFFIX_COMPONENT) { out += kotlinSet(entity) } } return out } /// Generate single component should-function func kotlinShould( _ name: String, _ contextName: String, _ branches: [ShouldBranch] ) -> String { var outBranches = "" for branch in branches { outBranches += KOTLIN_SHOULD_BRANCH_T .replacingOccurrences(of: "%ABOUT%", with: branch.about) .replacingOccurrences(of: "%FIELD%", with: name) .replacingOccurrences(of: "%CONDITION%", with: kotlinFormatCode(branch.condition)) .replacingOccurrences(of: "%REACTION%", with: kotlinFormatCode(branch.reaction)) } let prefix = String(contextName.dropLast(KOTLIN_SUFFIX_CONTEXT.count)).lowercased() let funcName = prefix + KOTLIN_SHOULD_RESET + otherCapitalize(name) return KOTLIN_SHOULD_T .replacingOccurrences(of: "%FUNC%", with: funcName) .replacingOccurrences(of: "%CONTEXT%", with: contextName) .replacingOccurrences(of: "%BRANCHES%", with: outBranches) } /// Generate should-functions for all components func kotlinShoulds( _ entities: [String], _ entityShoulds: [Int: [String]], _ entityShouldBranches: [Int: [Int: [ShouldBranch]]] ) -> String { var out = "" // Collect entity ids with shoulds var entityIds = [Int]() for entityId in entityShoulds.keys.sorted() { let shoulds = entityShoulds[entityId]! if !shoulds.isEmpty { entityIds.append(entityId) } } // Generate should-functions for each component for entityId in entityIds { let contextName = kotlinContextName(entities[entityId]) let shoulds = entityShoulds[entityId] ?? [] var shouldId = 0 for should in shoulds { let branches = entityShouldBranches[entityId]?[shouldId] ?? [] if !branches.isEmpty { out += kotlinShould(should, contextName, branches) } shouldId += 1 } } return out } /// Generate single entity `struct` declaration func kotlinStruct( _ name: String, _ fields: [String], _ fieldTypes: [Int: String] ) -> String { var outFields = "" var fieldId = 0 for field in fields { let type = fieldTypes[fieldId]! let defaultValue = kotlinTypeDefaultValue(type) outFields += KOTLIN_STRUCT_FIELD_T .replacingOccurrences(of: "%NAME%", with: field) .replacingOccurrences(of: "%TYPE%", with: kotlinType(type)) .replacingOccurrences(of: "%DEFAULT%", with: defaultValue) fieldId += 1 } return KOTLIN_STRUCT_T .replacingOccurrences(of: "%NAME%", with: name) .replacingOccurrences(of: "%FIELDS%", with: outFields) } /// Generate entities of `struct` type func kotlinStructs( _ entities: [String], _ entityTypes: [Int: String], _ entityFields: [Int: [String]], _ entityFieldTypes: [Int: [Int: String]] ) -> String { var out = "" // Locate structs var entityId = 0 var structIds = [Int]() for _ in entities { let type = entityTypes[entityId] if type == KOTLIN_TYPE_STRUCT { structIds.append(entityId) } entityId += 1 } // Generate each struct for id in structIds { out += kotlinStruct( entities[id], entityFields[id]!, entityFieldTypes[id]! ) } return out } /// Generate the Kotlin type for a dialect type func kotlinType(_ type: String) -> String { var isCollection = false var inner = type if inner.hasPrefix("[") && inner.hasSuffix("]") { isCollection = true inner = String(inner.dropFirst().dropLast()) } // Map collections let parts = kotlinTypeParts(inner) if parts.count == 2 { return KOTLIN_MAP_T .replacingOccurrences(of: "%KEY%", with: kotlinType(parts[0])) .replacingOccurrences(of: "%VALUE%", with: kotlinType(parts[1])) } if isCollection { return KOTLIN_LIST_T .replacingOccurrences(of: "%TYPE%", with: kotlinType(parts[0])) } // Map primitives, the rest are already valid Kotlin types if inner == KOTLIN_TYPE_BOOL { return KOTLIN_MAPPED_BOOL } return inner } /// Generate the default value for a dialect type func kotlinTypeDefaultValue(_ type: String) -> String { if type.hasPrefix("[") && type.hasSuffix("]") { if type.contains(":") { return KOTLIN_DEFAULT_MAP } return KOTLIN_DEFAULT_LIST } if type == KOTLIN_TYPE_BOOL { return KOTLIN_DEFAULT_BOOL } if type == KOTLIN_TYPE_INT { return KOTLIN_DEFAULT_INT } if type == KOTLIN_TYPE_STRING { return KOTLIN_DEFAULT_STRING } return KOTLIN_DEFAULT_NAMED_T .replacingOccurrences(of: "%TYPE%", with: type) } /// Split a dialect type into parts, ignoring colons inside brackets func kotlinTypeParts(_ type: String) -> [String] { var parts = [String]() var current = "" var depth = 0 for ch in type { if ch == "[" { depth += 1 } if ch == "]" { depth -= 1 } if ch == ":" && depth == 0 { parts.append(String(current.drop(while: { $0 == " " }))) current = "" } else { current.append(ch) } } parts.append(String(current.drop(while: { $0 == " " }))) return parts } class LLMComponent { let ctrl = DialectController(LLMContext()) static private(set) weak var singleton: LLMComponent? init() { Self.singleton = self llmRegisterEffects(ctrl) llmRegisterShoulds(ctrl) } func setup() { llmSet(F.didSetup, true) } } import Foundation func llmSetAsync( _ key: String, _ value: Any ) { DispatchQueue.main.async { llmSet(key, value) } } let LLM_DEFAULT_HOST = "localhost" let LLM_DEFAULT_MODEL = "qwen2.5-coder:3b" let LLM_DEFAULT_PORT = 11434 let LLM_LINE_DELIMITER = "\",\"" let LLM_REPLY_PREFIX = "response\":\"" let LLM_SEED = 42 let LLM_TEMPERATURE = 0.0 let LLM_TOP_K = 1 let LLM_URL_GENERATE_T = "http://%HOST%:%PORT%/api/generate" import Foundation func llmLoad( _ req: NetRequest, _ keyResponse: String, _ keyResponseError: String ) { netLoad( req, { res in llmSetAsync(keyResponse, res) }, { res in llmSetAsync(keyResponseError, res) } ) } import Foundation func llmBody(_ prompt: String) -> String { let payload: [String: Any] = [ "model": LLM_DEFAULT_MODEL, "options": [ "seed": LLM_SEED, "temperature": LLM_TEMPERATURE, "top_k": LLM_TOP_K ], "prompt": prompt, "stream": false ] guard let data = try? JSONSerialization.data(withJSONObject: payload) else { return "" } return String(data: data, encoding: .utf8) ?? "" } // Extract "reponse" out of JSON func llmExtractReply(_ json: String) -> String { let lines = json.components(separatedBy: LLM_LINE_DELIMITER) for ln in lines { if ln.hasPrefix(LLM_REPLY_PREFIX) { return llmUnescape(String(ln.dropFirst(LLM_REPLY_PREFIX.count))) } } return "ERROR Could not parse response" } func llmReqPrompt( _ host: String, _ port: Int, _ prompt: String ) -> NetRequest { var req = NetRequest() req.headers = [NET_CONTENT_TYPE: NET_APP_JSON] req.method = NET_POST req.url = LLM_URL_GENERATE_T .replacingOccurrences(of: "%HOST%", with: host) .replacingOccurrences(of: "%PORT%", with: "\(port)") req.body = llmBody(prompt) return req } func llmUnescape(_ str: String) -> String { var out = String() var idx = str.startIndex while idx < str.endIndex { let ch = str[idx] let nextIdx = str.index(after: idx) guard ch == "\\", nextIdx < str.endIndex else { out.append(ch) idx = nextIdx continue } let esc = str[nextIdx] let afterEsc = str.index(after: nextIdx) switch esc { case "\"": out.append("\"") case "\\": out.append("\\") case "/": out.append("/") case "b": out.append("\u{08}") case "f": out.append("\u{0C}") case "n": out.append("\n") case "r": out.append("\r") case "t": out.append("\t") case "u": guard str.distance(from: afterEsc, to: str.endIndex) >= 4 else { out.append(ch) out.append(esc) idx = afterEsc continue } let hexEnd = str.index(afterEsc, offsetBy: 4) let hex = String(str[afterEsc ..< hexEnd]) guard var code = UInt32(hex, radix: 16) else { out.append(ch) out.append(esc) idx = afterEsc continue } idx = hexEnd if (0xD800 ... 0xDFFF).contains(code), str.distance(from: idx, to: str.endIndex) >= 6, str[idx] == "\\", str[str.index(after: idx)] == "u" { let lowStart = str.index(idx, offsetBy: 2) let lowEnd = str.index(lowStart, offsetBy: 4) if let low = UInt32(String(str[lowStart ..< lowEnd]), radix: 16), (0xDC00 ... 0xDFFF).contains(low) { code = 0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00) idx = lowEnd } } if let scalar = Unicode.Scalar(code) { out.append(Character(scalar)) } else { out.append(contentsOf: "\\u" + hex) } continue default: out.append(ch) out.append(esc) idx = afterEsc continue } idx = afterEsc } return out } import Foundation func netLoad( _ req: NetRequest, _ reportSuccess: @escaping (NetResponse) -> Void, _ reportError: @escaping (NetResponse) -> Void ) { var res = NetResponse() res.req = req guard let url = URL(string: req.url) else { res.contents = NET_INVALID_URL reportError(res) return } var r = URLRequest(url: url) r.httpMethod = req.method r.httpBody = req.body.isEmpty ? nil : req.body.data(using: .utf8) for (key, value) in req.headers { r.setValue(value, forHTTPHeaderField: key) } let session = URLSession(configuration: .ephemeral) session.dataTask(with: r) { data, response, error in if let error = error { res.contents = "\(error)" reportError(res) } else if let http = response as? HTTPURLResponse, !(200 ..< 300).contains(http.statusCode) { let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" res.contents = "\(http.statusCode) \(body)" reportError(res) } else if let data = data { res.contents = String(data: data, encoding: .utf8) ?? "" reportSuccess(res) } }.resume() } let NET_APP_JSON = "application/json" let NET_CONTENT_TYPE = "Content-Type" let NET_INVALID_URL = "Invalid URL" let NET_POST = "POST" import Foundation /// Decode a base64 string back into a regular string func otherBase64ToString(_ encoded: String) -> String { guard let data = Data(base64Encoded: encoded), let str = String(data: data, encoding: .utf8) else { return "" } return str } /// Capitalize the first letter of a string func otherCapitalize(_ s: String) -> String { guard let first = s.first else { return s } return String(first).uppercased() + String(s.dropFirst()) } /// Launch to wait for asynchrnous actions func otherLaunch() { RunLoop.current.run() } /// Count leading spaces in a line func otherLineIndent(_ line: String) -> Int { var count = 0 for ch in line { if ch == " " { count += 1 } else { break } } return count } /// Print to stderr func otherPrintStderr(_ txt: String) { if let dat = "\(txt)\n".data(using: .utf8) { FileHandle.standardError.write(dat) } } /// Print each key/value processed by a controller into stderr func otherSetupConsoleLogging( _ ctrl: DialectController, _ prefix: String ) { ctrl.registerCallback { c -> Void in let value = c.fieldAny(c.recentField) let line = "ИГР \(prefix) k/v: '\(c.recentField)'/'\(value)'" otherPrintStderr(line) } } /// Write output text to a file func otherWriteFile( _ path: String, _ content: String ) { try? content.write(toFile: path, atomically: true, encoding: .utf8) } /// Terminate the main RunLoop func otherShutdown() { exit(0) } class SwiftComponent { let ctrl = DialectController(SwiftContext()) static private(set) weak var singleton: SwiftComponent? init() { Self.singleton = self swiftRegisterEffects(ctrl) swiftRegisterShoulds(ctrl) } func setup() { swiftSet(F.didSetup, true) } } let SWIFT_CONTEXT_FIELD_T = " public var %NAME% = %DEFAULT%\n" let SWIFT_CONTEXT_GETTER_T = """ %ELSE%if (name == \"%NAME%\") { return %NAME% as! T } """ let SWIFT_CONTEXT_SETTER_T = """ %ELSE%if (name == \"%NAME%\") { %NAME% = value as! %TYPE% } """ let SWIFT_CONTEXT_T = """ public struct %NAME%: DialectContext { %FIELDS% public var recentField = "" public func field(_ name: String) -> T { %GETTERS% return "unknown-field-name" as! T } public mutating func setField( _ name: String, _ value: Any ) { %SETTERS% } } """ let SWIFT_FIELD_T = " public static let %NAME% = \"%NAME%\"\n" let SWIFT_FIELDS_T = """ // Context field names for static type check public struct F { %ITEMS% } """ let SWIFT_REGISTER_EFFECTS_SUFFIX = "RegisterEffects" let SWIFT_REGISTER_EFFECTS_T = """ func %FUNC%(_ ctrl: DialectController) { let _: %CONTEXT%? = registerOneliners(ctrl, [ %ITEMS% ]) } """ let SWIFT_REGISTER_EFFECT_ITEM_T = """ F.%FIELD%, { (c: %CONTEXT%) in %REACTION% }, """ let SWIFT_REGISTER_SHOULDS_SUFFIX = "RegisterShoulds" let SWIFT_REGISTER_SHOULDS_T = """ func %FUNC%(_ ctrl: DialectController) { [ %ITEMS% ].forEach { f in ctrl.registerFunction { c in f(c as! %CONTEXT%) } } } """ let SWIFT_SET_SUFFIX = "Set" let SWIFT_SET_T = """ public func %FUNC%( _ key: String, _ value: Any ) { %COMPONENT%.singleton!.ctrl.set(key, value) } """ let SWIFT_STRUCT_FIELD_T = " public var %NAME% = %DEFAULT%\n" let SWIFT_STRUCT_T = """ public struct %NAME% { %FIELDS% } """ let SWIFT_SHOULD_BRANCH_T = """ /* %ABOUT% */ if %CONDITION% { %REACTION% c.recentField = F.%FIELD% return c } """ let SWIFT_SHOULD_INDENTATION = " " let SWIFT_SHOULD_RESET = "ShouldReset" let SWIFT_SHOULD_T = """ func %FUNC%(_ c: %CONTEXT%) -> %CONTEXT% { var c = c %BRANCHES% c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE return c } """ let SWIFT_SUFFIX_COMPONENT = "Component" let SWIFT_SUFFIX_CONTEXT = "Context" let SWIFT_TYPE = "swift" let SWIFT_TYPE_COMPONENT = "component" let SWIFT_TYPE_CONTEXT = "context" let SWIFT_TYPE_STRUCT = "struct" let SWIFT_EMB64_CORE="Ci8vIFJldXNhYmxlICJub25lIiBjb25zdGFudApwdWJsaWMgbGV0IERJQUxFQ1RfQ09OVEVYVF9SRUNFTlRfRklFTERfTk9ORSA9ICJub25lIgoKLy8gQmFzZSBwcm90b2NvbCBmb3IgZWFjaCBjb21wb25lbnQncyBzdGF0ZQpwdWJsaWMgcHJvdG9jb2wgRGlhbGVjdENvbnRleHQgewogICAgdmFyIHJlY2VudEZpZWxkOiBTdHJpbmcgeyBnZXQgc2V0IH0KCiAgICBmdW5jIGZpZWxkPFQ+KF8gbmFtZTogU3RyaW5nKSAtPiBUCiAgICBmdW5jIGZpZWxkQW55KF8gbmFtZTogU3RyaW5nKSAtPiBBbnkKICAgIG11dGF0aW5nIGZ1bmMgc2V0RmllbGQoXyBuYW1lOiBTdHJpbmcsIF8gdmFsdWU6IEFueSkKfQoKLy8gRGVmYXVsdCBpbXBsZW1lbnRhdGlvbiBvZiBgZmllbGRBbnlgIG1ldGhvZCBmb3IgdGhlIHByb3RvY29sCnB1YmxpYyBleHRlbnNpb24gRGlhbGVjdENvbnRleHQgewogICAgZnVuYyBmaWVsZEFueShfIG5hbWU6IFN0cmluZykgLT4gQW55IHsKICAgICAgICByZXR1cm4gZmllbGQobmFtZSkKICAgIH0KfQoKLy8gVGhlIGVuZ2luZSBvZiB0aGUgZGlhbGVjdCBjb21wb25lbnRzCnB1YmxpYyBjbGFzcyBEaWFsZWN0Q29udHJvbGxlciB7CiAgICB2YXIgY2FsbGJhY2tzID0gWyhEaWFsZWN0Q29udGV4dCkgLT4gVm9pZF0oKQogICAgdmFyIGNvbnRleHQ6IERpYWxlY3RDb250ZXh0CiAgICB2YXIgZnVuY3Rpb25zID0gWyhEaWFsZWN0Q29udGV4dCkgLT4gRGlhbGVjdENvbnRleHRdKCkKICAgIHZhciBpc1Byb2Nlc3NpbmdRdWV1ZSA9IGZhbHNlCiAgICB2YXIgcXVldWUgPSBbRGlhbGVjdENvbnRleHRdKCkKCiAgICBwdWJsaWMgaW5pdChfIGNvbnRleHQ6IERpYWxlY3RDb250ZXh0KSB7CiAgICAgICAgc2VsZi5jb250ZXh0ID0gY29udGV4dAogICAgfQoKICAgIGZ1bmMgZXhlY3V0ZUZ1bmN0aW9ucygpIHsKICAgICAgICBsZXQgYyA9IHF1ZXVlLnJlbW92ZUZpcnN0KCkKICAgICAgICAvLyBLZWVwIFNTT1Q6IE9ubHkgYWxsb3cgc2luZ2xlIGZpZWxkIGNoYW5nZSBwZXIgc2hvdWxkLWZ1bmN0aW9uCiAgICAgICAgY29udGV4dC5yZWNlbnRGaWVsZCA9IGMucmVjZW50RmllbGQKICAgICAgICBjb250ZXh0LnNldEZpZWxkKGMucmVjZW50RmllbGQsIGMuZmllbGRBbnkoYy5yZWNlbnRGaWVsZCkpCiAgICAgIAogICAgICAgIGZvciBmIGluIGZ1bmN0aW9ucyB7CiAgICAgICAgICAgIGxldCBjdHggPSBmKGNvbnRleHQpCiAgICAgICAgICAgIGlmIGN0eC5yZWNlbnRGaWVsZCAhPSBESUFMRUNUX0NPTlRFWFRfUkVDRU5UX0ZJRUxEX05PTkUgewogICAgICAgICAgICAgICAgcXVldWUuYXBwZW5kKGN0eCkKICAgICAgICAgICAgfQogICAgICAgIH0KICAgICAgCiAgICAgICAgcmVwb3J0Q29udGV4dCgpCiAgICB9CgogICAgZnVuYyBwcm9jZXNzUXVldWUoKSB7CiAgICAgICAgLy8gUHJldmVudCByZWN1cnNpb24uCiAgICAgICAgaWYgaXNQcm9jZXNzaW5nUXVldWUgewogICAgICAgICAgICByZXR1cm4KICAgICAgICB9CiAgICAgIAogICAgICAgIGlzUHJvY2Vzc2luZ1F1ZXVlID0gdHJ1ZQogICAgICAKICAgICAgICB3aGlsZSAocXVldWUuY291bnQgPiAwKSB7CiAgICAgICAgICAgIGV4ZWN1dGVGdW5jdGlvbnMoKQogICAgICAgIH0KICAgICAgCiAgICAgICAgaXNQcm9jZXNzaW5nUXVldWUgPSBmYWxzZQogICAgfQoKICAgIHB1YmxpYyBmdW5jIHJlZ2lzdGVyQ2FsbGJhY2soXyBjYjogQGVzY2FwaW5nIChEaWFsZWN0Q29udGV4dCkgLT4gVm9pZCkgewogICAgICAgIGNhbGxiYWNrcy5hcHBlbmQoY2IpCiAgICB9CgogICAgcHVibGljIGZ1bmMgcmVnaXN0ZXJGaWVsZENhbGxiYWNrKAogICAgICAgIF8gZmllbGROYW1lOiBTdHJpbmcsCiAgICAgICAgXyBjYjogQGVzY2FwaW5nIChEaWFsZWN0Q29udGV4dCkgLT4gVm9pZAogICAgKSB7CiAgICAgICAgY2FsbGJhY2tzLmFwcGVuZCh7IGMgaW4KICAgICAgICAgICAgaWYgYy5yZWNlbnRGaWVsZCA9PSBmaWVsZE5hbWUgewogICAgICAgICAgICAgICAgY2IoYykKICAgICAgICAgICAgfQogICAgICAgIH0pCiAgICB9CgogICAgcHVibGljIGZ1bmMgcmVnaXN0ZXJGdW5jdGlvbihfIGY6IEBlc2NhcGluZyAoRGlhbGVjdENvbnRleHQpIC0+IERpYWxlY3RDb250ZXh0KSB7CiAgICAgICAgZnVuY3Rpb25zLmFwcGVuZChmKQogICAgfQoKICAgIGZ1bmMgcmVwb3J0Q29udGV4dCgpIHsKICAgICAgICBmb3IgY2IgaW4gY2FsbGJhY2tzIHsKICAgICAgICAgICAgY2IoY29udGV4dCkKICAgICAgICB9CiAgICB9CgogICAgcHVibGljIGZ1bmMgc2V0KAogICAgICAgIF8gZmllbGROYW1lOiBTdHJpbmcsCiAgICAgICAgXyB2YWx1ZTogQW55CiAgICApIHsKICAgICAgICB2YXIgYyA9IGNvbnRleHQKICAgICAgICBjLnNldEZpZWxkKGZpZWxkTmFtZSwgdmFsdWUpCiAgICAgICAgYy5yZWNlbnRGaWVsZCA9IGZpZWxkTmFtZQogICAgICAgIHF1ZXVlLmFwcGVuZChjKQogICAgICAgIHByb2Nlc3NRdWV1ZSgpCiAgICB9Cn0KCi8vIFJlZ2lzdGVyIHNldmVyYWwgb25lbGluZXIgY2FsbGJhY2tzIHRvIGEgY29udHJvbGxlcgpmdW5jIHJlZ2lzdGVyT25lbGluZXJzPFQ+KAogICAgXyBjdHJsOiBEaWFsZWN0Q29udHJvbGxlciwKICAgIF8gaXRlbXM6IFtBbnldCikgLT4gVD8gewogICAgbGV0IGhhbGZDb3VudCA9IGl0ZW1zLmNvdW50IC8gMgogICAgZm9yIGkgaW4gMC4uPGhhbGZDb3VudCB7CiAgICAgICAgbGV0IGZpZWxkID0gaXRlbXNbaSAqIDJdIGFzISBTdHJpbmcKICAgICAgICBsZXQgY2FsbGJhY2sgPSBpdGVtc1tpICogMiArIDFdIGFzISAoVCkgLT4gVm9pZAogICAgICAgIGN0cmwucmVnaXN0ZXJGaWVsZENhbGxiYWNrKGZpZWxkKSB7IGNjIGluCiAgICAgICAgICAgIGxldCBjID0gY2MgYXMhIFQKICAgICAgICAgICAgY2FsbGJhY2soYykKICAgICAgICB9CiAgICB9CgogICAgLy8gQSBoYWNrIGZvciBnZW5lcmljcyB0byBvcGVyYXRlCiAgICByZXR1cm4gbmlsCn0K" import Foundation /// Generate single `context` entity func swiftContext( _ name: String, _ fields: [String], _ fieldTypes: [Int: String] ) -> String { var outFields = "" var outGetters = "" var outSetters = "" var fieldId = 0 for field in fields { let els = (fieldId == 0) ? "" : "else " let type = fieldTypes[fieldId]! let defaultValue = swiftTypeDefaultValue(type) outFields += SWIFT_CONTEXT_FIELD_T .replacingOccurrences(of: "%DEFAULT%", with: defaultValue) .replacingOccurrences(of: "%NAME%", with: field) outGetters += SWIFT_CONTEXT_GETTER_T .replacingOccurrences(of: "%ELSE%", with: els) .replacingOccurrences(of: "%NAME%", with: field) outSetters += SWIFT_CONTEXT_SETTER_T .replacingOccurrences(of: "%ELSE%", with: els) .replacingOccurrences(of: "%NAME%", with: field) .replacingOccurrences(of: "%TYPE%", with: type) fieldId += 1 } return SWIFT_CONTEXT_T .replacingOccurrences(of: "%NAME%", with: name) .replacingOccurrences(of: "%FIELDS%", with: outFields) .replacingOccurrences(of: "%GETTERS%", with: outGetters) .replacingOccurrences(of: "%SETTERS%", with: outSetters) } /// Generate the context name for a component func swiftContextName(_ entity: String) -> String { return entity.replacingOccurrences(of: SWIFT_SUFFIX_COMPONENT, with: SWIFT_SUFFIX_CONTEXT) } /// Generate entities of `context` type func swiftContexts( _ entities: [String], _ entityTypes: [Int: String], _ entityFields: [Int: [String]], _ entityFieldTypes: [Int: [Int: String]] ) -> String { var out = "" // Locate contexts var entityId = 0 var contextIds = [Int]() for _ in entities { let type = entityTypes[entityId] if type == SWIFT_TYPE_CONTEXT { contextIds.append(entityId) } entityId += 1 } // Generate each context for id in contextIds { out += swiftContext( entities[id], entityFields[id]!, entityFieldTypes[id]! ) } return out } /// Generate `struct F` holding one string constant per field name func swiftFields(_ entityFields: [Int: [String]]) -> String { var names = Set() // Collect field names for fields in entityFields.values { for field in fields { names.insert(field) } } // Construct the body of the struct var sitems = "" for name in names.sorted() { sitems += SWIFT_FIELD_T.replacingOccurrences(of: "%NAME%", with: name) } // Construct the whole struct return SWIFT_FIELDS_T.replacingOccurrences(of: "%ITEMS%", with: sitems) } /// Join branch lines, indenting each by 8 spaces while keeping relative indent func swiftFormatShould(_ lines: [String]) -> String { return lines.map { SWIFT_SHOULD_INDENTATION + $0 }.joined(separator: "\n") } /// Generate single component `RegisterEffects` function func swiftRegisterEffect( _ contextName: String, _ oneliners: [Oneliner] ) -> String { let prefix = String(contextName.dropLast(SWIFT_SUFFIX_CONTEXT.count)).lowercased() let funcName = prefix + SWIFT_REGISTER_EFFECTS_SUFFIX var outItems = "" for oneliner in oneliners { let field = oneliner.field let reaction = oneliner.reaction outItems += SWIFT_REGISTER_EFFECT_ITEM_T .replacingOccurrences(of: "%CONTEXT%", with: contextName) .replacingOccurrences(of: "%FIELD%", with: field) .replacingOccurrences(of: "%REACTION%", with: reaction) } return SWIFT_REGISTER_EFFECTS_T .replacingOccurrences(of: "%FUNC%", with: funcName) .replacingOccurrences(of: "%CONTEXT%", with: contextName) .replacingOccurrences(of: "%ITEMS%", with: outItems) } /// Generate `RegisterEffects` functions for all components func swiftRegisterEffects( _ entities: [String], _ entityOneliners: [Int: [Oneliner]] ) -> String { var out = "" // Collect entity ids with oneliners var entityIds = [Int]() for entityId in entityOneliners.keys.sorted() { let oneliners = entityOneliners[entityId]! if !oneliners.isEmpty { entityIds.append(entityId) } } // Generate register-effects function for each component for entityId in entityIds { let contextName = swiftContextName(entities[entityId]) let oneliners = entityOneliners[entityId] ?? [] if !oneliners.isEmpty { out += swiftRegisterEffect(contextName, oneliners) } } return out } /// Generate single component `RegisterShoulds` function func swiftRegisterShould( _ contextName: String, _ shoulds: [String] ) -> String { let prefix = String(contextName.dropLast(SWIFT_SUFFIX_CONTEXT.count)).lowercased() let funcName = prefix + SWIFT_REGISTER_SHOULDS_SUFFIX var outItems = "" for should in shoulds { let shouldFuncName = prefix + SWIFT_SHOULD_RESET + otherCapitalize(should) outItems += SWIFT_SHOULD_INDENTATION + shouldFuncName + ",\n" } return SWIFT_REGISTER_SHOULDS_T .replacingOccurrences(of: "%FUNC%", with: funcName) .replacingOccurrences(of: "%CONTEXT%", with: contextName) .replacingOccurrences(of: "%ITEMS%", with: outItems) } /// Generate `RegisterShoulds` functions for all components func swiftRegisterShoulds( _ entities: [String], _ entityShoulds: [Int: [String]] ) -> String { var out = "" // Collect entity ids with shoulds var entityIds = [Int]() for entityId in entityShoulds.keys.sorted() { let shoulds = entityShoulds[entityId]! if !shoulds.isEmpty { entityIds.append(entityId) } } // Generate register-shoulds function for each component for entityId in entityIds { let contextName = swiftContextName(entities[entityId]) let shoulds = entityShoulds[entityId] ?? [] if !shoulds.isEmpty { out += swiftRegisterShould(contextName, shoulds) } } return out } /// Generate single component `Set` function func swiftSet(_ entity: String) -> String { let contextName = swiftContextName(entity) let prefix = String(contextName.dropLast(SWIFT_SUFFIX_CONTEXT.count)).lowercased() let funcName = prefix + SWIFT_SET_SUFFIX return SWIFT_SET_T .replacingOccurrences(of: "%FUNC%", with: funcName) .replacingOccurrences(of: "%COMPONENT%", with: entity) } /// Generate `Set` functions for all components func swiftSets(_ entities: [String]) -> String { var out = "" // Generate each component's `Set` function for entity in entities { if entity.hasSuffix(SWIFT_SUFFIX_COMPONENT) { out += swiftSet(entity) } } return out } /// Generate single should function func swiftShould( _ name: String, _ contextName: String, _ branches: [ShouldBranch] ) -> String { var outBranches = "" for branch in branches { outBranches += SWIFT_SHOULD_BRANCH_T .replacingOccurrences(of: "%ABOUT%", with: branch.about) .replacingOccurrences(of: "%FIELD%", with: name) .replacingOccurrences(of: "%CONDITION%", with: swiftFormatShould(branch.condition)) .replacingOccurrences(of: "%REACTION%", with: swiftFormatShould(branch.reaction)) } let prefix = String(contextName.dropLast(SWIFT_SUFFIX_CONTEXT.count)).lowercased() let funcName = prefix + SWIFT_SHOULD_RESET + otherCapitalize(name) return SWIFT_SHOULD_T .replacingOccurrences(of: "%FUNC%", with: funcName) .replacingOccurrences(of: "%CONTEXT%", with: contextName) .replacingOccurrences(of: "%BRANCHES%", with: outBranches) } /// Generate should-functions for all components func swiftShoulds( _ entities: [String], _ entityShoulds: [Int: [String]], _ entityShouldBranches: [Int: [Int: [ShouldBranch]]] ) -> String { var out = "" // Collect entity ids with shoulds var entityIds = [Int]() for entityId in entityShoulds.keys.sorted() { let shoulds = entityShoulds[entityId]! if !shoulds.isEmpty { entityIds.append(entityId) } } // Generate should-functions for each component for entityId in entityIds { let contextName = swiftContextName(entities[entityId]) let shoulds = entityShoulds[entityId] ?? [] var shouldId = 0 for should in shoulds { let branches = entityShouldBranches[entityId]?[shouldId] ?? [] if !branches.isEmpty { out += swiftShould(should, contextName, branches) } shouldId += 1 } } return out } /// Generate single `struct` entity func swiftStruct( _ name: String, _ fields: [String], _ fieldTypes: [Int: String] ) -> String { var outFields = "" var fieldId = 0 for field in fields { let type = fieldTypes[fieldId]! let defaultValue = swiftTypeDefaultValue(type) outFields += SWIFT_STRUCT_FIELD_T .replacingOccurrences(of: "%NAME%", with: field) .replacingOccurrences(of: "%DEFAULT%", with: defaultValue) fieldId += 1 } return SWIFT_STRUCT_T .replacingOccurrences(of: "%NAME%", with: name) .replacingOccurrences(of: "%FIELDS%", with: outFields) } /// Generate entities of `struct` type func swiftStructs( _ entities: [String], _ entityTypes: [Int: String], _ entityFields: [Int: [String]], _ entityFieldTypes: [Int: [Int: String]] ) -> String { var out = "" // Locate structs var entityId = 0 var structIds = [Int]() for _ in entities { let type = entityTypes[entityId] if type == SWIFT_TYPE_STRUCT { structIds.append(entityId) } entityId += 1 } // Generate each struct for id in structIds { out += swiftStruct( entities[id], entityFields[id]!, entityFieldTypes[id]! ) } return out } /// Generate default value for a type func swiftTypeDefaultValue(_ type: String) -> String { return "\(type)()" } class YMLComponent { let ctrl = DialectController(YMLContext()) static private(set) weak var singleton: YMLComponent? init() { Self.singleton = self ymlRegisterEffects(ctrl) ymlRegisterShoulds(ctrl) } func setup() { ymlSet(F.didSetup, true) } } let YML_FIELD_DELIMITER = ": " let YML_INDENT_SHOULD = 8 let YML_INDENT_SHOULD_BRANCH_DESC = 12 let YML_INDENT_SHOULD_BRANCH_IF = 20 let YML_INDENT_SHOULD_BRANCH_THEN = 20 let YML_PREFIX_FIELD = " " let YML_PREFIX_FIELDS = " fields:" let YML_PREFIX_ONELINER = " - " let YML_PREFIX_ONELINERS = " oneliners:" let YML_PREFIX_OUTPUT = "output:" let YML_PREFIX_OUTPUT_PATH = " " let YML_PREFIX_OUTPUT_TYPE = " type: " let YML_PREFIX_SHOULD_BRANCH_IF = " if:" let YML_PREFIX_SHOULD_BRANCH_THEN = " then:" let YML_PREFIX_SHOULDS = " shoulds:" let YML_PREFIX_TYPE = " type: " let YML_PREFIX_VERSION = "version: " func ymlReadLines(_ input: String) { let lines = input.split(separator: "\n", omittingEmptySubsequences: false).map(String.init) ymlSet(F.inputLines, lines) } func ymlIsLineChunkEnd(_ ln: String) -> Bool { return ln.isEmpty } func ymlIsLineChunkStart(_ ln: String) -> Bool { // A line is the start of a chunk if: // 1. it has no indentation // 2. it is not empty return !ln.hasPrefix(" ") && !ln.isEmpty } func ymlParseChunks(_ lines: [String]) -> [String: [String]] { var chunks = [String: [String]]() var currentChunkLines = [String]() var isChunk = false for ln in lines { // Detect chunk start/end if ymlIsLineChunkEnd(ln) { isChunk = false } if ymlIsLineChunkStart(ln) { isChunk = true } // Collect chunk lines if isChunk { currentChunkLines.append(ln) } // Create chunk while parsing if !isChunk, let firstLine = currentChunkLines.first { chunks[firstLine] = currentChunkLines } // Flush collected chunk lines for the next chunk if !isChunk { currentChunkLines = [] } } // Create chunk for the ending chunk if let firstLine = currentChunkLines.first { chunks[firstLine] = currentChunkLines } return chunks } func ymlParseEntities(_ chunks: [String: [String]]) -> [String] { var entities = [String]() for key in chunks.keys { // Ignore known non-entity chunks. if key == YML_PREFIX_OUTPUT { continue } if key.hasSuffix(":") { entities.append(String(key.dropLast(1))) } } return entities.sorted() } func ymlParseEntityFieldTypes( _ chunks: [String: [String]], _ entities: [String], _ entityFields: [Int: [String]] ) -> [Int: [Int: String]] { var result = [Int: [Int: String]]() var entityId = 0 for entity in entities { guard let lines = chunks["\(entity):"] else { entityId += 1 continue } var types = [Int: String]() var fieldId = 0 var inFields = false for ln in lines { if ln.hasPrefix(YML_PREFIX_FIELDS) { inFields = true continue } if inFields && !ln.hasPrefix(YML_PREFIX_FIELD) { break } if inFields { let nameAndType = String(ln.dropFirst(YML_PREFIX_FIELD.count)) let parts = nameAndType.split( separator: YML_FIELD_DELIMITER, maxSplits: 1, omittingEmptySubsequences: false ) if parts.count == 2 { types[fieldId] = String(parts[1]) fieldId += 1 } } } result[entityId] = types entityId += 1 } return result } func ymlParseEntityFields( _ chunks: [String: [String]], _ entities: [String] ) -> [Int: [String]] { var result = [Int: [String]]() var i = 0 for entity in entities { var fields = [String]() guard let lines = chunks["\(entity):"] else { i += 1 continue } var inFields = false for ln in lines { if ln.hasPrefix(YML_PREFIX_FIELDS) { inFields = true continue } if inFields && !ln.hasPrefix(YML_PREFIX_FIELD) { break } if inFields { let name = String(ln.dropFirst(YML_PREFIX_FIELD.count).split(separator: ":")[0]) fields.append(name) } } result[i] = fields i += 1 } return result } func ymlParseEntityOneliners( _ chunks: [String: [String]], _ entities: [String] ) -> [Int: [Oneliner]] { var result = [Int: [Oneliner]]() var entityId = 0 for entity in entities { var isParsing = false var oneliners = [Oneliner]() guard let lines = chunks["\(entity):"] else { entityId += 1 continue } for ln in lines { // Detect oneliners' section if ln.hasPrefix(YML_PREFIX_ONELINERS) { isParsing = true continue } if ln.hasPrefix(YML_PREFIX_SHOULDS) { isParsing = false continue } if isParsing && ln.hasPrefix(YML_PREFIX_ONELINER) { let kv = String(ln.dropFirst(YML_PREFIX_ONELINER.count)) let parts = kv.split( separator: YML_FIELD_DELIMITER, maxSplits: 1, omittingEmptySubsequences: false ) if parts.count == 2 { var item = Oneliner() item.field = String(parts[0]) item.reaction = String(parts[1]) oneliners.append(item) } } } result[entityId] = oneliners entityId += 1 } return result } func ymlParseEntityShouldBranches( _ chunks: [String: [String]], _ entities: [String], _ entityShoulds: [Int: [String]] ) -> [Int: [Int: [ShouldBranch]]] { var result = [Int: [Int: [ShouldBranch]]]() // Collect entity ids with shoulds var entityIds = [Int]() for id in entityShoulds.keys.sorted() { let shoulds = entityShoulds[id]! if !shoulds.isEmpty { entityIds.append(id) } } // Collect should branches for entityId in entityIds { let entity = entities[entityId] guard let lines = chunks["\(entity):"] else { continue } var isParsing = false var isParsingCondition = false var isParsingReaction = false var shouldId = -1 var shouldSections = [Int: [ShouldBranch]]() for ln in lines { // Detect parsed region if ln.hasPrefix(YML_PREFIX_SHOULDS) { isParsing = true continue } if !isParsing { continue } // Detect parsing `condition` if ln.hasPrefix(YML_PREFIX_SHOULD_BRANCH_IF) { isParsingCondition = true continue } if ln.hasPrefix(YML_PREFIX_SHOULD_BRANCH_THEN) { isParsingCondition = false } // Detect parsing `reaction` if ln.hasPrefix(YML_PREFIX_SHOULD_BRANCH_THEN) { isParsingReaction = true continue } if otherLineIndent(ln) == YML_INDENT_SHOULD { isParsingReaction = false } // Detect should section if otherLineIndent(ln) == YML_INDENT_SHOULD { shouldId += 1 shouldSections[shouldId] = [] continue } // Parse branch description if otherLineIndent(ln) == YML_INDENT_SHOULD_BRANCH_DESC { isParsingCondition = false isParsingReaction = false shouldSections[shouldId]!.append(ShouldBranch()) let lastId = shouldSections[shouldId]!.count - 1 let about = String(ln.dropFirst(YML_INDENT_SHOULD_BRANCH_DESC).dropLast()) shouldSections[shouldId]![lastId].about = about } // Parse branch condition if isParsingCondition { let lastId = shouldSections[shouldId]!.count - 1 let condition = String(ln.dropFirst(YML_INDENT_SHOULD_BRANCH_IF)) shouldSections[shouldId]![lastId].condition.append(condition) } // Parse branch reaction if isParsingReaction { let lastId = shouldSections[shouldId]!.count - 1 let reaction = String(ln.dropFirst(YML_INDENT_SHOULD_BRANCH_THEN)) shouldSections[shouldId]![lastId].reaction.append(reaction) } } result[entityId] = shouldSections } return result } func ymlParseEntityShoulds( _ chunks: [String: [String]], _ entities: [String] ) -> [Int: [String]] { var result = [Int: [String]]() var i = 0 for entity in entities { var shoulds = [String]() guard let lines = chunks["\(entity):"] else { i += 1 continue } var inShoulds = false for ln in lines { if ln.hasPrefix(YML_PREFIX_SHOULDS) { inShoulds = true continue } if inShoulds && otherLineIndent(ln) == YML_INDENT_SHOULD && ln.hasSuffix(":") { let name = ln.dropFirst(YML_INDENT_SHOULD).dropLast() shoulds.append(String(name)) } } result[i] = shoulds i += 1 } return result } func ymlParseEntityTypes( _ chunks: [String: [String]], _ entities: [String] ) -> [Int: String] { var result = [Int: String]() var i = 0 for entity in entities { var type = "" guard let lines = chunks["\(entity):"] else { i += 1 continue } for ln in lines { if ln.hasPrefix(YML_PREFIX_TYPE) { type = String(ln.dropFirst(YML_PREFIX_TYPE.count)) break } } result[i] = type i += 1 } return result } func ymlParseOutputPaths(_ chunks: [String: [String]]) -> [OutputPath] { var paths = [OutputPath]() guard let lines = chunks[YML_PREFIX_OUTPUT] else { return paths } var currentPath = "" for ln in lines { // Type if ln.hasPrefix(YML_PREFIX_OUTPUT_TYPE) { var p = OutputPath() p.path = currentPath p.type = String(ln.dropFirst(YML_PREFIX_OUTPUT_TYPE.count)) paths.append(p) } // Path else if ln.hasPrefix(YML_PREFIX_OUTPUT_PATH) { currentPath = String(ln.dropFirst(YML_PREFIX_OUTPUT_PATH.count).dropLast(1)) } } return paths } func ymlParseVersion(_ chunks: [String: [String]]) -> Int { for key in chunks.keys { if key.hasPrefix(YML_PREFIX_VERSION) { let versionStr = key.dropFirst(YML_PREFIX_VERSION.count) if let version = Int(versionStr) { return version } } } return -1 } let cli = CLIComponent() let conv = ConvComponent() let generator = GeneratorComponent() let kotlin = KotlinComponent() let llm = LLMComponent() let swift = SwiftComponent() let yml = YMLComponent() //otherSetupConsoleLogging(generator.ctrl, "Generator") //otherSetupConsoleLogging(llm.ctrl, "LLM") conv.setup() cli.setup() yml.setup() llm.setup() kotlin.setup() swift.setup() otherLaunch()