SPB Git

Repository Public License

FlowEditorSupport.swift 27.6 KB 492 lines swift

1// FlowEngine — pure functions for the workflow editor: highlighting, completion, formatting.2import Foundation34// MARK: - Highlighting56public struct FlowHighlightToken: Hashable, Sendable {7    public enum Kind: String, Sendable, CaseIterable {8        case keyword, action, label, function, type, option, string, interpolation, number, comment, punctuation, identifier, invalid9    }10    /// UTF-16 offsets, usable as an `NSRange`.11    public var range: Range<Int>12    public var kind: Kind13}1415public enum FlowHighlighter {16    /// Classifies every token of the source. Tokens are in source order and do not overlap. Works on any17    /// text, valid or not; it only lexes and looks at neighbouring tokens.18    public static func highlight(_ source: String, registry: FlowActionRegistry = .standard) -> [FlowHighlightToken] {19        let tokens = FlowLexer.tokenize(source).tokens20        var result: [FlowHighlightToken] = []21        var statementStart = true22        var action: FlowActionDefinition?23        var afterColon = false24        var index = 025        while index < tokens.count {26            let token = tokens[index]27            let range = token.range.utf16Range28            defer { index += 1 }29            switch token.kind {30            case .end: break31            case .newline:32                statementStart = true; action = nil; afterColon = false33            case .comment: result.append(FlowHighlightToken(range: range, kind: .comment))34            case .invalid: result.append(FlowHighlightToken(range: range, kind: .invalid))35            case .number, .duration: result.append(FlowHighlightToken(range: range, kind: .number)); statementStart = false36            case .string(let parts):37                // Cut the literal around its interpolations.38                var cursor = range.lowerBound39                for part in parts {40                    guard case .interpolation(_, let inner) = part else { continue }41                    let piece = inner.utf16Range42                    if piece.lowerBound > cursor { result.append(FlowHighlightToken(range: cursor..<piece.lowerBound, kind: .string)) }43                    result.append(FlowHighlightToken(range: piece, kind: .interpolation))44                    cursor = piece.upperBound45                }46                if range.upperBound > cursor { result.append(FlowHighlightToken(range: cursor..<range.upperBound, kind: .string)) }47                statementStart = false48            case .symbol(let text):49                result.append(FlowHighlightToken(range: range, kind: .punctuation))50                if text == ";" || text == "{" || text == "}" { statementStart = true; action = nil }51                afterColon = text == ":"52            case .identifier(let name):53                defer { statementStart = false; afterColon = false }54                let next = tokens[min(index + 1, tokens.count - 1)]55                if afterColon, FlowKeywords.typeNames.contains(name) {56                    result.append(FlowHighlightToken(range: range, kind: .type))57                } else if statementStart, !FlowKeywords.reserved.contains(name), registry.firstWords.contains(name) {58                    if let second = next.identifier, let definition = registry.definition(named: "\(name) \(second)") {59                        action = definition60                        result.append(FlowHighlightToken(range: range.lowerBound..<next.range.utf16Range.upperBound, kind: .action))61                        index += 162                    } else {63                        action = registry.definition(named: name)64                        result.append(FlowHighlightToken(range: range, kind: .action))65                    }66                } else if FlowKeywords.reserved.contains(name), !(name == "as" && action?.usesAsLabel == true) {67                    result.append(FlowHighlightToken(range: range, kind: .keyword))68                } else if next.isSymbol("("), next.range.start == token.range.end, FlowFunctions.names.contains(name) {69                    result.append(FlowHighlightToken(range: range, kind: .function))70                } else if let action, action.labels.contains(name) {71                    result.append(FlowHighlightToken(range: range, kind: .label))72                } else if let action, action.parameters.contains(where: { if case .option(let words) = $0.kind { return words.contains(name) } else { return false } }),73                          let previous = index > 0 ? tokens[index - 1].identifier : nil, action.labels.contains(previous) {74                    result.append(FlowHighlightToken(range: range, kind: .option))75                } else {76                    result.append(FlowHighlightToken(range: range, kind: .identifier))77                }78            }79        }80        return result81    }82}8384// MARK: - Completion8586public struct FlowCompletionItem: Hashable, Sendable {87    public enum Kind: String, Sendable { case keyword, action, label, variable, function, type, option, field }88    public var label: String89    public var kind: Kind90    public var detail: String91    public var insertText: String92}9394public struct FlowCompletionResult: Hashable, Sendable {95    /// UTF-16 range the chosen item replaces (the word being typed; empty when nothing was typed yet).96    public var replacementRange: Range<Int>97    public var items: [FlowCompletionItem]98}99100public enum FlowCompletion {101    /// Suggestions at a cursor position (UTF-16 offset): keywords, actions, parameter labels, option words,102    /// fields, functions and the variables in scope there. Pure; works on incomplete or invalid text.103    public static func complete(_ source: String, utf16Offset: Int, registry: FlowActionRegistry = .standard) -> FlowCompletionResult {104        let cursor = min(max(0, utf16Offset), source.utf16.count)105        let lexed = FlowLexer.tokenize(source)106        let all = lexed.tokens107        // A string still being typed (no closing quote yet) ends at the cursor: the cursor is inside it.108        if let open = all.last(where: { $0.range.end.offset == cursor && $0.range.start.offset < cursor }), case .string = open.kind,109           lexed.diagnostics.contains(where: { $0.code == "unterminated-string" && $0.range.start == open.range.start }) {110            return completeInString(source, token: open, cursor: cursor, registry: registry)111        }112        // The token under the cursor, if the cursor is inside or at the end of a word.113        var prefix = ""114        var replacement = cursor..<cursor115        var before = all.filter { $0.range.end.offset <= cursor && $0.kind != .end }116        if let last = before.last, last.range.end.offset == cursor, let word = last.identifier {117            prefix = word118            replacement = last.range.start.offset..<cursor119            before.removeLast()120        } else if let inside = all.first(where: { $0.range.start.offset < cursor && $0.range.end.offset > cursor }) {121            switch inside.kind {122            case .identifier(let word):123                let units = Array(word.utf16.prefix(cursor - inside.range.start.offset))124                prefix = String(decoding: units, as: UTF16.self)125                replacement = inside.range.start.offset..<cursor126            case .string:127                return completeInString(source, token: inside, cursor: cursor, registry: registry)128            default:129                return FlowCompletionResult(replacementRange: replacement, items: [])130            }131        }132        if case .comment? = before.last?.kind, before.last?.range.end.offset == cursor {133            return FlowCompletionResult(replacementRange: replacement, items: [])134        }135        // Tokens of the statement being typed.136        var statement: [FlowToken] = []137        for token in before.reversed() {138            if token.kind == .newline || token.isSymbol(";") || token.isSymbol("{") || token.isSymbol("}") { break }139            if case .comment = token.kind { continue }140            statement.insert(token, at: 0)141        }142        let compilation = FlowCompiler.compile(source, registry: registry)143        let variables = compilation.symbols.filter { $0.visibleFrom <= replacement.lowerBound && replacement.lowerBound <= $0.visibleTo }144        var items: [FlowCompletionItem] = []145        func keyword(_ word: String, _ detail: String, insert: String? = nil) -> FlowCompletionItem {146            FlowCompletionItem(label: word, kind: .keyword, detail: detail, insertText: insert ?? word)147        }148        func values(matching types: [FlowType]? = nil) -> [FlowCompletionItem] {149            var result: [FlowCompletionItem] = []150            var seen = Set<String>()151            for symbol in variables.reversed() where seen.insert(symbol.name).inserted {152                if let types, !symbol.type.containsUnknown, !types.contains(where: { symbol.type.isAssignable(to: $0) }),153                   // A value whose field could have the right type is still useful (page.url, article.links).154                   symbol.type.members.isEmpty { continue }155                result.append(FlowCompletionItem(label: symbol.name, kind: .variable, detail: "\(symbol.type) · \(symbol.kind.rawValue)", insertText: symbol.name))156            }157            result.sort { $0.label < $1.label }158            result += FlowFunctions.all.map { FlowCompletionItem(label: $0.name, kind: .function, detail: $0.display, insertText: "\($0.name)(") }159            result += [keyword("true", "bool"), keyword("false", "bool"), keyword("not", "negation", insert: "not ")]160            return result161        }162        let last = statement.last163        let previousSignificant = before.last { $0.kind != .newline && !{ if case .comment = $0.kind { return true } else { return false } }($0) }164165        if let last, last.isSymbol("."), statement.count >= 2, let owner = statement[statement.count - 2].identifier {166            // Field access: only when the owner is a known variable.167            if let symbol = variables.last(where: { $0.name == owner }) {168                items = symbol.type.members.sorted { $0.key < $1.key }169                    .map { FlowCompletionItem(label: $0.key, kind: .field, detail: "\($0.value)", insertText: $0.key) }170            }171        } else if statement.isEmpty {172            let hasHeader = before.contains { $0.isWord("flow") }173            let insideBlock = before.contains { $0.isSymbol("{") }174            if !hasHeader {175                items = [keyword("flow", "flow \"Name\" version 1", insert: "flow \"\" version \(FlowLanguage.currentVersion)")]176            } else {177                if !insideBlock {178                    items += [keyword("param", "param name: text", insert: "param "),179                              keyword("allow", "allow domains \"example.org\"", insert: "allow domains \""),180                              keyword("limit", "limit steps 40, duration 300s", insert: "limit "),181                              keyword("space", "space \"Name\" { … }", insert: "space \"")]182                }183                if previousSignificant?.isSymbol("}") == true { items.append(keyword("else", "else { … }", insert: "else {")) }184                items += [keyword("let", "let name = value", insert: "let "), keyword("for", "for item in list limit 10 { … }", insert: "for "),185                          keyword("parallel", "parallel limit 3 { … }", insert: "parallel limit "),186                          keyword("if", "if condition { … }", insert: "if "), keyword("collect", "collect value into name", insert: "collect ")]187                items += registry.names.compactMap { name in188                    registry.definition(named: name).map { FlowCompletionItem(label: name, kind: .action, detail: $0.signature, insertText: name + " ") }189                }190            }191        } else if let head = statement.first?.identifier {192            switch head {193            case "flow":194                if case .string? = last?.kind { items = [keyword("version", "language version", insert: "version \(FlowLanguage.currentVersion)")] }195            case "param":196                if last?.isSymbol(":") == true {197                    items = FlowKeywords.typeNames.map { FlowCompletionItem(label: $0, kind: .type, detail: "parameter type", insertText: $0) }198                }199            case "allow":200                if statement.count == 1 { items = [keyword("domains", "allow domains \"example.org\"", insert: "domains \"")] }201            case "limit":202                if statement.count == 1 || last?.isSymbol(",") == true {203                    let used = Set(statement.compactMap(\.identifier))204                    items = [("steps", "whole number, e.g. 40"), ("duration", "e.g. 300s"), ("timeout", "per step, e.g. 30s")]205                        .filter { !used.contains($0.0) }.map { keyword($0.0, $0.1, insert: $0.0 + " ") }206                }207            case "space": break208            case "let":209                if statement.contains(where: { $0.isSymbol("=") }) { items = values() }210            case "if":211                items = values()212                if statement.count > 1 { items += [keyword("and", "both"), keyword("or", "either")] }213            case "collect":214                if statement.count == 1 { items = values() } else if !statement.contains(where: { $0.isWord("into") }) {215                    items = [keyword("into", "collect value into name", insert: "into ")]216                }217            case "for":218                let hasIn = statement.contains { $0.isWord("in") }, hasLimit = statement.contains { $0.isWord("limit") }219                if statement.count == 2 { items = [keyword("in", "for item in list", insert: "in ")] }220                else if hasIn, last?.isWord("in") == true { items = values() }221                else if hasIn, !hasLimit { items = [keyword("limit", "maximum number of iterations", insert: "limit ")] }222                else if hasLimit, case .number? = last?.kind { items = [keyword("parallel", "iterations at the same time", insert: "parallel ")] }223            case "parallel":224                if statement.count == 1 { items = [keyword("limit", "branches at the same time", insert: "limit ")] }225            default:226                items = completeAction(statement, registry: registry, values: values)227            }228        }229        let needle = prefix.lowercased()230        let filtered = items.filter { needle.isEmpty || $0.label.lowercased().hasPrefix(needle) }231        return FlowCompletionResult(replacementRange: replacement, items: filtered)232    }233234    private static func completeAction(_ statement: [FlowToken], registry: FlowActionRegistry,235                                       values: ([FlowType]?) -> [FlowCompletionItem]) -> [FlowCompletionItem] {236        guard let first = statement.first?.identifier else { return [] }237        var definition = registry.definition(named: first)238        var consumed = 1239        if statement.count >= 2, let second = statement[1].identifier, let two = registry.definition(named: "\(first) \(second)") {240            definition = two241            consumed = 2242        }243        guard let definition else {244            // First word of a two-word action: offer the second words.245            guard statement.count == 1 else { return [] }246            return registry.names.filter { $0.hasPrefix(first + " ") }.compactMap { name in247                let second = String(name.dropFirst(first.count + 1))248                return registry.definition(named: name).map { FlowCompletionItem(label: second, kind: .action, detail: $0.signature, insertText: second + " ") }249            }250        }251        let arguments = Array(statement.dropFirst(consumed))252        let last = arguments.last253        if let word = last?.identifier, let parameter = definition.parameter(label: word), arguments.count >= 1,254           // `as` is a label only for actions that declare it.255           word != "as" || definition.usesAsLabel {256            switch parameter.kind {257            case .option(let words):258                return words.map { FlowCompletionItem(label: $0, kind: .option, detail: parameter.summary.isEmpty ? "option of “\(word)”" : parameter.summary, insertText: $0) }259            case .value(let types):260                return values(types)261            }262        }263        if last?.isWord("as") == true { return [] }   // a new name follows264        var items: [FlowCompletionItem] = []265        if arguments.isEmpty, let positional = definition.positional, case .value(let types) = positional.kind { items += values(types) }266        guard arguments.isEmpty || !(last?.isSymbol("(") ?? false) && !(last?.isSymbol(",") ?? false) else { return values(nil) }267        let used = Set(arguments.compactMap(\.identifier))268        for parameter in definition.parameters {269            guard let label = parameter.label, !used.contains(label) else { continue }270            let detail: String271            switch parameter.kind {272            case .value(let types): detail = types.map(\.description).joined(separator: " | ")273            case .option(let words): detail = words.joined(separator: " | ")274            }275            items.append(FlowCompletionItem(label: label, kind: .label, detail: detail + (parameter.isRequired ? "" : " (optional)"), insertText: label + " "))276        }277        if definition.result != .void, !definition.usesAsLabel, !used.contains("as") {278            items.append(FlowCompletionItem(label: "as", kind: .keyword, detail: "name the \(definition.result) result", insertText: "as "))279        }280        return items281    }282283    /// Inside a string literal: after an unclosed `{`, suggest the names that can be interpolated.284    private static func completeInString(_ source: String, token: FlowToken, cursor: Int, registry: FlowActionRegistry) -> FlowCompletionResult {285        let units = Array(source.utf16)286        var start = cursor287        while start > token.range.start.offset + 1 {288            let unit = units[start - 1]289            if unit == 0x7B { break }290            let scalar = Unicode.Scalar(unit)291            guard let scalar, scalar == "_" || scalar.properties.isAlphabetic || (scalar.value >= 48 && scalar.value <= 57) else {292                return FlowCompletionResult(replacementRange: cursor..<cursor, items: [])293            }294            start -= 1295        }296        guard start > token.range.start.offset + 1, units[start - 1] == 0x7B,297              start < 2 || units[start - 2] != 0x5C else {298            return FlowCompletionResult(replacementRange: cursor..<cursor, items: [])299        }300        let prefix = String(decoding: units[start..<cursor], as: UTF16.self).lowercased()301        let symbols = FlowCompiler.compile(source, registry: registry).symbols302            .filter { $0.visibleFrom <= token.range.start.offset && token.range.start.offset <= $0.visibleTo }303        var seen = Set<String>()304        let items = symbols.reversed().filter { seen.insert($0.name).inserted && (prefix.isEmpty || $0.name.lowercased().hasPrefix(prefix)) }305            .filter { if case .list = $0.type { return false } else { return true } }306            .map { FlowCompletionItem(label: $0.name, kind: .variable, detail: "\($0.type)", insertText: $0.name + "}") }307            .sorted { $0.label < $1.label }308        return FlowCompletionResult(replacementRange: start..<cursor, items: items)309    }310}311312// MARK: - Formatting313314public enum FlowFormatter {315    public static let indentation = "    "316317    /// Pretty-prints the source, or returns `nil` when it has syntax errors (formatting a half-read program318    /// would drop text). Comments on their own line are kept; a comment at the end of a line moves above the319    /// next statement. `format(format(x)) == format(x)`.320    public static func format(source: String, registry: FlowActionRegistry = .standard) -> String? {321        let parsed = FlowParser.parse(source, registry: registry)322        guard !parsed.diagnostics.contains(where: { $0.severity == .error }) else { return nil }323        return format(parsed.program)324    }325326    public static func format(_ program: FlowProgram) -> String {327        var lines: [String] = []328        func comments(_ list: [String], indent: String = "") { for comment in list { lines.append(indent + (comment.isEmpty ? "#" : "# \(comment)")) } }329        comments(program.headerComments)330        lines.append("flow \(quote(program.name)) version \(program.version)")331        if !program.parameters.isEmpty {332            lines.append("")333            for parameter in program.parameters {334                comments(parameter.comments)335                var line = "param \(parameter.name): \(parameter.typeName)"336                if let value = parameter.defaultValue { line += " = \(expression(value))" }337                lines.append(line)338            }339        }340        if !program.domains.isEmpty || !program.limits.isEmpty || !program.domainComments.isEmpty || !program.limitComments.isEmpty {341            lines.append("")342            comments(program.domainComments)343            if !program.domains.isEmpty { lines.append("allow domains " + program.domains.map { quote($0.domain) }.joined(separator: ", ")) }344            comments(program.limitComments)345            if !program.limits.isEmpty {346                lines.append("limit " + program.limits.map { limit in347                    "\(limit.kind.rawValue) " + (limit.kind == .steps ? number(limit.value) : duration(limit.value))348                }.joined(separator: ", "))349            }350        }351        if let space = program.spaceName {352            lines.append("")353            comments(program.bodyComments)354            lines.append("space \(quote(space)) {")355            block(program.body, indent: indentation, into: &lines)356            lines.append("}")357        } else if !program.body.statements.isEmpty || !program.body.trailingComments.isEmpty {358            lines.append("")359            block(program.body, indent: "", into: &lines)360        }361        return lines.joined(separator: "\n") + "\n"362    }363364    private static func block(_ block: FlowBlock, indent: String, into lines: inout [String]) {365        for statement in block.statements {366            for comment in statement.comments { lines.append(indent + (comment.isEmpty ? "#" : "# \(comment)")) }367            self.statement(statement.kind, indent: indent, into: &lines)368        }369        for comment in block.trailingComments { lines.append(indent + (comment.isEmpty ? "#" : "# \(comment)")) }370    }371372    private static func statement(_ kind: FlowStatementKind, indent: String, into lines: inout [String], prefix: String = "") {373        let inner = indent + indentation374        switch kind {375        case .action(let action):376            var line = action.name377            for argument in action.arguments {378                line += argument.label.map { " \($0) \(expression(argument.value))" } ?? " \(expression(argument.value))"379            }380            if let binding = action.binding { line += " as \(binding)" }381            lines.append(indent + prefix + line)382        case .let_(let statement):383            lines.append(indent + prefix + "let \(statement.name) = \(expression(statement.value))")384        case .collect(let collect):385            lines.append(indent + prefix + "collect \(expression(collect.value)) into \(collect.target)")386        case .forEach(let loop):387            var line = "for \(loop.variable) in \(expression(loop.sequence))"388            if let limit = loop.limit { line += " limit \(limit)" }389            if let width = loop.parallelWidth { line += " parallel \(width)" }390            lines.append(indent + prefix + line + " {")391            block(loop.body, indent: inner, into: &lines)392            lines.append(indent + "}")393        case .parallel(let parallel):394            lines.append(indent + prefix + "parallel" + (parallel.width.map { " limit \($0)" } ?? "") + " {")395            block(parallel.body, indent: inner, into: &lines)396            lines.append(indent + "}")397        case .conditional(let conditional):398            lines.append(indent + prefix + "if \(expression(conditional.condition)) {")399            block(conditional.thenBlock, indent: inner, into: &lines)400            if let elseBlock = conditional.elseBlock {401                if elseBlock.statements.count == 1, elseBlock.trailingComments.isEmpty, elseBlock.statements[0].comments.isEmpty,402                   case .conditional = elseBlock.statements[0].kind {403                    // `else if`: the closing brace and the next condition share a line.404                    var chained: [String] = []405                    statement(elseBlock.statements[0].kind, indent: indent, into: &chained, prefix: "} else ")406                    lines += chained407                    return408                }409                lines.append(indent + "} else {")410                block(elseBlock, indent: inner, into: &lines)411            }412            lines.append(indent + "}")413        }414    }415416    static func quote(_ text: String) -> String { "\"" + escape(text) + "\"" }417418    private static func escape(_ text: String) -> String {419        var result = ""420        for scalar in text.unicodeScalars {421            switch scalar {422            case "\"": result += "\\\""423            case "\\": result += "\\\\"424            case "\n": result += "\\n"425            case "\t": result += "\\t"426            case "{": result += "\\{"427            case "}": result += "\\}"428            default: result.unicodeScalars.append(scalar)429            }430        }431        return result432    }433434    /// A number in the only notation the lexer reads: digits with an optional fraction, no exponent.435    static func number(_ value: Double) -> String {436        if value == value.rounded(), abs(value) < 1e18 { return String(format: "%.0f", value) }437        let plain = String(value)438        guard plain.contains("e") else { return plain }439        var text = String(format: "%.17f", value)440        while text.hasSuffix("0") { text.removeLast() }441        return text.hasSuffix(".") ? text + "0" : text442    }443444    static func duration(_ seconds: Double) -> String {445        if seconds == seconds.rounded() { return "\(number(seconds))s" }446        let milliseconds = (seconds * 1_000).rounded()447        if abs(milliseconds / 1_000 - seconds) < 1e-12 { return "\(number(milliseconds))ms" }448        return "\(number(seconds))s"449    }450451    private static func precedence(_ expression: FlowExpression) -> Int {452        switch expression {453        case .binary(.or, _, _, _): return 1454        case .binary(.and, _, _, _): return 2455        case .not: return 3456        case .binary: return 4457        default: return 5458        }459    }460461    static func expression(_ expression: FlowExpression) -> String {462        func child(_ value: FlowExpression, minimum: Int) -> String {463            let text = self.expression(value)464            return precedence(value) < minimum ? "(\(text))" : text465        }466        switch expression {467        case .string(let literal):468            return "\"" + literal.parts.map { part -> String in469                switch part {470                case .text(let text): return escape(text)471                case .interpolation(let path, _): return "{\(path.joined(separator: "."))}"472                }473            }.joined() + "\""474        case .number(let value, _): return number(value)475        case .bool(let value, _): return value ? "true" : "false"476        case .duration(let seconds, _): return duration(seconds)477        case .identifier(let name, _): return name478        case .member(let base, let name, _): return "\(child(base, minimum: 5)).\(name)"479        case .call(let name, let arguments, _): return "\(name)(\(arguments.map { self.expression($0) }.joined(separator: ", ")))"480        case .list(let items, _): return "[\(items.map { self.expression($0) }.joined(separator: ", "))]"481        case .not(let operand, _): return "not \(child(operand, minimum: 3))"482        case .binary(let op, let left, let right, _):483            switch op {484            case .or: return "\(child(left, minimum: 1)) or \(child(right, minimum: 2))"485            case .and: return "\(child(left, minimum: 2)) and \(child(right, minimum: 3))"486            default: return "\(child(left, minimum: 5)) \(op.rawValue) \(child(right, minimum: 5))"487            }488        case .invalid: return "\"\""489        }490    }491}492
Files main
Menu

Theme